Legal Information

Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

1995-2005 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Direct3D, DirectAnimation, DirectDraw, DirectInput, DirectMusic, DirectPlay, DirectShow, DirectSound, DirectX, Visual C++, Visual Studio, Win32, Xbox, Xbox 360 and XNA are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

For specific information about using, modifying, or reproducing sample code or the DirectX Redistributable, see the license agreements contained in the following folder:

<Installed SDK Location>\Documentation\License Agreements\

© 2007 Microsoft Corporation. All rights reserved.


The DirectX Software Development Kit

DirectX is a set of low-level APIs for creating games and other high-performance multimedia applications. It includes support for high-performance 2D and 3D graphics, sound, and input.

The Microsoft DirectX software development kit is your backstage pass to multimedia applications that sizzle. DirectX is a set of low-level APIs for creating games and other high-performance multimedia applications. It includes support for high-performance 2D and 3D graphics, sound, and input.

The SDK contains information on the following DirectX components:

  • DirectX Audio
  • DirectX Input
  • DirectX Graphics
  • The Windows Vista Game Explorer

The SDK also contains a number of technical articles written by technology experts to help you with practical advice for using these components.

In addition, here are some other related programming resources.

  • The DirectX Developer Center has the latest information about what's happening in DirectX as well as lots of software downloads.
  • XNA Game Studio Express is a set of tools and technologies aimed at helping students and hobbyists build games on both Windows and Xbox 360.
  • GDI+ is a software technology designed for creating high-quality text.


What's New in the June 2007 DirectX SDK

This version of the DirectX SDK contains the following new features, tools, and documentation.

New RPC Editing Window and Other Improvements for the XACT User Interface

The XACT authoring tool includes an all-new runtime parameter control (RPC) editing window, which features multiple new curve types, zoom and pan controls, enhanced point editing and selection, mirror editing, and multilevel undo/redo for all RPC edits. Separately, the XACT GUI now properly supports both relative and absolute paths for content. Note that as part of this work, a project must be created and saved before it can be edited. This includes specifying a project path.

Listener Cones and Per-Source Radius and Elevation Control in X3DAudio

X3DAudio has two new features: listener cones, and per-source radius and elevation control. Listener cones provide directionality for the listener, like that already available for emitters. X3DAudio also now allows the developer to specify an inner radius and angle. The inner radius allows the developer to define smooth spatial transitions around the listener. This can help avoid sharp discontinuities as sounds pass through, or over or under, the listener. The inner radius angle specifies an area of space that takes elevation into account when the volume values for each speaker are determined.

Improvements to PIX for Windows

This release of PIX for Windows includes several new features.

  • There is now source-level shader debugging for Direct3D 10 applications. This functionality was previously available only for Direct3D 9 applications.
  • Developers who run PIX on Windows Vista can now capture GPU timing information together with the CPU timing information. This information can help determine if an application is GPU or CPU bound. GPU timing captures are available only on Windows Vista.
  • You can now select a checkbox in the experiment target program settings window to disable D3DX analysis. This option can help improve performance and avoid some issues with applications that call certain D3DX functions.

New Version of GDF Maker Supports the New Korean Ratings System and Updates Support for the Japanese Ratings System

GDF Maker now has support for the new Korean ratings systems ("Game Rating Board"). Operating system support for this rating system will ship with Windows Vista SP 1. Developers can add their ratings for the new system to their GDF project now. The ratings are ignored by Windows Vista RTM, but they will be present for Windows Vista SP 1. For more information on the new ratings system, see http://www.grb.or.kr.

Additionally, support for the Japanese ratings system (CERO) has been updated to deal with the A, B, C, D, and Z ratings. Existing projects are automatically updated if they use older CERO data.

D3X9 and D3DX10 Updated

There are new versions of the D3DX9 and D3DX10 DLLs (d3dx9_34.dll and d3dx10_34.dll). As part of this, FX9 has been updated to support large address-aware 32-bit applications. For more details see D3DFX_LARGEADDRESSAWARE. Finally, the HLSL compiler has been updated with numerous bug fixes and improvements.

Direct3D9 and DirectDraw Headers Now Include the Windows Vista Direct3D9Ex API

The Direct3D9 and DirectDraw headers have been updated to make the Windows Vista Direct3D9Ex APIs available for use. Updated documentation for this Windows Vista API is integrated into the DirectX SDK. Samples for Direct3D9Ex can be found in the Microsoft Windows SDK for Windows Vista.

New Samples

This release includes three new samples. All graphics samples have been updated to use the new version of DXUT that supports rendering with either Direct3D 9 or Direct3D 10. The old version of DXUT that supported only Direct3D 9 has been removed.

  • The Advanced Shader Authoring Workshop GDC 2007 is a series of guided lessons that are derived from the Advanced Shader Authoring Workshop that was presented at the Game Developers Conference 2007. The lessons are divided into six Visual C++ project files that contain near-complete HLSL code. Each project requires the student to add the missing code that is needed to implement the target graphics technique for the lesson. This workshop format gives you an opportunity to experiment with the power and flexibility of HLSL even if you have only a minimal knowledge of HLSL syntax.
  • The Performance Workshop GDC 2007 is a series of guided lessons that are derived from the Performance Workshop that was presented at the Game Developers Conference 2007. The lessons are divided into three Visual C++ project files. Each project requires the student to find the performance bottleneck for the application, and fix the bottleneck in code.
  • The ParentalControlTimeLimits sample shows how an application can obtain the Windows Parental Control Time Limit information for the current user. The Time Limit features allow parents to control the time that their children spend on the computer. A game or application should be time limit aware, and provide appropriate feedback to a user whose account is under time restrictions.

Previous Releases

For a description of what was added in previous releases, see Features Introduced in Previous Releases.


Features Introduced In Previous Releases

Discover what new features have been added to DirectX in previous SDK updates:

  • What's New in the April 2007 DirectX SDK
  • What's New in the February 2007 DirectX SDK
  • What's New in the December 2006 DirectX SDK
  • What's New in the October 2006 DirectX SDK
  • What's New in the August 2006 DirectX SDK
  • What's New in the June 2006 DirectX SDK
  • What's New in the April 2006 DirectX SDK
  • What's New in the February 2006 DirectX SDK
  • What's New in the December 2005 DirectX SDK
  • What's New in the October 2005 DirectX SDK
  • What's New in the August 2005 DirectX SDK
  • What's New in the June 2005 DirectX SDK
  • What's New in the April 2005 DirectX SDK
  • What's New in the February 2005 DirectX SDK
  • What's New in the December 2004 DirectX SDK
  • What's New in the Summer 2004 DirectX SDK


What's New in the April 2007 DirectX SDK

This version of the DirectX SDK contains the following new features, tools, and documentation.

Improvements to the XACT User Interface

This release includes several new features, which include new property pages, a Programmer's Report, and improved audition monitoring.

  • The property pages can now be undocked from the main XACT window. The most frequently edited properties can now be adjusted with a single mouse click. In addition, the property controls have an updated look and feel that provides a more visually intuitive interface.
  • As part of the build process, XACT can now generate a Programmer's Report. This report provides details about the cues, sounds banks, variables, and other information that is useful to the programmer when playing back XACT content. You can generate the report in both plain text format and tab-delimited format.
  • Sound designers can now track resource usage, audio output levels, and activity in the XACT engine, from within the authoring tool itself.
  • Projects that use runtime parameter controls (RPCs) can now be merged.

Improvements to PIX

This releases adds diagnostic logging and customizable pane layouts.

  • If a program exits unexpectedly while PIX is performing a capture of the program, PIX will now report that there was a problem and offer to run the experiment again in diagnostic logging mode. In this mode, PIX will create a log of all function calls and all debug output generated by Direct3D and the target program. This log file will help identify what the target program was doing when the crash occurred. There is also a new option to pause execution as soon as the target program starts, to allow time to attach a debugger and more easily track down what is going wrong.
  • PIX now supports three user-definable custom pane layouts when viewing a run file. This allows users to define and quickly switch between three different arrangements of the various views of the run file.
Updated Shader Compiler

This release includes a new shader compiler that provides many optimizations and bug fixes for HLSL and Effect compilation. This updated version is available for shader models 2.x and 3.x using either FXC.exe or D3DX9_33.dll. For shader model 4.0, developers can use either FXC.exe or one of the new functions D3DX10CompileShaderFromFile, D3DX10CompileShaderFromResource, and D3DX10CompileShaderFromMemory (contained in D3DX10_33.dll).

Effect Pools Sample

One of the downsides to using multiple effects in a single application is that many effect variables need to be set for each effect. Frequently, many of these variables are common between effects. Without a method for sharing variables or shaders between effects, many redundant state-setting calls will need to be made for each effect. Effect pools are meant to solve this problem. This sample demonstrates the use of effect pools on Direct3D 9 and Direct3D 10.

Previous Releases

For a description of what was added in previous releases, see Features Introduced in Previous Releases.


What's New in the February 2007 DirectX SDK

This version of the DirectX SDK contains the following new features, tools, and documentation.

PIX 64-bit Support

A version of PIX is now provided that runs natively on 64-bit editions of Windows Vista and Windows XP and captures data on 64-bit target programs. The capture files created by the 32-bit and 64-bit versions are compatable and can be played back on either operating system.

PIX Vista Limited User Account Support

PIX now runs with user accounts on Windows Vista that do not have administrator privledges.

PIX Direct3D 10 Frame Counters

PIX has new frame counters for Direct3D 10 API usage similar to the frame counters available for Direct3D 9 in previous releases.

DirectSound Header Updated With Windows Vista Specific Speaker Configurations

The DirectSound header has been updated with with new configurations and capabilities that are specific to Windows Vista. For details, see What's New in DirectSound.

New Technical Article: Installation Best Practices for Massively Multiplayer Online Games

The Installation Best Practices for Massively Multiplayer Online Games article discusses creating a chain of trust design for MMOG client installation and custom game update systems which works well with the Windows operating system and the new Windows Vista security model. The approach is designed to enable patching of MMOG titles while supporting standard user accounts which have restricted access to the hard drive and system registry.

Samples

This release includes two new samples.

  • The DDSWithoutD3DX sample demonstrates loading a DDS file without taking a D3DX dependency.
  • The MultiMon10 sample demonstrates how to drive multiple monitors with D3D10.

Previous Releases

For a description of what was added in previous releases, see Features Introduced in Previous Releases.


What's New in the December 2006 DirectX SDK

This version of the DirectX SDK contains the following new features, tools, and documentation.

Direct3D 10 RTM

The DirectX December 2006 SDK contains the first official release of Direct3D 10, the latest graphics platform from Microsoft. Developers can now publish and distribute Direct3D 10 applications and games that leverage all of the software and hardware features of Direct3D 10 in Windows Vista.

XACT: Code-driven API

The XACT code-driven API provides access for more programmatic control of basic objects, such as playing waves (from streaming and in-memory XACT wavebanks or directly from wave files) along with pitch and volume control. The API leverages the existing engine features of XACT such as streaming and wavebank parsing allowing a developer to develop code-driven audio without requiring extensive use of the XACT user interface to create content.

XACT: Cue Visibility API

Titles that want run-time visibility into the contents of an XACT cue can use a new method, IXACTSoundBank::GetCueProperties. This method returns information about the properties of a cue. In addition, the IXACTCue::GetProperties method from Xbox 360 is now available on Windows. It returns specific data on a prepared cue. The returned cue property data includes information such as the currently active variation for sounds and waves.

PIX Improvements

This release of PIX has the following improvements.

  • Assembly-level debugging of Direct3D 10 shaders is now available.
  • The Run File window layout has been redesigned to make it easier to configure and show more information at once.
  • The Create Run File action has a new option to disable write caching while capturing the run file. If the option is enabled, capture performance is somewhat reduced but PIX will capture more data in the event that the target program crashes.

Samples

This release includes several new and updated samples.

  • The ContentStreaming sample demonstrates streaming content in the background for applications that need to display more data than can fit in video or system RAM at any given time. This sample supports both Direct3D 9 and Direct3D 10.
  • The CoreDetection sample demonstrates how to obtain CPU core topology information for the system and the current process. That information is then used to target specific cores for thread execution.
  • The XACTCodeDriven sample shows how to use the XACT code-driven API to load and play a wave file without using the XACT user interface.
  • The GameUXInstallHelper sample has been updated to support Windows Media Center registration using the Game Definition File (GDF) metadata.

Technical Articles

This release includes several new technical articles.

  • The User Account Control for Game Developers article discusses the User Account Control (UAC) security feature, introduced in Windows Vista. This article describes the guidelines and best practices for game developers to work effectively with the UAC security feature.
  • The DirectX Installation for Game Developers article addresses some of the common questions about the DirectX runtime, the DirectX version number, the DirectX libraries, best practices for installing DirectX, and how to deploy the DirectX debug runtime.
  • The Games for Windows: Technical Requirements article discusses best practices for creating games that work well on Windows XP and Windows Vista. The Games for Windows: Test Requirements article provides test cases for the best practices described in the article on technical requirements.

Previous Releases

For a description of what was added in previous releases, see Features Introduced in Previous Releases.


What's New in the October 2006 DirectX SDK

This version of the DirectX SDK contains the following new features, tools, and documentation.

PIX: HLSL Shader Debugging in Direct3D 9

Using PIX, you can now debug HLSL pixel shaders and vertex shaders in the context of your game. The shader debugger can be started from either the pixel history view or from the mesh viewer. Using the debugger, you can step through the code (forward and backward), stop on the cursor or user-set breakpoints, and add highlights to syntax to make the code easier to read.

Preview Release of the new HLSL Shader Compiler for Direct3D 9 Targets

This release has a beta version of d3dx9d_31_beta.dll that includes the Direct3D 10 HLSL compiler enabled for Direct3D 9 targets (shader models 2.0 and later). The new compiler has no support for 1_x targets. This debug-only DLL allows developers to utilize the new Direct3D 10 HLSL compiler for their Direct3D 9 shaders, and will become the default compiler for all Direct3D shaders. Please try the new compiler by building your application with d3dx9d_31_beta.dll instead of d3dx9d_31.dll.

For developers using Direct3D 9, the beta DLL provides a programmatic way of using the shader compiler, FXC10.exe, that ships as part of the Direct3D 10 Technology Preview.

It is important to note that this library is still in the beta stage of development. If you have any questions, bugs reports, or feedback, please contact directx@microsoft.com.

Usability Improvements in XACT

Several usability features have been added to XACT. One such notable feature is that waves in a wavebank that are unused by any sounds are highlighted in red and italics, making it easy to identify those waves that can be removed.

Improved Control of Chart Quality Using UVAtlas Functions

The Direct3DX DLL has been updated with several improvements. Notably, both D3DXUVAtlasCreate and D3DXUVAtlasPartition now have an additional parameter, dwOptions, that allows developers to control the quality of the generated charts. The file name of the updated DLL is d3dx9_31.dll.

XInput

The XInput DLL has been updated with a new function, XInputGetKeystroke. This function provides a more general way of getting input data than using XInputGetState. Additionally, the file name of the updated DLL is xinput1_3.dll.

Previous Releases

For a description of what was added in previous releases, see Features Introduced in Previous Releases.


What's New in the August 2006 DirectX SDK

This version of the DirectX SDK contains the following new features, tools, and documentation.

PIX: Direct3D 9 Shader Debugging

PIX now enables you to debug vertex shaders and pixel shaders inside of a single frame capture. You can step through the assembly instructions, set breakpoints, and restart the shader from the beginning. If the shader was compiled with debug information and if the HLSL source file is available, the source code will be shown as well. Currently the shader debugger shows register contents. In future releases it will also show the contents of HLSL variables and will allow source-level stepping.

PIX: Current Mesh Viewing

It is now possible to view the mesh data for the currently selected draw call event. The 3D data is displayed in wireframe and numeric forms for each stage of the rendering pipeline: before vertex processing, after vertex processing, after the geometry shader, and in screen space. This allows you to inspect how the data changes as it flows through the pipeline for each draw call event.

XACT: 3D Pan Property

New properties on the Play event allow a sound designer to specify a panning direction for wave playback of mono or multichannel content. See the XACT Event, Play Wave reference for more information.

Direct3D 10 Technology Preview

Samples and applications built with the Direct3D ® 10 Technology Preview in the August 2006 DirectX ® SDK require Windows ® Vista TM RC1 to run. The Windows Vista RC1 will be available to MSDN ® subscribers.

Developers will notice that syntax has changed for several of the Direct3D 10 core APIs between the Windows Vista Beta 2 and Windows Vista RC1. Several APIs have been added, renamed, or removed. For a full list of changes, please refer to the August release notes.

New Technical Articles

This release includes three new technical articles:

  • Graphics APIs in Windows Vista: describes the new display driver model.
  • Coding For Multiple Cores on Xbox 360 and Microsoft Windows: gives some advice on how to get started with multithreaded programming.
  • Making Video Games Accessible: Business Justifications and Design Considerations: descibes how to add basic accessibility features to games.
Skinning10 Sample

The Skinning10 sample demonstrates four different methods to perform skinning on Direct3D 10 hardware.

Previous Releases

For a description of what was added in previous releases, see What's New in the DirectX SDK.


What's New in the June 2006 DirectX SDK

The following features have changed in the June 2006 DirectX SDK update:

  • Direct3D 10 Technology Preview
  • PIX
  • Microsoft Cross-Platform Audio Creation Tool (XACT)
  • D3DX9

Direct3D 10 Technology Preview

The Direct3D 10 Technology Preview showcases the newest set of graphics API's for games and other high-performance multimedia applications on next-generation graphics hardware. This technology preview provides reference material, conceptual content, developer libraries, tutorials and samples that demonstrate how to use Direct3D 10. Additional content will provided in upcoming SDK releases.

Samples and applications built with the Direct3D 10 Technology Preview in the June 2006 DirectX SDK require Windows Vista Beta2 to run. The Windows Vista Beta2 will be available to MSDN subscribers.

Developers will notice that syntax has changed for several of the Direct3D 10 core API's between the Windows Vista February CTP and Windows Vista Beta2. Several API's have been added, renamed, or removed. For a full list of changes, see the June 2006: Overview of Direct3D 10 Header and Behavior Updates page in the Direct3D 10 documentation. All Direct3D 10 samples and tutorials have been updated in this SDK to reflect the new syntax. New samples have also been added in this release. Developers can expect a series of changes to arrive in subsequent SDK's.

For known limitations of this Technology Preview, refer to the Microsoft DirectX SDK ReadMe.

This documentation set is intended for developers using the C/C++ programming language.

HLSL Shader Compilation

Starting in the Direct3D10 February 2006 Tech Preview, a preview version of the new HLSL compiler targeting downlevel (Direct3D9) shader models was included. The compiler preview has been updated this SDK with a series of shader-code-generation improvements, as well as support for compiling Direct3D9 Effects files for use with the D3DX9 Effects system (fx_2_0 target).

Using FXC10 included in this SDK, you can try out the new compiler (with new language features such as Improved Flow Control Management) on Shader Model 3.0 and below. Keep in mind that not all HLSL optimizations and new features are active in this release. Generated shaders will not be fully optimized.

This new compiler will be integrated into D3DX9 in a future release. For issues relating to the compilation of shaders in the D3DX9 HLSL compiler, it is recommended that developers test their shaders through the new compiler where possible (via FXC10), and include the results when reporting issues to Microsoft.

Samples

New SoftParticles sample for Direct3D 10. SoftParticles augments various particle rendering techniques to avoid ugly particle vs geometry intersection artifacts by reading the depth buffer back as a texture and fading the particles out as they approach scene geometry.

The Direct3D 10 samples now use a custom binary mesh format (.sdkmesh) intended only for samples. Loader functions can be found in sdkmesh.h and sdkmesh.cpp. The meshconvert.exe tool can be used to convert from the .x format to the .sdkmesh format.

Debug Layer

Additional pipeline and parameter validation has been added to the Direct3D 10 Debug Layer.

PIX

PIX has been updated for June with the following major improvements and new features:

  • PIX introduces a new feature called pixel history. When investigating a single frame capture in PIX, you can select a pixel in a render target or surface and choose to debug the pixel. When this option is selected, everything that touched the pixel in the frame is displayed even if it fails a test like depth, alpha, or stencil. It shows the value of the pixel coming out of the pixel shader and the Framebuffer value for each primitive that affects the pixel. See Pixel History View.
  • Realtime counters can now be displayed ontop of your game when you check the corresponding HUD checkbox is checked. This allows you to see in realtime what the counter values are as you play the game rather than just getting the report after the game is terminated. See HUD.
  • PIX supports the new Direct3D 10 APIs that are included in Windows Vista Beta2. PIX will no longer execute on pre-beta2 builds of Windows Vista.
  • You can now specify a pixrun file that contains full stream capture data as the target program in an experiment. When specified, PIX will replay the data in the pixrun file and perform the experiment on that stream. This was achievable prior to this release but it was difficult to setup.
  • You can now select event rows in the Events window and copy them to the clipboard. It is possible to select one or more rows from the Events window by using standard Windows conventions.

Microsoft Cross-Platform Audio Creation Tool (XACT)

XACT has been updated for June with the following major improvements:

  • The XACT GUI now allows for the import, export, and sharing of variables, categories, and presets across XACT projects. Multiple sound designers and composers can work on a single game and yet maintain their own XACT projects, sharing only those settings that are needed.

D3DX9

The D3DX9 library has not been updated in this release. The DLL is unchanged from the DirectX April 2006 SDK Release. Additional updates will be made in future releases.

For issues relating to the compilation of shaders in the D3DX9 HLSL compiler, it is recommended that developers test their shaders through the new compiler where possible (see HLSL Shader Compilation), and include the results when reporting issues to Microsoft.

See Also

What's New in the June 2007 DirectX SDK


What's New in the April 2006 DirectX SDK

The following features have changed in the April 2006 DirectX SDK update:

  • Direct3D 10 Technology Preview
  • Windows Vista Game Explorer (Beta)
  • XInput
  • Microsoft Cross-Platform Audio Creation Tool (XACT)
  • Tools
  • Technical Article Updates

Direct3D 10 Technology Preview

The Direct3D 10 Technology Preview showcases the newest set of graphics API's for games and other high-performance multimedia applications on next-generation graphics hardware. This technology preview provides reference material, conceptual content, developer libraries, tutorials and samples that demonstrate how to use Direct3D 10. Additional content will provided in upcoming SDK releases.

Samples and applications built with the Direct3D 10 Technology Preview in the April 2006 DirectX SDK require the Windows Vista February 2006 CTP to run. The Windows Vista February 2006 CTP is available to MSDN subscribers.

The D3D10 libraries in the April 2006 DirectX SDK (Reference Rasterizer, Debug Layer, D3DX10) are unchanged from the Direct3D 10 February 2006 Tech Preview Update in the February 2006 DirectX SDK. New samples have been added in this release. Developers can expect a series of changes to arrive in subsequent SDK's.

For known limitations of this Technology Preview, refer to the Microsoft DirectX SDK ReadMe.

This documentation set is intended for developers using the C/C++ programming language.

HLSL Shader Compilation

In the Direct3D10 February 2006 Tech Preview, a preview version of the new HLSL compiler targeting downlevel (Direct3D9) shader models was included. The compiler preview has been updated this SDK with a series of shader-code-generation improvements.

Using FXC10.exe included in this SDK, you can try out the new HLSL compiler (with new language features such as Improved Flow Control Management) on Shader Model 3.0 and below. Keep in mind that not all HLSL optimizations and new features are active in this release. Generated shaders will not be fully optimized.

Samples

A new sample illustrating displacement mapping on dynamic objects using geometry-shader prism extrusion and pixel-shader raytracing has been added. This technique adds significantly more surface and silhouette detail to an object, and is scalable across levels-of-detail.

A new sample illustrating multi-stream rendering has been added. This sample supports both Direct3D 9 and Direct3D 10. The Direct3D 10 version also illustrates multi-stream rendering with multiple index buffers.

General Information

For more information on the Direct3D10 April 2006 Technology Preview, see the Direct3D 10 documentation. For known limitations of this Technology Preview, refer to the Microsoft DirectX SDK ReadMe.

To access the Direct3D 10 documentation, click the Start Menu, choose All Programs, Microsoft DirectX SDK (April 2006), and select "Documentation for Direct3D 10". To access the ReadMe, click the Start Menu, choose All Programs, Microsoft DirectX SDK (April 2006), and select "Microsoft DirectX SDK ReadMe".

Windows Vista Game Explorer (Beta)

The Windows Vista Game Explorer documentation has been updated for April with new information about using the Game Definition File Editor.

To access the Game Explorer documentation, click the Start Menu, choose All Programs, Microsoft DirectX SDK (April 2006), and select "Documentation for Game Explorer".

XInput

The XInput API has been updated with the following features for this release:

  • Support for arcade sticks and wheel controls through subtypes.
  • A new function, XInputEnable, which can activate or deactivate XInput processing to respond to focus change events.

Additionally, the name of the XInput DLL has been changed to XInput1_1.dll.

Microsoft Cross-Platform Audio Creation Tool (XACT)

XACT has been updated for April with the following new feature:

  • The IXACTSoundBank::Prepare and IXACTSoundBank::Play methods of the IXACTSoundBank interface have been updated to support seeking to a specified time offset for playback.

Tools

PIX

Texture/Surface viewing support has been improved.

  • Use the texture viewer to select which mip level/face/texture to view
  • View image channels separately or together using the channel(s) combo box
  • Adjust image brightness and contrast, and see high-dynamic range image information using the channel levels control
  • The depth and stencil channels are viewed via the Render tab, or by viewing depth/stencil surfaces directly

Vertex/Index Buffer Viewing Support

  • The contents of vertex buffers and index buffers can now be displayed, using a user-specifiable format

Improved Direct3D10 support

  • ID3D10Device state can be viewed
  • ID3D10StateBlock contents can be viewed
  • ID3D10Buffer contents can be viewed
  • ID3D10Texture contents can be viewed in more ways

D3DX9 Improved UVAtlas Partitioning Algorithm

In this version of D3DX9, the UVAtlas partitioning algorithm has been significantly improved to produce better results (including fewer charts) for a given stretch threshold.

For example, using the mesh: Samples\Media\MicroscopeCity\occcity.x, the comparative results with the Feb SDK are as follows:

Stretch Threshold | Number of Charts (Feb 2006 SDK) | Number of Charts (April 2006 SDK)
0.3 | 228 | 194
0.166667 | 403 | 363
0.01 | 1880 | 1109
D3DX9 February 2006 SDK | D3DX9 April 2006 SDK

The new algorithm in April is more computationally intensive, so the UVAtlas API's will revert to the previous algorithm for input meshes with more than 25,000 faces. The new algorithm also does not support signal specialized parameterization, so if IMT is specified, the old algorithm is always used.

Additional user control over performance vs. quality, as well as support for signal-specialized parameterization, is planned for a future release.

Technical Article Updates

A variety of new articles have been added to the SDK:

  • 64-bit programming for Game Developers
  • Optimizing DVD performance for Windows Games
  • Patching Game Software in Windows XP and Windows Vista
  • Taking Advantage of High-Definition Mouse Movement
  • Top Tools and Techniques for Making More Robust Windows Games

See Also

What's New in the June 2007 DirectX SDK


What's New in the February 2006 DirectX SDK

The following features have changed in the February 2006 DirectX SDK update:

  • Direct3D 10 Technology Preview
  • D3DX9
  • Microsoft Cross-Platform Audio Creation Tool (XACT)
  • Windows Vista Game Explorer (Beta)
  • Tools

Direct3D 10 Technology Preview

FXC10 D3D9 HLSL Shader Compilation

  • The HLSL compiler included in this update to the Direct3D10 Tech Preview now targets downlevel shader models. Using FXC10.exe included in this SDK, you can try out the new compiler (with new language features such as Improved Flow Control Management) on Shader Model 3.0 and below. Keep in mind that only a subset of HLSL optimizations and new features are active in this release. Generated shaders will not be fully optimized.

New Direct3D 10 Samples and Tutorials

  • A new sample illustrating object-space motion blur (MotionBlur10) has been added. No filter kernels are used: High-quality motion blur is achieved via fin extrusion in the Geometry Shader and accumulated in the frame buffer using Alpha-To-Coverage. Texture-space motion blur is achieved using anisotropic filtering.
  • A new tutorial illustrating manipulation of Direct3D10 rendering state has been added. See Tutorial 14.

D3DX10

  • A series of improvements have been made to the ID3DX10Sprite interface. Sprites now take advantage of additional Direct3D10 features (geometry shader, texture arrays) to achieve higher performance. See ID3DX10Sprite.
  • The D3DX interfaces for multithreaded [asynchronous] resource loading and processing have been improved in this release. See ID3DX10ThreadPump and related pages.

Direct3D10 Debug Layer

  • Additional pipeline and parameter validation has been added to the Direct3D10 Debug Layer.

For more information on the Direct3D10 February 2006 Technology Preview, see the Direct3D 10 documentation. For known limitations of this Technology Preview, refer to the Microsoft DirectX SDK ReadMe.

To access the Direct3D 10 documentation, click the Start Menu, choose All Programs, Microsoft DirectX SDK (February 2006), and select "Documentation for Direct3D 10". To access the ReadMe, click the Start Menu, choose All Programs, Microsoft DirectX SDK (February 2006), and select "Microsoft DirectX SDK ReadMe".

D3DX9

UVAtlas

  • UVAtlas now supports texture parameterization for polygonal meshes. By providing a list of false edges to the UVAtlas APIs, meshes comprised of quads or N-sided polygons can be atlased. False edges will not be split during parameterization. See D3DXUVAtlasCreate, D3DXUVAtlasPartition.
  • A new adjacency input parameter has been added to D3DXUVAtlasPack. This change was required to fix special cases where D3DXUVAtlasPack was classifying meshes incorrectly as non-manifold. The new adjacency output parameter from D3DXUVAtlasPartition will provide this adjacency information. See D3DXUVAtlasPartition, D3DXUVAtlasPack.
  • A callback has been added to monitor progress of IMT computation. See D3DXComputeIMTFromSignal, D3DXComputeIMTFromTexture, D3DXComputeIMTFromPerVertexSignal.
  • A new primitive ID parameter has been added to the app-specified-signal callback for IMT computation. This can be used to specify custom signals that vary over a mesh. See LPD3DXIMTSIGNALCALLBACK.

Microsoft Cross-Platform Audio Creation Tool (XACT)

XACT has been updated for February with new features, as well as improved performance.

  • ADPCM compression has been added, which allows built wave banks to take up significantly less space on disk.
  • Information on Using the X3DAudio API has been added.

Windows Vista Game Explorer (Beta)

The Windows Vista Game Explorer has been updated for February with new features:

  • Applications can now take advantage of Rich Save Games in Windows Vista.
  • The Game Definition File schema now includes a required manifest of the executables that a game installs or extracts.

To access the Game Explorer documentation, click the Start Menu, choose All Programs, Microsoft DirectX SDK (February 2006), and select "Documentation for Game Explorer".

Tools

PIX

PIX has been updated with these workflow improvements:

  • PIX now supports single-frame capture and playback of Direct3D10 applications.
  • PIX now supports the display of Direct3D10 texture resources, including the back buffer. Image data can be viewed with or without the alpha channel. See View Texture Data.
  • CreateObject and DestroyObject events are now added to PIXRun files, to more clearly indicate when Direct3D objects are created and destroyed.

Note Direct3D 10 support is only available on Windows Vista

See Also

What's New in the June 2007 DirectX SDK


What's New in the December 2005 DirectX SDK

The following features have changed in the December 2005 DirectX SDK update:

  • Direct3D 10 Technology Preview
  • Microsoft Cross-Platform Audio Creation Tool (XACT Beta)
  • Managed DirectX for .NET Framework 2.0 (Beta)
  • Windows Vista Game Explorer (Beta)
  • Redist
  • D3DX9
  • XInput
  • Tools
  • Samples
  • Technical Article Updates

Direct3D 10 Technology Preview

The Direct3D 10 Technology Preview showcases the newest set of graphics APIs for games and other high-performance multimedia applications on next-generation graphics hardware. This technology preview provides reference material, conceptual content, developer libraries, tutorials and samples that demonstrate how to use Direct3D 10. Additional content will provided in upcoming SDK releases.

Samples and applications built with the Direct3D 10 December 2005 Technology Preview require the Windows Vista December 2005 CTP to run. The Windows Vista December 2005 CTP is available to MSDN subscribers.

Instantiating a Direct3D 10 hardware device requires Direct3D 10-capable graphics hardware with a Windows Vista Display Driver Model (WDDM) driver. As of the release of this Technology Preview, such hardware is not publicly available. A software fallback (the Direct3D 10 reference rasterizer) is provided.

For more information (including known limitations of this Technology Preview), refer to the Microsoft DirectX SDK ReadMe.

To access the Direct3D 10 documentation, click the Start Menu, choose All Programs, Microsoft DirectX SDK (December 2005), and select "Documentation for Direct3D 10". To access the ReadMe, click the Start Menu, choose All Programs, Microsoft DirectX SDK (December 2005), and select "Microsoft DirectX SDK ReadMe".

Microsoft Cross-Platform Audio Creation Tool (XACT Beta)

XACT has been updated for December with new features, as well as improved performance.

To access the XACT documentation, click the Start Menu, choose All Programs, Microsoft DirectX SDK (December 2005), and select "Microsoft Audio Creation Tool Documentation".

To get started using the XACT design tool, click click the Start Menu, choose All Programs, Microsoft DirectX SDK (December 2005), Utilities, and select "Microsoft Audio Creation Tool".

Managed DirectX for .NET Framework 2.0 (Beta)

Included with the December 2005 DirectX SDK is updated support for the .NET Framework 2.0 in Managed DirectX. This assembly addresses the issues users were having with using Managed DirectX in Visual Studio 2005. It also includes new features designed to take full advantage of the features included in the .NET Framework 2.0 such as generics.

To use the new assembly, load up Visual Studio 2005, and after creating a new project add a reference to "Microsoft.DirectX.dll" You may see multiple versions of this assembly depending on any past DirectX SDK's you've installed, so add the reference to the one with the version 2.0.0.0. The namespaces you'll find in this assembly are:

  • Microsoft.DirectX - Which includes all of the common math structures, as well as the new GraphicsBuffer class which replaces the GraphicsStream class from the original Managed DirectX
  • Microsoft.DirectX.Diagnostics - DxDiag functionality
  • Microsoft.DirectX.Direct3D - Direct3D and D3DX functionality
  • Microsoft.DirectX.DirectSound - DirectSound functionality
  • Microsoft.DirectX.DirectInput - Direct Input functionality
  • Microsoft.DirectX.Xact - XACT audio functionality
  • Microsoft.DirectX.XInput - XInput functionality

Besides support for the .NET Framework 2.0, this updated assembly has a number of new additions which we would love feedback on, including better performance, and a cleaner API.

Note Managed DirectX for .NET Framework 2.0 is an early beta; complete samples and documentation will be provided in a later release of the DirectX SDK.

Windows Vista Game Explorer (Beta)

The Windows Vista Game Explorer is a new feature of Windows Vista that provides a rich game browsing experience. The documentation details how you can prepare your game to appear in the Game Explorer.

To access the Game Explorer documentation, click the Start Menu, choose All Programs, Microsoft DirectX SDK (December 2005), and select "Documentation for Game Explorer".

Redist

The Redist now includes by default the core DirectX runtime and the all versions of the SDK redistributable components (D3DX, Managed DirectX, and XInput). See Installing DirectX with DirectSetup for updated instructions on DirectSetup and the DirectX Redist.

D3DX9

An API set has been added for preprocessing of shaders. This allows for all #define and #include instructions in shaders to be preprocessed, leaving a self-contained shader that can be compiled at a later point.

  • D3DXPreprocessShader
  • D3DXPreprocessShaderFromFile
  • D3DXPreprocessShaderFromResource

XInput

A new article has been posted detailing the differences between XInput and DirectInput, and how the two APIs can be used together: XInput and DirectInput

Tools

PIX

PIX has been updated with these workflow improvements:

  • When setting up an experiment, it is now valid to configure PIX to begin a full stream capture of your program at any time during its execution, rather than requiring the capture to begin in response to the "Program Start" trigger. Starting a full-stream capture later can help PIX generate a smaller PIXRun file that focuses on the area of your program that you are interested in.
  • When setting up an experiment in Basic View, you have the option to instruct PIX to take a single-frame capture of Direct3D whenever F12 is pressed.

A list of D3DX functions that are supported by PIX is now available, see D3DX.

DxErr

The DirectX Error Handling Utility Library has been updated to support new API sets, including Direct3D 10, D3DX 10, and XACT, using the new DxErr.h header file and DxErr.lib library file.

Samples

A new sample detailing the intermediate processing steps of high dynamic range (HDR) lighting has been added to the SDK: HDRDemo Sample

The Pick sample has been updated and added back into the SDK. You can access this sample through the Sample Browser.

Technical Article Updates

A variety of new articles have been added to the SDK:

  • Game Timing and Multicore Processors: Use this method to obtain reliable high-resolution processor timings.
  • Authenticode Signing for Game Developers: Obtain and use digital certificates to sign your code.
  • Best Security Practices in Game Development: Find and close common security holes in your games.
  • Crash Dump Analysis: Create a game crash minidump for analysis.
  • Simplifying Game Installation: Reduce the number of steps a user must go through from installation to playing your game.
  • Windows Game Explorer for Game Developers: Integrate your game into the Windows Vista Game Explorer.
  • Games and Firewalls (Updated): Add your game to the Windows Firewall exception list at install time.

See Also

What's New in the June 2007 DirectX SDK


What's New in the October 2005 DirectX SDK

The following features have changed in the October 2005 DirectX SDK update:

  • XInput
  • Microsoft Cross-Platform Audio Creation Tool (XACT Beta)
  • Managed DirectX for .NET Framework 2.0 (Beta)
  • Samples and Tools
  • Technical Article Updates

XInput

XInput is an API that allows applications to receive input from the Xbox 360 controller for Windows. Controller rumble effects and voice input and output are supported.

For a quick start guide to using the XInput API, see Getting Started With XInput, and the XInput Reference. Four XInput Samples are available in the Sample Viewer. See XInput Frequently Asked Questions for answers to commonly-asked questions about XInput.

Microsoft Cross-Platform Audio Creation Tool (XACT Beta)

XACT is an audio design tool and associated API that allow application designers and audio content designers to work together to bring vibrant sounds to games.

To access the XACT documentation, click the Start Menu, choose All Programs, Microsoft DirectX 9.0 SDK Update (October 2005), and select "Microsoft Audio Creation Tool Documentation".

To get started using the XACT design tool, click click the Start Menu, choose All Programs, Microsoft DirectX 9.0 SDK Update (October 2005), Utilities, and select "Microsoft Audio Creation Tool".

Managed DirectX for .NET Framework 2.0 (Beta)

Included with the October 2005 DirectX SDK is the first support for the .NET Framework 2.0 in Managed DirectX. This assembly addresses the issues users were having with using Managed DirectX in Visual Studio 2005. It also includes new features designed to take full advantage of the features included in the .NET Framework 2.0 such as generics.

To use the new assembly, load up Visual Studio 2005 (Beta 2 or later), and after creating a new project add a reference to "Microsoft.DirectX.dll" You may see multiple versions of this assembly depending on any past DirectX SDK's you've installed, so add the reference to the one with the version 2.0.900. The namespaces you'll find in this assembly are:

  • Microsoft.DirectX - Which includes all of the common math structures, as well as the new GraphicsBuffer class which replaces the GraphicsStream class from the original Managed DirectX
  • Microsoft.DirectX.Direct3D - Direct3D and D3DX functionality
  • Microsoft.DirectX.DirectSound - DirectSound functionality
  • Microsoft.DirectX.DirectInput - Direct Input functionality
  • Microsoft.DirectX.XInput - The newly released XInput functionality

Besides support for the .NET Framework 2.0, this updated assembly has a number of new additions which we would love feedback on, including better performance, and a cleaner API.

Note Managed DirectX for .NET Framework 2.0 is an early beta; complete samples and documentation will be provided in a later release of the DirectX SDK.

Samples and Tools

The DirectX Ops tool (see DirectX Ops (dxops.exe)) can accept an expression string, which contains a series of script commands, files and optional arguments. Each expression is built from one or more script commands. See DirectX Ops Script Commands.

EffectEdit and Mesh Viewer are no longer shipped with the SDK. The equivalent functionality for these tools can be achieved by using the new DirectX Ops (dxops.exe) and DirectX Viewer (Dxviewer.exe) tools.

Graphics Card Capabilities: A new chart containing a collection of the capabilities exposed by current drivers on a wide range of graphics hardware available on the market today is available in the SDK. To view it, use the DirectX SDK Sample Browser and search for "Graphics Card Capabilities".

Technical Article Updates

The article introducing the gaming experience on Windows XP Media Center Edition 2005 has been updated with a new section to help you make your application accessible using the Media Center interface. Two new corresponding samples, MCELauncher and MediaCenterGame, have been added to illustrate this. For more information see: Installing Games on Windows XP Media Center Edition.

See Also

What's New in the June 2007 DirectX SDK


What's New in the August 2005 DirectX SDK

The following features have changed in the August 2005 DirectX SDK update:

  • SDK Updates
  • Graphics Updates

SDK Updates

The following features have been updated in the SDK:

  • Performance Tools

Performance Tools

Enhancements to PIX include:

  • You can use the new object view to analyze properties of Direct3D objects in a PIXRun file.
  • You can view detailed properties of shader, vertex declaration, and state block objects.
  • You can use the new events toolbar to navigate by draw calls and events, or find specific calls or memory addresses within events.
  • You can use the previous draws brightness slider in the render window to analyze the results of individual draw calls.

Graphics Updates

  • D3DX
  • Samples and Tools

The following graphics-related features have been updated in this release:

D3DX

  • Effects System: Use ID3DXEffect::SetRawValue to set a contiguous range of shader constants with a memory copy. For instance, you could set an array of twenty matrices with 20 calls to ID3DXBaseEffect::SetMatrix or by calling SetRawValue once.
  • ID3DXTextureGutterHelper::ResampleTex - Resamples a texture from one parameterization into another. This can be used in conjunction with the UVAtlas Functions to create a new, optimal texture atlas for a mesh and then resample the original texture into the new parameterization.
  • Sprite depth and texture sort - When submitting sprites for rendering, you may sort sprite drawing order by depth (D3DXSPRITE_SORT_DEPTH_FRONTTOBACK or D3DXSPRITE_SORT_DEPTH_BACKTOFRONT) and then by texture (D3DXSPRITE_SORT_TEXTURE). This is useful for rendering UI components as sprites (see D3DXSPRITE).
  • Skipping the highest mip levels during texture loading - You can now choose to skip the highest mip level(s) when loading a texture from file. This can be useful for adapting applications to low-memory situations, and can be specified in the extended texture creation API's (such as D3DXCreateTextureFromFileEx).
  • Using PRT with textures - Instead of representing transfer vectors at the vertices of a mesh, you could use PRT to represent transfer vectors in texture maps. This alternative has the same data cost but is independent of mesh complexity. See Representing PRT With Textures (Direct3D 9).

Samples and Tools

  • DirectX Viewer (Dxviewer.exe) - This tool is designed for viewing any DXSAS compliant effect on geometry in an x file. See note 1.
  • IrradianceVolume Sample - This sample donated by ATI Technologies (www.ati.com) builds upon the PRTDemo Sample and adds preprocessing of the scene to allow a PRT object to use the local lighting environment as it moves through a scene.

Note 1: This new tool replaces some of the functionality previously found in effectedit and mview. EffectEdit and MView will be deprecated in a future DirectX SDK release.

See Also

What's New in the June 2007 DirectX SDK


What's New in the June 2005 DirectX SDK

The following features have changed in the June 2005 DirectX SDK update:

  • SDK Updates
  • Graphics Updates
  • Technical Article Updates

SDK Updates

The following features have been updated in the SDK:

  • Performance Tools
  • Content Tools
  • Redistributing the SDK

Performance Tools

Enhancements to PIX include:

  • The ability to view the contents of a Direct3D surface such as a render target or a texture surface. This allows you to debug visually what is being written to (or read from) the surface. See Surface View.
  • The ability to view the Direct3D device state as of any moment within a frame. The state is organized into categories that correspond to the different stages of the pipeline. See State View.
  • A new action to save all device state to an HTML file. See Experiment - Advanced View.
  • New keyboard shortcuts to pause, single-step or toggle wireframe mode when playing back a full-stream capture. See Playing back a Full Stream Capture.

Content Tools

Enhancements to the DirectX Extensions for DCC applications include:

  • Maya - You can now access DirectX shader parameters using the MEL scripting language. This allows a developer to create standard MEL scripts to interact with the DirectX shader assignment and parameters to make it better fit with your content pipeline. See DirectX Extensions for Alias Maya.
  • DXSAS 1.0 Viewer - Use the DirectX Viewer (Dxviewer.exe) to view meshes and effects that implement the Microsoft DirectX Standard Annotations and Semantics specification.

Redistributing the SDK

DirectXSetup has been updated so that you can specify which components are optional for the purpose of reducing the size of the redistributable. For this release, D3DX and/or Managed DirectX are optional components, and are not required when you wish to redistribute DirectX. The default behavior remains unchanged; DirectSetup will install all SDK components.

Graphics Updates

  • D3DX
  • Samples and Tools

The following features have been updated in the graphics component:

D3DX

  • Effects System: A new method has been added to delete unused effect parameter blocks at runtime, reducing the amount of memory used by the effects system. See ID3DXEffect::DeleteParameterBlock.
  • UVAtlas Functions - The April 2005 SDK introduced the UVAtlas library for generating a unique UV texture mapping on an arbitrary mesh. This release features improvements to the UVAtlas algorithm, as well as new documentation describing usage, best-practices, and example results (see Using UVAtlas (Direct3D 9)).
  • IMT computation - A series of new functions have been added to automatically compute Integrated Metric Tensors for a mesh based on an input signal. The output of these functions can be used to drive texture-space prioritization for texture parameterization via the UVAtlas API's. For example: using IMT computed from a normal map (see D3DXComputeIMTFromTexture) will generate a UV Atlas that devotes more texture space to triangles with high-frequency normal-map detail; flat triangles with constant normal data will receive appropriately less texture space. IMT can be computed from a texture, from per-vertex values, or from a user-defined per-vertex or per-texel procedural signal. See UVAtlas Functions for more details.
  • PRT speed improvements - All of the PRT runtime functions (D3DXSHEvalDirection, D3DXSHRotate, and all of the D3DXSH*Light functions) have been optimized; rotations in particular are significantly faster, showing a 20x improvement at 6th order.

Samples and Tools

Support for VS.NET 2005 for C++ and MDX samples.

  • Added VS.NET 2005 support for C++ and managed samples.
  • Improved Direct3D starting point samples. A new sample called EmptyProject provides a minimal starting point for a Direct3D sample application, and a new sample called SimpleSample provides a basic starting point similar to the other Direct3D samples which shows the typical policy used by the rest of the DirectX SDK samples.
  • Upgraded the UV Atlas Command Line Tool to include Integrated Metric Tensor (IMT) array support and more adjacency options.

Technical Article Updates

  • A new technical article concerning Direct3D resources including topics such as how managed and unmanaged resources behave and how resources are typically handled by the runtime and drivers. See Resource Management Best Practices
  • The Games for Microsoft Windows Logo Program Guide and Games for Microsoft Windows Logo for Applications have been moved into Technical Articles in the SDK. These articles describe the steps necessary to earn the Windows Logo on your game.

See Also

What's New in the June 2007 DirectX SDK


What's New in the April 2005 DirectX SDK

This page is a record of the features that were added in the DirectX April 2005 update. To see the latest features in the SDK, see What's New in the June 2007 DirectX SDK.

  • SDK Updates
  • Graphics Updates
  • Technical Article Updates

SDK Updates

The following features have been updated in the SDK:

  • Documentation
  • Performance Tools
  • Content Tools

Documentation

Setup documentation - The DXSetup documentation has been updated to explain the redist naming scheme and how you can customize the redist to reduce your installation size. See Installing DirectX with DirectSetup.

Performance Tools

Enhancements to the PIX performance analysis tool include:

  • You can now open full-stream capture PIXRun files, and render frames from them within PIX, the same way you can with single-frame capture PIXRun files (see Analyzing PIX Data).
  • You can save rendered frames to an image file from within PIX.
  • You can adjust the scaling of the Y-axis of the event timeline to see data graphed more clearly (see TimeLine View).

Content Tools

Enhancements to the DirectX Extensions for DCC applications include:

  • The Installing DirectX with DirectSetup plug-in has been added to support exporting data to the DirectX X-File format (.x).

Graphics Updates

The following features have been updated in the graphics component:

  • D3DX

D3DX

The following new features were added to D3DX:

  • UVAtlas API - These new API's (see UVAtlas Functions) automatically generate a unique UV texture mapping for an arbitrary mesh, maximizing texture space usage and minimizing texture undersampling (stretch). See Using UVAtlas (Direct3D 9).
  • Reduced effects memory footprint - A new flag (D3DXFX_NOT_CLONEABLE ) has been added to allow users to specify that an effect will never need to be cloned by the effect system. Using this flag can notably reduce the memory footprint for an effect.
  • Precomputed Radiance Transfer (PRT)
    • Passing in a NULL parameter for sample locations in the ComputeVolumeSamples API's (see ID3DXPRTEngine) will result in transfer matrices being computed at each vertex in the mesh.
    • Improvements have been made to increase the physical accuracy of radiance transfer simulations.

Technical Article Updates

  • The DirectX developer Frequenty Asked Questions (FAQs) page has been added to the documentation. See DirectX Frequently Asked Questions.
  • A new technical article about the Windows XP Media Center Edition 2005 has been added. See Introduction to the 10-Foot Experience for Windows Game Developers.

See Also

What's New in the June 2007 DirectX SDK


What's New in the February 2005 DirectX SDK

This page is a record of the features that were added in the DirectX February 2005 update. To see the latest features in the SDK, see What's New in the June 2007 DirectX SDK.

  • SDK Updates
  • Graphics Updates
  • Technical Article Updates

SDK Updates

The following features have been updated in the SDK:

Performance Tool Updates

Enhancements to PIX have been made:

  • You can now capture the Direct3D calls made by a single frame of your application and play them back within PIX.
  • When grabbing screen shots:
    • You can append an incrementing number, or the current frame number, to the screen shot filename.
    • You can specify whether to overwrite existing image files with the same filename.
    • You can specify whether to show or hide the mouse cursor in the screen shot.
  • New command-line options are available to:
    • Convert a .PIXRun file to a .csv format that can be read by Microsoft Excel.
    • Save an exclusive-or comparison of two images to a file.

See Command-Line Syntax.

Graphics Updates

The following features have been updated in the graphics component:

  • D3DX
  • New Samples

D3DX

The following new features were added to D3DX:

  • D3DX Is Now a Dynamic-Link Library - Starting with this software development kit (SDK) release, D3DX is being released as a dynamic-link library (DLL). Updates to D3DX in the future will continue to ship as uniquely-named DLLs that exist side-by-side on the system. This allows for continued improvements to the library without imposing regression risk. D3DX9.lib is still provided as the import library for the DLL for your application to statically link against.

    The D3DX DLL included in the SDK is automatically installed as part of Installing DirectX with DirectSetup. If your application does not use D3DX, you can remove D3DX from the redistributable (see Directx redist.txt for details). The statically-linked debug library (D3DX9dt.lib) has been removed; use D3DX9d.lib instead. For more information, see D3DX.

  • DirectX Standard Annotations and Semantics - Standard annotations and semantics (DXSAS) define a contract between an effect and a host application, that enables shaders to share metadata with tools, applications, and game engines. The DXSAS standard defines a set of semantics and annotations that must be implemented in both host applications and effects. This release documents version 1.0.0 of the DXSAS standard. See DirectX Standard Annotations and Semantics Reference.
  • Effects - A new effect function (D3DXCreateEffectEx) was added that allows an application to control which parameters can be updated by the application; that is, ignored by the effects system. Add each constant to a string that is supplied to the function. Each constant must be bound to a constant register, and may only be used in high-level shader language (HLSL) code. Companion functions for creating an effect from a file (D3DXCreateEffectFromFileEx) or a resource (D3DXCreateEffectFromResourceEx) were also added.
  • Precomputed Radiance Transfer - The precomputed radiance transfer (PRT) application programming interface (API) has been enhanced. Rapid ray-tracing methods ID3DXPRTEngine::ShadowRayIntersects and ID3DXPRTEngine::ClosestRayIntersects are provided to determine whether a point is in shadow.

New Samples

The following sample was added:

  • PRTCmdLine - This sample uses a NULL reference Microsoft Direct3D device and an Extensible Markup Language (XML) options file to run the PRT simulator. See the sample in the sample browser.

Technical Article Updates

The following articles have changed:

  • Updated Install-on-Demand for Games and "Gaming with Least Privileged User Accounts" [replaced by User Account Control for Game Developers for December 2006] with information about patching.
  • Top Issues for Windows Titles is a new article.

See Also

What's New in the June 2007 DirectX SDK


What's New in the December 2004 DirectX SDK

This page is a record of the features that were added in the DirectX December 2004 update. To see the latest features in the SDK, see What's New in the June 2007 DirectX SDK.

  • SDK Updates
  • Graphics Updates
  • Technical Articles

SDK Updates

The following features have been updated in the SDK:

  • Content Tools
  • Performance Tools
  • SDK Samples

Content Tools

DirectX tools are now documented in DirectX SDK Tools. Tools for programming and debugging shaders (which is primarily a graphics topic) are located in Direct3D 9 Tools.

The tools are now located in (SDK root)\Utilities\Bin\x86 or x64. The corresponding path to the source files is: (SDK root)\Utilities\Source\x86 or x64.

The DirectX Extensions for Alias Maya now supports options to control the set of exported data, and it can export and preview smooth skinned meshes.

The debug monitor (Dbmon.exe) has been removed from the SDK, but it can still be found in the Platform SDK.

The force feedback editor (Fedit.exe) has been removed from the SDK.

Performance Tools

The following enhancements have been made to PIX:

  • A collection of countersets is provided as a starting point for you to record useful runtime data from your application.
  • A new key combination trigger is provided.
  • You can now set triggers to recur.
  • Options are available to display PIX information on top of your running application.
  • You can set a call capture action on a single frame.
  • Full stream capture performance is improved.
  • You can launch experiment and log files, or open image files, simply by dragging them onto a PIX window.
  • The tool is compatible with older versions of DirectX.
  • Many bugs have been fixed.

D3DSpy has been removed. Nearly all of its functionality is duplicated by PIX.

SDK Samples

The following samples are upgrades are available in the update:

  • Samples and tool source code now use safer string functions.
  • Project and solution files for both Microsoft Visual Studio .NET 2002 and Visual Studio .NET 2003 are now provided.
  • A new Install-on-Demand for Games sample.

Graphics Updates

The following features have been updated in the graphics component:

  • D3DX
  • Graphics Samples

D3DX

The following new features were added to D3DX:

  • Effects - The SetPixelShader and SetVertexShader methods have been removed from ID3DXBaseEffect, ID3DXEffect, and ID3DXEffectCompiler. These methods do not perform well within the effect framework when shaders are swapped at run time. Use the following methods instead: IDirect3DDevice9::SetPixelShader and IDirect3DDevice9::SetVertexShader
  • PRT - ID3DXPRTEngine::ComputeConvCoeffs method has been renamed to ID3DXPRTEngine::ComputeLDPRTCoeffs to reflect its use with locally-deformable precomputed radiance transfer (LDPRT).

    New optional parameters have been added to the following functions: D3DXCreatePRTCompBuffer, D3DXCreatePRTEngine.

    The following new functions, and methods have been added: D3DXComputeTangentFrame, D3DXComputeTangentFrameEx, ID3DXPRTEngine::ComputeSSAdaptive, ID3DXPRTEngine::ComputeSurfSamplesBounce, ID3DXPRTEngine::ComputeSurfSamplesDirectSH, ID3DXPRTEngine::SetMinMaxIntersection.

Graphics Samples

The following samples are upgrades are available in the update:

  • The PRTPerVertex sample was renamed LocalDeformablePRT.

Technical Articles

A new section (DirectX SDK Technical Articles) has been added to the documentation with the latest tips on programming games for Windows.

See Also

What's New in the June 2007 DirectX SDK


What's New in the Summer 2004 DirectX SDK

The following features have changed in this SDK update:

  • SDK Updates
  • Graphics Updates

SDK Updates

The following features have been updated in the SDK:

  • Performance Tools

Performance Tools

A new tool designed to capture detailed performance information from a running application is now available. It is called PIX and is available at the following location:

(SDK root)\Utilities\PIX\PIX.exe

To help get started, see PIX.

Graphics Updates

The following features have been updated in the graphics component:

  • D3DX

D3DX

The following new features were added to D3DX:

  • Precomputed Radiance Transfer - To simulate scenes with precomputed radiance transfer (PRT), use the following D3DX interfaces and functions, which largely replace previous PRT functions: ID3DXPRTBuffer, ID3DXPRTCompBuffer, ID3DXPRTEngine, ID3DXTextureGutterHelper. See Precomputed Radiance Transfer (Direct3D 9).
  • HLSL Supports Shader Model 3 - High-level shader language (HLSL) now supports shader model 3 for vertex and pixel shaders (see Shader Model 3). The shader models are simplified considerably from earlier shader versions. As a result, if you are implementing shaders in hardware, you may only use vs_3_0 with ps_3_0, and you may not use either shader type with the fixed function pipeline. These changes make it possible to simplify drivers and the runtime. HLSL pixel shader input semantics must have matching semantics in vertex shader output semantics. Some examples are shown in Match Semantics on vs_3_0 and ps_3_0 Shaders. For additional improvements, see Shader Model 3.
  • Add User Intent to Effects with Standard Annotations and Semantics - To communicate information about effect parameters that are intended to be shared between effects and applications, Microsoft is working with its partners to create a set of industry-standard semantics and annotations. These can be attached to shared parameters to allow applications to understand standardized effects. See DirectX Standard Annotations and Semantics Reference.
  • Draw Multiple Instances of Geometry More Efficiently - Given a scene that contains many objects that use the same geometry, you can draw many instances of that geometry at different orientations, sizes, colors, and so on with dramatically better performance by reducing the amount of data you need to supply to the renderer. Instancing requires a device that supports vs_3_0. See Efficiently Drawing Multiple Instances of Geometry (Direct3D 9).
  • Effect System Improvements Include Preshaders and Parameter Blocks - There are a number of improvements with the effect system such as:
    • The sequence of calls for applying effect state to a device has changed to the following: ID3DXEffect::Begin starts the active technique. ID3DXEffect::BeginPass begins a pass. ID3DXEffect::CommitChanges updates changes to any set calls in the pass. ID3DXEffect::EndPass ends a pass. ID3DXEffect::End ends the active technique. You no longer call ID3DXEffect::Pass because it has been removed from the header file. For more information, see Render An Effect.
    • Effect Preshaders - Preshaders improve the efficiency of an effect. See PreShaders Improve Performance.
    • Effect Parameter Sharing and Parameter Blocks - Use an ID3DXEffectPool interface to share effect parameters. See Sharing Effect Parameters. Use parameter blocks to help manage the parameters in one or more effects. See Use Parameter Blocks to Manage Effect Parameters.

D3DX9Mesh.h

The following new methods have been added:

  • ID3DXPRTEngine::ClosestRayIntersects
  • ID3DXPRTEngine::ShadowRayIntersects

See Also

What's New in the June 2007 DirectX SDK


DirectX Components

DirectX is made up of the following components:

  • The DirectX Graphics component combines the Direct3D 9 component and the D3DX 9 utility library, which simplifies many graphics programming tasks (see Direct3D 9 Graphics). The newest graphics and utility components, Direct3D 10, and D3DX 10, are documented separately.
  • The DirectInput component supports for a variety of input devices, including full support for force-feedback technology. DirectInput will maintain its current status until new technology in these areas is made available (see DirectInput).
  • The DirectSound component can be used in the development of high-performance audio applications that play and capture waveform audio. DirectSound will maintain its current status until new technology in these areas is made available (see DirectSound).

Older Components

  • Use of DirectDraw is no longer recommended. With the release of Direct3D 9.0, all two-dimensional functionality is contained within Direct3D and its associated helper functions in D3DX. However, the DirectDraw documentation is still available and can be viewed on MSDN at DirectDraw.
  • DirectMusic will maintain its current status until new technology in these areas is made available. DirectMusic documentation can be found at: (SDK Root)\Documentation\DirectX9.
  • DirectPlay is deprecated, and Microsoft strongly recommends against using it to develop new applications. Game developers should use Windows Sockets (see Windows Sockets) and the Windows Firewall APIs (see Windows Firewall for Game Developers).
  • DirectShow is no longer recommended for game development. All of the DirectShow components (headers, libraries, utilities, tools, and samples) were removed from the DirectX SDK in the April 2005 release. DirectShow is available in the latest Platform SDK Install.


DirectX SDK Programming Guide

This section contains information for using Microsoft DirectX applications.

  • Installing DirectX with DirectSetup
  • Programming DirectX with C/C++
  • Using COM

The following table lists the version of DirectX that comes standard with each version of Microsoft Windows.

Operating System | DirectX Version
Windows Vista | DirectX 10.0
Windows XP | DirectX 8.1
Windows Server 2003 | DirectX 8.1
Windows 2000 | DirectX 7.1
Windows Millennium Edition | DirectX 7.1
Windows 98 SE | DirectX 6.0
Windows 98 | DirectX 5.0
Windows NT 4.0 | DirectX 3.0
Windows NT | DirectX 2.0
Windows 95 OEM Service Release 2 | DirectX 3.0 (Can upgrade to DirectX8)
Windows 95 | does not come with DirectX

All operating systems after Windows 95 can upgrade DirectX to the current version. To check what version of DirectX is installed from an application, see the GetDXVer Sample.


Programming DirectX with C/C++

Most Microsoft DirectX application development with C/C++ involves conventional programming techniques. However, there are several aspects of DirectX programming that may be unfamiliar to some developers. This section provides a brief overview of specialized topics, along with some guidelines for compiling and debugging DirectX applications.

  • Using Callback Functions
  • Debugging DirectX Applications

Compiler Support

Developing C++ applications with this release requires Visual Studio .NET 2003 or later. Visual Studio .NET 2002 and Visual Sutdio 6 are no longer supported.

Developing managed applications requires Visual Studio .NET 2003 and .NET Framework runtime, version 1.1.


Using Callback Functions

A callback function is essentially an event handler that is implemented by an application and called by the system. Windows applications typically implement multiple callback functions, each one designed for a particular set of events. When an event occurs, the system notifies the application by calling the appropriate callback function. The callback function also usually has a parameter list that the system can use to pass the application more detailed information about the event. The most common example of a callback function is the window procedure. This function is used by the system to pass Windows messages to the applications that owns the window.

DirectX uses callback functions for a variety of purposes. For example, your system supports multiple devices. DirectInput represents each device by a device object that contains the details of the device's capabilities. Your application typically needs to enumerate the available devices and examine the device objects in order to handle user input properly. To do this enumeration, you must implement a DIEnumDeviceObjectsCallback callback function.

You start the enumeration process by calling IDirectInputDevice8::EnumObjects and passing to the method a pointer to your DIEnumDeviceObjectsCallback callback function. The system calls this function once for each device, and it passes in a DIDEVICEOBJECTINSTANCE structure that contains information about the device's capabilities. After your callback function has processed the information, it can return DIENUM_CONTINUE, to request the next device object, or DIENUM_STOP, to stop the enumeration.

DirectX uses a number of other callback functions for a variety of purposes. For details, see the documentation for the particular DirectX component.

Implementing a Callback Function

Because callback functions have different purposes and usage, they are documented in the appropriate reference section in much the same way as a regular function. However, a callback function reference is essentially a template that describes how to implement the function, and it is not a normal API reference. The callback function reference provides the following information:

  • How the function is used
  • The function's syntax
  • An explanation of the information that will be contained by each parameter
  • An explanation of the possible return values

You should declare the function type as CALLBACK or WINAPI. Either type is acceptable. You can use any function name. The name used in the documentation is just a convenient label for a particular callback function.

Implement the function according to the description in the reference. The implementation details depend on the particular function and the requirements of your application. See the sample code for some examples of how to implement various callback functions.

Pass a pointer to the function to the appropriate DirectX component. The DirectX component can then use the function pointer to call the function. The way in which you pass this pointer varies from function to function, so you should see the particular function's reference for details.

The following code fragment is borrowed from the DirectInput Joystick sample. It sketches out the essential elements of implementing DIEnumDeviceObjectsCallback, a callback function that is used to enumerate the axes of a joystick.

// The function declaration
BOOL CALLBACK EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
                                VOID* pContext );
...
// Pass the function pointer to DirectInput by calling the
// IDirectInputDevice9::EnumObjects method

if ( FAILED( hr = g_pJoystick->EnumObjects(EnumAxesCallback,
                                            (VOID*)hDlg,
                                            DIDFT_AXIS )));

...

// The function implementation
BOOL CALLBACK EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
                                VOID* pContext )
{
// Process the information passed in through the two parameters
// Return DIENUM_CONTINUE to request the next device object
// Return DIENUM_STOP to stop the enumeration
}


Debugging DirectX Applications

This section covers the following topics pertaining to debugging C and C++ applications.

  • Debug vs. Retail DLLs
  • Removing or Adding Debug DLLs
  • Other Resources

Debug vs. Retail DLLs

When you develop software in C++, it is best to install the debug versions of the DLLs. The debug DLLs have additional code that validates internal data structures and outputs debug error messages, using the OutputDebugString function, while your program is executing. When an error occurs, the debug output gives you a more detailed description of the problem. The debug DLLs run more slowly than the retail DLLs but are much more useful for debugging an application. Be sure to ship the retail retail versions with your application.

The DirectX SDK installation program provides the option of installing debug builds of the DirectX DLLs. You can choose to do this by being sure to select Developer Runtime Support for installation on the local hard drive, the default. This option is presented during installation on the Custom Setup page, under the Install DirectX Runtime node.

Note Developer Runtime Support is a required component for DirectX extensions for Visual Studio .NET.

If you have installed Developer Runtime Support, you can use the DirectX Control Panel to switch between the debug and retail builds of most components. To launch the DirectX Control Panel, navigate the Start menu to DirectX Utilities, in Microsoft DirectX SDK, and click DirectX Control Panel. This opens DirectX Properties, and on the Direct3D tab, you can select either Use Debug Version of Direct3D or Use Retail Version of Direct3D.

To see the debug messages, configure your system so that debug output appears in a window or on a remote computer. A development environment, such as Visual Studio .NET 2003, enables you to do this. Consult the environment's documentation for setup instructions.

To ensure that the debugger can find the relevant symbolic information when using debug builds, locate the symbol files as follows:

.pdb file location
Same directory as binary
.dbg file location
%SystemRoot%\Symbols\binary extension\

Removing or Adding Debug DLLs

You can change the installed DLLs by changing the DirectX SDK components that are installed on your computer. You can add additional components by using Add or Remove Programs in Control Panel to change your installation, if you still have the original installation files on your computer. (These files are not required if you are simply removing components.) If you no longer have the original installation files, you might need to download the SDK again; after doing so, simply run setup again to add components to your existing installation.

Other Resources

The Microsoft Application Compatibility Toolkit contains the tools and documentation you need to evaluate and mitigate application compatibility issues before deploying your application.

To find C++ memory corruption and other problems, you can use the Microsoft Windows Application Verifier (AppVerifier). AppVerifier monitors an application for things like heap corruption, locks usage, and invalid handles. See Testing Applications with AppVerifier on TechNet for instructions on using this tool.


Installing DirectX with DirectSetup

Applications and games that depend on DirectX can use the DirectXSetup function to install the necessary system components into an existing Windows installation.

  • Checking the Installed Version of DirectX
  • Standard Install
  • Custom Install
  • Removing the DirectX SDK
  • Enabling AutoPlay
  • DirectX Redistribution
  • Naming Convention
  • Reducing the DirectX Redistribution Size
  • Dependency on previous released optional SDK components

Checking the Installed Version of DirectX

Before you install, here are several ways to find out what version of DirectX is installed:

  • Run the DirectX Diagnostic Tool
  • Run the GetDXVer Sample
  • Call DirectXSetupGetVersion from an application.

Use D3DXCheckVersion to make sure that the D3DX headers that you build against match the D3DX library that you're linking with.

Standard Install

DXSetup.exe is a standard installer that comes with the DirectX SDK. It provides an easy way for developers to install the DirectX runtime without having to write a custom installer. The standard installer is included in the following folder:

SDK root\Redist

The installer uses the DirectSetup API for version checking, setting up the type of installation, displaying the end user license agreement (EULA), installing DirectX, reporting progress, and handling messages. The installer displays all of the user interface (UI) components during the installation, including the click-through EULA, progress meter, and message handling.

The standard install is easy:

  1. If your application requires managed code, verify that the Microsoft .NET Framework is installed. Otherwise, skip to the next step.
  2. Call DXSetup.exe from the command line.

The installer supports Microsoft Windows 2000 and newer releases. The installer also supports languages shown in the following table.

Chinese (Simplified) | Chinese (Traditional) | Czech
Dutch | English (American) | French
German | Italian | Japanese
Korean | Polish | Portuguese (Brazil)
Russian | Spanish | Swedish

Note The EULA will be displayed in English on machines that support the use of multiple languages.

The standard installation supports one command line option, /silent, which specifies a non-interactive installation.

Custom Install

DirectSetup facilitates one-call installation of the DirectX components. DirectSetup Reference includes several API functions and structures as well as a callback function for customizing the user interface during the installation process. The DirectX SDK includes a sample application that demonstrates the use of this callback function (see Dinstall Sample). Follow the instructions for Redistributable Code contained in the license agreements within the following folder:

SDK root\Documentation\License Agreements.

The DirectXSetup function takes a parameter (lpszRootPath), that points to the root directory of the installation. It can be NULL to indicate that the root path is the current directory.

The root directory must contain DXupdate.cab, DXDllreg_x86.cab, Dsetup.dll, Dsetup32.dll, and any of the optional DirectX SDK redistributable files. To create the proper structure on your application setup disk, copy the redistributable code from one of the following locations into the root path of your setup program:

  • If the SDK is installed, the installed location is SDK root\Redist
  • The location on the DirectX CD is CD root\Redist
  • If you download the SDK, the location is Extracted location\Redist
  • The latest Redist download can be obtained at http://msdn.microsoft.com/directx/sdk

DirectSetup enables you to define a callback function for customizing the DirectX setup process. This callback function is referred to as DirectXSetupCallbackFunction, but you can give it any name.

You can use the callback function to do the following:

  • Employ a custom interface. Your setup program might display messages in ways other than by using a message Box or standard dialog boxes. The callback function enables you to integrate messages for the DirectX component of your installation into your own interface.
  • Update a progress indicator.
  • Suppress the display of status and error messages. Designers of programs for novice users might want to suppress error messages and let the setup program handle errors and make upgrade choices silently. This approach requires a greater development effort for the setup program, but it might be appropriate for the target audience.

If a callback function is not provided by the setup program, the DirectXSetup function displays status and error information in a dialog box and obtains user input by calling the MessageBox function. If a callback is provided, the information that would have been used to create the status dialog or message box is instead passed to the callback. The callback function is called once for each DirectX component that can be installed or upgraded.

Create a callback function that conforms to the DirectXSetupCallbackFunction prototype, as in the following declaration.

DWORD WINAPI DirectXSetupCallbackFunction(
        DWORD dwReason,
        DWORD dwMsgType,
        LPSTR szMessage,
        LPSTR szName,
        void *pInfo);

In the Dinstall Sample, the name of the function is the same as that of the prototype, but this is optional. The way your callback function interprets the parameters is entirely up to you. Typically, you would choose which messages to display (based on dwReason) and when to present the user with alternatives, and you would modify the interface accordingly.

The callback function must return:

  • IDOK if there are no choices to be made by the user.
  • MB_OK or MB_OK | MB_ICONERROR if there are errors.

Before calling DirectXSetup, notify DirectSetup that you want to use a callback by calling the DirectXSetupCallbackFunction and passing a pointer to the callback.

Removing the DirectX SDK

To remove the DirectX SDK, use Add/Remove Programs in Control Panel to remove the SDK.

Enabling AutoPlay

If you are building an AutoPlay compact disc title, copy the Autorun.inf file in the root directory of the SDK compact disc to the root of your application directory. This text file contains the following information.

[autorun]
OPEN=SETUP.EXE

If your application's setup program is called Setup.exe, you do not have to make any changes to this file; otherwise, edit this file to contain the name of your setup program.

DirectX Redistribution

Stand-alone developer runtime installers only install the DirectX developer and debug runtime for redistribution purposes. These installers are available for all supported platforms and are located in the following folder:

SDK root\Developer Runtime\

Applications can use the supplied standard installer, DXSetup.exe, to redistribute DirectX. Be sure to follow the instructions for Redistributable Code contained in the license agreements in the following folder:

SDK root\Documentation\License Agreements

These files must be included in any distribution of DirectX as explained in the file DirectX Redist.txt, found in the following folder:

CD root\Documentation\License Agreements

Note The D3DX library included in this release is dependant on the Direct3D runtimes that shipped with this SDK. Applications linking against the version of D3DX in this release must also redistribute the runtime from this SDK.

Naming Convention

The following naming convention is used for the optional redistributable components that are included in the DirectX redist folder:

D3DX

For D3DX files, the naming convention is MonthYear_Component_HeaderVersion_Platform.file-extension.

So, for example, if you were installing the D3DX components from the December 2005 SDK release, you would use the following file names:

Dec2005_d3dx9_28_x86.cab
Dec2005_d3dx9_28_x64.cab

Note There were no changes to the D3DX component for the October 2005 SDK release.

If you were installing the D3DX components from the August 2005 SDK release, you would use the following file names:

Aug2005_d3dx9_27_x86.cab
Aug2005_d3dx9_27_x64.cab

If you were installing the D3DX components from the June 2005 SDK release, you would use the following file names:

Jun2005_d3dx9_26_x86.cab
Jun2005_d3dx9_26_x64.cab

If you were installing the D3DX components from the April 2005 SDK release, you would use the following file names:

Apr2005_d3dx9_25_x86.cab
Apr2005_d3dx9_25_x64.cab

If you were installing the D3DX components from the Feb 2005 SDK release, you would use the following file names:

Feb2005_d3dx9_24_x86.cab
Feb2005_d3dx9_24_x64.cab

Follow this naming convention for future SDK releases.

DirectX for Managed Code

For DirectX for Managed Code, the naming convention for files is MonthYear_Component_Platform.file-extension.

MonthYear_Component_Platform.Ext

Note Starting with the December release, managed components are named MDX1.

So if you were installing the managed code components from the December 2005 SDK release, you would use the follwing file name:

Dec2005_MDX1_x86.cab

Starting with the December release, older managed code components are contained in a .cab file with Archive in its name. Use this .cab file instead of previous release .cab files to support older MDX components:

Dec2005_MDX1_x86_Archive.cab

XInput

For XInput files, the naming convention is MonthYear_Component_Platforms.file-extension.

So, if you were installing the XInput components from the December 2005 SDK release, you would use the following file names:

Oct2005_xinput_x86.cab
Oct2005_xinput_x64.cab

Note There were no behavioral changes to XInput in the December 2005 SDK release.

Reducing the DirectX Redistribution Size

The DirectX redist default file set contains all the files that are needed to support all DirectX applications. It is highly recommend that developers use all the files in the DirectX Redist folder. To reduce the size of the DirectX redist footprint, you may remove optional DirectX SDK redistributable files. These files are listed in the CD root\Documentation\License Agreements\DirectX Redist.txt.

For example, here are several common scenarios:

No BDA Support (3 megabyte savings)
If your application does not require broadcast driver architecture (BDA) support then the following can be removed BDA.CAB, BDANT.CAB, and BDAXP.CAB.
No Managed DirectX (approximately 5 megabyte savings)
If your application does not require Managed DirectX then the MonthYear_MDX1_x86.CAB and MonthYear_MDX1_x86_Archive.cab files may be removed from the redist folder.
D3DX Support (approximately 17 megabyte savings)
If your application does not require D3DX 9 or if you only require a specific month's release, then the older MonthYear_d3dx9_HeaderVersion_x86.cab and the MonthYear_d3dx9_HeaderVersion_x64.cab files may be removed from the redist folder.
No 64-bit support (approximately 10 megabyte savings)
If your application is NOT a native 64-bit application then the MonthYear_d3dx9_HeaderVersion_x64.cab, MonthYear_Xinput_x64.cab, and MonthYear_XACT_x64.cab files may be removed from the redist folder.
DirectX 9.0c is installed
If your application requires DirectX 9.0c (or higher), then you may remove the DirectX.cab and the DXnt.cab from the redist folder. However, if you remove these cabs from the redist folder (and DirectX 9.0c (or higher) is not installed), DirectXSetup will fail.
No XInput support ( less than 1 megabyte savings)
If your application does not require the XInput API, you may remove the MonthYear_xinput_x86.cab and MonthYear_xinput_x64.cab files from the redist folder.
No XACT Support (approximately 1 megabyte savings)
If your application does not require the XACT API, you may remove the MonthYear_xact_86.cab and MonthYear_xact_x64.cab files from the Redist folder.

For instance, suppose you know that your customer has DirectX 9.0c installed, and you want the smallest redist that only includes the 32-bit version of the D3DX library from the December 2005 SDK release. For this scenario, you need to include the following CAB files in the redist folder:

  • dxsetup.exe
  • dsetup32.dll
  • dsetup.dll
  • dxupdate.cab
  • dxdllreg_x86.cab
  • Dec2005_d3dx9_28_x86.cab

Your installation can use the DirectXSetup API or run DXSetup.exe to install the D3DX component.

Dependency on previous released optional SDK components

By default the DirectX Redist includes the previous versions of SDK redistributable components.

All the developer would need to do is include the default DirectX redist, which includes the all of the previously released SDK redist component packages (.cab files). No other changes are required by the developer.

DirectX Setup detects that the component's .cab package is available and installs the component's files appropriately via file version checking of the DLLs. These files would only be installed if they had higher versions. If for instance, a component of your application requires an optional component from the August 2005 release of the SDK, you would need to copy the appropriate .cab files from the August 2005 release redist folder to the current redist folder.

D3DX Applications Require the following files:

Aug2005_d3dx9_27_x86.CAB
Aug2005_d3dx9_27_x64.CAB

Managed DirectX Applications Require the following files:

Dec2005_MDX1_x86_Archive.cab
Aug2005_d3dx9_27_x86.CAB
Aug2005_d3dx9_27_x64.CAB


Using COM

The Microsoft DirectX Component Object Model (COM) is an object-oriented programming model used by numerous applications. Because the bulk of the DirectX runtime is in the form of COM-compliant objects, all DirectX developers need to have at least a basic understanding of COM principles and programming techniques. Although COM has a reputation for being difficult and complex, the COM programming required by most DirectX applications is straightforward.

There are two distinct types of COM programming:

  • Using existing COM objects.
  • Implementing your own COM objects. This can be a complicated and demanding task. Much of COM's reputation for complexity comes from this type of COM programming.

Most DirectX applications need to use only the COM objects provided by DirectX. They do not need to implement their own COM objects. In other words, most DirectX developers need to concern themselves only with the first — and easiest — type of COM programming.

This section provides a brief introduction to using the COM objects provided by DirectX. It is primarily intended for novice COM programmers. For a more detailed discussion of how to use COM objects, or for information about how to implement your own COM objects, see Further Information.

  • COM Object Overview
  • Creating a COM Object
  • Using COM Interfaces
  • Managing a COM Object's Lifetime
  • Using C to Access COM Objects
  • Using Macros to Call DirectX COM Methods
  • DirectX COM Documentation Conventions
  • Using ATL with DirectX COM Interfaces
  • IUnknown


COM Object Overview

COM objects are basically black boxes that can be used by applications to perform one or more tasks. They are most commonly implemented as a DLL. Like a conventional DLL, COM objects expose methods that your application can call to perform any of the supported tasks. Applications interact with COM objects in somewhat the same way they do with C++ objects. However, there are some distinct differences:

  • COM objects enforce stricter encapsulation than C++ objects. You cannot just create the object and call any public method. A COM object's public methods are grouped into one or more interfaces. To use a method, you must create the object and obtain the appropriate interface from the object. An interface typically contains a related set of methods that provide access to a particular feature of the object. For example, the IDirect3DCubeTexture9 interface contains methods that enable you to manipulate cube texture resources. Any methods that are not part of an interface are not accessible.
  • COM objects are not created in the same way as C++ objects. There are several ways to create a COM object, but all involve COM-specific techniques. The DirectX API includes a variety of helper functions and methods that simplify creating most of the DirectX objects.
  • You must use COM-specific techniques to control the lifetime of the object.
  • COM objects do not need to be explicitly loaded; COM objects are typically contained in a DLL. However, you do not need to explicitly load the DLL, or link to a static library, in order to use a COM object. Each COM object has a unique registered identifier that is used to create the object. COM automatically loads the correct DLL.
  • COM is a binary specification. COM objects can be written in and accessed from a variety of languages. You don't need to know anything about the object's source code. For example, Visual Basic applications routinely use COM objects that were written in C++.

This topic contains the following sections:

  • Objects and Interfaces
  • GUIDs
  • HRESULT Values
  • The Address of a Pointer

Objects and Interfaces

It is important to understand the distinction between objects and interfaces. In casual usage, an object may sometimes be referred to by the name of its principal interface. However, strictly speaking, the two terms are not interchangeable. An object may expose any number of interfaces. For example, while all objects must expose the IUnknown interface, they normally expose at least one additional interface, and they might expose many. To use a particular method, you must not only create the object, you must also obtain the correct interface.

In addition, more than one object might expose the same interface. An interface is a group of methods that perform a specified set of operations. The interface definition specifies only the syntax of the methods and their general functionality. Any COM object that needs to support a particular set of operations can do so by exposing a suitable interface. Some interfaces are highly specialized and are exposed only by a single object; others are useful in a variety of circumstances and are exposed by many objects. The extreme case is the IUnknown interface, which must be exposed by all COM objects.

Note If an object exposes an interface, it must support every method in the interface definition. In other words, you must be able to call any method and be confident that it exists. However, the details of how a particular method is implemented may vary from object to object. For example, different objects may use different algorithms to arrive at the final result. There is also no guarantee that a method will be supported in a nontrivial way. Sometimes an object exposes a commonly-used interface, but needs to support only a subset of the methods. You will still be able to call the remaining methods successfully, but they will return E_NOTIMPL. You should refer to its documentation to see how an interface is implemented by any particular object.

The COM standard requires that an interface definition must not change once it has been published. You cannot, for example, add a new method to an existing interface. You must instead create a new interface. While there are no restrictions on what methods must be in that interface, a common practice is to have the next-generation interface include all the of the old interface's methods, plus any new methods.

It is not unusual for an interface to have several generations. Typically, all generations perform essentially the same overall task, but they are different in detail. Often, an object exposes every generation of interface. Doing so allows older applications to continue using the object's older interfaces, while newer applications can take advantage of the features of the newer interfaces. Typically, a family of interfaces all have the same name, plus an integer that indicates the generation. For example, if the original interface were named IMyInterface, the next two generations would be called IMyInterface2 and IMyInterface3. In the case of DirectX interfaces, successive generations are typically named for the version number of DirectX.

GUIDs

GUIDs are a key part of the COM programming model. At its most basic, a GUID is a 128-bit structure. However, GUIDs are created in such as way as to guarantee that no two GUIDs are the same. COM uses GUIDs extensively for two primary purposes:

  1. To uniquely identify a particular COM object.

    A GUID that is assigned to a COM object is called a CLSID, and you use a CLSID when you want to create an instance of the associated COM object.

  2. To uniquely identify a particular COM interface.

    The GUID that is associated with a particular COM interface is called an IID, and you use an IID when you request a particular interface from an object. An interface's IID will be the same, regardless of which object exposes the interface.

Note For convenience, documentation normally refers to objects and interfaces by a descriptive name such as IDirect3D9. In the context of the documentation, there is rarely any danger of confusion. However, strictly speaking, there is no guarantee that another object or interface does not have the same descriptive name. The only unambiguous way to refer to a particular object or interface is by its GUID.

Although GUIDs are structures, they are often expressed as an equivalent string. The general format of the string form of a GUID is 32 hexadecimal digits in the format 8-4-4-4-12. That is, {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}, where each x corresponds to a hexadecimal digit. For example, the string form of the IID for the IDirect3D9 interface is {1DD9E8DA-1C77-4D40-B0CF-98FEFDFF9512}.

Because the actual GUID is somewhat clumsy to use and easy to mistype, an equivalent name is usually provided as well. You can use this name instead of the actual structure when you call functions, such as CoCreateInstance. The customary naming convention is to prepend either IID_ or CLSID_ to the descriptive name of the interface or object, respectively. For example, the name of the IDirect3D9 interface's IID is IID_IDirect3D9.

HRESULT Values

All COM methods return a 32-bit integer called an HRESULT. With most methods, the HRESULT is essentially a structure that contains two primary pieces of information:

  1. Whether the method succeeded or failed.
  2. More detailed information about the outcome of the operation supported by the method.

Some methods return HRESULT values only from the standard set defined in Winerror.h. However, methods are free to return custom HRESULT values with more specialized information. These values are normally documented on the method's reference page.

Note The list of HRESULT values that you find on a method's reference page is often only a subset of the possible values that may be returned. The list typically covers only those values that are specific to the method and those standard values that have some method-specific meaning. You should assume that a method may return a variety of standard HRESULT values, even if they are not explicitly documented.

While HRESULT values are often used to return error information, you should not think of them as error codes. The fact that the bit that indicates success or failure is stored separately from the bits that contain the detailed information allows HRESULT values to have any number of success and failure codes. By convention, the names of success codes are prefixed by S_ and failure codes by E_. For example, the two most commonly used codes are S_OK and E_FAIL, which indicate simple success or failure, respectively.

The fact that COM methods may return a variety of success or failure codes means that you have to be careful how you test the HRESULT value. For example, consider a hypothetical method with documented return values of S_OK if successful and E_FAIL if not. However, remember that the method may also return other failure or success codes. The following code fragment illustrates the danger of using a simple test, where hr contains the HRESULT value returned by the method.

if(hr == E_FAIL)
{
    //Handle the failure
}

else
{
    //Handle the success
}

As long as the method returns only E_FAIL to indicate failure, this test works properly. However, the method might also return an error value, such as E_NOTIMPL or E_INVALIDARG. That value would be interpreted as a success, perhaps causing your application to fail.

If you need detailed information about the outcome of the method call, you need to test each relevant HRESULT value. However, you may be interested only in whether the method succeeded or failed. A robust way to test whether an HRESULT value indicates success or failure is to pass the value to the one of the following macros, defined in Winerror.h:

  • The SUCCEEDED macro returns TRUE for a success code and FALSE for a failure code.
  • The FAILED macro returns TRUE for a failure code and FALSE for a success code.

You can fix the preceding code fragment by using the FAILED macro, as shown in the following code.

if(FAILED(hr))
{
   //Handle the failure
}

else
{
   //Handle the success
}

This code fragment properly treats E_NOTIMPL and E_INVALIDARG as failures.

Although most COM methods return structured HRESULT values, a small number use the HRESULT to return a simple integer. Implicitly, these methods are always successful. If you pass an HRESULT of this sort to the SUCCEEDED macro, the macro always returns TRUE. A commonly used example is the IUnknown::Release method. This method decrements an object's reference count by one and returns the current reference count. See Managing a COM Object's Lifetime for a discussion of reference counting.

The Address of a Pointer

If you view a few COM method reference pages, you will probably run across something like the following:

HRESULT CreateDevice(..., IDirect3DDevice9 **ppReturnedDeviceInterface);

While a normal pointer is quite familiar to any C/C++ developer, COM often uses an additional level of indirection. This second level of indirection is indicated by two asterisks, **, following the type declaration, and the variable name typically has a prefix of pp. For the preceding example, the ppReturnedDeviceInterface parameter is typically referred to as the address of a pointer to an IDirect3DDevice9 interface.

Unlike a C++ object, you do not access a COM object's methods directly. Instead, you must obtain a pointer to an interface that exposes the method. To invoke the method, you use essentially the same syntax as you would to invoke a pointer to a C++ method. For example, to invoke the IMyInterface::DoSomething method, you would use the following syntax.

IMyInterface *pMyIface;
...
pMyIface->DoSomething(...);

The need for a second level of indirection comes from the fact that you do not create interface pointers directly. You must call one of a variety of methods, such as the CreateDevice method shown in the first example. To use such a method to obtain an interface pointer, you declare a variable as a pointer to the desired interface, and then pass the address of that variable to the method. In other words, you pass the address of a pointer to the method. When the method returns, the variable will point to the requested interface, and you can use that pointer to call any of the interface's methods. For more information about how to use interface pointers, see Using COM Interfaces.


Creating a COM Object

There are several ways to create COM objects. The two most commonly used in DirectX programming are:

  1. Directly, by passing the object's CLSID to the CoCreateInstance function. The function creates an instance of the object, and it returns a pointer to an interface that you specify.
  2. Indirectly, by calling a DirectX method or function that creates the object for you. The method creates the object and returns an interface on the object. When you create an object this way, you usually cannot specify which interface should be returned.

Before you create any objects, COM must be initialized by calling the CoInitialize function. If you are creating objects indirectly, the object creation method handles this task. If you need to create an object with CoCreateInstance, you must call CoInitialize explicitly. When you are finished, COM must be uninitialized by calling CoUninitialize. If you make a call to CoInitialize you must match it with a call to CoUninitialize. Typically, applications that need to explicitly initialize COM do so in their startup routine, and they uninitialize COM in their cleanup routine.

To create a new instance of a COM object with CoCreateInstance, you must have the object's CLSID. If this CLSID is publicly available, you will find it in the reference documentation or the appropriate header file. If the CLSID is not publicly available, you cannot create the object directly.

The CoCreateInstance function has five parameters. For the COM objects you will be using with DirectX, you can normally set the parameters as follows:

rclsid
Set to the CLSID of the object you want to create.
pUnkOuter
Set to NULL. This parameter is used only if you are aggregating objects. See Further Information for a discussion of aggregation.
dwClsContext
Set to CLSCTX_INPROC_SERVER. This setting indicates that the object is implemented as a DLL and runs as part of your application's process.
riid
Set to the IID of the interface that you would like to have returned. The function will create the object and return the requested interface pointer in the ppv parameter.
ppv
Set this parameter to the address of a pointer that will be set to the interface specified by riid when the function returns. This variable should be declared as a pointer to the requested interface, and the reference to the pointer in the parameter list should be cast as (LPVOID *).

Creating an object indirectly is usually much simpler: You pass the object creation method the address of an interface pointer, and the method then creates the object and returns an interface pointer. When you create an object indirectly, you typically cannot choose which interface the method will return. However, you can often specify a variety of things about how the object should be created.

For example, the following code fragment calls the IDirect3D9::CreateDevice method discussed earlier to create a device object to represent a display adapter. It returns a pointer to the object's IDirect3DDevice9 interface. The first four parameters provide a variety of information needed to create the object, and the fifth parameter receives the interface pointer. (See the reference documentation for details.)

IDirect3DDevice9 *g_pd3dDevice = NULL;
...
if( FAILED( g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,
                                 3DDEVTYPE_HAL,
                                 hWnd,
                                 D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                 &d3dpp,
                                 &g_pd3dDevice )))

  return E_FAIL;


Using COM Interfaces

When a COM object is created, the creation method returns an interface pointer. You can then use that pointer to access any of the interface's methods. The syntax is identical to that used with a pointer to a C++ method.

Requesting Additional Interfaces

In many cases, the interface pointer that you receive from the creation method may be the only one that you need. In fact, it is relatively common for an object to export only one interface other than IUnknown. However, many objects export multiple interfaces, and you may need pointers to several of them. If you need more interfaces than the one returned by the creation method, there is no need to create a new object. Instead, request another interface pointer by using the object's IUnknown::QueryInterface method.

If you create your object with CoCreateInstance, you can request an IUnknown interface pointer and then call IUnknown::QueryInterface to request every interface you need. However, this approach is inconvenient if you need only a single interface, and it doesn't work at all if you use an object creation method that does not allow you to specify which interface pointer should be returned. In practice, you usually don't need to obtain an explicit IUnknown pointer because all COM interfaces extend the IUnknown interface.

Extending an interface is similar to inheriting from a C++ class. The child interface exposes all of the parent interface's methods plus one or more of its own. In fact, you will often see "inherits from" used instead of "extends." What you need to remember is that the inheritance is internal to the object. Your application cannot inherit from or extend an object's interface. However, you can use the child interface to call any of the methods of the child or parent.

Because all interfaces are children of IUnknown you can use any of the interface pointers that you already have for the object to call QueryInterface. When you do so, you must provide the IID of the interface that you are requesting and the address of a pointer that will contain the interface pointer when the method returns.

For example, the following code fragment calls IDirectSound9::CreateSoundBuffer to create a primary buffer object. This object exposes several interfaces. The CreateSoundBuffer method returns an IDirectSoundBuffer9 interface. The subsequent code then uses the IDirectSoundBuffer9 interface to call QueryInterface to request an IDirectSound3DListener9 interface.

IDirectSoundBuffer9* pDSBPrimary = NULL;
IDirectSound3DListener9* pDSListener;
...
if(FAILED(hr = g_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL )))
  return hr;

if(FAILED(hr = pDSBPrimary->QueryInterface(IID_IDirectSound3DListener9,
                                           (LPVOID *)&pDSListener)))
  return hr;


Managing a COM Object's Lifetime

When an object is created, the system allocates the necessary memory resources. When an object is no longer needed, it should be destroyed. The system can use that memory for other purposes. With C++ objects, you can control the object's lifetime directly with the new and delete operators. COM does not enable you to create or destroy objects directly. The reason for this practice is that the same object may be used by more than one application. If one of those applications were to destroy the object, the other applications would probably fail. Instead, COM uses a system of reference counting to control an object's lifetime.

An object's reference count is the number of times one of its interfaces has been requested. Each time that an interface is requested, the reference count is incremented. An application releases an interface when that interface is no longer needed, decrementing the reference count. As long as the reference count is greater than zero, the object remains in memory. When the reference count reaches zero, the object destroys itself. You don't need to know anything about the reference count of an object. As long as you obtain and release an object's interfaces properly, the object will have the appropriate lifetime.

Properly handling reference counting is a crucial part of COM programming. Failure to do so can easily create a memory leak. One of the most common mistakes that COM programmers make is failing to release an interface. When this happens, the reference count never reaches zero, and the object remains in memory indefinitely.

Incrementing and Decrementing the Reference Count

Whenever you obtain a new interface pointer, the reference count must be incremented by a call to IUnknown::AddRef. However, your application does not usually need to call this method. If you obtain an interface pointer by calling an object creation method or by calling IUnknown::QueryInterface, the object automatically increments the reference count. However, if you create an interface pointer in some other way, such as copying an existing pointer, you must explicitly call IUnknown::AddRef. Otherwise, when you release the original interface pointer, the object may be destroyed even though you may still need to use the copy of the pointer.

You must release all interface pointers, regardless of whether you or the object incremented the reference count. When you no longer need an interface pointer, call IUnknown::Release to decrement the reference count. A common practice is to initialize all interface pointers to NULL, and then set them back to NULL when they are released. That convention allows you to test all interface pointers in your cleanup code. Those that are not NULL are still active, and they must be released before you terminate the application.

The following code fragment extends the sample discussed in Using COM Interfaces to illustrate how to handle reference counting.

IDirectSoundBuffer9* pDSBPrimary = NULL;
IDirectSound3DListener9* pDSListener = NULL;
IDirectSound3DListener9* pDSListener2 = NULL;

...

//Create the object and obtain an additional interface.
//The object increments the reference count.

if(FAILED(hr = g_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL )))
  return hr;

if(FAILED(hr=pDSBPrimary->QueryInterface(IID_IDirectSound3DListener9,
                                        (LPVOID *)&pDSListener)))
  return hr;

//Make a copy of the IDirectSound3DListener9 interface pointer.
//Call AddRef to increment the reference count and to ensure that
//the object is not destroyed prematurely.

pDSListener2 = pDSListener;
pDSListener2->AddRef();
...
//Cleanup code. Check to see if the pointers are still active.
//If they are, call Release to release the interface.

if(pDSBPrimary != NULL)
{
  pDSBPrimary->Release();
  pDSBPrimary = NULL;
}

if(pDSListener != NULL)
{
  pDSListener->Release();
  pDSListener = NULL;
}

if(pDSListener2 != NULL)
{
  pDSListener2->Release();
  pDSListener2 = NULL;
}


Using C to Access COM Objects

Although C++ is the most commonly used language for COM programming, you can also access COM objects using C. Doing so is relatively straightforward, but requires a somewhat more complex syntax:

  • All methods have an additional parameter added to the beginning of the parameter list. This parameter must be set to the interface pointer.
  • You must explicitly reference the object's vtable.

Every COM object has a vtable that contains a list of pointers to the methods that the object exposes. An interface pointer points to the appropriate location in the vtable, which in turn contains a pointer to the particular method that you are calling. The vtable is not mentioned elsewhere in this documentation, because the vtable is essentially invisible with C++. However, if you want to call COM methods with C, you must include an additional level of indirection that explicitly references the vtable.

Some components have macros defined in their header files that resolve to the correct calling convention. See Using Macros to Call DirectX COM Methods for details.


Using Macros to Call DirectX COM Methods

For many of the Microsoft DirectX Component Object Model (COM) interfaces, macros are defined for each method. The macros simplify the use of the methods in your application. You can find definitions of these macros in the same header file as the interface declaration. The macros are designed to be used by both C and C++ applications. To use the C++ macros, you must define _cplusplus. Otherwise, the C macros will be used. The macro syntax is the same for both languages, but the header files include separate sets of macro definitions that expand to the appropriate calling convention.

For example, the following code fragment from the d3d.h header file shows the definitions of the C and C++ macros for the IDirect3D9::GetAdapterIdentifier method.

...
#define IDirect3D9_GetAdapterIdentifier(p,a,b,c) (p)->lpVtbl->GetAdapterIdentifier(p,a,b,c)
...
#else
...
#define IDirect3D9_GetAdapterIdentifier(p,a,b,c) (p)->GetAdapterIdentifier(a,b,c)
...
#endif

To use one of these macros, you must first obtain a pointer to the associated interface. The first parameter of the macro must be set to that pointer. The remaining parameters map to the method's parameters. The macro's return value is the HRESULT value that is returned by the method.

The following code fragment uses a macro to call the IDirect3D9::GetAdapterIdentifier method. Note that pD3D is a pointer to an IDirect3D9 interface.

hr = IDirect3D9_GetAdapterIdentifier(pD3D,
                                     Adapter,
                                     dwFlags,
                                     pIdentifier);


DirectX COM Documentation Conventions

By convention, COM methods and interfaces are referred to in the documentation by their equivalent C++ class names. The CreateDevice method of the IDirect3D9 interface is thus referred to as IDirect3D9::CreateDevice. The primary reason for this convention is that different interfaces may export a method with the same name but with entirely different functionality and syntax. For example, many interfaces have methods named Create or CreateDevice, but the functionality and parameters that they provide and use may be quite different. However, by using the C++ class name, a specific method is uniquely identified.

The text and sample code generally uses C++ conventions for calling COM methods. See Using C to Access COM Objects, for a discussion of how to convert a C++ method call to its C equivalent.


Using ATL with DirectX COM Interfaces

To use ATL with DirectX, you must redefine the interfaces for ATL compatibility. This allows you to properly use the CComQIPtr class to obtain a pointer to an interface.

If you do not redefine the interfaces for ATL, you get the following error message:

C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\atlmfc\include\atlbase.h(4704) :
  error C2787: 'IDirectXFileData' : no GUID has been associated with this object

The following code sample shows how to define the IDirectXFileData interface.

// Explicit declaration
struct __declspec(uuid("{3D82AB44-62DA-11CF-AB39-0020AF71E433}")) IDirectXFileData;

// Macro method
#define RT_IID(iid_, name_) struct __declspec(uuid(iid_)) name_
RT_IID("{1DD9E8DA-1C77-4D40-B0CF-98FEFDFF9512}", IDirectXFileData);

After redefining the interface, you must use the Attach method to attach the interface to the interface pointer returned by ::Direct3DCreate9. If you do not, the IDirect3D9 interface will not be properly released by the smart pointer class.

The CComPtr class internally calls IUnknown::AddRef on the interface pointer when the object is created and when an interface is assigned to the CComPtr class. To avoid leaking the interface pointer, do not call IUnknown::AddRef on the interface returned from ::Direct3DCreate9.

The following code properly releases the interface without calling IUnknown::AddRef.

CComPtr<IDirect3D9> d3d;
d3d.Attach(::Direct3DCreate9(D3D_SDK_VERSION));

Use the previous code. Do not use the following code, which calls IUnknown::AddRef followed by IUnknown::Release and does not release the reference added by ::Direct3DCreate9.

CComPtr<IDirect3D9> d3d = ::Direct3DCreate9(D3D_SDK_VERSION);

Note that this is the only place in Direct3D where you will have to use the Attach method in this manner.

For more information about the CComPTR and CComQIPtr classes, see their definitions in the Atlbase.h header file.


DirectX SDK Tools

The DirectX SDK contains several tools to help you develop DirectX applications.

  • DirectX Content Tools help you create and modify content.
  • DirectX Performance Tools help you tune performance.
  • DirectX System Tools help you diagnose system hardware issues.

Related Topics

Graphics tools for compiling and debugging shaders and effects.


DirectX Content Tools

This section describes tools to help you create and maintain 2D and 3D content for your applications. This includes:

  • DirectX Extensions for DCC applications - Digital context creation plug-ins.

Texture tools for Windows Explorer:

  • Texture Viewer (Windows Explorer Extension)
  • Texture Converter (Windows Explorer Extension)

Other menu-based and command-line tools for working with textures:

  • DirectX Texture Editor (Dxtex.exe)
  • Texture Conversion Tool (Texconv.exe)

Other tools:

  • DirectX Viewer (Dxviewer.exe)
  • DirectX Ops (dxops.exe)

DirectX Viewer replaces some of the functionality previously found in effectedit and mview. EffectEdit and MView are no longer shipping with the DirectX SDK.


DirectX Extensions for DCC applications

This section describes some plug-ins for digital-content-creation applications, including:

  • DirectX Extensions for Autodesk 3ds Max
  • DirectX Extensions for Alias Maya
  • DirectX Extensions for Adobe Photoshop

See Also

DirectX Frequently Asked Questions


DirectX Extensions for Autodesk 3ds Max

This plug-in tool allows you to export scenes from 3ds Max (version 7) to the DirectX X-File (.x) file format. The exporter supports conversions of a variety of vertex, mesh, frame-hierarchy, and material data.

Compatibility Chart

Direct3D 9 | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | No | No | Yes | Yes

This topic covers the following subjects:

  • Installing the Exporter
  • Using the Exporter
  • Supported Vertex Data
  • Supported Material Data
  • Batch Exporting with the DirectX X-File Exporter

Installing the Exporter

If Autodesk 3ds Max is already installed, the Microsoft DirectX SDK installation program will configure 3ds Max to automatically find and load the DirectX Extensions for 3ds Max plug-in. If one installs 3ds Max after the DirectX SDK has already been installed then one needs to edit the plugin.ini file located in the 3ds Max installation directory and add the following line to the [Directories] section. Here is an example:

[Directories]
DirectX={SDK ROOT}\Utilities\Bin\Plugins\Max\Max7

Once the plugin.ini is configured properly (either by the DirectX SDK installation program or manually), the plugin automatically loads when 3ds Max starts.

Using the Exporter

Exporting a scene from 3ds Max follows the traditional export workflow. Given a scene that has been loaded or constructed, here is an example of how to export the data:

  1. Select the File->Export menu item.
  2. Enter the filename (such as MyFile.x) in the File name: text box of the dialog that pops up.
  3. Check the Save as Type text box to see that it has DirectX X-File (*.x) in it.
  4. Select Save.

This set of steps saves the entire scene to an x file, including geometry, frame-hierarchy, materials etc. If you would like to save part of a scene instead, select File->Export Selected... in step 1.

Supported Vertex Data

While exporting, the exporter attempts to automatically determine the appropriate vertex data to extract from 3ds Max. The following table explains how vertex data from 3ds Max is mapped to Direct3D vertex element semantics.

3ds Max Data | Direct3D Vertex Data Type | Direct3D Vertex Element Usage
Vertex | float3 | POSITION
Normal | float3 | NORMAL
Binormal | float3 | BINORMAL
Tangent | float3 | TANGENT
Color Vertex | float4 (r, g, b elements) | COLOR0
Alpha Vertex | float4 (a element) | COLOR0
Illumination Vertex | float4 (Scalar value is replicated to r, g, b channels, alpha channel is set to 1.0) | COLOR1
Texture Vertex | float2 | TEXCOORD0

Supported Material Data

The exporter extracts material data from a few classes of 3ds Max materials. In the case of the DirectX Shader Material, the exporter extracts the values for the parameters that appear in the rollout for the Effect in the Material Editor and creates a D3DXDEFAULTEFFECT definition from the parameter values. In the case of a Standard Material, the exporter extracts the diffuse (color and texture), specular color, self-illumination color, opacity, and shininess from 3ds Max and creates a D3DXMATERIAL definition from the data. In the case of a Multi/Sub-Object Material, the exporter extracts one level of sub-materials from the Multi/Sub-Object material and exports the data for them. Multi/Sub-Object materials with more than one level of depth are not supported.

Batch Exporting with the DirectX X-File Exporter

The exporter fully supports unassisted exports via 3ds Max's MAXScript language. The following example shows how to load a file and export it to a .X file using MAXScript.

fn makeXFile maxFile =
(
    baseName = getFilenameFile maxFile
    xPath = getFilenamePath maxFile
    xFile = xPath + baseName + ".x"

    makeDir xPath
    loadMaxFile maxFile quiet:true
    exportFile xFile #noPrompt selectedOnly:false

    return xFile
)

One could then use the function makeXFile to export data as follows:

// creates the file c:\art\maxfiles\dude.x
makeXFile "c:\art\maxfiles\dude.max"


DirectX Extensions for Alias Maya

The Maya plug-in enables game developers to create, edit, and preview high-level shader language (HLSL) shaders in real-time within Maya. The plug-in also supports exporting a shader into a DirectX .x file.

The plug-in works with Alias Maya version 6.0 and 6.5.

Compatibility Chart

Direct3D 9 | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | No | No | Yes | Yes
  • Installing the Plug-in
  • Loading the Plug-in
  • Creating a DirectX material
  • Exporting to a .x File
  • Preview Effect Parameters in Real-Time

Installing the Plug-in

The plug-in is installed automatically by the DirectX SDK setup program. There is no need to move or copy files on your machine.

Loading the Plug-in

The plug-in is loaded into Maya via the plug-in manager window. This menu is in the top level Window menu, under the submenu Settings/Preferences. Choose the Plug-in Manager option.

In the plug-in manager, scroll down near the bottom to find the D3D exporter plug-in and choose the loaded option to load the plug-in. If you select the auto-load option, the plug-in will be loaded every time Maya is started.

Hint: The D3D Exporter plug-in is named for the version of Maya that you are running: for instance, D3DMaya6ExportX.mll or D3DMaya65ExportX.mll.

Creating a DirectX material

First, to associate your geometry with a effect (.fx) file, create a DirectX material and associate it with the geometry in Maya. Here is one way to create a DirectX material:

  1. Launch Maya
  2. Import a scene from the File/Import... menu item.
  3. From the Window menu, select Rendering Editors and Hypershade. Verify that the Materials tab is active.
  4. In the Create Bar, make sure the Create tab is active, and click on the DirectX Shader surface which will create an empty material object.

Exporting to a .x File

You can export geometry, animation, and skinning data to a .x file. First, set up the exporter options from the DirectX menu:

The options are a series of Booleans that determine what type of data is exported. These include:

  • Adjacencies - Set to True to export mesh adjacency data, or False if you don't want adjacency data exported.
  • Animation - Set to True to export animation data, or False if you don't want animation data exported.
  • Make Relative Paths - Set to True to make all file paths relative, or False otherwise.
  • Materials - Set to True to export materials, or False otherwise.
  • Meshes - Set to True to export meshes, or False otherwise.
  • New Effect Path - Set to True to change the path to the .fx files to the path you enter in the text box, or False otherwise.
  • New Texture Path - Set to True to change the path to the texture files to the path you enter in the text box, or False otherwise.
  • pop-up on Export - Set to True to force a pop-up to open during file export, or False otherwise.
  • Replace Effect Path - Set to True to replace the .fx file paths with the path you enter in the text box, or False otherwise.
  • Replace Texture Path - Set to True to replace all texture file paths with the path you enter in the text box, or False otherwise.

Once the export options are set, export data by choosing the Export All from the DirectX menu:

This opens the scene window to allow you to save a .x file. Enter the name of the .x file in the filename text box and click the save button.

Preview Effect Parameters in Real-Time

Once there is a DirectX shader associated with the geometry, you can view the shader on the geometry in real-time.

  1. Open the hypershade window and make the DirectX material visible. (The one we created was called DirectXShader1).

  2. Launch the Attribute Editor for the shader object by right-clicking on the DirectXShader1 material and selecting the DirectXShader1... menu item. Here's what the Attribute Editor looks like when it opens up:

  3. Associate an effect file (.fx) with the material by clicking on the browse button next to the DirectX Effect File text box. You might need to minimize the Hypershader window so you can work in the Attribute Editor window. We chose the default.fx file that ships in the SDK Media folder.

    The effect parameters are loaded into the Attribute Editor.
  4. Launch the Direct3D preview pipeline window from the DirectX/Viewers.../Floating menu item.

    This window displays the scene with the HLSL effect just as it will appear when Direct3D renders it.

    Note When nodes not being monitored by the DirectX plug-in are changed, they may effect monitored nodes but because the original change was in an unmonitored node, the rendered output will not update. In this case, select the Rebuild All option from the DirectX menu to update the rendered output and see your changes.


DirectX Extensions for Adobe Photoshop

The Photoshop texture file converter is a file format plug-in to Adobe Photoshop to open or save texture files. The following are the available input and output formats: .dds, .hdr, .pfm, and .ppm. See D3DXIMAGE_FILEFORMAT for more information on these texture file formats.

Compatibility Chart

Direct3D 9 | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | No | No | Yes | Yes

Requirements

Minimum Operating System Microsoft Windows 2000
Required Applications
  • Adobe Photoshop version 7.0, 8.0, or CS.

Installation

The texture converter plug-in is automatically installed when you install the Microsoft DirectX SDK. The installer checks for valid versions of Photoshop and copies the D3DXTextureFormat.8bi file to the application plug-in folder.

User's Guide

The texture plug-in allows you to open or save files in Photoshop in any of the nine texture file formats listed above.

Opening a Texture File

Follow these steps to open a texture file.

  1. In the Photoshop File menu, select Open... or Open As....
  2. In the Files of type list at the bottom of the dialog box, select the following format:
    D3DXTextureFormat(*.DDS;*.HDR;*.PFM;*.PPM)
  3. Select the file you want to open, and either double-click the file icon or click the Open button. The texture file is now available to edit in Photoshop.

If more than one mip level is available in the mipmap, the following dialog box will appear.

Figure 1. Mip level dialog box

The Open entire file option is the default selection. If this option is selected, all mip levels are joined together in a single Photoshop 2D image display.

Figure 2. Display of all mip levels

You can then edit any or all of the mip levels in Photoshop. Alternately, you can select Open a particular mip level if you want to edit only one mip level in Photoshop, for example the 128x32 pixel level shown here.

Figure 3. Display of the 128x32 pixel mip level

If the file to be opened is a cube or volume texture, a similar dialog box will appear that lets you select a view of all cube faces or volume slices simultaneously, or one at a time. Mip levels of a cube or volume texture are not available for display with this plug-in.

Note It is not recommended that you open a texture file by right-clicking it and selecting Open With and then Adobe Photoshop.

Saving a Simple Texture File

Complete the following steps to save a texture file to any supported format except .dds.

  1. In the Photoshop File menu, select Save As....
  2. In the Files of type list at the bottom of the dialog box, select the following format:
    D3DXTextureFormat(*.DDS;*.HDR;*.PFM;*.PPM)
  3. Select the directory location where you want to save the file.
  4. Type in the name of the file to save, along with the three-letter file extension (any supported format listed above except .dds). You may overwrite your original file.
  5. Click the Save button.
  6. The following dialog box will appear.

    Figure 4. Simple texture file save dialog box

    Select the pixel format from the list of available formats at the bottom of the dialog box. No other save options will be available in this dialog.

  7. Click OK to save the file.

Saving a DDS File

Follow these steps to save a texture file to .dds format.

  1. In the Photoshop File menu, select Save As....
  2. In the Files of type list at the bottom of the dialog box, select the following format:
    D3DXTextureFormat(*.DDS;*.HDR;*.PFM;*.PPM)
  3. Select the directory location where you want to save the file.
  4. Type in the name of the file to save, along with the .dds file extension.
  5. Click the Save button. The following dialog box will appear.

    Figure 5. DDS texture file save dialog box

  6. Make selections for the type of texture to save.
    • If you select the Cube map or Volume texture, then you can also click the checkbox to duplicate the image on all cube faces or volume slices.
    • If you select a Volume texture, then in the Depth box type in the number of volume slices you want the volume texture to contain.
    • If you select Cube map but your texture file format is not square, a warning message will appear noting that the image will be cropped to be a square format.
  7. From the list of available mip levels, select the number of mip levels you want the new texture file to contain.
  8. From the list of available formats, select the pixel format in which to save the file.
  9. Click OK to save the file.

Note To avoid generating invalid results, the plug-in does not allow saving a full volume as a cube, or a full cube as a volume.

Resizing and Saving a Texture File

If you change the image size of an individual mip level in Photoshop and then try to save the file using Save from the Photoshop File menu, an error message will appear and the file will not be saved. You should instead try one of the following procedures:

  • Open the file with the Open a particular mip level option and then change the image size in Photoshop. Use Save As... from the Photoshop File menu, and the new saved file will be properly resized.
  • Open the file with the Open entire file option and then change the image size in Photoshop. If you use Save As... to save to the original file type, all mip levels will be resized proportionally in your new saved file.
  • Open the file with the Open entire file option and then change the image size in Photoshop. If you use Save As... to save to a different file type, in your new saved file the entire image displayed in Photoshop will become the new top-level texture, front cube face, or top volume slice.


DirectX Viewer (Dxviewer.exe)

This tool loads and renders D3DX effects (*.fx) and 3D mesh objects from DirectX X (.x) files that are compliant with DirectX standard annotations and semantics (DXSAS). It can be used to verify changes made to .x files and to effects (.fx) files, and to see how changes to effects or meshes look when loaded.

If an effects (.fx) file or an X (.x) file changes while it is loaded in the viewer, the viewer automatically reloads the file. This is especially useful for quickly checking the validity of any effects files as you are modifying them.

For details on DXSAS, see DirectX Standard Annotations and Semantics Reference.

Compatibility Chart

Direct3D 9 | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | Yes | Yes | Yes | Yes

Launching DirectX Viewer

You can start DirectX Viewer at the command line by running dxviewer or from the Start menu.

To launch DirectX Viewer from the Start menu

  • Click Start, point to All Programs, then to Microsoft DirectX SDK, then to DirectX Utilities, and then click DirectX Viewer.

Figure 1. DirectX Viewer's initial display

List of Keyboard Shortcuts

DirectX Viewer provides several keyboard shortcuts.

Pressing the HOME key resets the camera to the default position. Other keys place the camera at the edge of the model's bounding sphere along the locations described in the following table.

Keyboard Shortcut | Location on the Model's Bounding Sphere
X | Negative X axis
Y | Negative Y axis
Z | Negative Z axis
Shift+X | Positive X axis
Shift+Y | Positive Y axis
Shift+Z | Positive Z axis

Open Button

To load X (.x) files and effects (.fx) files, click Open. If an effects file is loaded, it is rendered onto default geometry, usually a sphere. The X files and effects files that ship in the SDK are located in DirectX SDK root\Samples\Media.

Load a file by clicking on the Open button.

Figure 2. Open file dialog box

Select a file and click Open. A 3D object will load with the default effect.

Note You may also load .x files or .fx files by dragging and dropping them into the View window.

File Merging

When opening a file with the CTRL key held down, you can change the model's geometry by selecting an .x file, or change the model's material by selecting an .fx file.

Viewing Geometry

After loading an .x file (or .fx file), you can use the left mouse button to rotate geometry and the right mouse button to rotate the camera; use the mouse wheel to zoom the camera in or out. The buttons in the DirectX Viewer window are covered in the following sections.

View Button

Push the view button to launch the view button dialog to change how the geometry will be viewed.

Figure 3. View dialog box in DirectX Viewer

The options and settings in the View dialog box are described in the following table.

View Dialog Options | Description
Environment | Load an environment map from a DDS texture, provided that the currently loaded effect handles environment maps.
Fill Mode | Solid, Wireframe, or to use the fill mode specified in the effect, Auto.
Statistics | Displays video card type, frames per second, display format, and other info.
Manual Refresh | Refresh the viewer only when the Refresh Button is clicked.
Adjacency | Draw adjacency data as dark purple lines.
Binormal | Draw binormals (or bitangents) as green lines.
Bounds | Draw bounding boxes around the geometry with white lines.
Creases | Draw creases as orange lines.
Edges | Draw triangle edges as purple lines.
Normals | Draw vertex normals as red lines.
Points | Draw points as yellow squares.
Tangents | Draw tangents as blue lines.
Close | Close the menu.

Effect Button

Push the Effect Options button to launch the Effect Options dialog to experiment with effect parameters.

Figure 4. Effect Options dialog in DirectX Viewer

The options and settings available in Effect Options are described in the following table.

Effect Button Options | Description
Technique | Select a render technique.
Pass Mode Effect pass to render (see Pass Index also). There are three choices:
All Passes
Renders all passes for a technique
Selected Pass
Renders only the selected name or referenced pass by index for a technique
Up to selected pass
Renders all passes up to the selected named or referenced pass by index for a technique.
Pass Index | Effect pass index. Displays the named passes and indexes for the selected techniques or all available if the first valid technique is chosen for technique.
Defines | Specify DXSAS data binding defines for the effects.
Includes | Set up include paths that are needed when compiling shaders.
Debug Pixel Shaders | Force pixel shading to run on the CPU and enable debug info.
Debug Vertex Shaders | Force any vertex shaders to use vertex processing, so they are run on the CPU and enable debug info.
Optimize Shaders | Enables or disable shader optimization for the shader compiler.
Validate Shaders | Enable or disable HLSL shader validation.
Allow Preshaders | Enable or disable preshaders.
Allow Partial Precision | Enable or disable partial precision.
Prefer Dynamic Flow / Avoid Dynamic Flow | Enable or disable dynamic flow control.

Refresh Button

The Refresh button is unavailable unless you select manual refresh. You can change the refresh by clicking View and selecting or clearing Manual Refresh. Once manual refresh is selected, click View to render the geometry.

Direct3D10 Mode Button

This button switches the viewer between Direct3D 9 mode and Direct3D 10 mode. The viewer starts in Direct3D 9 mode by default. The Direct3D 10 mode only works if the viewer is running on Windows Vista. In Direct3D 10 mode, only Effects with Technique10 will load.

Help Button

The Help button opens up the SDK documentation.

Additional Features

There are a few additional features:

  • File Change Monitoring
  • Setting Start Up Conditions

File Change Monitoring

DirectX Viewer automatically detects changes in files that are being viewed, and it reloads these files to display the results. This allows you to edit an .x file or .fx file while it is loaded in DirectX Viewer, and automatically view the results of the edit.

As an example, you can see DirectX Viewer automatically load changed made to Glow.fx, by executing the following steps:

  1. Launch DirectX Viewer and open Glow.fx, located in DirectX SDK root\Samples\Media\SharedFx.

  2. Open Glow.fx in Notepad (or some other text editor), and change GlowColor's value from the following (on line 17):

    float4(0.5f, 0.2f, 0.2f, 1.0f)

    to the following:

    float4(0.0f, 0.0f, 1.0f, 1.0f)
  3. Save Glow.fx.
  4. DirectX Viewer automatically detects the changes saved to the file and reloads the file to display the changes. The following figure shows the original and edited versions of Glow.fx.

Figure 5. Before and after views of the example image

Setting Start Up Conditions

Configure the tool using the following command line syntax.

Syntax

DirectX Viewer supports the following command-line syntax:

dxviewer
                [ -shape { cube | sphere | cylinder } ]
                [ -Zip ]
                [ -Ziv ]
                [ -Zi ]
                [ -D string ]
                [ -I string ]
                [ file names ]

The following table describes these command-line options.

Switch Options | Description
-shape { cube | sphere | cylinder } | Default geometry. If the user specifies the default shape (-shape) and an .x file (which also has geometry), the default shape will take priority and the .x file will not be loaded.
-Zip | Debug pixel shaders.
-Ziv | Debug vertex shaders.
-Zi | Debug pixel and vertex shaders.
-D string | List of defines, delimited by semicolons.
-I string | List of included paths, delimited by semicolons.
file names Optional file names, either .x or .fx files, with the following constraints:
  • If two file names are specified, one must be an .x file and the other must be a DXSAS-compliant .fx file.
  • If one file name is specified, it must be either an .x file or an .fx file.
  • If a specified file name does not contain an .x or .fx extension, the file is ignored.

See Also

DirectX Content Tools, DirectX Standard Annotations and Semantics Reference


DirectX Ops (dxops.exe)

This command line tool can be used to modify .x files or textures by specifying a script file and/or set of command line arguments. Each script is comprised of a series of script commands. The given script must specify at least one load command and one save command.

Compatibility Chart

Direct3D 9 | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | No | No | Yes | Yes

Path

Executable: (SDK root)\Utilities\Bin\x86 or x64

Syntax

dxops [-f scriptfile] [-s "expression"] [-log filename] [-?] [-m]

Where:

Options | Description
-f scriptfile | A script file containing a series of script commands.
-s "script commands" | A string that contains a series of script commands.
-? | Shows help message.
-log filename | Name and location of the log file. If the file already exists, it will be overwritten.
-m path | Specifies a search path. When loading files, DXOps will search the relative path and also the path(s) specified with this command. Use -m multiple times to specify multiple paths.

As a minimum, you must use at least the -f or -s switch option. If -f and -s are used together, they will be executed in the order they are specified. See example below.

Examples

Here are some sample usages of DXOps. For information on the script commands used in these examples, refer to DirectX Ops Script Commands.

  • Generating Vertex Data
  • Printing Mesh Data To A File
  • Using .NET Regular Expressions
  • Using the Shade Script Command

Generating Vertex Data

Assume you have a file called tiger.x in the current directory, and you want to generate (or update) its vertex data (normals, tangents, and adjacency). You could do that from the command line like this:

dxops.exe -s "load tiger.x;" -f  "script1.txt" -s "save new_tiger.x"

-s "load tiger.x;" loads the tiger mesh for modification.

-f "script1.txt" executes the script that will generate the normals, tangent frames, and adjacency data for the mesh. The AddVData commands add the fields to the tiger mesh's vertex declaraction (normals, tangents, and adjacency) and the Gen* commands fill those data fields.

Where script1.txt is:

AddVData type:FLOAT3 usage:NORMAL usageIdx:0;
GenNormals;
AddVData type:FLOAT3 usage:TANGENT usageIdx:0;
AddVData type:FLOAT3 usage:BINORMAL usageIdx:0;
GenTangentframes;
GenAdjacency;

-s "save new_tiger.x;" saves the newly modified tiger mesh to a file called new_tiger.x.

Printing Mesh Data To A File

In this example we will be loading meshes from a folder and printing their data to a log file. Assume that you have .x files stored a folder called C:\myGameData\. From the command line:

dxops -m "C:\myGameData\" -log "modelData.txt" -s "load 'myModels\*.x'; meshes;"

The load command will first search myModels\ (relative to the current working directory) for *.x files, and if it does not find any then it will look in C:\myGameData\ for .x files. The -m option is used as a secondary directory for DXOps to search if it does not find the specified file. The -log option tells DXOps to write the data out to modelData.txt.

Using .NET Regular Expressions

Almost all of the DXOps Script Commands have a name parameter that can take a string with .NET Framework Regular Expressions. In this example you will learn how to use these regular expressions to do a simple script on many different files with similar names.

Say you are developing a racing game and have a series of x files, one for each car, and each file follows the naming convention car_<name of car>.x. You wish to generate normals for each car. Using regular expressions you can run a script like this:

load car_1.x;
load car_2.x;
gennormals car_.*;

This will generate vertex normals for car_1 and car_2. The load command can optionally use DOS wildcards when specifying the file(s) to load, and gennormals uses .NET Framework Regular Expressions.

Using the Shade Script Command

The shade script command can be used as a powerful tool for processing textures. It works very similarly to pixel and vertex shaders in that it will execute an algorithm defined in the High-Level Shader Language (HLSL).

Here is an example of how to use the shade script command to add a color blend effect to a cube map. It uses the LobbyCube.dds texture found in (SDK Root)\Samples\Media\Lobby.

From the command line:

dxops -f "shadeScript.txt"

Where shadeScript.txt is:

load 'LobbyCube.dds';
shade 'texShader.psh';
save 'LobbyShaded.dds';

Where texShader.psh is:

textureCUBE TargetTex;
samplerCUBE Target = sampler_state  //note that naming the sampler 'Target' will cause
{                                   //the shade command to initialize the sampler with
    Texture = (TargetTex);          //the destination texture.
    MinFilter = Linear;
    MagFilter = Linear;
};

float4 main(float3 UVW : TEXCOORD0, float3 PixelSize : TEXCOORD1) : COLOR
{
    float3 normUVW = (1.0f+UVW)*0.5;
    float4 color = float4(0,0,0,1);

    if(PixelSize.x == 0)
    {
        if(UVW.x > 0) //+
        {
            color.g = normUVW.y;//up
            color.r = 1.0f-normUVW.z;//right
        }
        else //-
        {
            color.g = normUVW.y;//up
            color.r = normUVW.z;//right
        }
    }

    if(PixelSize.y == 0)
    {

        if(UVW.y > 0) //+
        {
            color.g = 1.0f-normUVW.z;//up
            color.r = normUVW.x;//right
        }
        else //-
        {
            color.g = normUVW.z;//up
            color.r = normUVW.x;//right
        }
    }

    if(PixelSize.z == 0)
    {
        if(UVW.z > 0) //+
        {
            color.g = normUVW.y;//up
            color.r = normUVW.x;//right
        }
        else //-
        {
            color.g = normUVW.y;//up
            color.r = 1.0f-normUVW.x;//right
        }
    }
    return texCUBE(Target, UVW) + color;
}

After running this shader, the positive X of the cube map should look like this:

Note DDS cube map textures are viewable using the DirectX Texture Editor (Dxtex.exe)

See Also

DirectX Content Tools, DirectX Ops Script Commands


DirectX Ops Script Commands

DirectX Ops (dxops.exe) can accept an expression string, which contains a series of script commands, files, and optional arguments. Each expression is built from one or more of the script commands. The script commands can be entered into the tool as command-line arguments or from a script file.

Each script command has zero or more arguments passed in as name-value pairs, with the name and the value separated by a colon. All commands are either for I/O or perform some operation on the loaded meshes. Almost every script command has corresponding API(s) in the DirectX SDK that do almost the exact same thing.

The DirectX Ops script commands are shown in the following table.

I/O Script Commands | Description
load | Load a model or texture file
save | Save model or texture to file
unload | Remove textures or models from DXOps
Mesh Script Commands | Description
addvdata | Add vertex elements to a mesh vertex stream
clean | Clean mesh
clonevdata | Add a new vertex element with the data copied from an existing element
delvdata | Deletes vertex elements to a mesh vertex stream
flatten | Removes hierarchy from mesh
genadjacency | Generates adjacency data for mesh
gennormals | Generates normals for mesh
gentangentframes | Generates tangent frames for mesh
meshes | Print information about loaded meshes
optimize | Optimize meshes
reset | Resets DXOps
stripify | Convert a mesh into triangle strips
uvatlas | Creates UVAtlas for mesh
validate | Validate mesh
Texture Script Commands | Description
genmipmaps | Generates mipmaps for texture(s)
newtex2d | Creates a new texture
newtex3d | Creates a new volume texture
newtexcube | Creates a new cube texture
reformat | Changes texture format
resize | Resizes the texture
shade | Applies a shader to a texture
slice2d | Creates a new 2D texture from an existing texture surface
splice2d | Inserts a surface into an existing texture
textures | Print information about loaded textures

addvdata

Adds vertex elements to the vertex streams associated with the meshes.

Syntax

appvdata src:string type:string usage:string usageIdx:integer;
Parameter | Description
src:string | Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", which specifies all currently loaded objects.
type:string | The data type. Use the values in D3DDECLTYPE without the D3DDECLTYPE_ prefix; for example, type:FLOAT3. There is no default value. This argument is required and can be unnamed — that is, passed in as FLOAT3 instead of type:'FLOAT3').
usage:string | The name of the element. Use the values in D3DDECLUSAGE without the D3DDECLUSAGE_ prefix; for example, usage:TANGENT. The default value is TEXCOORD.
usageIdx:integer; | Integer value used for the usage index of the new vertex declaration entry. The default value is the first valid index for the specified usage.

Example

addvdata type:FLOAT3 usage:TANGENT usageIdx:0;

Remarks

The new element is appended to the end of the vertex declaration and to the end of each vertex in the vertex buffer. Note that this command will not initialize any new data added to each vertex. For example, if adding normals a call to gennormals is needed to generate valid normal values for each vertex after they have been added to the declaration.

clean

Description:

Clean the mesh (or meshes).

Syntax:

clean src:string;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.

Example:

clean src:tiger;

Remarks:

Clean calls validation internally; if validation fails, the mesh cannot be cleaned.

Cleans the following issues with the mesh:

  • Backfacing - Merge triangles that share the same vertex indices but have face normals pointing in opposite directions (back-facing triangles). Unless the triangles are not split by adding a replicated vertex, mesh adjacency data from the two triangles may conflict.
  • Bowties - If a vertex is the apex of two triangle fans (a bowtie) and mesh operations will affect one of the fans, then split the shared vertex into two new vertices. Bowties can cause problems for operations such as mesh simplification that remove vertices, because removing one vertex affects two distinct sets of triangles.

This script command uses D3DXCleanMesh.

clonevdata

Description:

Add a new vertex element to the vertex streams associated with the meshes, with the data copied from an existing element.

Syntax:

clonevdata usage:string usageIdx:int newUsage:string;

Where:

  • usage:string - Which vertex element to copy the vertex data from. If a mesh does not contain vertex data of the given usage, the operation is ignored for that mesh. This argument is required and can be unnamed (i.e. passed in as 'TANGENT' instead of usage:'TANGENT').
  • usageIdx:int - Integer to further identify which vertex element to copy vertex data from. If no usageIdx is specified, this command will match the first valid element that matches the specified usage.
  • newUsage:string - The name of the new vertex element. Use the values in D3DDECLUSAGE without the D3DDECLUSAGE_ prefix (for example: usage:TANGENT). The default value is TEXCOORD.

Example:

clonevdata usage:TANGENT usageIdx:0 newUsage:TEXCOORD newUsageIdx:1;

Remarks:

The new element is appended to the end of the vertex as well as the vertex declaration.

delvdata

Description:

Removes vertex elements from the vertex streams associated with the meshes.

Syntax:

delvdata src:string usage:string usageIdx:int;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.
  • usage:string - The name of the element that is being deleted. The element names are defined in D3DDECLUSAGE (without the D3DDECLUSAGE_ prefix). There is no default value. If the specified parameter is not contained in a given mesh, the operation will not be performed on that mesh. This argument is required and can be unnamed (i.e. passed in as 'TANGENT' instead of usage:'TANGENT').
  • usageIdx:int - An integer to further identify which vertex element to remove. If no usageIdx is specified, this command will match the first valid element that matches the specified usage.

Example:

delvdata usage:TANGENT usageIdx:1;

Remarks:

This will remove the specified element from the declaration as well as from the vertices themselves.

flatten

Description:

Converts all of the meshes in a model into a single non-hierarchical mesh.

Syntax:

flatten dst:string src:string;

Where:

  • dst:string - The name of the resulting flattened model. This argument is required and can be unnamed (i.e. passed in as 'nonHierarchicalModel' instead of dst:'nonHierarchicalModel').
  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.

Example:

flatten dst:christmasTreeOneMesh src:christmasTreeWithSeparateOrnaments;

Remarks:

This will also remove any skin or animation information from the mesh.

This script command uses D3DXConcatenateMeshes.

genadjacency

Description:

Generates adjacency data for meshes, replacing existing data if it exists.

Syntax:

genadjacency src:string type:[topological|geometric] epsilon:float;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.
  • type:[topological|geometric] - Specifies how the adjacency should be created. Either topological (default) or geometric.
  • epsilon:float - Epsilon value. Defaults to 10e-6f.

Example:

genadjacency type:topological;

Remarks:

This script command uses ID3DXBaseMesh::ConvertPointRepsToAdjacency for the topological method, and ID3DXBaseMesh::GenerateAdjacency for the geometric method.

genmipmaps

Description:

Generates mipmaps for the specified textures.

Syntax:

genmipmaps src:string start:int dither:int filter:string;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.
  • start:int - The zero-based index of the mipmap to use as the source of the generated mipmaps. Default is 0.
  • dither:int - Enables or disables dithering during mipmap generation. 0 for false, 1 for true. Default is 1.
  • filter:string - The mipmap filter to use when generating the mipmaps. Either None, Point, Linear, Triangle, or Box. Box is the default.

Example:

genmipmaps src:LobbyCube start:0 filter:Linear;

Remarks:

This script command uses D3DXFilterTexture.

gennormals

Description:

Computes vertex normals for every mesh.

Syntax:

gennormals src:string;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.

Example:

gennormals src:tiger;

Remarks:

If no normals are stored in the mesh before this command is called, then a call to the addvdata command must be made first, which will add normal data to the vertex declaration and assign empty values for the normals. Calling this command after adding normals to the vertex declaration will turn the normals into valid values.

This script command uses D3DXComputeNormals.

gentangentframes

Description:

Computes tangent frames for every mesh.

Syntax:

gentangentframes src:string texIdx:int ortho:string normalizePartials:[0|1] weight:string wrap:string threashPE:float threashSP:float threashNE:float;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.
  • texIdx:int - Specifies the set of texture coordinates to use for calculating the tangents. 0 specifies the first texture coordinate set, 1 specifies the second texture coordinate set, and so on. The default value is 0.
  • ortho:string - Possible values: None, U, V, UV, where None is default. Specifying None generates does not orthonormalize the tangent frame. Specifying U orthonormalizes the tangentframe based on the final computation of the non-orthonormalized tangent vector. Specifying V orthonormalizes the tangentframe based on the final computation of the non-orthonormalized binormal vector. Specifying UV orthonormalizes the tangentframe to the nearest matrix both the non-orthonormalized tangent and binormal vectors.
  • normalizePartials:[0|1] - Possible values: 0 or 1, 1 being default. If 0 is specified, it will not normalize partial derivatives with respect to texture coordinates. If not normalized, the scale of the partial derivatives is proportional to the scale of the 3D model divided by the scale of the triangle in (u, v) space. This scale value provides a measure of how much the texture is stretched in a given direction. The resulting vector length is a weighted sum of the lengths of the partial derivatives.
  • weight:string - Possible Values: Area, Equal, Default, where Default is default. Specifying Equal computes a unit-length normal vector for each triangle of the input mesh. Specifying Area weights the direction of the computed per-vertex normal or partial derivative vector according to the areas of triangles attached to that vertex. Specifying Default will give weight by angle, which gives weight based on how much angle the triangle covers for the vertex. Specifying Default tends to give results that make more sense.
  • wrap:string - Possible Values: None, U, V, UV, where None is default. For details, see Texture Wrapping (Direct3D 9).
  • threshPE:float - Defaults to 0.8f. Specifies the maximum cosine of the angle at which two partial derivatives are deemed to be incompatible with each other. If the dot product of the direction of the two partial derivatives in adjacent triangles is less than or equal to this threshold, then the vertices shared between these triangles will be split.
  • threshSP:float - Defaults to 0.5f. Specifies the maximum magnitude of a partial derivative at which a vertex will be deemed singular. As multiple triangles are incident on a point that has nearby tangent frames, but altogether cancel each other out (such as at the top of a sphere), the magnitude of the partial derivative will decrease. If the magnitude is less than or equal to this threshold, then the vertex will be split for every triangle that contains it.
  • threshNE:float - Defaults to 0.8f. Similar to threshPE, this specifies the maximum cosine of the angle between two normals that is a threshold beyond which vertices shared between triangles will be split. If the dot product of the two normals is less than the threshold, the shared vertices will be split, forming a hard edge between neighboring triangles. If the dot product is more than the threshold, neighboring triangles will have their normals interpolated.

Example:

gentangentframes texIdx:1 ortho:U weight:Area threshNE:0.5f;

Remarks:

This script command uses D3DXComputeTangentFrameEx.

load

Description:

Load a mesh or texture file.

Syntax:

load fileName:string srgb:int;

Where:

  • fileName:string - Name of a model or texture file. Use the .x extension for model files. Supported texture formats: BMP, DDS, DIB, HDR, JPG, PFM, PNG, PPM, and TGA. This parameter supports wildcards, so *.jpg will load all jpg files in the current working directory, as well as any paths specified with the -m option. This argument is required and can be unnamed (i.e. passed in as 'tiger.x' instead of fileName:'tiger.x').
  • srgb:int - Whether or not to treat the image as sRGB. 1 for true, 0 for false. 0 is default.

Example:

load fileName:tiger.x;

Remarks:

If the model file has a hierarchy, the hierarchy will be maintained when loading; if filename contains wildcards, all files matching the file specification are loaded; if filename is not an absolute path, the path is assumed to be relative to the current working directory.

This script command uses D3DXLoadMeshHierarchyFromX if loading a mesh, and D3DXCreateTextureFromFile if loading a texture.

meshes

Description:

Log information about all models and their meshes into the log file specified in the command line arguments.

Syntax:

meshes src:string;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.

Example:

meshes src:tiger;

newtex2d

Description:

Creates a new 2D texture.

Syntax:

newtex2d dst:string format:string width:int height:int mips:int src:string;

Where:

  • dst:string - Name of the new texture. This argument is required and can be unnamed (i.e. passed in as 'newTex' instead of dst:'newTex').
  • format:string - Any of the following formats: A16B16G16R16, A16B16G16R16F, A1R5G5B5, A2B10G10R10, A2R10G10B10, A2W10V10U10, A32B32G32R32F, A4L4, A4R4G4B4, A8, A8B8G8R8, A8L8, A8R3G3B2, A8R8G8B8, DXT1, DXT2, DXT3, DXT4, DXT5, G16R16, G16R16F, G32R32F, L16, L8, R16F, R32F, R3G3B2, R5G6B5, R8G8B8, X1R5G5B5, X4R4G4B4, X8B8G8R8, or X8R8G8B8. See D3DFORMAT for more information about each format. Required argument.
  • width:int - Width of the texture, in pixels. Required argument.
  • height:int - Height of the texture, in pixels. Required argument.
  • mips:int - The number of mipmaps to allocate within the texture. The default is 0 meaning to create as many mipmaps as necessary for the width and height.
  • src:string - Name of a source texture used to initialize the new texture. This must already be loaded. The default is 0 meaning no source texture is used.

Example:

newtex2d dst:newLobby format:A16B16G16R16 width:500 height:500;

Remarks:

This script command uses IDirect3DDevice9::CreateTexture.

newtex3d

Description:

Creates a new cube texture.

Syntax:

newtex3d dst:string format:string width:int height:int depth:int mips:int src:string;

Where:

  • dst:string - Name of the new texture. This argument is required and can be unnamed (i.e. passed in as 'newTex' instead of dst:'newTex').
  • format:string - Any of the following formats: A16B16G16R16, A16B16G16R16F, A1R5G5B5, A2B10G10R10, A2R10G10B10, A2W10V10U10, A32B32G32R32F, A4L4, A4R4G4B4, A8, A8B8G8R8, A8L8, A8R3G3B2, A8R8G8B8, DXT1, DXT2, DXT3, DXT4, DXT5, G16R16, G16R16F, G32R32F, L16, L8, R16F, R32F, R3G3B2, R5G6B5, R8G8B8, X1R5G5B5, X4R4G4B4, X8B8G8R8, or X8R8G8B8. See D3DFORMAT for more information about each format. Required argument.
  • width:int - The width of the texture, in pixels. Required argument.
  • height:int - The height of the texture, in pixels. Required argument.
  • depth:int - The depth of the texture. Required argument.
  • mips:int - The number of mipmaps to allocate within the texture. The default is 0 meaning to create as many mipmaps as necessary for the size.
  • src:string - Name of a source texture used to initialize the new texture. This must already be loaded. The default is 0 meaning no source texture is used.

Example:

newtex3d dst:newLobby3D format:A16B16G16R16F width:500 height:500;

Remarks:

This script command uses IDirect3DDevice9::CreateVolumeTexture.

newtexcube

Description:

Creates a new cube texture.

Syntax:

newtexcube dst:string format:string size:int mips:int srcXP:string srcXM:string srcYP:string srcYM:string srcZP:string srcZM:string;

Where:

  • dst:string - Name of the new texture. This argument is required and can be unnamed (i.e. passed in as 'newTex' instead of dst:'newTex').
  • format:string - Any of the following formats: A16B16G16R16, A16B16G16R16F, A1R5G5B5, A2B10G10R10, A2R10G10B10, A2W10V10U10, A32B32G32R32F, A4L4, A4R4G4B4, A8, A8B8G8R8, A8L8, A8R3G3B2, A8R8G8B8, DXT1, DXT2, DXT3, DXT4, DXT5, G16R16, G16R16F, G32R32F, L16, L8, R16F, R32F, R3G3B2, R5G6B5, R8G8B8, X1R5G5B5, X4R4G4B4, X8B8G8R8, or X8R8G8B8. See D3DFORMAT for more information about each format. Required argument.
  • size:int - Size of one edge of the cube texture, in pixels. Required argument.
  • mips:int - The number of mipmaps to allocate within the texture. The default is 0 meaning to create as many mipmaps as necessary for the size.
  • srcXP:string - Name of a source texture used to initialize the positive x face. This must already be loaded into memory. The default is 0 meaning no source texture is used.
  • srcXM:string Name of a source texture used to initialize the negative x face. This must already be loaded into memory. The default is 0 meaning no source texture is used.
  • srcYP:string - Name of a source texture used to initialize the positive y face. This must already be loaded into memory. The default is 0 meaning no source texture is used.
  • srcYM:string - Name of a source texture used to initialize the negative y face. This must already be loaded into memory. The default is 0 meaning no source texture is used.
  • srcZP:string - Name of a source texture used to initialize the positive z face. This must already be loaded into memory. The default is 0 meaning no source texture is used.
  • srcZM:string - Name of a source texture used to initialize the negative z face. This must already be loaded into memory. The default is 0 meaning no source texture is used.

Example:

newtexcube dst:newEnvironmentMap format:A16B16G16R16F size:512;

Remarks:

This script command uses IDirect3DDevice9::CreateCubeTexture.

optimize

Description:

Optimizes and welds vertices the meshes.

Syntax:

optimize src:string splits:int noCache:int weldAll:[none|epsilon|all] e:float P:float W:float N:float T:float B:float UV:float D:float S:float PS:float F:float;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.
  • splits:int - Whether or not vertices shared between attribute groups can be split 1 means no splits allowed, 0 (default) means splits are allowed.
  • noCache:int - Whether or not the optimization should use a vertex cache size based on information from the current device. The default is 1, meaning that the device vertex cache should be ignored.
  • weldAll:[none|epsilon|all] - Epsilon is the default value. If none is specified, no vertices will be welded. If epsilon is specified, it will weld vertices only if they are within the specified epsilon values. If all is specified, it will weld vertices reguardless of epsilon values.
  • e:float - Epsilon value for the welding algorithm to use across all components. Default value: 10e-6f. If this is specified, all other epsilon values are assigned to this value.
  • P:float - Position epsilon value. The welding algorithm will check this value before all other epsilon values when determining if two vertices need to be welded.
  • W:float - Blend Weights epsilon value.
  • N:float - Normals epsilon value.
  • T:float - Tangents epsilon value.
  • B:float - Binormals (or Bitangents) epsilon value.
  • UV:float - Texture Coordinates epsilon value.
  • D:float - Diffuse Colors epsilon value.
  • S:float - Specular Colors epsilon value.
  • PS:float - Point Sizes epsilon value.
  • F:float - Tessellation Factors epsilon value.

Example:

optimize e:10e-9f;

Remarks:

This optimization allows the meshes to be more optimal for performance. The primary optimization that this command does is vertex welding, which optimizes the mesh by removing duplicate vertices.

This script command uses D3DXWeldVertices and ID3DXMesh::Optimize.

reformat

Description:

Changes the format of the specified textures.

Syntax:

reformat src:string format:string;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.
  • format:string - Any of the following formats: A16B16G16R16, A16B16G16R16F, A1R5G5B5, A2B10G10R10, A2R10G10B10, A2W10V10U10, A32B32G32R32F, A4L4, A4R4G4B4, A8, A8B8G8R8, A8L8, A8R3G3B2, A8R8G8B8, DXT1, DXT2, DXT3, DXT4, DXT5, G16R16, G16R16F, G32R32F, L16, L8, R16F, R32F, R3G3B2, R5G6B5, R8G8B8, X1R5G5B5, X4R4G4B4, X8B8G8R8, or X8R8G8B8. See D3DFORMAT for more information about each format. This argument is required and can be unnamed (i.e. passed in as 'A8L8' instead of format:'A8L8').

Example:

reformat format:A4R4G4B4;

Remarks:

This script command uses D3DXLoadSurfaceFromSurface.

reset

Description:

Resets as if DXOps has been restarted. Equivalent to calling unload on all objects.

Syntax:

reset;

resize

Description:

Resizes a texture.

Syntax:

resize src:string width:int height:int depth:int dither:int filter:string;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.
  • width:int - The width of the texture, in pixels. Required argument.
  • height:int - The height of the texture, in pixels. Required argument.
  • depth:int - The depth of the texture.
  • dither:int - Enables or disables dithering during mipmap generation. 0 for false, 1 for true. Default is 1.
  • filter:string - The mipmap filter to use when generating the mipmaps. Either None, Point, Linear, Triangle, or Box. Box is the default.

Example:

resize width:200 height:200;

Remarks:

This script command uses D3DXLoadSurfaceFromSurface.

save

Description:

Saves the models or textures to a file.

Syntax:

save src:string fileName:string xFileType:string;

Where:

  • src:string - Specifies which currently loaded objects to save. This string can optionally use .NET Framework Regular Expressions, but the expressions must resolve to one item. The default is ".*", meaning perform this operation on all currently loaded items.
  • fileName:string - Name of destination output file. This argument is required and can be unnamed (i.e. passed in as 'tiger.x' instead of fileName:'tiger.x').
  • xFileType:string - If saving to an x file, this is used to determine the type of x file. Can be either text (default), binary, or compressed. Text is the recommended format.

Example:

save src:tiger fileName:tiger_modded.x xFileType:text;

Remarks:

This script command uses D3DXSaveMeshHierarchyToFile if saving a model.

shade

Description:

Calls a user-defined HLSL shader to modify a texture.

Syntax:

shade src:string shader:string fileName:string ...parameters...;

Where:

  • src:string - The name of the target texture. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded textures.
  • shader:string - Name of the shader to use. Default value is main.
  • fileName:string - Name of the text file that contains the HLSL shader. This argument is required and can be unnamed (i.e. passed in as 'texShader.psh' instead of fileName:'texShader.psh').
  • ...parameters... - corresponds to the names of the parameters specified in the HLSL shader file. See teh Passing Parameters Into Shaders section below.

Passing Parameters Into Shaders

The shade script command allows you to initialize parameters in your HLSL shader. Doing so follows the basic syntax <name of parameter>:string. The string will be used initialize the specified parameter and the format of that string will depend on the data type of parameter that you are initializing.

For integers, floating point numbers, and matrices, the values are passed in as comma-delimited lists of numbers. For example:

float pi;
float3 viewVec;
matrix4x4 viewMat;

Would be initialized in the shade command by:

pi:'3.14' viewVec:'0,1,0' viewMat:'1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1'

Textures are passed into the shader by the name of their sampler. For example:

textureCUBE TableClothTex;
samplerCUBE TableClothSamp = sampler_state
{
    Texture = (TableClothTex);
    MinFilter = Linear;
    MagFilter = Linear;
};

Would be initialized in the shade command by:

TableClothSamp:'TabCloth'

Where TabCloth is a texture loaded into DXOps before the shade command was called. Below is an example usage of the shade script command that will create a texture that blends from white to black in the y direction.

If the HLSL file defines a sampler parameter with the name "Target", then the shade script command will automatically fill that parameter with the target texture. See the Using the Shade Script Command example.

HLSL Function Requirements

The function definitions for these HLSL texture shaders follow a syntax slightly different from vertex and pixel shaders. There can be three types of texture shader functions - one for 2D textures, one for 3D textures, and one for cube textures - each of which follows this convention:

For 2D textures:

float4 main(float2 UV : TEXCOORD0, float2 PixelSize : TEXCOORD1) : COLOR

Where UVs are 0 to 1

For 3D textures:

float4 main(float3 UVW : TEXCOORD0, float3 PixelSize : TEXCOORD1) : COLOR

Where UVWs are 0 to 1.

For cube textures:

float4 main(float3 UVW : TEXCOORD0, float3 PixelSize : TEXCOORD1) : COLOR

Where UVWs are -1 to 1.

PixelSize will have a zero on one of the axes. This will indicate which axis of the cube you are currently shading. Look to the sign of the corresponding axis in the UVW variable to determine if you are working on the positive or negative face along that axis. See the Using the Shade Script Command example.

Example:

newtex2d dst:'test' format:A8R8G8B8 width:64 height:64 mips:0;
shade fileName:'ramp.psh' top:'1,1,1' bottom:'0,0,0';
save fileName:'t-ShadeTex2.dds';

Where ramp.psh is:

float3 top;
float3 bottom;

float4 main(float2 UV : TEXCOORD0, float2 PixelSize : TEXCOORD1) : COLOR
{
    return float4( lerp(bottom, top, UV.yyy ), 1);
}

This example will generate an image that looks like this:

Remarks:

This will not work on DXT compressed textures. If you have a DXT compress texture and wish to run the shade command on it, try reformatting the texture to a format that is valid as a render target and then reformatting it back to the desired format afterwards.

reformat 'A16B16G16R16F';
shade 'RedXGreenYPlusTarget-cube.psh';
reformat 'Dxt1';

This script command uses D3DXFillTextureTX.

slice2d

Description:

Creates a new 2D texture from an existing texture surface.

Syntax:

slice2d dst:string src:string volume:int face:string mipMap:int;

Where:

  • dst:string - The name of the texture to be generated. This argument is required. A regular expression may be used for this argument as long as it resolves to one name. This argument is required and can be unnamed (i.e. passed in as 'resizedTex' instead of dst:'resizedTex').
  • src:string - The source image from which the surface will be extracted. This must already be loaded. Required argument.
  • volume:int - If extracting from a volume texture, this specifies the surface to be extracted. This uses zero-based indexing. The default value is 0.
  • face:string - If extracting from a cube texture, this specifies the face to be extracted. This can either be +x, -x, +y, -y, +z, or -z. The default is +x.
  • mipMap:int - If extracting from a mipmap texture, this specifies the zero-based index into the mipmap. The default value is 0.

Example:

slice2d dst:bliss2 src:bliss;

Remarks:

This script command uses D3DXLoadSurfaceFromSurface.

splice2d

Description:

Inserts a surface into an existing texture.

Syntax:

splice2d dst:string src:string volume:int face:string mipMap:int;

Where:

  • dst:string - The name of the destination texture. A regular expression may be specified here for multiple destinations. This argument is required and can be unnamed (i.e. passed in as 'destTex' instead of dst:'destTex').
  • src:string - The name of the source texture. This must already be loaded into memory. Required argument.
  • volume:int - If pasting into a volume texture, this specifies the destination surface using zero-based indexing. The default value is 0.
  • face:string - If pasting into a cube texture, this specifies the destination face. This can either be +x, -x, +y, -y, +z, or -z. The default is +x.
  • mipMap:int - If pasting into a mipmap texture, this specifies the destination surface using zero-based indexing. The default value is 0.

Example:

splice2d dst:bliss src:azul;

Remarks:

This script command uses D3DXLoadSurfaceFromSurface.

stripify

Description:

Attempts to optimize meshes by ordering their triangles into strips.

Syntax:

stripify src:string splits:[0|1];

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.
  • splits:[0|1] - Whether or not the operation will be allowed to introduce duplicate vertices. It is recommended to allow the algorithm to introduce duplicates because otherwise the resulting triangle strips could render inefficiently. Default value is 1.

Example:

stripify src:tiger;

Remarks:

Does the following:

  • Minimizes the number of attribute groups by performing an attribute sort.
  • Reorders the mesh faces to maximize strip length.
  • Converts every mesh subset of every mesh to a single triangle strip.

This script command uses ID3DXMesh::Optimize (with D3DXMESHOPT_STRIPREORDER).

textures

Description:

Log information about all meshes into the log file specified in the command line arguments.

Syntax:

textures src:string;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.

unload

Description:

Removes the specified texture(s) or model(s) from DXOps.

Syntax:

unload src:string type:string;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects. This argument is required and can be unnamed (i.e. passed in as 'tiger' instead of src:'tiger').
  • type:string - Possible values: models or textures. Specifies the type of object that you wish to unload.

Example:

unload tiger type:models;

uvatlas

Description:

Partitions and packs a uvatlas for the meshes.

Syntax:

uvatlas src:string maxCharts:int stretch:float gutter:int width:int height:int;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.
  • maxCharts:int - The maximum number of charts to partition the mesh into. Use 0 to tell D3DX that the atlas should be parameterized based on stretch.
  • stretch:float - The amount of stretching allowed. 0 means no stretching is allowed, 1 means any amount of stretching can be used.
  • gutter:int - The minimum distance, in texels, between two charts on the atlas. The gutter is always scaled by the width; so, if a gutter of 2.5 is used on a 512x512 texture, then the minimum distance between two charts is 2.5 / 512.0 texels.
  • width:int - Texture width.
  • height:int - Texture height.

Example:

uvatlas maxCharts:0 stretch:0.5 gutter:2.5 width:512 height:512;

Remarks:

This script command uses D3DXUVAtlasCreate.

validate

Description:

Validates meshes and sends warnings to the log if there are any.

Syntax:

validate src:string;

Where:

  • src:string - Specifies which currently loaded objects to perform this operation on. This string can optionally use .NET Framework Regular Expressions. The default is ".*", meaning perform this operation on all currently loaded objects.

Example:

validate src:tiger;

Remarks:

Checks the following data:

  • Backfacing - triangles that share the same vertex indices but have face normals pointing in opposite directions (back-facing triangles).
  • Bowties - If a vertex is the apex of two triangle fans (a bowtie) and mesh operations will affect one of the fans. Bowties can cause problems for operations such as mesh simplification that remove vertices.

This script command uses D3DXValidMesh.

See Also

DirectX Content Tools, DirectX Ops (dxops.exe)


Texture Viewer (Windows Explorer Extension)

The texture viewer displays thumbnail images in the Microsoft Windows file preview system.

Texture viewer can display the following image formats:

  • Bitmap (.bmp file)
  • DirectDraw Surface (.dds file)
  • DIB (.dib file)
  • HDR image (.hdr file)
  • JPEG (.jpg file)
  • PFM (.pfm file)
  • PNG (.png file)
  • PPM (.ppm file)
  • TGA (.tga file)

For more information about these image formats, see D3DXIMAGE_FILEFORMAT.

For a cube texture, the forward cube face will be displayed on the screen. For a volume texture, the first plane will be displayed. These display properties cannot be configured by the user.

Compatibility Chart

Direct3D 9 | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | No | Yes | Yes | Yes

Requirements

The texture viewer requires a Windows 2000, Windows XP, Windows Vista operating system; it does not work on Windows Millennium.

Installation

The texture viewer is automatically installed from Txview.dll when you install the DirectX SDK.

Note Installation does not override any existing Windows viewer settings for any texture file formats.

User's Guide

From a folder view of your texture files, use the Windows View menu to view thumbnail images with texture file information. Use one of the following procedures.

Thumbnail View

In the View menu, select Thumbnails. Thumbnails of all supported file formats (see list above) will be displayed. If more than one level is available in a file's mipmap, only the top mipmap level will be displayed.

Figure 1. Texture view using the Explorer menu

Details View

If necessary, first switch out of Windows classic folder view; see the note below. Select the file that you want to view, and then on the View menu, click Details. A rendering of the image will be displayed in the Details pane of the Explorer bar.

Figure 2. Details View in Windows Explorer

Texture view using Details panel of the Explorer bar

Note The Details view functionality will not work if you are using the Microsoft Windows classic folder view. To change your folder settings, use the following procedure.

  1. Open any folder.
  2. In the folder's Tools menu, select Folder Options...
  3. In the General tab, select the radio button labeled Show common tasks in folders.
  4. Click Apply and then OK.
To go back to the Windows classic folder view, use this same procedure, but instead select the radio button labeled Use Windows classic folders.

Figure 3. Folder Options dialog box


Texture Converter (Windows Explorer Extension)

The texture file converter saves one or more texture files to a new file format. The following are the available input and output formats: BMP, DDS, DIB, HDR, JPEG, PFM, PNG, and TGA.

For more information on these texture file formats, see D3DXIMAGE_FILEFORMAT.

Compatibility Chart

Direct3D 9 | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | No | Yes | Yes | Yes

Requirements

The texture converter requires Windows 2000, Windows XP, or Windows Vista.

Installation

The texture file converter is automatically installed from Txview.dll when you install the DirectX SDK.

User's Guide

The texture file converter is activated when you right-click one or more selected file or folder names, and then click Convert to file format on the context menu.

The following conversion dialog box will appear with options for output size, formats, filtering, and file location.

Figure 1. Texture Conversion Dialog Box

Texture conversion dialog box

If Image Options is set to Default, the original image size and/or mipmap levels will be retained. The Depth setting applies only to volume textures.

The following table describes the additional settings available in the conversion dialog box.

Options and Filters | Description
Miplevels | Level of mipmap sampling. For more information, see Texture Filtering with Mipmaps (Direct3D 9).
Pixel Format | Available unsigned, signed, and mixed formats described in D3DFORMAT.
Image Filter | D3DX_FILTER_NONE, _POINT, _LINEAR, and _TRIANGLE texture channel flags described in D3DX_FILTER.
Mirror | D3DX_FILTER_MIRROR_U, _V, and _W texture channel flags described in D3DX_FILTER.
sRGB | In setting indicates the input data is in sRGB (gamma 2.2) color space. Out setting indicates the output data is to be in sRGB (gamma 2.2) color space.
Mip Filter | D3DX_FILTER_BOX, _POINT, and _TRIANGLE texture channel flags described in D3DX_FILTER.
Dither | Ordered (standard 4×4) or Error Propagation (statistically based) dither algorithms can be applied to the output from the Image Filter and Mip Filter. Alternately, no dithering can be applied.

Note The Miplevels and Mip Filter choices are disabled unless DDS output format and Enable extended .DDS file options are both selected.

Behavior of the converter varies according to whether a single file, multiple files, or a folder have been selected, as described in the following sections.

Converting a Single File

To convert a single file to a single format, use the following procedure.

To convert a single file to a single format

  1. Right-click a texture file to convert, then select Convert to file format from the context menu. The conversion dialog box, like that shown in Figure 1, appears.
  2. Insert a path, file name, and extension for the converted file. Alternately, click the browse button (...), which opens a Save As dialog box to select the converted file's name, format, and destination folder.

Converting Multiple Files

The procedure for converting multiple files is slightly different depending on whether you choose to convert all of the files to the same format, which you specify once, or to multiple formats, which you specify individually for each file.

To convert multiple files to a single format

  1. Select multiple texture files, right-click the selection, and then click Convert to file format on the context menu.
  2. In the Bulk File Conversion dialog box, select Convert all files at once to convert all files to the same output format.
  3. In the Bulk texture file conversion dialog box, specify the output size, format, and filtering to apply to all the files that you have selected.
  4. Select the output format for the file.
  5. Insert a path to a destination folder in which to store the converted file, or click the browse button (...), which opens a Save As dialog box to select the converted file's name, format, and destination folder.

To convert multiple files to multiple formats

  1. Select multiple texture files, right-click the selection, and then click Convert to file format on the context menu.

  2. In the Bulk File Conversion dialog box, select Convert each file to specify the output format for each file individually.

    For each file in your selection, a conversion dialog box, like that in Figure 1, will be displayed in series. If you click Cancel, the file named in the title bar is skipped, and you are prompted for settings for the next file in your selection.

  3. Select the output format for the file.
  4. Insert a path to a destination folder in which to store the converted file, or click the browse button (...), which opens a Save As dialog box to select the converted file's name, format, and destination folder.
  5. Click OK.
  6. For each file in your selection, repeat the preceding steps.

Converting Files in a Folder

You can convert all of the files in a folder in bulk. The converter provides options for cases in which more than one file of the same name will be created; for example, when two files to be converted have the same name but different extensions.

Also, if the destination folder that you specify is the same as or located in the source folder, a message box informs you that the files will not be converted. However, any other selected source files not in this destination folder will be converted.

To convert several texture files in a single folder

  1. Right-click a folder containing texture files (or several files and a folder), then click Convert to file format from the context menu. A Bulk texture file conversion dialog box, similar to the conversion dialog box shown above, appears.
  2. Specify the output size, format, and filtering that will apply to all the files within the folder, along with any other files you have selected.
  3. Insert a path to a destination folder in which to store the converted files, or click the browse button (...) to select a destination folder.


DirectX Texture Editor (Dxtex.exe)

The DirectX texture editor (DxTex) enables DirectX SDK users to create texture maps that use the DXTn compression formats.

Compatibility Chart

Direct3D 9 | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | No | Yes | Yes | Yes

Installation

When you install the DirectX SDK, the source code and the executable file, Dxtex.exe, of the DirectX texture editor are automatically installed to the following locations (the location of the executable depends on the platform):

Source code
DirectX SDK root\Utilities\Source\dxtex
32-bit executable file
DirectX SDK root\Utilities\Bin\x86
64-bit executable file
DirectX SDK root\Utilities\Bin\x64

User's Guide

The DirectX texture editor allows you to open, view, manipulate, and save textures in various formats, and to use various texture features. The texture editor uses a traditional document-based UI. Each texture map is a document, and several documents can be open simultaneously.

Opening and Creating Textures

The following procedures describe how to use the DirectX texture editor to open a texture and how to create a new texture.

To open an existing texture

  1. Start the DirectX texture editor.
  2. On the File menu, click Open.
  3. In Open dialog box, navigate to and select an image file to open as a texture. Click Open.

To create a new texture

  1. Start the DirectX texture editor.
  2. On the File menu, click New Texture.
  3. In the New Texture dialog box, specify the options for the texture that you want to create, and then click OK.

Converting, Viewing, and Saving Textures

Follow these steps to convert an existing texture to a different format, compare the original and new formats, and save the resultant texture.

  1. In the DirectX texture editor, open an existing texture and select it.
  2. On the Format menu, click Change Surface Format.
  3. In the Change Surface Format dialog box, set a new format by clicking a selection in the Surface/Volume Format list. Click OK.
  4. To compare the original format to the new format, click in the displayed texture to toggle between the original and the new formats. The title bar of the texture's window identifies the format that is currently displayed..
  5. To save the texture in the new format, select the File -> Save As... menu item and select a new file name from the dialog that pops up. Click Save to save the texture file.

Note When changing formats, the original bitmap is used as the source image, and any previous format change is overwritten. This is to prevent progressive degradation of the image that would otherwise occur with multiple format changes.

Using Alpha Channels

Many texture formats include an alpha channel, which provides opacity information at each pixel. DxTex fully supports alpha in textures. When a bitmap is applied as alpha to a texture, the blue channel of the bitmap is used to provide the alpha data.

There are two ways to provide a texture with alpha data. You can use a special file naming convention to notify DxTex to add a specified bitmap as alpha to a texture automatically, or you can add a bitmap as alpha to a texture manually. For both methods, you must have a texture you wish to add alpha data to, and a bitmap that will provide the alpha data to the texture.

Note Some DxTex operations (Open as Alpha Channel, conversion to DXT3, and conversion to DXT5) are not possible on DXT2 and DXT4 formats. For more information, see the Premultiplied Alpha section.

Automatically Opening Into An Alpha Channel

Follow these steps to open a texture with alpha automatically.

  1. Using Windows Explorer, browse to a bitmap you wish to open with alpha. The second bitmap that will supply the alpha data must also be in this directory.
  2. Right-click on the bitmap that will supply the alpha data, and select Rename.
  3. Rename this bitmap to match the name of the bitmap you wish to apply the alpha to, appending an "_a" suffix to the file name. For instance, if you wish to apply alpha to "flowers.bmp", the alpha data bitmap must be named "flowers_a.bmp".
  4. Open the DirectX texture editor.
  5. Select the File->Open... menu item and select the bitmap you wish to open with alpha. The second bitmap that contains the alpha data will be loaded into the alpha channel automatically.

Manually Opening Into An Alpha Channel

Follow these steps to open a bitmap as an alpha channel in an existing texture.

  1. Open an existing texture that has an alpha channel by selecting the File -> Open... menu item.
  2. Select the File -> Open Onto Alpha Channel of This Texture... menu item. Select a bitmap that contains alpha data from the dialog that pops up.

Note If the existing texture is a volume map or cube map, you must select the File -> Open Onto Alpha Channel of This Surface menu item after selecting an appropriate surface in the cube mapped or volume mapped texture. See the Cube Map and Volume Map sections of the user's guide for more information.

Viewing An Alpha Channel

When alpha data is applied to a texture, the texture will display with the alpha channel overlayed. To display the alpha channel by itself as a grayscale image, select the View -> Alpha Channel Only menu item.

Cube and Volume Maps

DxTex can convert textures to cube and volume map textures, and provides the ability to navigate and save these textures. A cube map texture is a collection of six textures that are arranged like the faces of a cube, one texture per face. A volume map texture is a collection of one or more textures arranged in "slices," where each pixel can be thought of as having three dimensions: height and width, which describe the pixel's location on a slice texture, and depth, which identifies the slice the pixel is on.

Creating and Importing onto Cube Maps

Follow these steps to convert a texture into a cube map.

  1. Open an existing texture by selecting the File -> Open... menu item.
  2. Select the Format -> Make Into Cube Map... menu item.
  3. The current texture will occupy one face of the cube map. From the dialog that pops up, select which face you want the texture to occupy, and click OK.

Follow these steps to import texture data into each face of a cube map.

  1. Select the View->Cube Map Face menu item and select a face from the list that appears.
  2. Select the File->Open Onto This Cubemap Face... menu item and select a texture to open from the dialog that pops up.
  3. Repeat this process for each face.

Creating and Importing onto Volume Maps

Follow these steps to convert a texture into a volume map.

  1. Open an existing texture by selecting the File -> Open... menu item.
  2. Select the Format -> Make Into Volume Map... menu item.
  3. From the dialog that pops up, select the number of slices (layers) you want the texture to occupy, and click OK.

Follow these steps to import texture data into each slice of a volume map.

  1. Select the View->Higher Volume Slice or the View->Lower Volume Slice menu item to change the current slice being viewed.
  2. Select the File->Open Onto This Surface... menu item and select a texture to open from the dialog that pops up.
  3. Repeat this process for each slice.

Mipmapping

Mipmapping is a technique that improves image quality and reduces texture memory bandwidth by providing prefiltered versions of the texture image at multiple resolutions. Filtering is done through a simple box filter. That is, the four nearest pixels are averaged to produce each destination pixel.

Follow these steps to generate a mipmap for a texture.

  1. Open an existing texture by selecting the File -> Open... menu item.
  2. Select the Format -> Generate Mip Maps menu item.
  3. Select the View -> Smaller Mip Level or View -> Larger Mip Level menu item to navigate through each image in the mipmap.

Note To generate mipmaps in DxTex, the width and height of the source image must both be powers of two.

Command-Line Mode

You can use command-line options to pass input files, an output file name, and processing options to DxTex. If an output file name is specified, the application exits automatically after writing the output file, and no user interface is presented.

dxtex [infilename] [-a alphaname] [-m] [DXT1|DXT2|DXT3|DXT4|DXT5] [outfilename]

infilename:               Name of the file to load.  This can be a
                            .bmp or .dds file.

-a alphaname:             The next parameter is the name of a .bmp
                            file to load as the alpha channel. If no
                            alpha filename is specified, DxTex still
                            looks for a file named Infilename_a.bmp. If
                            it exists, use that file as the alpha
                            channel.

-m:                       Mipmaps are generated.

DXT1|DXT2|DXT3|DXT4|DXT5: Compression format. If no format is
                            specified, the image will be in ARGB-8888.

outfilename:              Name of the destination file. If this
                            option is not specified, the user interface
                            shows the current file and all requested
                            operations.  If an outfilename is specified,
                            the application exits after saving the
                            processed file without presenting a user
                            interface.

Notes

Creating Textures

Creating a DXTn-compressed texture is not difficult. However, Direct3D can do the conversion for you when using the IDirect3DTexture9 interface. Advanced developers will probably want to write their own tools that meet their specific needs, but the DirectX texture editor provides useful basic functionality.

Performance

DxTex uses the Direct3D Reference Rasterizer to draw the textures, regardless of what 3D hardware is available. So with larger textures (greater than 256-by-256 pixels), the application may be somewhat slow, depending on your CPU speed.

DDS File Format

See DDS File Reference for more detailed information about the DDS file format.

Note DxTex does not currently support textures with surface formats that do not contain at least an R, G, and B texture (such as D3DFMT_G16R16 and D3DFMT_A8), although D3DX can load and save such textures in DDS format.

Premultiplied Alpha

The DXT2 and DXT4 formats use premultiplied alpha. This means that the red, green, and blue values stored in the surface are already multiplied by the corresponding alpha value. Direct3D cannot copy from a surface that contains premultiplied alpha to one that contains non-premultiplied alpha, so some DxTex operations (Open as Alpha Channel, conversion to DXT3, and conversion to DXT5) are not possible on DXT2 and DXT4 formats. Supporting textures using these formats is difficult on Direct3D devices that do not support DXTn textures. This is because Direct3D cannot copy them to a traditional ARGB surface either, unless that ARGB surface uses premultiplied alpha as well, which is rare. For this reason, you might find it easier to use DXT3 rather than DXT2, and DXT5 rather than DXT4, when possible.


Texture Conversion Tool (Texconv.exe)

A command line tool that converts textures between the following formats: BMP, DDS, JPEG, HDR, PFM or PNG.

Compatibility Chart

Direct3D 9 | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | No | Yes | Yes | Yes

Path

The executable file, Texconv.exe, is in the following platform-dependent locations:

32-bit
DirectX SDK root\Utilities\Bin\x86
64-bit
DirectX SDK root\Utilities\Bin\x64

Syntax

Texconv.exe uses the following command syntax:

texconv
        [-w number]
        [-h number]
        [-d number]
        [-m number]
        [-f format]
        [-if filter]
        [-mf filter]
        [-c color]
        [-srgbi]
        [-srgbo]
        [-px string]
        [-sx string]
        [-o directory]
        [-ft file-type]
        [-nologo]
        file-name

The file-name parameter indicates the file to convert.

The optional command-line switches are described in the following table.

Optional Switches | Description
-c color | Colorkey value. Wherever this color appears in the source texture it is replaced with a transparent black value (0x000000) in the output texture. If an alpha channel is present in the output texture, this makes the specified color transparent. If no alpha channel is present it is changed to black. When specifying this color, always include an alpha value (use FF if the color is opaque). For example, -c FFFE02A5 sets the colorkey value to a solid magenta.
-d number | Depth of the output texture. This setting applies only to volume textures.
-f format | Output format. Use any of the formats in D3DFORMAT without the D3DFMT_ prefix (except: D3DFMT_MULTI2_ARGB8).
-ft file-type | A file type for the output texture. Use one of the following: bmp, dds, jpg, hdr, pfm, or png. The default value is dds.
-h number | Height of the output texture in pixels.
-w number | Width of the output texture in pixels.
-if filter | Image filter. Use one of the following: NONE, POINT, LINEAR, TRIANGLE, BOX, NONE_DITHER, POINT_DITHER, LINEAR_DITHER, TRIANGLE_DITHER, or BOX_DITHER. Filters with DITHER in their name indicate that a 4×4 ordered dither algorithm is also applied. See D3DX_FILTER for descriptions of the filters.
-m number | Number of mipmap levels to generate in the output texture. This setting only applies to DDS output. For more information, see Texture Filtering with Mipmaps (Direct3D 9).
-mf filter | Mipmap filter value described in D3DX_FILTER.
-o directory | Output directory.
-px string | Text string to attach to the front of the resulting texture's name.
-srgbi or -srgbo | Use -sRGBi to indicate that the input data is in the sRGB (gamma 2.2) color format. Use -sRGBo to indicate that the output data should be in sRGB color format.
-sx string | Text string to attach to the end of the resulting texture's name.
-nologo | Suppress copyright message.


DirectX Performance Tools

This section describes tools to help you improve the performance of your DirectX application.

  • PIX - Use PIX to analyze, debug, test, and help optimize the performance of a DirectX application.

See Also

DirectX SDK Tools


PIX

PIX is a tool for analyzing, optimizing, and debugging Direct3D applications. PIX is designed to capture detailed information from an application while it is running. PIX can be configured to gather data, such as the name of the Direct3D APIs called, timing information, mesh vertices before and after transformations, screenshots, and various statistics. PIX can also be used for debugging vertex and pixel shaders, including setting breakpoints and stepping through shader code.

The documentation for PIX includes:

  • User's Guide - A user's guide that describes how to use PIX.
  • Tutorials - Tutorials that demonstrate how to analyze some common application problems.
  • Reference - A complete description of the feature set.

Versions

PIX runs with the following versions of DirectX.

Runtime | Windows XP | 64-bit Windows XP | Windows VistaTM | 64-bit Windows VistaTM
Direct3D 9 | x | x | x | x
Direct3D 10 |  |  | x | x

PIX experiment files and run files are identical regardless of the version of the runtime or the operating system. Therefore, a run file captured on a 32-bit version of Windows can be played back on a 64-bit version of Windows to make sure that the run file renders correctly in that environment.

Path

On a 32-bit operating system, the 32-bit version of PIX is located in:

<SDK root>\Utilities\Bin\x86\

On a 64-bit operating system, the 64-bit version of PIX is located in:

<SDK root>\Utilities\Bin\x64\

See Also

DirectX Performance Tools


User's Guide

PIX is a tool designed to capture detailed information from a Direct3D application while it is running. Here are four kinds of data that can be captured with PIX.

  • Capture a full stream of call data from the target program. A full stream is a record of every Direct3D call made by the application, including the contents of textures, shaders, and other Direct3D objects.
  • Capture multi-frame statistics with counters.
  • Capture a single-frame to debug state setting, and shader settings.
  • Capture a screenshot to analyze or compare frames visually.

PIX can be configured and controlled either through its graphical user interface, or from the command line.

Running PIX from the Graphical-User Interface

To run PIX from the graphical-user interface to both capture and analyze data, follow these steps.

  1. Configure Settings - Create an experiment to specify the data to collect, how to collect it, and the application to collect it on.
  2. Gather Data - Run an experiment to collect data on the target program while it is running.
  3. Analyze the Results - Review statistics over many frames or analyze a single frame in depth.

Running PIX from the Command Line

Use PIX to collect and store data in a run file to compare results on different hardware, submit bugs, or simply perform analysis at another time. In these cases, it may make more sense to run PIX from the command line.

Running PIX on Windows Vista

See User-Account Control for information about running PIX on target programs using user-account control.

See Also

PIX


Configure Settings

The first step for configuring PIX is to prepare an experiment, which contains information about the target program to analyze and what data to gather. An experiment can be created using a basic view (a good idea if you are new to PIX) or an advanced view (if you are experienced with PIX and want to customize the data collection).

Create an Experiment

A PIX experiment specifies what application to analyze, and what data to gather while analyzing it. If you save an experiment to an experiment file (.PIXExp), it can be reused. To create an experiment, launch PIX and select New Experiment from the file menu.

By default, the basic view of an experiment opens.

Configure an Experiment from the Basic View

The basic view of an experiment only requires two pieces of information: the target program to profile and how to collect the data. You can either use the browse button to find the target program or enter the full path to the target program in the text box. For help see Collect Data with the Basic View.

Configure an Experiment from the Advanced View

The advanced view of an experiment gives you much more control over the data collected and how it is collected. Switch to the advanced view by clicking on the More Options button from the basic view. The advanced view uses triggers (events that fire when you tell them to fire) and actions (the action to take when a trigger fires) to specify what data to collect and how often to collect it. Using an advanced view gives you more control over how an experiment is run. For help see Collect Customized Data with the Advanced View.

Save an Experiment

Once you have configured your experiment, you can save it to a file if you intend to reuse it later. You can save changes to an experiment in an experiment file (.PIXExp) by choosing Save from the file menu.

After the experiment is configured, run the experiment to collect the data.

See Also

User's Guide


Gather Data

PIX gathers the data specified in an experiment file, and stores the results in a .PIXRun file, when you run an experiment. There are two ways to run an experiment:

  • Gathering Data from the Graphical User Interface
  • Gathering Data from the Command Line

Gathering Data from the Graphical User Interface

There is more than one way to start gathering data.

From an experiment, you can either

  • Click the Start Experiment button.

  • From the File menu, choose Start Experiment.

Configuring the the Information Overlay

PIX can display statistics and other information on top of your application. From the PIX View menu, select Options to specify what, where, and how you want PIX to display when your application is running.

Gathering Data from the Command Line

Running PIX from the command line may be more convenient when setting up an automated batch action such as overnight testing. See Command-Line Syntax.

See Also

User's Guide


Analyze the Results

As PIX analyzes the target program, it generates two kinds of data files:

  • Screen shots are stored as standard image files.
  • Other information is stored in a PIXRun file.

When the experiment is finished collecting data (stopping according to values you set in the experiment), open and display the PIXRun or image file data using PIX's File menu or by dragging the file onto the PIX main window. In many cases, PIX will open the PIXRun file automatically when the experiment ends.

  • Analyze Direct3D Calls
  • Analyze Single-Frame Capture Data
  • Analyze Frame Statistics

Limitations when Analyzing Data

PIX is not meant for capturing the elapsed time for API calls because Direct3D calls are batched up and sent to a command buffer. This makes profiling more difficult. To get elapsed time for API calls, use an instrumented profiler (such as VTune) which measures the amount of CPU time it takes to execute an API call.

See Also

User's Guide


Analyze Frame Statistics

Frame statistics are per-frame values that indicate data such as the number of times something happened per frame. Use frame statistics to:

  • Compare performance between frames to find poorly performing frames.
  • Identify performance problems within a frame.

Compare Performance Between Frames

There are two very quick ways to use PIX to find frames which are performing poorly.

  • Use the Use the Timeline View to find Slow Frames Visually to quickly visually compare the CPU processing time for all the frames.
  • Use the event view to compare the calculated frames-per-second (FPS) values for each frame.

Use the Timeline View to find Slow Frames Visually

The timeline view displays the amount of time it takes the CPU to process each frame.

For instance, here is the CPU load for an entire experiment.

Figure 1. Viewing CPU Processing Time for All Frames

Use the zoom button to expand the horizontal axis to see individual frames more clearly. For instance, this hypothetical example shows many different frames. Arrows mark frames that consume different amounts of time on the CPU.

Figure 2. CPU Load View Expanded to View Individual Frames

  • A slow start-up frame where resources are being created or loaded
  • An average quick frame
  • A very fast frame that collapses to a line

Use the Event View to find Slow Frames

Figure 3. Using the Events View

Get Insight about Performance Within a Frame

Once you identify fast frames and slow frames, you will probably want to figure out why the slower frames take so long to finish.

  • Use the Timeline graph to display counters to tell you more about what is happening within a frame.
  • Use the heads-up-display (HUD) feature to overlay the curves from the timeline graph over the application in realtime.

Use the Timeline Graph to View Counters

Figure 4. Using the Graph in the Timeline View

Use the HUD to View the Timeline and the Application Simultaneously

Here is an example of the heads-up-display (HUD) displaying the data that PIX is collecting on an application while it is running.

Figure 5. The HUD and an Application in Realtime

This example uses the StateManager sample. This sample is a good way to see how PIX works. The sample has three controls that vary the amount of rendering work for each frame.

Figure 6. The HUD Counters Actual Size

See Also

User's Guide


Analyze Direct3D Calls

You can use PIX to log all the Direct3D calls made by the target program. This is a convenient method of learning how the target program uses Direct3D. Because a log is simply a listing of the API calls, there are several empty windows when PIX opens the PIXRun file:

  • The timeline view is empty
  • There is no object view
  • The details view has the summary tab, render tab and the mesh tab; but the render tab is empty.
  • The event view lists the Direct3D calls made while the experiment was running.

Viewing a Log of Direct3D Calls in the Event View

This analysis is done running the BasicHLSL sample and logging the calls made in frame 3. Here are the events you see when you run the experiment.

API Calls made by the Target Program

There are five events listed, starting with event number 1 and ending with event number 736. Expanding frame 3 shows that these events take place in frame 3.

The event view shows an event by event listing of all the API calls made in frame 3. The frame starts by clearing the rendertarget, followed by a call to BeginScene and goes right into SetTechnique. Followed by 733 other events. Notice that the first 5 events, say from event 4 - 9, are each Direct3D API calls made by the target program. So the call log shows all the Direct3D calls made by your target program.

API Calls made by D3DX

However, PIX does more than that. Skip down to event 17, which is BeginPass. Have you ever wanted to know what happens when BeginPass is called when rendering an effect? You can find out by expanding this node in PIX.

As you can see, BeginPass sets the vertex shader, updates a constant value, and sets the pixel shader. These API calls are not made by the target program, they are made by D3DX as a result of the target program calling BeginPass. You can use PIX to see API calls that are made by the target program as well as calls made by D3DX.

Also shown in the same figure is the detail behind a DrawSubset call. Notice that the target program calls DrawSubset, which calls SetVertexDeclaration, SetStreamSource, SetIndices and DrawIndexedPrimitive. So when you are profiling DrawSubset and trying to figure out why the profiler is returing numbers bigger than you expect, PIX can help you see the state changes that occur as a result of a single API call.

This example was done selecting the call logging option with an experiment using the basic view. This option defaults to the counters you see shown here in the event view. You may not customize the counters from the basic view when logging calls. If you need more control over the data collected, switch to the advanced view and customize your triggers and actions to choose from a very large set of counters.

See Also

User's Guide


Analyze Single-Frame Capture Data

Single frame capture data is a record of all the events that occur in single frame, along with the startup and shutdown events required to run the experiment. PIX collects information on all the function calls and Direct3D objects used in that frame as well being able to render the frame and any textures or surfaces used by the application. Once the data is collected, there are several ways to analyze the results.

Analyzing Events

Once you have run an experiment (either basic or advanced) and closed the target program, PIX automatically opens the runfile. The events window will show the frames that were captured.

Click on the plus sign next to a frame number to view all of the Direct3D function calls made during that frame.

Notice that the event table shows each function call, with memory addresses for each Direct3D object. The addresses are shown here rendered in black. This means that the objects are not yet alive. Once they are alive, you can click on the objects to look at object data (see analyzing object data).

Notice the columns in the event table correspond to the counters specified in the experiment. If you use an advanced view to configure the experiment, you can customize the counters.

Viewing Object Data

Each Direct3D object has data associated with it; this is referred to as pipeline state. Use PIX to view object data in the details view, or the appropriate object tab. Since this experiment captured a single-frame capture, PIX captured all the setup information necessary to rereun the program and keep pointers to the actual objects used.

The object view is a table that lists all the Direct3D objects used by the application and their current status.

Notice the status column. Each object has a status of dead. This means that the object does not exist yet because no frames have been rendered yet. You can only view object data on objects whose status is alive. To create the objects, tell PIX to render a frame by clicking on the event you want selected (in the event window) and click on the render tab in the details view. Once you render a frame, the objects in the object view now have an alive status.

Now you can click on any object, and use the contextual menu to view information about the object.

The first item in the contextual menu opens a new tab in the details view for viewing object data. If you prefer, you can double-click on any object to open the object tab.

For example, to see the data in a texture, double-click on any texture object to get a texture tab.

There is also a tutorial that walks through these steps (see View Texture Data).

The details view has links to all of the types of objects that can be viewed.

Viewing Render Data

The render tab displays the rendered output for the currently selected frame.

Use the controls to vary the range of data displayed to make the data more visible. The render tab renders the current frame. If you have no frame selected, there is nothing to render.

See Also

User's Guide


Running PIX from the Command Line

Here are some examples launching PIX from the command line. To see a full list of the command-line options, see Command-Line Syntax.

Open a .PIXExp Experiment File

Assume the following.

  • Input: an experiment called game.PIXExp, an application to profile called game.exe
  • Output: Save the results in a run file called game1.PIXRun

Here is the syntax for running the experiment and saving the results to a run file.

PIXWin.exe game.PIXExp -targetpath game.exe -runfile game1.PIXRun -start

To change the location of where the run file will be saved, add the runfile option.

PIXWin.exe game.PIXExp -targetpath game.exe -runfile datafiles\game1.PIXRun -start

Save a .PIXRun File As a .csv File

Assume the following.

  • Input: A run file called game.PIXRun
  • Output: Save the results to a game.csv so that you can view it in Excel.

Here is the syntax for launching a run file and saving it to a .csv file.

PIXWin.exe game.PIXRun -exporttocsv game.csv

Compare Two Image Files

Assume the following.

  • Input: Two image files file1.jpg and file2.jpg
  • Output: XOR the files and save the results in diff.jpg.

Here is the syntax for opening both image files and doing a per-pixel comparison.

PIXWin.exe file1.jpg file2.jpg [-outputdiffxor diff.jpg]

See Also

PIX, Command-Line Syntax


User-Account Control (PIX)

Windows Vista includes a feature called User Account Control (UAC), in which all users including administrators run executables with standard user privilege by default. When a task requires administrative privileges, UAC shows an elevation dialog that allows the task to run with administrative privileges. UAC reduces the ability of malware to cause undesired changes to the system.

PIX Tasks Requiring Elevation

The vast majority of functionality in PIX operates under standard user privileges. A small number of tasks require administrative privileges, and require special handling by PIX.

  • GPU Timing - This feature uses Event Tracing for Windows, which requires administrative privileges. Starting any experiment which contains a Start Gathering GPU Events action will show an elevation dialog if the PIX executable isn't already running with administrative privileges.
  • Performance Counters - To view or use performance counters requires administrative privileges. In the PIX Counters dialog box, you will be unable to open the All Performance Counters section of the counters tree unless PIX is running with administrative privileges. Starting any experiment which contains performance counters will show an elevation dialog if PIX executable isn't already running with administrative privileges.
  • Shader Debugging - In order to debug Direct3D 9 vertex shaders or pixel shaders, PIX may need to disable the DXDebug Service and/or adjust some registry keys related to shader debugging. In these cases, PIX will show an elevation dialog if PIX executable isn't already running with administrative privileges.

Running PIX as Administrator

By running PIX as Administrator, the above tasks can be performed without interruption. There are several ways to accomplish this.

  1. Right-click on PIX for Windows in the Start menu, and choose Run as Administrator. You will get the elevation dialog once, then PIX will have full privileges until you exit it.
  2. Create a shortcut to PIXWin.exe. In the shortcut properties, go to the Shortcut tab, click Advanced, then check the Run as administrator checkbox. Whenever you open that shortcut, you will get the elevation dialog once.
  3. Start PIXWin.exe from a command shell that is already running as Administrator.
  4. Disable the UAC feature, using the User Accounts control panel.

Note that turning off the UAC feature removes the protection provided by UAC for all programs and all users.

The Target Program's Privileges

Keep in mind that in some cases, PIX may launch the target program with administrative privileges. This gives the target program the ability to perform system wide operations without an elevation prompt.

Differences between Windows XP and Windows Vista:

Visual Studio must also be run as an Administrator when debugging an experiment launched with Administrator privileges.

See Also

User's Guide


Tutorials

This section contains several tutorials demonstrating how to use PIX for gathering and analyzing data.

  • Collect Data with the Basic View - Collect data with an experiment using the basic view. Use the basic view to get started learning PIX.
  • Collect Customized Data with the Advanced View - Collect data using an experiment with the advanced view. This tutorial demonstrates how to choose custom triggers and actions to customize the data collected.
  • Compare Visual Quality with Screen Shots - Use screen captures to compare images between two device types and debug rendering problems.
  • View Buffer Data - View vertex buffer and index buffer data using HLSL to cast the data so that it is easily recognizable.
  • View Depth-Buffer Data - View depth-buffer data. Vary the range and internsity of the data displayed to make the data more visible.
  • View Mesh Data - View mesh data. See mesh data before and after a vertex shader runs. Launch the shader debugger to step through vertex shader code.
  • View Pixel Data with Pixel History - View every event that causes a change in per-pixel data. This includes depth, stencil and color data.
  • View Texture Data - View texture data using the texture viewer. Isolate RGB data, alpha data, or individual mip levels.
  • Debugging a Crashing Application - Use PIX to help identify problems with Direct3D usage in a Crashing Application.
  • Debugging a Pixel Shader - Set breakpoints and step through a pixel shader using the shader debugger.
  • Debugging a Vertex Shader - Set breakpoints and step through a vertex shader using the shader debugger.

See Also

PIX


Collect Data with the Basic View

This tutorial shows how to run PIX for the first time using a experiment to collect data for a single frame. The tutorial is divided into the following steps:

  • Step 1 - Launch PIX
  • Step 2 - Create an Experiment
  • Step 3 - Choose a Target Program
  • Step 4 - Choose What Data to Collect
  • Step 5 - Collect the Data
  • Step 6 - Save the PIXRun file

Step 1 - Launch PIX

Launch PIX from the start menu.

Start->All Programs->Microsoft DirectX SDK->DirectX Utilities->PIX for Windows

To launch the 64 bit version of PIX.

Start->All Programs->Microsoft DirectX SDK->DirectX Utilities (64 bit)->PIX for Windows

Figure 1. Launching PIX

Step 2 - Create an Experiment

Create a new experiment by selecting New Experiment from the File menu.

Figure 2. PIX Experiment

By default, this creates an experiment with the basic view.

Step 3 - Choose a Target Program

The target program is the application (.exe) that you would like to analyze. Enter the full path name to the target program in the text box, or use the browse button to find it.

Figure 3. Set the Target Program

This example uses the HDRCubeMap sample.

Step 4 - Choose What Data to Collect

Next, choose what data PIX will collect. Select single-frame capture using the F12 key. This tells PIX to capture all the data required to render a frame each time the F12 key is pressed.

Figure 4. Choose a single frame capture

For an explanation of the other data collection methods, see data gathering options.

Step 5 - Collect the Data

Click the Start Experiment button to start collecting data.

Figure 5. Start Experiment Button

PIX will launch the target program.

Figure 6. HDRCubeMap Sample

Wait until at least one frame has been rendered and then press F12. PIX will capture all the state and API calls made for whatever frame it is currently rendering. To end the experiment, close the target program; one way to do this is to click the window close button (the little x) in the top right corner of the target program.

Figure 7. Close Button

When the target program closes, PIX automatically opens the PIXRun file that contains the data that was collected. For help analyzing run files, see Run Files.

Step 6 - Save the PIXRun file

When you exit PIX, you will be asked if you want to save the either the experiment or the PIXRun file. Since an experiment contains all the setup information for PIX, saving an experiment allows you to reopen PIX later and repeat your setup steps. This can be handy for rerunning an experiment across different machine combinations (CPU/adapters/drivers).

The PIXRun file contains the pipeline state and object data for the Direct3D objects. It can be used to return to an event, and reproduce the exact state conditiions that led to the rendered output. A PIXRun file is a handy way to go back and examine the results of this experiment without collecting any additional data.

See Also

Tutorials


Collect Customized Data with the Advanced View

This tutorial shows how to do more advanced profiling using an advanced view of an experiment to customize triggers and actions. The tutorial is divided into the following steps:

  • Step 1 - Launch PIX
  • Step 2 - Create an Experiment
  • Step 3 - Switch to the Advanced View
  • Step 4 - Choose a Target Program
  • Step 5 - Customize a Trigger
  • Step 6 - Customize an Action
  • Step 7 - Collect the Data

To run PIX for the first time, you may want to use the basic view of the experiment instead.

Step 1 - Launch PIX

Launch PIX from the start menu.

Step 2 - Create an Experiment

Create a new experiment by selecting New Experiment from the File menu. This creates an experiment using the basic view.

Step 3 - Switch to the Advanced View

Click the More Options button to switch from the basic view to the advanced view.

Figure 1. Advanced View

Step 4 - Choose a Target Program

Click the Target Program tab. Choose the HDRCubeMap sample as the target program.

Figure 2. Target Program

Step 5 - Customize a Trigger

Click the Triggers/Actions tab. Since this is a new experiment, PIX displays a default trigger (Program Start) identified with a capital T and a single default action (Unspecified Action) identified with a capital A.

A trigger is an event that causes PIX to take an action. You can add more triggers and actions by clicking the T and A buttons in the Triggers/Actions toolbar. Multiple actions can be attached to each trigger.

To set the trigger event, select the T icon with the text program start. In the trigger type drop down select the Frame option. Enter 30 in the frame text box that appears.

This initializes PIX to trigger an event at frame 30. The next step is to associate an action with the event.

Step 6 - Customize an Action

The action defines what PIX does when the event occurs. To customize the action, select the unspecified action. In the Action Type drop down box that is displayed, select Set Call Capture. This will display a second box called Capture Type. Select single-frame capture.

This trigger/action combination tells PIX to perform a single-frame capture for frame 30.

Step 7 - Collect the Data

Click the Start Experiment button to launch the experiment.

Figure 3. Start Experiment Button

PIX will launch the target program and collect the data specified by the experiment.

Figure 4. HDRCubeMap Sample

PIX displays the current frame over the top of the upper left corner of the target program. When the current frame is greater than 30, close the target program by clicking the window close button (the x in the top right corner).

Figure 5. Close Button

When the target program closes, PIX automatically displays the PIXRun file, displaying the single-frame-capture data. Analyze the Results. For help analyzing run files, see Run Files.

See Also

Tutorials


Compare Visual Quality with Screen Shots

This tutorial shows how to use PIX to generate and compare screen shots of the target program. Screen shots are a handy way to compare how the target program looks on different device types. The tutorial is divided into the following steps:

  • Step 1 - Get a Screen Shot on a HAL Device
  • Step 2 - Get a Screen Shot on a Reference Device
  • Step 3 - Compare the Screen Shots

Setup

This tutorial uses the advanced view to create an experiment with custom triggers and actions. To set up this experiment, choose the ShadowVolume sample as the target program and select the single-frame-capture option for data collection. Modify the experiment using the steps below to save a screen shot rendered on two different device types.

Step 1 - Get a Screen Shot on a HAL Device

Use an advanced view to create an experiment for capturing a screen shot. Modify the experiment as follows.

  1. Set the trigger event to fire when frame 1000 occurs.

  2. Set the Grab Screenshot action to perform when the event occurs. Enter a file to save the screen shot in using either the browse button, or enter the full path name in the text entry box.

Click Start Experiment to run the sample and capture a screen shot.

Figure 1. Screen Shot on a HAL Device

When the frame number exceeds 1000, close the target program to end the experiment. This screen shot is rendered on a HAL device, which is the default type for an experiment.

Step 2 - Get a Screen Shot on a Reference Device

Use the same experiment to capture a second screen shot. This will require adding a second trigger/action combination to force the target program to run on a reference device.

  1. Either start from the same experiment, or begin a new experiment by creating a trigger event at frame 1000 whose action is to grab a screen shot.
  2. Create a second trigger and make sure the frame number is set to 1 (this is the default value).

  3. Select the Modify D3D Device action for this trigger. In the Device modification drop down, select Force REF, to force the target program to run on a reference device.

    Figure 2. Set a Reference Device

Click Start Experiment to run the sample and capture a screen shot.

Figure 3. Screen Shot on a HAL Device

When the frame number exceeds 1000, close the target program to end the experiment.

Step 3 - Compare the Screen Shots

At this point, you have two files saved, a screen shot at frame 1000 on a HAL device, and a screen shot at frame 1000 on a reference device. Use PIX to compare the per-pixel data.

To do a visual comparison, select Compare Images from the File menu.

Click Source 1, then click the Open button in the lower right corner to browse for the first screen shot. Then click Source 2 and do the same thing to select the second screen shot. Finally, click the Compare button.

Figure 4. Compare Per-Pixel Data Visually

The image comparison shows the differences in RGB values between the two images. Image comparison is supported for the following file types: .bmp, .emf, .exif, .gif, .icon, .jpg, .png, .tif, and .wmf.

See Also

Tutorials


View Buffer Data

This tutorial uses a vertex declaration view and a buffer view to display buffer data. Use HLSL syntax to format the buffer data so it is easily readable. The tutorial is divided into the following steps:

  • Step 1 - Select a Frame
  • Step 2 - Look Up the Vertex Declaration
  • Step 3 - Select a Vertex Buffer
  • Step 4 - Format the Vertex Buffer Data

Setup

To set up this experiment, choose the HDRCubeMap sample as the target program and select the single-frame-capture option for data collection.

Step 1 - Select a Frame

Go to the event view and select the frame that was captured (68 in this example).

Figure 1. Select a Frame in the Event View

Render the frame by clicking on the render tab in the details view.

Figure 2. Render the Frame

Step 2 - Look Up the Vertex Declaration

The vertex buffer declaration identifies the layout of the data in the vertex buffer. You will need this information to format the display of the vertex buffer data.

To see the vertex declaration, double click the vertex declaration (the blue address in SetVertexDeclaration).

Figure 3. Vertex Declaration

The vertex declaration tab displays the declaration of each data type in the vertex buffer. We will use the information from the type column in the buffer tab in a moment.

Step 3 - Select a Vertex Buffer

Double click the blue address in the SetStreamSource call. This will open a buffer tab in the details view.

Figure 4. Buffer Data before Formatting

Step 4 - Format the Vertex Buffer Data

Replace the single float in the buffer tab with the values from the type column in the order they appear.

Figure 5. Buffer Data after Formatting

See Also

Tutorials


View Depth-Buffer Data

This tutorial views depth-buffer data, using a range slider control to adjust the range of the data displayed. The tutorial is divided into the following steps:

  • Step 1 - Select the Captured Frame
  • Step 2 - Select the Depth Component to Display
  • Step 3 - Adjust the Data Range

Setup

To set up this experiment, choose the HDRCubeMap sample as the target program and select the single-frame-capture option for data collection.

Step 1 - Select the Captured Frame

Go to the event view and select the one frame that was captured (68 in this example).

Figure 1. Select a Frame in the Event Window

Render the frame by clicking on the render tab in the details view.

Figure 2. Render the Frame

Step 2 - Select the Depth Component to Display

Select depth from the channel(s) drop-down menu to display the z-component of the depth.

Figure 3. Display Depth Data

The image contains a teapot in the center that is almost too dark to see.

Step 3 - Adjust the Data Range

The slider control next to the channel(s) drop down is the channel level slider. The slider gives you control over the threshold of the data to display.

By default, the slider displays all data between 0.0 and 1.0. In this example however, the slider has been set to display only the data between 0.8 and 1.0.

Figure 4. Display Data near the Top of the Range

See Also

Tutorials


View Mesh Data

The mesh tab displays mesh data before and after transformation by the vertex shader; the data is displayed in a table as well as rendered. From the post-transformed vertices, you can launch the vertex shader debugger to walk through and debug vertex shader code.

  • Step 1 - Initialize the Mesh Tab
  • Step 2 - View Untransformed Data
  • Step 3 - View Transformed Data
  • Step 4 - Step Into the Vertex Shader

Setup

To set up this experiment, choose the StateManager sample as the target program and select the single-frame-capture option for data collection.

Step 1 - Initialize the Mesh Tab

Collect the data and open PIX in analysis mode.

  • Select a captured frame.

  • Navigate to a draw event.

  • Render the frame by clicking on the render tab.
  • Click on the mesh tab.

Step 2 - View Untransformed Data

The mesh tab opens and defaults to untransformed data, prior to the vertex shader running.

The data in the PreVS tab correspond to the data displayed in the Pre-Vertex Shader display. PIX reads the mesh input declaration and labels the data using the HLSL semantics; you can look at the data by vertex, by index, or by semantic.

Step 3 - View Transformed Data

To see the transformed mesh data, click on the PostVS tab.

This tab displays the mesh data after the vertex shader has been run. The data in this table, corresponds to the data displayed by the Post-Vertex Shader display. You can look at the data by primitive, by vertex, by index, or by semantic. The vertex data column (VTX) is filled with bold numbers with an underscore. These are links to the vertex shader that transformed the vertices. To launch the shader debugger and debug the vertex shader, click on one of these links.

Step 4 - Step Into the Vertex Shader

To step into the shader debugger and debug a vertex shader, pick a primitive and click on one of the blue, bold, underscored vertices (if you hover the mouse over a vertex Debug this vertex will pop up reminding you that this will launch the shader debugger).

The debugger tab will open displaying the vertex shader assembly code. The cursor (the yellow arrow) marking the line of code that the debugger is paused at, is on the first line of executable code.

For more information about debugging a vertex shader see Debugging a Vertex Shader.


View Pixel Data with Pixel History

This tutorial displays each event that causes a change in pixel data. Using the pixel history feature, you can track pixel data changes, see pipeline state changes, and view the corresponding shader code. The tutorial is divided into the following steps:

  • Step 1 - Launch Pixel History
  • Step 2 - View a Pixel Shader
  • Step 3 - View a Vertex Shader

Setup

To set up this experiment, choose the StateManager sample as the target program and select the single-frame-capture option for data collection.

Step 1 - Launch Pixel History

Select a pixel in the details view in the render tab

Figure 1. Rendered View of a Single-Frame Capture

Right click on the pixel, and select Debug This Pixel from the contextual menu.

The pixel history window by clicking on the contextual menu in the render tab in the details view.

Figure 2. Contextual Menu for Opening Pixel History

Here is an example of the pixel history that is displayed.

Figure 3. Pixel History

Step 2 - View a Pixel Shader

To see the pixel shader that computed the pixel data for an event, click on the pixel shader link within an event.

Figure 4. Pixel Shader Code

Step 3 - View a Vertex Shader

To see the vertex shader that computed the vertex data for an event, click on the vertex shader link within an event.

Figure 5. Vertex Shader Code


View Texture Data

This tutorial displays texture data. You can view individual mip levels and further isolate data into components such as color, alpha, or depth. The tutorial is divided into the following steps:

  • Step 1 - Select a Frame
  • Step 2 - Render the Frame
  • Step 3 - Select a Texture
  • Step 4 - Select Components to Display
  • Step 5 - Adjust the Range of the Data To Display
  • Step 6 - View Mip Levels

Setup

To set up this experiment, choose the HDRCubeMap sample as the target program and select the single-frame-capture option for data collection.

Step 1 - Select a Frame

Go to the event view and select the one frame that was captured (68 in this example).

Figure 1. Select a Frame in the Event View

Step 2 - Render the Frame

Render the frame by clicking on the render tab in the details view.

Figure 2. A Single Rendered Frame

Step 3 - Select a Texture

In the object view set the drop down menus to these values.

Drop Down | Value
Type | D3D9 Texture
Created By | Application
Format | D3DFMT_A8R8G8B8

From the list of textures, double click the second texture in the window.

Figure 3. Select a Texture

A new tab (named Texture) will open in the details view. The channel(s) drop down contains RGBA which means that all four components are displayed. A checkerboard pattern is shown in the background to highlight which areas of the texture are partially transparent.

Figure 4. Display RGBA Texture Data

Step 4 - Select Components to Display

To view color data only, select RGB from the channel(s) drop down.

Figure 5. Texture RGB Data

To view alpha data only, select alpha from the channel(s) drop down. The alpha data is displayed as a gray scale image; transparency is darker (the upper left ellipse is nearly transparent), opacity is lighter (the upper right ellipse is nearly opaque).

Figure 6. Texture Alpha Data

Step 5 - Adjust the Range of the Data To Display

The channel(s) drop down has a slider control associated with it. The slider gives you control over the threshold of the data to display.

By default, the slider displays all data between 0.0 and 1.0. In this example however, the slider has been set to display only the data between 0.8 and 1.0.

Figure 7. Control the Range of the Data to Display

Step 6 - View Mip Levels

To view individual mip levels, go to the object view and set the format drop down to all textures.

Drop Down | Value
Format | All

With all the textures displayed, find and select any texture with mip levels. That is, double click any texture that has a value greater than 1 in the mips column.

Figure 8. Select a Texture in the Object View

The details view displays the texture you selected, and shows each mip level on the left side.

By default, mip level 0 opens.

Figure 9. Texture with Mip Levels

You can view any mip level by selecting it.

Figure 10. Displaying Mip levels

Notice that the texture type and texture format are also listed.

See Also

Tutorials


Debugging a Crashing Application

In this tutorial, you will use the PIX diagnostic log to debug a crashing application. But first, you will need to take a Direct3D SDK sample and modify it so that it crashes. The diagnostic log will contain a record of all the Direct3D calls made by the target program.

  • Create a Crashing Application
  • Launch the Crashing Application from PIX
  • Generating a Diagnostic Log
  • Reading the Diagnostic Log

Create a Crashing Application

Create a crashing application by setting an uninitialized vertex shader in the render loop. To do this, comment this line of code out of the OnFrameRender function in the HLSLwithoutEffects Sample:

pd3dDevice->SetVertexShader( g_pVertexShader);

Commenting out this line of code means that the pipeline will not have a valid vertex shader. This will make rendering primitives impossible, and will cause the sample to crash. If you like, you can run the application by itself now just to show yourself that it will indeed crash.

Launch the Crashing Application from PIX

Launch PIX and specify your new crashing application (HLSLwithoutEffects.exe) as the target program. PIX will start the target application, and when the target application crashes, PIX will generate the dialog box shown in the following figure.

The dialog box specifies the file where the error occured, the line number, and the API call that is failing. It also gives you the option to either debug the target program or simply end your diagnostic session.

Generating a Diagnostic Log

If you choose to debug the target program, PIX will launch the following UI to help you determine the next step to take. In this tutorial, you know that the crash is coming from the target program, but in a real-life debugging scenario, you might instead have a perfectly good target program, and you may have uncovered a bug in PIX.

The steps listed are steps you can take to debug your target program. These are the steps you should follow to convince yourself that the target program is using Direct3D calls correctly. In general, it is good practice to enable the debug runtime and check the debug messages that are being output from the debugger. To get this same output in the form of the diagnostic log, make sure Include debug output messages is selected (it is selected by default) and click the Restart Experiment button.

PIX will relaunch the target program and output the debug messages to the diagnostic log, which will be displayed in the PIX Diagnostic Log window, like that shown in the following figure.

You can choose to discard the log, which closes the log window and returns PIX to the Unexpected Exit dialog box; or you can choose to save the log to a file by clicking Save As and providing a file name.

Reading the Diagnostic Log

The following text shows an example of the debug output that goes into the log.

Frame 000001 ........PRE: <this=0x02c23008>IDirect3DDevice9::BeginScene()
Frame 000001 ........POST: <S_OK><this=0x02c23008> IDirect3DDevice9::BeginScene()
Frame 000001 ........PRE: <this=0x02c23008>IDirect3DDevice9::SetVertexDeclaration(0x02C99488)
Frame 000001 ........POST: <S_OK><this=0x02c23008> IDirect3DDevice9::SetVertexDeclaration(0x02C99488)

This part of the log shows two API calls, BeginScene and SetVertexDeclaration. The log records the rendering frame where these API calls were made and the return value of each API call. Both of these methods returned S_OK; there were no problems with these API calls.

Skipping down to the bottom of the log, you can see the following entry:

Frame 000001 ........PRE: <this=0x02c23008>IDirect3DDevice9::DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 4096, 0, 7938)
Direct3D9: Decl Validator: X247: (Element Error) (Decl Element [0]) Declaration can't map to fixed function FVF because position must use D3DDECLTYPE_FLOAT3.
Direct3D9: Decl Validator: X288: (Global Error) Declaration can't map to fixed function FVF because position field is missing. Usage: D3DDECLUSAGE_POSITION, with usage index 0 is required for fixed function.
Direct3D9: (ERROR) :DrawIndexedPrimitive failed.

Frame 000001 ........POST: <D3DERR_INVALIDCALL><this=0x02c23008> IDirect3DDevice9::DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 4096, 0, 7938)
c:\program files\microsoft directx sdk (april 2007)\samples\c++\direct3d\hlslwithouteffects\hlslwithouteffects.cpp(431): pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, g_dwNumVertices, 0, g_dwNumIndices/3 ) hr=D3DERR_INVALIDCALL (0x8876086c)
An unhandled exception occurred.

This is the error caused by removing our vertex shader. Notice that the PRE marker includes the following debug message:

Direct3D9: (ERROR) :DrawIndexedPrimitive failed.

And looking at the POST marker, you can see the following debug message:

hr=D3DERR_INVALIDCALL (0x8876086c)
An unhandled exception occurred.

The problem, therefore, is that DrawIndexedPrimitive failed because there was no valid vertex shader.

See Also

Tutorials


Debugging a Pixel Shader

This tutorial illustrates shader debugging including: setting breakpoints, stepping through shader code and watching register values.

Setup

To set up this experiment, choose the BasicHLSL10 sample as the target program and select the single-frame-capture option for data collection.

  • Step 1 - Launch the Shader Debugger
  • Step 2 - View Shaders in HLSL or Assembly
  • Step 3 - Set a Breakpoint
  • Step 4 - Stepping Through Shader Code

Step 1 - Launch the Shader Debugger

The shader debugger is launched from the debugger tab while viewing pixel history.

To debug a pixel shader, click on the Debug Pixel (x,y) link. (If you do not know how to access pixel history, see step 1 in View Pixel Data with Pixel History).

Step 2 - View Shaders in HLSL or Assembly

Differences between Direct3D 9 and Direct3D 10:

If you are programming with Direct3D 9, use PIX to debug shaders in assembly. If you are programming with Direct3D 10, use PIX to debug shaders in either assembly or HLSL.

Step 2a - View Direct3D 10 Shaders in HLSL

The debugger tab will open to display the shader HLSL code. The lower section is blank but will be filled in with the contents of shader variables when the debugger stops on a line of shader code that uses variables.

The debugger is stopped on the first executable line in the shader; it is marked by the yellow arrow. The variables displayed are the variables used within this line of code.

Step 2b - View Direct3D 9 and Direct3D 10 Shaders in Assembly

Click on the Disassembly tab to view the shader assembly code. The lower section is blank but will be filled in with the contents of the shader registers when the debugger stops on a line of shader code that uses registers.

The debugger is stopped on the first executable line in the shader; once again marked by the yellow arrow.

Step 3 - Set a Breakpoint

To set one or more breakpoints, click down to the left of the line of shader code.

A red dot will appear marking the breakpoint. (Click on a breakpoint to remove it)

Step 4 - Stepping Through Shader Code

Use the buttons on the toolbar to navigate through shader code.

See Also

Tutorials


Debugging a Vertex Shader

This tutorial illustrates vertex shader debugging including setting breakpoints, and stepping through vertex shader code, watching register values. The tutorial is divided into the following steps:

Setup

To set up this experiment, choose the BasicHLSL10 sample as the target program and select the single-frame-capture option for data collection.

  • Step 1 - Launch the Shader Debugger
  • Step 2 - View Shaders in HLSL or Assembly
  • Step 3 - Set a Breakpoint
  • Step 4 - Stepping Through Shader Code

Step 1 - Launch the Shader Debugger

The shader debugger can be lauched to debug a vertex shader from two places.

Step 1a - Launch the Shader Debugger from Pixel History

The vertex shader debugger can be launched from the Pixel History tab.

To debug a vertex shader, click on any Debug Vertex link in a draw event.

Step 1b - Launch the Shader Debugger from the Mesh Tab

Differences between Direct3D 9 and Direct3D 10:

If you are programming with Direct3D 9, you can launch the vertex shader debugger from the mesh tab. If you hover your mouse over an underlined vertex, the Debug this vertex popup will display. Click on this to open the shader debugger.

Step 2 - View Shaders in HLSL or Assembly

Differences between Direct3D 9 and Direct3D 10:

If you are programming with Direct3D 9, use PIX to debug shaders in assembly. If you are programming with Direct3D 10, use PIX to debug shaders in either assembly or HLSL.

Step 2a - View Direct3D 10 Shaders in HLSL

The debugger tab will open to display the shader HLSL code. The lower section is blank but will be filled in with the contents of shader variables when the debugger stops on a line of shader code that uses variables.

The debugger is stopped on the first executable line in the shader; it is marked by the yellow arrow. The variables displayed are the variables used within this line of code.

Step 2b - View Direct3D 9 and Direct3D 10 Shaders in Assembly

Click on the Disassembly tab to view the shader assembly code. The lower section is blank but will be filled in with the contents of the shader registers when the debugger stops on a line of shader code that uses registers.

The debugger is stopped on the first executable line in the shader; once again marked by the yellow arrow.

Step 3 - Set a Breakpoint

To set one or more breakpoints, click down to the left of the line of shader code.

A red dot will appear marking the breakpoint. (Click on a breakpoint to remove it)

Step 4 - Stepping Through Shader Code

Use the buttons on the toolbar to navigate through shader code.

See Also

Tutorials


Reference

PIX can be run from a user interface or from the command line (as PIXWIN.exe).

  • The PIX for Windows Application - Use the user interface to prepare experiments, collect data, and analyze the collected data.
  • PIX Functions - Add these optional functions to your target program to customize the presentation of the data that PIX collects.

See Also

PIX


The PIX for Windows Application

PIX implements a user interface for collecting and analyzing data.

  • PIX Main Window - The PIX main window is the first thing that the user sees when running PIX. The window is the starting point for creating experiments, opening PIXRun files, and comparing images.
  • Event-Trace Files - Event trace files capture and store GPU events so that the GPU timeline can be displayed.
  • Experiment Files - PIX uses an experiment to save and restore initial conditions before collecting data. There are two views for configuring an experiment: a basic view, which contains default settings to get you started, and an advanced view that allows you to completely customize the data that you want PIX to collect.
  • Image Files - Render frames and save them as screen shots; then, use PIX to compare image quality between frames to debug rendering problems.
  • Run Files - Once you have generated data for analysis (by using an experiment), PIX implements several views for analyzing the data. Some views display information that is meaningful to all API calls (such as statistics), while other views display object-specific data into the pipeline data and pipeline state stored in the many Direct3D objects.
  • Diagnostic Log - To help debug a crashing application, use the diagnostic mode. In the diagnostic mode, PIX generates a log of all the Direct3D calls made prior to the crash.
  • Command-Line Syntax - Use the command line to run PIX.

See Also

Reference


PIX Main Window

The PIX main window opens when a user launches PIX. It contains controls for starting new experiments, loading experiments, and setting PIX options.

The main window supports these drop-down menus.

  • File Menu
  • Edit Menu
  • View Menu
  • Window Menu
  • Help Menu

The main window also has a toolbar with icons for frequently used functions.

File Menu

Use the file menu to create new files, open existing files, or exit PIX.

Menu Item | Decription
New Experiment | Open a new experiment window.
Open | Open a saved PIX experiment or a full-stream capture.
Playback Stream | Playback a previously captured full-stream capture.
Compare Images | Compare two images.
Exit | Exit PIX

Edit Menu

Use the edit menu to cut, copy, and paste information on the clipboard and to search for events.

Menu Item | Decription
Undo | Undo the last action.
Cut | Cut the selected text.
Copy | Copy the selected text.
Paste | Paste the selected text.
Find Event | Find an event using a text search.
Go To Event | Go to an event using an event ID.

View Menu

Use the view menu to control what PIX displays. You can toggle toolbars on or off, or control the information that PIX displays while it is running.

Menu Item | Description
Toolbar | Toggle the Toolbar on and off.
Status Bar | Toggle the Status Bar on and off.
Options | Open more Options.

The Options menuitem opens a dialog box with additional options. See Options Dialog Box.

Window Menu

Use the window menu to arrange (and optionally save) the layout of information within a file; the menu also has options for displaying multiple files.

Menu Item | Decription
Cascade Windows | Display run files, one on top of each other, diagonally offset, with the most recently opened on top.
Tile Windows Horizontally | Display run files in left-to-right order.
Tile Windows Vertically | Display run files in top-to-bottom order.
Arrange Icons | Arrange the toolbar icons in the default order.
Arrange Panes in Standard Layout | Display panes in the default layout.
Arrange Panes in Custom Layout | Display panes in a previously-saved custom layout. See
Save As Custom Pane Layout | Save the current pane in a custom layout.

Help Menu

The help menu provides a link to help on PIX, as well as to version information for PIX.

Menu Item | Description
Help Topics | Open the help documentation for PIX.
About PIX | Display PIX version information.

Toolbar

The toolbar contains icons for quick access to frequently used features.

Icon | Function
 | Open a new experiment window.
 | Open an experiment file, a run file, or an image file.
 | Save an experiment.
 | Cut selected text.
 | Copy selected text.
 | Paste selected text.
 | Start an experiment.
 | Open PIX help.

See Also

Reference


Options Dialog Box

The Options menuitem opens the following dialog box.

General Options

General options | Description
Automatically open run files after data gathering is complete | Automatically open a run file after closing the target program.
Maximize window when opening run file | Maximize the window when it opens.
Never use Basic View for experiments | Create an advanced view of an experiment when a new experiment is created.

Overlay Options

PIX information overlay options | Description
Show PIX logo | Display the PIX logo while collecting data.
Show statistics (frame, time, file size) | Display statistics while collecting data.
Show informational messages | Display information messages while collecting data.
Show error messages | Display error messages while collecting data.
Overlay Location | Locate the overlay on top of the target program in one of the following: Upper-left, Upper-right, Lower-left, or Lower-right
Overlay Size | Make the overlay either large or small.

Timeline Options

This control adjusts a value that PIX uses to determine which GPU events apply to which frames. The default value is 100000 ns; it is recommended that you not adjust this value.

See Also

Reference


Custom Layouts in PIX

PIX supports custom layouts. A custom layout is a description of window sizes and positions when a file is displayed. You can save up to three custom layouts.

To save a custom layout, click on Window, then mouse over the Save As Custom Pane Layout entry. This will open the custom layout drop down menu.

Each time you save a layout, it goes from grayed out to active in the drop down box. You can also use shortcut keys CTRL+1, CTRL+2, or CTRL+3 to change between layouts.

To restore a custom layout that you have previously saved, click on Window, then mouse over the Arrange Panes in Custom Layout menuitem.

When PIX starts for the first time, it defaults to a standard layout that displays the timeline, object view, event view and detail view.

To return to the standard layout that PIX opens with, click on Window, then mouse over the Arrange Panes in Standard Layout menuitem.

See Also

Reference


Event-Trace Files

Starting with the June 2007 DirectX SDK, the timeline view displays GPU timing. This is done by capturing events using Windows Event Tracing.

When PIX is running, events are stored in an events-trace log or .etl file. The events are used by PIX during analysis to reconstruct the GPU timeline display. To share the results of a PIX experiment between computers, you must copy both the run file and the event-trace file; if you forget the event-trace file, the timeline cannot display the GPU timeline information.

Differences between Windows XP and Windows Vista:

Event files are only available in Windows Vista or a later operating system.

See Also

The PIX for Windows Application


Experiment Files

An experiment file is a collection of settings that identifies the program that PIX will profile and how it will collect data for analysis. There are two ways to view an experiment: with a basic or an advanced view.

  • Experiment - Basic View - Provides an easy way to get started, because PIX uses many default options.
  • Experiment - Advanced View - For more advanced users who want to customize the data collected.

PIX uses counters to collect data. After you run an experiment and collect data, you can save the results in a run file for analysis.

See Also

Reference


Experiment - Basic View

The basic view of an experiment is the easiest way to get PIX up and running. It only requires two pieces of information to be entered by the user: the target program to profile and how to gather the data. Here is a tutorial that creates an experiment using the basic view. If you want more control over the types of data that can be collected, use the advanced view instead.

To create an experiment using the basic view, select New Experiment from the file menu.

There are two sets of information to enter in the basic view.

  • The Target Program to Profile
  • Information Gathering Options

There are also two buttons in the basic view.

  • Start Experiment
  • More Options

The Target Program to Profile

A target program is an application that you create that uses Direct3D, that you would like to analyze. Enter the path to the target program (or use the browse button) in this text box.

PIX uses this information to automatically launch your program when you start the experiment. If you specify a run file as the target program, PIX will play the run file.

Information Gathering Options

There are several kinds of information PIX can gather.

Information Gathering Options | Description
Statistics for each frame | Count the number of Direct3D and D3DX API calls.
Single-frame capture | Capture API calls, associated pipeline state, and object references within a single frame. A single frame capture can be saved in a run file and replayed.
A log of all Direct3D/D3DX calls made in frame number | List all the Direct3D and D3DX API calls made in a single frame.
A replayable Direct3D call stream | Collect a full-stream data capture, with all the events and pipeline state. This option can be saved in a run file and replayed. This is equivalent to a single-frame capture for all frames. It is the best option for doing a full analysis.

Differences between Windows XP and Windows Vista:

You must be running Windows Vista to gather GPU timing data. If you choose to gather statistics for each frame, the data is automatically gathered; otherwise, you must enable the data collection by adding the appropriate actions in the advanced view.

More Options

This button switches from the basic view to the advanced view.

Use this option when you want to customize the data you collect.

Start Experiment

The start experiment button launches the program and begins gathering data.

See Also

Experiment Files


Experiment - Advanced View

An advanced view of an experiment gives you more control over the data collected than a basic view.

  • Triggers and Actions Tab - Create triggers to fire on certain events; assign one or more actions when each trigger fires.
  • Target Program Tab - Identify the target program and any start-up options.
  • Buttons - Use buttons to toggle between experiment views or to run the experiment.

Triggers and Actions Tab

The advanced view uses triggers and actions to customize data collection.

Triggers

Triggers are events that fire at a certain time. To profile a target program, first decide what you want to measure and how often you want to measure it. Then, choose a trigger that occurs when you want a measurement taken. You can choose from the types of triggers shown in the following table.

Triggers | Description
Program Start | Fires when the target program starts.
Frame | Fires at the beginning of the specified frame.
Time | Fires after this much time has passed after the target program starts.
User Marker | Fires when the target program calls D3DPERF_SetMarker with the marker name.
Begin User Event | Fires when the target program calls D3DPERF_BeginEvent with the begin-event name.
End User Event | Fires when the target program calls D3DPERF_EndEvent to end the event with the end-event name.
Key Combination | Fires when the user types the keystroke combination specified.

PIX checks triggers based on time and key combinations at the beginning of each frame; once a target program stops rendering, these triggers are no longer processed.

Actions

PIX takes one or more actions each time a trigger event occur. There are several types of actions available.

Actions | Description
Create a run file | Save the data collected in a run file. Select the Disable write caching option to write data immediately to disk (this is useful when the target program crashes).
Grab a screen shot | Save the frame buffer to an image file. See the file save options.
Modify Device | Toggle between a hardware accelerated device and a reference device when the device is created.
Modify Draw Calls | Enable or disable draw calls. There are three options: Normal - allows all draw calls, Block all - disables all draw calls, Block back buffer calls - Disables draw calls to the back buffer (This can be a handy speed up).
Post Window Message | Send Windows messages to the target progam.
Save Device State | Save device state to an HTML file after the next device interface API call executes. See the file save options.
Set Call Capture | Capture all the Direct3D/D3DX calls. The capture types are listed in the data gathering options in the basic view.
Set Per-Frame Counters | Select counters for collecting data.
Start Gathering GPU Events Gather GPU events.

Differences between Windows XP and Windows Vista:

This event is only available on Windows Vista.

Gathering may fail if a previous launched experiment failed to stop gathering GPU events before PIX was closed. (This might occur if PIX crashes or is closed with the task manager). To re-enable data gathering, either:

  • Reboot the computer or,
  • Set a Stop Gathering GPU Events action before a known crash point.
Stop Gathering GPU Events Stop accummulating GPU events; this event is called implicitly when PIX is closed normally.

Differences between Windows XP and Windows Vista:

This event is only available on Windows Vista.
Terminate Program | End the target program. Terminating an experiment causes PIX to stop collecting data and close the run file. Terminating a run file closes PIX entirely.

File Save Options

There are several options for saving a file.

  • Path to screen shot - Supply the folder and file name (do not include the file extension). The step feature automatically increments file names by inserting pound characters (#) as placeholders for digits in the file name. For example, to record to files names like C:\Image0001.bmp and C:\Image0002.bmp, specify C:\Image#### for the path.
  • File Type - The three-letter extension.
  • Overwrite - Overwrite an existing file.
  • Hide Cursor - Hide the mouse cursor.
  • Increment Type - The extension to apply to the file name.
    • None - Write to the same file name
    • Frame - Insert the current frame number
    • Step - Insert an increasing number

Trigger and Action Buttons

The event view has a toolbar with the push-button controls. Use event-view controls to toggle the display of data and navigate between events.

Symbol | Name | Description
 | Add Trigger | Create a new trigger.
 | Add Action | Create a new action.
 | Move Up | Swaps the position of the current Trigger or Action with the previous Trigger or Action in the tree.
 | Move Down | Swaps the position of the current Trigger or Action with the next Trigger or Action in the tree.
 | Delete | Deletes the currently selected Trigger or Action.

To modify a trigger (or an action), select the trigger (or the action) and use the corresponding drop down box to select an entry.

Target Program Tab

The target program tab is the place to enter information about the target program and how to launch it. On this tab, specify the path, startup folder, and command-line arguments for the target program.

In some situations, the application launched might be a helper program that launches the application that is to be analyzed. In this situation, set a number in Skip processes before gathering to tell PIX which application to analyze.

Field | Description
Program path | The target program, including the full file path.
Startup folder | The folder to run the target program in.
Command-line arguments | Command-line arguments to pass to the target program.
Skip processes before gathering | List of processes to ignore when PIX is collecting data. Use this option when the target program is a helper program that launches the actual target program to be analyzed.
Record a diagnostic log | Log the entry and exit of every API call that PIX monitors in a text file. The log may be helpful if the target program exits unexpectedly while PIX is analyzing it.
Include debug output messages in diagnostic log | Record all debug output along with the API entry/exit information in the diagnostic log. This item is grayed out until the diagnostic log is enabled.
Disable D3DX analysis | Prevent PIX from analyzing D3DX calls. This can speed up analysis and avoid problems that may occur with some D3DX functions.

Buttons

The advanced view also has a couple of buttons.

Use the Fewer Options button to toggle between a basic view and an advanced view.

Use the Start Experiment button to launch the target program and start collecting data.

See Also

Experiment Files


Counters

PIX contains a number of counters for collecting and displaying information. The counters are configured in an experiment file, which also identifies the program to be profiled, to capture information while your target program is running.

  • Selecting Counters for an Experiment Using the Basic View - Choosing counters for an experiment using the basic view is pretty simple.
  • Selecting Counters for an Experiment Using the Advanced View - Choosing counters for an experiment using the advanced view gives you much more flexibility on the data you collect.

Differences between Windows XP and Windows Vista:

To view and gather data with performance counters, Windows Vista may require you to be running PIX as an Administrator.

Selecting Counters for an Experiment Using the Basic View

If you are using a basic view, there is only one data-gathering option that supports counter selection, and that is to collect statistics for each frame. Select this option and the Draw_Submission counter set will appear in the dialog box.

Click on the drop-down arrow to display the counter options.

There are several choices:

  • Draw_Submission - Count API call associated with rendering.
  • Initial_Run - Count basic events, suitable for running a target program for the first time.
  • IO_Pass - Count the events associated with reading and writing resource data.
  • Resource_Usage - Count the events associated with using resources.

Selecting Counters for an Experiment Using the Advanced View

The Advanced View is designed to allow you to customize the counters you use to collect data. To customize the counters, click on the customize button in the Triggers/Actions tab.

The top half of the PIX Counters window shows all of the available counters and the counters you have selected for your experiment. Select a counter on the left side and click the Add button to add the selected counter to the list of chosen counters on the right side; select a counter on the right side and click the Remove button to remove the counter from the list of chosen counters.

Counter Sets

Notice that when you select a counter from the available counters list (such as Direct3D counters), that many counters are displayed in the chosen counters list. This is because each of the available counters is actually a group of counters called a counter set. Each of the data gathering options in the basic view use a predefined counter set to collect data. An advanced view lets you specify individual counters, sets of counters, or both.

PIX supports the following counter sets:

  • Direct3D Counters - Report information specifically about Direct3D.
  • Performance Counters - Report overall performance information.
  • Plug-in Counters - Report custom information, returned by third party plug-ins.

Direct3D Counters

Direct3D counters keep track of Direct3D API calls, and they consist of the types shown in the following figure.

  • General - Track simple metrics, including frames per second and number of calls per frame.
  • Primitives - Count the number of draw calls.
  • Resources - Keep track of memory allocation and object creation.
  • State Changes - Count the number of state changes.
  • Shader Constant Changes - Count the number of shader constants.

Performance Counters

Performance counters track overall performance of the target program, and they consist of the types shown in the following figure. There are several to choose from.

Plug-in Counters

PIX supports third-party plug-ins with custom counter sets. A third-party plug-in must be implemented in a separate DLL. See the sample program PIXPluginSample (in <SDK root>\Samples\C++\Misc\PixPluginSample) for an example of how to create a plug-in.

Creating Custom Counter Sets

If you choose to create your own counter set, choose the counters that you want and click Save As Counterset. After naming it, your counter set will appear in My Countersets.

The first time that PIX runs, it uses the four default counter sets shown in the preceding figure. At any time, you can rename or remove counter sets by right clicking on the name of the set and selecting the appropriate action.

See Also

Experiment Files


Image Files

Use PIX to compare the per-pixel values between two images using the image viewer. Launch the image comparison tool by selecting Compare Images from the file menu.

The image viewer looks like the following figure when it opens.

Image Loading Controls

To compare images, you must first load them.

To load an image

  1. Click one of the source buttons, Source 1 or Source 2, as shown in the following figure.

  2. Click on the browse button, as shown in the following figure (the image of the open folder), and select a file.

Remember to load a second image for comparison.

Image Comparison Controls

The toolbar of the image comparison tool provides buttons, as shown in the following figure, for manipulating images.

The following table shows and describes the functions of this toolbar.

Button | Action
 | Draw on the image.
 | Erase anything drawn by the pen.
 | Fit the image to the window.
 | Draw the image full size.

In the toolbar of the image comparison tool, you specify the type of comparison to make by selecting it from the drop-down box shown in the following figure.

This selection specifies the logical operation to use in the comparision of corresponding pixels in the two images. These operations are described in the following table.

Operation | Action
XOR | Exclusive OR.
SUB | Subtract the pixels in source 2 from source 1.
XNOR | Exlusive OR, then invert the pixels.

See Also

The PIX for Windows Application


Run Files

A PIX run file, identified by the file extension .PIXRun, contains data that is collected during an experiment. Frame statistics, call logs, and full call-captures can be stored as run files. Data gathered and stored in a run file can be read by subsequent PIX experiments or used to reproduce a suspected bug.

To analyze and debug the information contained in a run file, PIX implements several different views.

  • Event View
  • Object View
  • Timeline View
  • Details View

The views are displayed by various panes; you can control the arrangment and sizing of these panes (see Custom Layouts).

Additional Views for Objects

The Details view supports additional tabs for viewing objects. When the details view opens for the first time, a Summary tab, a Render tab, and a Mesh tab are displayed. However, you can create any of the following tabs to view other object types:

  • Buffer Tab
  • Pixel History View
  • Shader-Debugger View
  • Device Tab
  • Shader Tab
  • State-Block Tab
  • Surface Tab
  • Texture Tab
  • Vertex-Declaration Tab

See Also

The PIX for Windows Application


Event View

The event view lists the events captured by an experiment. Events are displayed in a table with one event per row. Initially, the event window displays one frame per row, and method calls that are captured during each frame are collapsed under that frame event. Expand each frame to display the events captured within that frame.

The following figure shows an example in which Frame 1 is expanded.

Expanding or collapsing a frame causes the frame to be displayed differently in the timeline view.

Event Toolbar

The Events view has a toolbar with the push-button controls shown in the following table. Use event-view controls to toggle the display of data and navigate between events.

Symbol | Name | Description
 | Pointers | Display object pointers.
 | Return Value | Toggle the display of API call return values.
 | Current Frame | Move forward (up) or backward (down) one frame
 | Draw Call | Move forward (up) or backward (down) to the next draw call.
 | Event ID | Go the the specified event ID.
 | Search | Search for a text string, including a memory address.

Use the toolbar to help navigate the event data and change what is displayed in the window. Use the pointers button to display (or hide) the this and ppObj pointers. Use the search button to search for specific events. For instance, you can search for an API call, or a memory address within the event view.

Event Table

The Events view displays the captured events in a table, the components of which are described in the following table.

Column Name | Description
EID | Event ID, which is a unique integer value.
Event | Event description.
Start Time | Event start time in nanoseconds (ns). This time is measured from the time the application was started.
Frame | Frame number
Duration | The amount of CPU time to process a frame.
FPS | Frames per second

An event description is dependent on what happens in that event. It could be simply a frame number, or it could be an API call and its associated input parameters. If you captured all the pipeline states in the experiment, the input parameters that represent objects in memory are shown with a blue address (a black address means there is no object data). To view each object, right-click on the blue memory address and select a view option. Doing so open a tab in the Details view.

See Also

Run Files


Object View

The Objects view displays Direct3D objects created by the target program. Use this view to quickly find and open objects.

The Objects view displays each object in a large table with one object per row. Any object that contains state information (whose status is Alive) can be viewed in the Details view, by right clicking on the open and selecting view from the contextual menu that opens.

Object Table

By object view displays the following object properties.

Column Name | Description
Address | Address of the object in memory.
Type | The Direct3D object type.
Created By How the object was created. The choices are:
  • Application (the target program)
  • D3DX
  • Direct3D
Creation | The number of the frame when the object was created.
Destruction | The frame number when the object was destroyed.
Status | Alive or Dead. Alive means at least one render event has occurred after the event was created; dead otherwise. Objects initially have a Dead status.
App Refs | The number of references that the target program holds for that object.
Size | Size of the object (in bytes).
Pool | The memory pool the resource was created in. For Direct3D 9 objects, see D3DPOOL.
Usage | The resource usage. For Direct3D 9 objects, see D3DUSAGE.
Format | The resource data format. For Direct3D 9 objects, see D3DFORMAT.
Width | Width (in pixels)
Height | Height (in pixels)
Depth | Depth (in pixels)
Mips | The number of mip levels

The status bar at the bottom of the table displays the number of objects displayed as well as the total number of objects.

Object Controls

You can use the following options to configure the data that is displayed in the table:

  • Display an Object
  • Sort or Filter Column Data

Display an Object

An object can only be selected if it is active (the status column for the object shows alive status). Objects are active only after PIX has rendered at least one frame. To activate all objects, click the render tab in the details view.

To select an object, right click on it to display a contextual menu.

The contextual menu display the static properties which are grayed out. The menu also contains a View menu. Click on the view menu to display the object in the details view. If you prefer, you can double click an object to view it.

Sort or Filter Column Data

Each column has a down arrow located above and to the right of the column. The arrow button filters and sorts the column data. For example, here is the drop down for the Creation column.

The first two options are sorting options.

  • Sort Ascending - Sort the column data from lowest to highest.
  • Sort Descending - Sort the column data from highest to lowest.

The remaining entries are filtering options. The filter options depend on the type of information in the column. In this example, the filtering options are:

  • (All) - Filter nothing, display all data.
  • Application - Only display objects created by the target program.
  • Direct3D - Only display objects created by Direct3D.
  • D3DX - Only display objects created by D3DX.

See Also

Run Files


Details View

The details view displays whatever information you ask PIX to display. The information displayed is separated into different tabs; click on each tab to see that view of the information.

  • Summary Tab - Displays basic information about the data collected.
  • Render Tab - Displays the output render target data.
  • Mesh Tab - Displays mesh data at various pipeline stages.
  • Object Tabs - Optional tabs for displaying object data. These tabs are only displayed when you request them.

Summary Tab

The default details view contains information about basic information about the PIX data that is displayed.

By default, the details view always displays the summary tab, the render tab, and the mesh tab.

Render Tab

The render tab displays the rendered output of the current frame. Use it to view the rendered output of any frame, and the launch the shader debugger.

Mesh Tab

The mesh tab displays mesh data before and after shader processing.

Object Tabs

The details view displays a new tab each time you select a new object to view. Each tab displays detailed object data on an object. The following object types can be viewed.

  • Buffer Tab
  • Device Tab
  • Shader Tab
  • State-Block Tab
  • Surface Tab
  • Texture Tab
  • Vertex-Declaration Tab

To view a new object, select the object in the object view or click an event with a blue pointer in the event view. The next time you view the same object, the object tab will already exist in the details view. To close a tab, click the black x to the right of the tab.

See Also

Run Files


Render Tab

The Render tab displays the rendered output of the current frame. The Render tab is always present in the Details view.

To render a frame, select the event that you want rendered, and click on the Render tab. Only those frames with a full-stream capture can be rendered. Such frames are displayed in bold type in the Events view.

Navigate between frames using the previous/next frame controls in the event view.

The render tab has two types of controls: common controls, for sizing an image or saving information, and Render tab controls for changing the rendered display.

  • Common Controls - common controls for sizing an image, or saving information to a file.
  • Render Tab Controls - controls for changing the rendered display.

Common Controls

Common controls perform common operations, like zooming and file saving. The following table shows and describes the buttons of the common controls.

Symbol | Name | Description
 | Zoom In | Enlarge the image.
 | Zoom Out | Shrink the image. You can also click down on the image, and then change the mouse wheel to zoom.
 | Fit Image | Zoom (in or out) until the image is completely visible.
 | Full Size | Reset the zoom to display the image at its normal size.
 | Save | Save the image to a file.
 | Wire Frame | Render any object(s) in wire frame.

To save a file, either click on the Save button, or right-click on the Render tab and select Save Picture As, as shown in the following figure.

Render Tab Controls

Render controls adjust the range of data displayed to make the data more visible.

The toolbar also contains a slider that controls the brightness of rendered objects that have been drawn previous to the current frame event.

Symbol Name Description

Previous Draw Brightness Specifies how bright to display draws that occurred earlier in the frame. Dragging the slider to the left decreases the brightness of previously drawn objects; dragging the slider to the right increases the brightness. Using this slider with the event view can help identify what objects are drawn by each draw call.

Channels Specifies the channels of the image to display. The channels available are:
  • RGB
  • Red
  • Green
  • Blue
  • Depth

If Alpha Channels are used in the scene, these channels are also available:

  • ARGB
  • Alpha

Channel Level Specifies the range of values to focus on. The minimum and maximum values of the range are specified by dragging the small triangles at the top and bottom of the slider. These values can also be directly specified by right-clicking on the control and entering values. Values close to the top of the range will be lighter and those that are closer to the bottom will be darker. Values greater than the top of the range will be completely white while those less than the bottom of the range will be completely black.

To adjust the minimum and maximum levels, right-click on the channel level control, and then click Adjust Min/Max, as shown in the following figure.

Doing so opens the dialog box, shown in the following figure, for setting the min/max levels.

See Also

Details View


Buffer Tab

A buffer tab displays the contents of a buffer. Use this tab to view the data in a vertex or index buffer.

The buffer tab has two sub-tabs: Buffer and Layout.

Buffer Sub-Tab

Buffer data is displayed in a table in the Buffer sub-tab; the default format is a single column of floats. Here are two methods for creating a buffer tab.

  • Click the memory address of a vertex buffer or index buffer (the memory address must be blue) in the event view.
  • Right-click a vertex buffer or index buffer (whose status is Alive) in the object view and select the view menuitem.

Layout Sub-Tab

Use the Layout sub-tab to format the display of data in the Buffer sub-tab. The Layout sub-tab is looking for a vertex (or index) buffer declaration to identify the layout of the data in the buffer. The easiest way to do this is to use HLSL syntax as if you were writing shader code.

The format is specified with type/name pairs such as:

float3 position

For instance, to format the Buffer sub-tab to display a buffer with position, normal and texture data (as shown in the figure at the beginning of this topic), you could use a declaration like that shown in the following figure.

The layout sub-tab does not require exact HLSL syntax, but you do need to use valid HLSL basic types. The variable names you assign are arbitrary. If the size of the buffer being displayed is not a multiple of the size of the of the HLSL types specified, an error message will be displayed.

The Layout sub-tab supports all the HLSL data types, including vectors and matrices. All of the following are valid type/name pairs:

float3
vector<uint 3>
float3x3
matrix<xshort,2,2>

In the table, some of the types are displayed differently:

  • A basic pair is displayed as a single column.
  • A vector pair is displayed as multiple columns grouped together.
  • A matrix pair is displayed as a column containing subtables.

The Layout sub-tab also supports the following type modifiers:

s = signed
u = unsigned
x = unsigned hex

Customizing the Layout

To assign a format to a type/name pair, but not display the data, use a percent sign between the type/name declaration; for example:

float3 % position

The type/name pair will be used as a placeholder, but the pair will not be displayed.

See Also

Details View


Debugger Tab

The Debugger tab supports two different views: the pixel-history view and the shader-debugger view. The pixel-history view displays the events that cause changes in pixel data as well as links for launching the shader debugger.

Figure 1. Pixel-History View

The pixel history view is displayed when the Debugger tab is first opened.

From the pixel history view, each draw event contains links for debugging vertex and pixel shaders. If you click on one of these links, the debugger tab will display the shader-debugger view.

Figure 2. Shader-Debugger View

Use the shader-debugger view to debug vertex and pixel shaders.

See Also

Details View


Pixel History View

Pixel history is an event by event record per-pixel render target data. The Debugger tab displays the pixel-history view the first time it is opened.

Display the Pixel-History View

To create a pixel-history tab, right-click on a particular pixel in the Render tab.

Select Debug this pixel from the contextual menu to create (or open an existing) debugger tab, which will display the pixel-history.

If you need more help opening the Debugger tab to display pixel history, see View Pixel Data with Pixel History.

Launch the Shader Debugger

Pixel history is one place where you can launch the shader debugger for vertex and pixel shaders. Shaders are invoked by draw calls, so you need to find a draw event to see the shaders that were executed by the draw event.

Each draw event contains RGBA data values output by the pixel shader as well as written into the frame buffer. The event also contains pointers for the vertex and pixel shaders and links to open the shader debugger (Debug Vertex and Debug Pixel). For more information about debugging shaders, see the shader debugger.

See Also

Debugger Tab


Shader-Debugger View

The debugger tab displays the shader-debugger view when you click on a vertex shader or pixel shader link (launch the shader debugger). The shader-debugger view supports debugging shaders including setting breakpoints and stepping through shader code while watching register contents. Open the shader debugger for a pixel shader from the pixel-history tab (see Debugging a Pixel Shader); open the shader debugger for a vertex shader from pixel-history or the mesh tab (see Debugging a Vertex Shader).

  • View Shader Code in the Code View
  • View the Contents of Registers and Variables
  • Navigate the Code View with the Toolbar
  • Set Breakpoints in the Code View
  • Best Practices for Debugging Shaders

View Shader Code in the Code View

The code view displays the shader code.

Differences between Direct3D 9 and Direct3D 10:

If you are developing in Direct3D 10, the HLSL (or effect) code is viewable in PIX. Both Direct3D 9 and Direct3D 10 shaders are viewable in assembly with PIX.

The debugger will always display the Disassembly tab. This displays the shader code in assembly. If you have built the shader to contain debug information, there will be one or more additional tabs for viewing the HLSL code.

View HLSL Code

If you are developing code using Direct3D 10, then you will see two tabs, one with the name of the file that contains the HLSL (or effects) code and the other with the name of the file that contains the assembly code.

View Assembly Code

All shaders can be viewed in assembly with PIX. Click on the Disassembly tab if it is not already selected.

View the Contents of Registers and Variables

Use PIX to view the contents of variables and registers.

Register View

To view registers, click on the Registers tab.

This table is a read-only display of the contents of the register after the instruction has completed. Registers whose contents have changed as a result of the current instruction are displayed in red.

Variable View

To view shader variables, click on the Variables tab.

This table is also a read-only display of the contents of the variables after the HLSL statement has completed.

Navigate the Code View with the Toolbar

The toolbar has several buttons for navigation: use these buttons to step forward and backward through code, or restart at the beginning of a shader.

Button Name | Button | Does this
Go |  | Continue to the next breakpoint.
Restart |  | Restart the debugger at the beginning of the shader.
Step |  | Move forward to the next executable line of code.
Run-to-cursor |  | Move forward to the executable line of code where the cursor is located.
Step-backward |  | Move backward to the previous line of executable code.

Set Breakpoints in the Code View

From the code view, you can set breakpoints on any line of executable code. To set a breakpoint, click down to the left of the line of code you want to stop at. To get rid of a breakpoint, click on it again.

Use the buttons in the Toolbar to navigate between breakpoints.

Best Practices for Debugging Shaders

Here are a few suggestions for improving your experience when using PIX to debug shaders.

  • Be sure to build your shaders using the debug flag (use D3D10_SHADER_DEBUG).
  • In general, do not build optimized shaders (use D3D10_SHADER_SKIP_OPTIMIZATION). Non-optimized code will run in the order that the code is displayed in the shader-debugger view.
  • You cannot step through shader code on instanced objects.

See Also

Debugger Tab


Device Tab

The Device tab displays the current device state.

Each of these subcategories display the states that are pertinent to a portion of the pixel pipeline. Within each tab, state values are represented as read-only name-value pairs. The state names are a combination of actual render-state names and implied state behavior.

The background color behind the value text is color-coded to make state changes easy to view. The background uses the following colors to indicate the following conditions:

White
The value has not changed since the last draw.
Blue
The value has changed since the last draw.
Red
The value has changed during the selected event (or the event's children).

As you click through individual API calls and events, the color-coding will tell you what states have changed.

The state of the device can by saved to an HTML file by right clicking anywhere in the device window and entering a file name.

The Device tab is divided into subordinate tabs that provide state-specific information, described in the following sections.

Device-Info Sub-Tab

This state controls all the operations performed before inputting data to the pipeline.

Input-State Sub-Tab

This state controls all the operations performed on input data to prepare it for tessellation or vertex processing.

Tesselation-State Sub-Tab

This state controls how high-order surface tesselation operations prior to per-vertex processing.

Vertex-State Sub-Tab

This state controls per-vertex operations by the vertex shader stage.

Pixel-State Sub-Tab

This state controls per-pixel operations by the pixel shader stage.

Output-State Sub-Tab

This state controls per-pixel operations after the pixel shader stage including: gamma, scissor and frame buffer state.

See Also

Details View


Mesh Tab

A mesh tab displays mesh data. Use this tab to view mesh vertex transformations before and after shader processing.

The mesh tab has two areas for displaying data.

  • Viewer
  • Vertex Data Tabs

Viewer

The viewer shows four different views of the mesh data; these correspond to four different locations in the pipeline.

View | Description
1 | View the mesh vertices before the vertex shader. The camera is pointed at the center of the object.
2 | View the mesh vertices after the vertex shader. The camera is pointed at the center of the object.
3 | View the mesh vertices after the geometry shader. The camera is pointed at the center of the object. If there is no geometry shader assigned, this view is blank (a solid shade of light gray).
4 | View the mesh vertices in screen space. The camera is set up identical to the camera in the target program.

Vertex Data Tabs

The vertices in the mesh can be viewed in the following tabs.

  • A PreVS Sub-tab - View vertices before the vertex shader.
  • A PostVS Sub-tab - View vertices after the vertex shader.
  • A PostGS Sub-tab - View vertices after the geometry shader.

Create a Mesh Tab

The mesh tab is automatically created when an experiment runs on a target program that contains a mesh. To initialize the mesh tab:

  1. Select a frame to display.
  2. Select an event within the frame that contains a draw call. Use the draw button in the event view to navigate between draw calls.
  3. Click on the mesh tab.

Debug a Vertex Shader

The vertex shader debugger is launched from the mesh tab. To debug a vertex shader, you must first choose the pipeline location that you want to view, and select the appropriate vertex data tab.

  1. Select a frame to display.
  2. Select an event within the frame that contains a draw call. Use the draw button in the event view to navigate between draw calls.
  3. Click on the mesh tab.
  4. Click on the PostVS tab to see the results of the vertex shader.
  5. Choose a vertex, and click on the vertex index in the VTX column. This will launch the shader debugger.

See Also

Details View


Shader Tab

A shader tab displays vertex shader or pixel shader code. By default, the compiled assembly code is shown.

Shader code is color coded: instructions are blue, registers are black and literals are green.

Create a Shader Tab

There are two ways to create a shader tab.

  • Click the memory address of a vertex shader or pixel shader object (the blue address) in the event view.
  • Right-click a vertex shader or pixel shader object (make sure the object has an Alive status) in the object view and select the view menuitem.

Viewing HLSL or Assembly Code

Click the src button to view HLSL code; click the asm button to view the corresponding assembly code.

If source code is not available, the source code button on the toolbar will be grayed out. To make the source code available, compile the shader with the debug flag specified.

See Also

Details View


State-Block Tab

A state-block tab displays pipeline states captured by a state block.

The contents of the state block are displayed in a table. The state names were chosen to correspond to state behavior; they are not an exact match of the API names.

Create a State-Block Tab

There are two ways to create a state-block tab:

  • Click the memory address of a state-block object (must be a blue address) in the event view.
  • Right-click a state-block object (whose status is Alive) object view and select the view menuitem.

See Also

Details View


Surface Tab

A surface tab shows the contents of a Direct3D surface. Use the surface tab to visually debug a render target or a texture.

Create a Surface Tab

There are two ways to create a surface tab:

  • Click the memory address of a surface object (the memory address must be blue) in the event view.
  • Right-click a surface object (whose status is Alive) in the object view and select the view menuitem.

A surface tab has the same common controls used on the render tab.

See Also

Details View


Texture Tab

A texture tab displays the contents of a Direct3D texture.

The upper portion of the left side of the texture tab displays a list of the mip levels; the lower portion displays the texture type and format. Select a particular mip level to render the data in the viewer on the right side.

In addition, each texture tab contains the common controls from the render tab. Use these controls to zoom in or out, fit the surface to the window, save the data to a file, or change the range of the data displayed.

Create a Texture Tab

There are two ways to create a texture tab.

  • Click the memory address of a texture object (the memory address must be blue) in the event view.
  • Right-click a texture object (with a status property of alive) in the object view and select the view menuitem.

See Also

Details View


Vertex-Declaration Tab

A vertex-declaration tab displays the vertex declaration that determines the data types in a vertex buffer. The vertex declaration is displayed as a table.

For this example, the vertex layout would be:

float3 position
float3 normal
float2 texcoord

Create a Vertex-Declaration Tab

There are two ways to create a vertex-declaration tab.

  • Click the memory address of a vertex-declaration object (the memory address must be blue) in the event window.
  • Right-click a vertex-declaration object (whose status is Alive) in the object view and select the view menuitem.

See Also

Details View


Timeline View

The timeline view displays performance information visually; it makes it easy to see performance bottlenecks. You have control over the amount and types of data displayed.

Figure 1. TimeLine View

There are two types of data displayed: the load on the CPU for each frame, and the data gathered by counters. To make visual debug easier, there is also a set of controls for adjusting the presentation of the data.

  • Control #1: View CPU Events
  • Control #2: View GPU Events
  • Control #3: View Counter Data
  • Control #4: Timeline Toolbar

Control #1: View CPU Events

The first portion of the timline displays the number of events that are processed by the CPU during each frame. Each frame is displayed using a gray rectangle with a thin black border. Frames that are calculated very quickly appear very narrow, and frames that take longer to calculate appear wider.

Figure 2. CPU Events

The event view shows each frame as a gray rectangle with a thin black border. Slow frames are wider while fast frames are narrower. When viewing frames that have very short durations the view may need to be scaled to see the individual frames.

Use the zoom in button to expand the horizontal scale to see individual events.

Timeline Ruler

To see the elapsed time, use the ruler just above the CPU events.

Figure 3. Timeline Ruler

Frame Arrow

To select a frame, mouse click on the frame arrow and move it left or right.

Figure 4. Frame Arrow

The frame number corresponds to the event selected in the event window. You can also select a frame by clicking down anywhere inside of the timeline.

Control #2: View GPU Events

The second portion of the timeline displays the number of events that are processed by the GPU during each frame (some information gathering options require a user-entered action to collect GPU events, other data gathering options collect GPU events by default).

Figure 5. GPU Events

Each frame is represented by a rectangle with a thin black border.

The GPU timeline uses several colors to differentiate the status of the GPU during that frame.

  • Blue - The GPU is rendering a packet of work. Each frame, the CPU sends one or more packets of work to the GPU.
  • Gray - The GPU is idle, waiting for more work.
  • Red - The GPU is blocked, waiting for a resource that is not yet available.

Just like the CPU timeline:

  • Use the zoom in button to expand the horizontal scale to see individual events.
  • Use the ruler above the CPU timeline to see the elapsed time.
  • The frame arrow appears when you have selected either a CPU frame or a GPU frame. When selecting a GPU frame, the frame appears off-white instead of gray.

GPU events are stored in an event-trace file, which is automatically created by PIX when analysis is performed.

Control #3: View Counter Data

The second section of the timeline displays counter data (see figure 1). Use the controls on the timeline toolbar to zoom in or out to make viewing easy.

The counter data displayed in the timeline was collected when the experiment was run. Display the data from up to four counters at the same time using the counter controls.

Control #4: Timeline Toolbar

The timeline also supports a toolbar fo adjusting the timeline display (see figure 1). There are two sets of controls: those that adjust the range and position of the data to display, and those that specify which counter data to display.

  • Range and Position Controls
  • Counter Controls

Range and Position Controls

There are three controls for adjusting the presentation of the data.

Icon | Name | Description
 | Zoom In | Zoom in (or expand) the time axis. This has no effect on the scale of the y axis.
 | Zoom Out | Zoom out (or compress) the time axis. This has no effect on the scale of the y axis.
 | Fit-to-Screen | Change the horizontal scale of the time axis to display all of the time data.

Counter Controls

There are four counter selection boxes. You may use any or all of them to specify up to 4 sets of counter data to display. Each control is color coded to match the color of the counter data in the timeline.

Figure 6. Counter Control

It has two drop down boxes, and a third text box. The first drop down box contains a list of the counter types.

Figure 7. Drop Down #1 - Counter Type

  • EID - An integer ID that uniquely identifies an event. This is the value that PIX assigns to an event so that it can be tracked in the event window.
  • StartTime - The time that an event starts.
  • Frame - The frame that an event starts.
  • Duration - Elapsed time between the start of one event and the next event.
  • FPS - Calculation of the possible number of frames-per-second that could be processed by the CPU.

Figure 8. Drop Down #2 - Vertical Scale

Use the vertical scale to fit the data you need to display.

The third portion of a counter control displays the data value. Here is an example of the first control displaying duration data.

Figure 9. Text Box Displays Duration Data

See Also

Reference


Diagnostic Log

The PIX Diagnostic Log is a record of events that can be used to help understand what the target program was doing before a crash occured. The diagnostic log can help you debug incorrect usage of Direct3D by the target program.

  • Unexpected Exit Dialog Box
  • Diagnostic Log

Unexpected Exit Dialog Box

To generate a diagnostic log for a crashing application, start by running PIX on the target program. PIX will launch the target program, and when it encounters a crash, PIX will open the Unexpected Exit dialog box. The dialog box gives you suggestions for what to do next, along with the UI elements to take the next step.

The dialog box has several suggestions listed for actions that you can take, and a few checkboxes. Basically, the idea is to rerun your target program using PIX, and to save all the debug output generated by the debug runtime to a diagnostic log. Then by going through the log, you can see a listing of the Direct3D calls your target program made just prior to the crash.

In general, there are a couple of things to remember to do:

  1. Enable the Direct3D debug runtime using the DirectX Control Panel. The debug runtime outputs information about the API calls, what the parameters were, what the HRESULTS of the function calls were. It is rich with information about what calls were made, and if they succeeded or not. This is the same information you get in the debug output when running a debugger like Visual Studio.
  2. Use the check boxes to choose to either add the debug messages to the log and/or pause when your target program launches so you can attach a debugging program (such as Visual Studio).
  3. Use the restart button to rerun the target program as many times as you like.

There is also a Disable D3DX Analysis checkbox. If you are having trouble with PIX analyzing your data, and you would like to eliminate D3DX calls as a possible cause, you may select this checkbox. This does not prevent the D3DX calls from being called by your application, but it does mean that PIX will not attempt to gather data about them.

When you want to end your debug session, use the Cancel button to exit the diagnostic mode. This returns you to the PIX main window.

Diagnostic Log

Once you restart the experiment, PIX generates a diagnostic log similar to this one.

The diagnostic log lists the target program and the Direct3D calls that were made by the target program prior to crashing. The dialog box contains a scrollable view of all the calls; scroll up to see the first call made, and scroll down to see the last call made.

Since a log file can get rather large (the one in this example is a half a megabyte), you can navigate the list using the PRE and POST markers. PIX adds these markers when an API call is made (the PRE marker) and when the call returns (the POST marker). In the log, the PRE/POST markers are indented so you can see API call nesting.

For an example of using the diagnostic log to analyze a crashing program, see Debugging a Crashing Application.

See Also

Reference


Command-Line Syntax

Use the following syntax to run PIX from the command line:

PIXWin.exe file-name [ file-options ]

File Options

There are three types of files PIX can open: experiment files, run files, and image files. Each file type uses optional file options.

Experiment File Options

Use the following syntax to open an experiment file:

PIXWin.exe file-name.PIXExp [ -targetpath path ]
                     [ -targetstartfolder folder ]
                     [ -targetargs arguments ]
                     [ -runfile path ]
                     [ -start ]
                     [ -run ]

Arguments | Description
file-name.PIXExp | Required. PIX experiment file.
-targetpath path | Optional. Set the target-program path.
-targetstartfolder folder | Optional. Set the target-program folder.
-targetargs arguments | Optional. Set command-line-arguments for the target program.
-runfile path | Optional. Set the location to save the .PIXRun file.
-start | Optional. Start the experiment.

Run File Options

Use the following syntax to open a run file:

PIXWin.exe file-name.PIXRun [ -playstandalone ] [ -exporttocsv file-name.csv ]

Arguments | Description
file-name.PIXRun | Required. PIX run file.
-playstandalone | Optional. Play a run file within PIX, without bringing up the full PIX UI.
-exporttocsv file-name.csv | Optional. Load a PIXRun file and export the results to a an Excel (.csv) file.

You must use at least one of these arguments.

Image File Options

PIX supports the following image formats and file extensions: bitmap (.bmp), Enhanced Metafile (.emf), Exif (.exif), GIF (.gif), icon (.icon), JPEG (.jpg), PNG (.png), TIFF (.tif), and Windows Metafile (.wmf).

Use the following syntax to open one or more image files:

PIXWin.exe image-file-name-1 [ image-file-name-2 [ -appenddiffmeasure text-file-name ] [ -outputdiffxor image-file-name-3 ] ]

Arguments | Description
image-file-name-1 | First image file to open.
image-file-name-2 | Optional. Second image file to open.
-appenddiffmeasure text-file-name | Optional. Measure the per-pixel differences between image-file-name-1 and image-file-name-2, and save the result in text-file-name.
-outputdiffxor image-file-name-3 | Optional. Combine image-file-name-1 and image-file-name-2 by Exclusive OR and save the result in image-file-name-3. You can combine this argument with -appenddiffmeasure.

See Also

PIX


PIX Functions

PIX can analyze a program without the need to modify it. However, more powerful analysis is possible when you add to the target program one or more function calls to the functions shown in the following table.

Function | Description
D3DPERF_BeginEvent | Mark the beginning of a user-defined event. PIX can use this event to trigger an action.
D3DPERF_EndEvent | Mark the end of a user-defined event. PIX can use this event to trigger an action.
D3DPERF_GetStatus | Determine the state of the profiler from the target program.
D3DPERF_QueryRepeatFrame | Determine if a performance profiler is requesting that the current frame be resubmitted to Direct3D for performance analysis. This function is not currently implemented.
D3DPERF_SetMarker | Mark an instantaneous event. PIX can use this event to trigger an action.
D3DPERF_SetOptions | Set profiler options specified by the target program.
D3DPERF_SetRegion | Mark a series of frames with the specified color and name in the PIXRun file. This function is not currently implemented.

See Also

The PIX for Windows Application


D3DPERF_BeginEvent

Marks the beginning of a user-defined event. PIX can use this event to trigger an action.

int D3DPERF_BeginEvent(
  D3DCOLOR col,
  LPCWSTR wszName
);

Parameters

col
Event color. This is the color to display the event in the event view.
wszName
Event name.

Return Values

The zero-based level of the hierarchy that this event is starting in. If an error occurs, the return value will be negative.

Remarks

User-defined events group together other events in a way that is meaningful to the target program so that they can be better represented in performance profiling tools. For example, a Draw Spaceship event might bracket a number of Direct3D calls that handle drawing a spaceship in a game. Events can be nested.

Each D3DPERF_BeginEvent call should have a matching D3DPERF_EndEvent call. Instantaneous events (which do not bracket other events) should be labeled by using D3DPERF_SetMarker rather than by D3DPERF_BeginEvent and D3DPERF_EndEvent.

Requirements

Header: Declared in D3d9.h.

See Also

PIX


D3DPERF_EndEvent

Mark the end of a user-defined event. PIX can use this event to trigger an action.

int D3DPERF_EndEvent();

Parameters

None.

Return Values

The level of the hierarchy in which the event is ending. If an error occurs, this value is negative.

Requirements

Header: Declared in D3d9.h.

See Also

PIX


D3DPERF_SetMarker

Mark an instantaneous event. PIX can use this event to trigger an action.

void D3DPERF_SetMarker(
  D3DCOLOR col,
  LPCWSTR wszName
);

Parameters

col
Event color. This is the color to display the event in the event view.
wszName
Event name.

Return Values

None.

Remarks

Instantaneous user events do not bracket or group other events. For example, when the user fires a weapon in a game, a Shot Fired event could be created by a D3DPERF_SetMarker call. To group together multiple events under a single, user-defined name, use D3DPERF_BeginEvent and D3DPERF_EndEvent rather than D3DPERF_SetMarker.

Requirements

Header: Declared in D3d9.h.

See Also

PIX


D3DPERF_SetRegion

Mark a series of frames with the specified color and name in the PIXRun file. This function is not currently supported by PIX.

void D3DPERF_SetRegion(
  D3DCOLOR col,
  LPCWSTR wszName
);

Parameters

col
Event color.
wszName
Event name or marker name.

Return Values

None

Remarks

To make analysis easier, the target program can use color to mark each level of a target program.

Requirements

Header: Declared in D3d9.h.

See Also

PIX


D3DPERF_QueryRepeatFrame

Determine whether a performance profiler is requesting that the current frame be resubmitted to Direct3D for performance analysis. This function is not currently supported by PIX.

BOOL D3DPERF_QueryRepeatFrame();

Parameters

None.

Return Values

If the return value is TRUE, the caller should repeat the same sequence of calls. If FALSE, the caller should continue.

Remarks

The function should be called immediately after IDirect3DDevice9::Present is called.

Requirements

Header: Declared in D3d9.h.

See Also

PIX


D3DPERF_SetOptions

Set profiler options specified by the target program.

void D3DPERF_SetOptions(
  DWORD dwOptions
);

Parameters

dwOptions
User options recognizable by PIX. Set this to 1 to notify PIX that the target program does not give permission to be profiled.

Return Values

None.

Requirements

Header: Declared in D3d9.h.

See Also

PIX


D3DPERF_GetStatus

Determine the current state of the profiler from the target program.

DWORD D3DPERF_GetStatus();

Parameters

None.

Return Values

Returns a non-zero value when PIX is profiling the target program; otherwise, returns zero.

Requirements

Header: Declared in D3d9.h.

See Also

Experiment - Basic View


DirectX System Tools

This section contains system-level tools to help you diagnose and understand how well DirectX works on your hardware.

  • DirectX Caps Viewer Tool
  • DirectX Control Panel Tool
  • DirectX Diagnostic Tool
  • DirectX Error Lookup Tool


DirectX Caps Viewer Tool

The DirectX Caps Viewer (DXCapsViewer.exe) shows information for the following components:

  • Direct3D devices and capabilities
  • DirectSound capture devices and capabilities
  • DirectInput devices and their capabilities
  • DirectMusic port capabilities

Compatibility Chart

Direct3D 9 | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | No | Yes | Yes | Yes

Caps viewer shows the DirectDraw capabilities of the primary display adapter:

Screen shot of DirectX Caps Viewer

Developers should use this tool to verify the capabilities of their development and test computers, making sure that DirectX applications correctly test for current computer capabilities. It is suggested that applications be designed with fallback strategies if the required features are not available.

Path

Executable: (SDK root)\Utilities\Bin\x86 or x64

User's Guide

Select items in the tree view on the left. Information about the selected item appears in the pane on the right.


DirectX Control Panel Tool

Use the DirectX Control Panel, which is installed automatically with the SDK, to examine and modify the properties of DirectX components. The tool is launchable from the Start menu under Programs, Microsoft DirectX SDK, DirectX Utilities. This tool contains tabs for each DirectX component. Using this tool you can:

  • Obtain version information for components.
  • Change the debug output level and debug settings to aid in troubleshooting during the development process.
  • View specific driver and hardware support information for components.
  • Toggle between debug and retail versions of the run-time files for Direct3D, DirectMusic, and DirectInput.

The control panel has a Managed tab, which contains the names of the DirectX Assemblies that are installed. For any assembly that is installed in the Global Assembly Cache (GAC), you can find the version listed under each assembly name by right clicking on a particular assembly version and selecting Properties from the popup menu.


DirectX Diagnostic Tool

The DirectX Diagnostic tool (DXDiag.exe) gathers information about the system and the DirectX installed components. It also provides a number of tests to ensure that components are working properly. Use the diagnostic tool to create a report about your computer by running Dxdiag.exe and clicking on the Save All Information button. Then send the data dump to Microsoft using the Report button on the More Help tab.

Launch Procedure

CPU Procedure
32 bit
  1. From the Start menu, select Run.
  2. Enter Dxdiag.exe and click OK.
The executable is located at %windir%\system32\DXDiag.exe.
64 bit
  1. From the Start menu, select Run.
  2. Enter DXDiag.exe and click OK.
  3. In the dialog box (this will only appear on a 64-bit computer), click Run 64-bit DxDiag. The 64-bit version of DXDiag will launch.

Remarks

DXDiag generates warnings when running with debug dll's; these can be ignored.

Additional debug information can be found in Debugging DirectX Applications.


DirectX Error Lookup Tool

The DirectX error tool (DXErr) displays a description of any HRESULT or error code from Direct3D, Direct Play, DirectMusic, DirectSound, DirectInput, DirectShow, and Win32.

Screen shot of DXErr

Path

Executable: (SDK root)\Utilities\Bin\x86 or x64


DirectX SDK Samples

The SDK contains the following samples:

  • GetDXVer Sample - can tell you what version of DirectX is installed.
  • Dinstall Sample - can tell you how to use DirectSetup to install Microsoft DirectX.
  • ParentalControlTimeLimits Sample - can tell you how you can get Windows Parental Control Time Limits information in your application.

Follow the instructions for sample code contained in the license agreements within: (SDK root)\Documentation\License Agreements

See Also

DirectX Graphics Samples DirectInput Samples DirectSound Samples

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


GetDXVer Sample

Applications sometimes need to know which version of DirectX is currently available on the system. If an older version of DirectX is on the system, your application may need to scale itself to the capabilities of that version or install the most recent version.

The table lists the version of DirectX that shipped with each operating system:

Operating System | DirectX Version
Windows 98 Gold | DirectX 5.2
Windows 98 SE | DirectX 6.1a
Windows 2000 | DirectX 7.0
Windows Millenium Edition | DirectX 7.1
Windows XP | DirectX 8.1

DirectX 9.0 is supported on Windows XP.

The GetDXVer SDK sample has a function in it called GetDXVersion that returns the version of DirectX that is installed. As long as this integer is greater than or equal to your desired version number, your application will run normally.

Path

Source: | (SDK root)\Samples\C++\Misc\GetDXVer
Executable: | (SDK root)\Samples\C++\Misc\Bin\GetDXVer

Checking the Operating System Version

Use the Windows function GetVersionEx to check the operating system installed. This function returns an OSVERSIONINFOEX structure that contains a variety of information about the operating system.


Dinstall Sample

This sample uses DirectSetup functions to install the DirectX subsystem. It shows how to use a callback function to present messages and get user input through a custom interface (a modeless dialog box).

Path

Source: (SDK root)\Samples\C++\Misc\DXInstall

User's Guide

  1. Copy the entire contents of the \Redist folder from the DirectX SDK CD into the same folder as Dinstall.exe.
  2. In your development environment, set the working directory to this folder as well. (In Microsoft Visual C++, this setting is on the Debug page of the Project Settings dialog box.)
  3. Run the program and, on the File menu, click Start Install. DirectSetup performs a simulated installation of DirectX (see Programming Notes below) and advises you of its progress in a modeless dialog box. You can use the Options menu to change the level of messages shown. However, if you are performing only a simulated installation, you will never see problem or update messages.
  4. On the File menu, click GET Version. The program shows the version and revision number of DirectX currently installed on the system.

Programming Notes

By default, the program passes DSETUP_TESTINSTALL to the DirectXSetup function. This means that no files are copied and the registry is not modified. To perform a real installation, delete this flag from the call.

Dinstall.exe employs a callback function to monitor the progress of installation and intercept messages. Depending on the user's preferred warning level, as tracked in g_fStatus, messages may be ignored or presented to the user in a modeless dialog box. If user input is required, the appropriate buttons are displayed and the application monitors the message queue until one of the buttons is pressed.

Although DirectX samples include Visual C++ project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly.

See Also

Installing DirectX with DirectSetup


ParentalControlTimeLimits Sample

Parents can limit the time their child spends on a Windows Vista machine by leveraging the Time Limit feature in Windows Parental Controls (WPC). A child under time restrictions will receive an account lock-out notification via the system tray at 15 minutes and 1 minute prior to a restricted hour, and will be immediately logged out of their account when the restricted hour is reached. All currently running programs will continue to execute during the lock-out.

Game authors should be aware that a user may have time restrictions enabled on their account and should provide feedback to the user where appropriate. For example:

  • A game might warn a user about an imminent lock-out before he/she chooses to embark on a lengthy MMO quest.
  • A fullscreen game may provide an in-game time limit notification as a substitute for the 15 minute and 1 minute system tray icon notifications that will go unseen.

This sample demonstrates how to query the WPC Time Limit information for the current user. The information is then used to display the restricted hours for each day of the week, as well as the time remaining until the user is logged off due to a time limit restriction.

Path

Source: | (SDK root)\Samples\C++\Misc\ParentalControlTimeLimits
Executable: | (SDK root)\Samples\C++\Misc\Bin\x86 or x64\ParentalControlTimeLimits.exe

Getting the Time Limit Information for the Current User

The sample files TimeLimitAPI.h and TimeLimitAPI.cpp define a small API that provides a clean interface to get the time limit information needed from the Windows Management Instrumentation (WMI) services. These files can be easily integrated into your own project so you can take advantage of the API. Your project will also take a dependency on wbemuuid.lib and msxml2.lib, and these libraries are part of the Windows SDK.

TimeLimitAPI Functions:

  • TimeLimitEnabled() -- Checks if the current user has time limit restrictions.
  • TimeLimitGetTimeRemaining() -- Gets the time remaining (days, hours, minutes and seconds)
  • TimeLimitGetSecondsRemaining() -- Gets the seconds remaining until the current user is locked out of their account due to a time restriction.
  • TimeLimitGetHourlyRestrictions() -- Gets the hourly time restrictions for each day of the week for the current user.

The sample demonstrates the TimeLimitAPI functions in OnFrameRender() in ParentalControlTimeLimits.cpp:

if( TimeLimitEnabled() )
{
   //
   // Draw account lock out time
   //
   TimeRemaining remaining;
   if( SUCCEEDED( TimeLimitGetTimeRemaining( &remaining ) ) )
   {
      V( miscTxt.DrawFormattedTextLine( drawRect,
                                        DT_CENTER | DT_VCENTER,
                            L"Time until account lock-out: %dd %dh %dm %ds",
                                        remaining.days,
                                        remaining.hours,
                                        remaining.minutes,
                                        remaining.seconds ) );
   }

   //
   // Fill in each grid cell that corresponds to a restriced hour
   //
   HourlyRestrictions restrictions;
   if( SUCCEEDED( TimeLimitGetHourlyRestrictions( &restrictions ) ) )
   {
      for( int day = 0; day < DaysPerWeek; ++day )
      {
         for( int hour = 0; hour < HoursPerDay; ++hour )
         {
            unsigned int hourMask = 1 << hour;
            if( !( restrictions.days[day] & hourMask ) )
            {
               // fill in the appropriate cell
               RECT cell;
               cell.left   = g_gridPos.x + g_gridCellWidth * hour;
               cell.right  = cell.left + g_gridCellWidth;
               cell.top    = g_gridPos.y + g_gridCellWidth * day;
               cell.bottom = cell.top + g_gridCellWidth;
               V( pd3dDevice->ColorFill( pSurface, &cell, ClrGridCell ) );
            }
         }
      }
   }
}


DirectX SDK Reference

This section contains reference information for the tools provided for working with the DirectX SDK. Material is divided into the following sections:

  • DirectX SDK Constants
  • The DirectX Error Handling Utility Library
  • DirectX Diagnostic Tool Reference
  • DirectSetup Reference
  • IUnknown


DirectX SDK Constants

These constant values refer to the product and build versions of the DirectX SDK update. These values are unique to each SDK update and allow you to conditionally compile your code against specific versions of the SDK.

#define | Description
_DXSDK_BUILD_MAJOR | DirectX SDK build major version
_DXSDK_BUILD_MINOR | DirectX SDK build minor version
_DXSDK_PRODUCT_MAJOR | DirectX SDK product major version
_DXSDK_PRODUCT_MINOR | DirectX SDK product minor version

An effective way to use these constants is to do an assert to make sure the correct build version of the DirectX SDK is installed on a developer's machine. This way, if a new developer joins your project and has the wrong version of the DirectX SDK installed he will get an error message when he runs the program.

Example:

assert(_DXSDK_BUILD_MAJOR == 299);  //this checks that the DirectX SDK (August 2005) build is installed.

Constant Information

Header | dxsdkver.h
Minimum operating system | Windows 98


The DirectX Error Handling Utility Library

The DirectX SDK includes a pair of utility functions and several macros designed to simplify the task of debugging your application. These functions are contained in the Dxerr.lib library. The function and macro declarations are in Dxerr.h.

  • DirectX Error Handling Functions
  • DirectX Error Handling Macros

Compatibility Chart

The following chart shows the compatibility of the error-handling utilities with various DirectX components, modes, and operating systems.

Direct3D 9 | Direct3D 9 EX | Direct3D 10 | 64-bit Native Mode | Windows XP | Windows Vista
Yes | No | Yes | Yes | Yes | Yes


DirectX Error Handling Functions

The functions described in this section are included in the DirectX error handling utility library, DxErr.lib.

Function | Description
DXGetErrorDescription | Returns a string that describes a DirectX HRESULT value.
DXGetErrorString | Returns the name associated with an error code.
DXTrace | Displays a message box, and passes the error code to DXGetErrorString.


DXGetErrorDescription

Returns a string that describes a DirectX HRESULT value.

TCHAR * DXGetErrorDescription(
  HRESULT hr
);

Parameters

hr
[in] Any HRESULT return code from XACT, Direct3D 10, D3DX10, Direct3D 9, D3DX9, Direct3D 8, D3DX8, DirectDraw, DirectMusic, DirectSound, DirectInput, or DirectShow.

Return Values

Returns a pointer to a character string that describes the HRESULT code.

Remarks

This function supports the Win32 error codes that are defined in Winerror.h.

Requirements

Header: Declared in Dxerr.h.


DXGetErrorString

Returns the name associated with an error code. This method is designed to handle error codes from all the DirectX components and Win32 functions.

TCHAR * DXGetErrorString(
  HRESULT hr
);

Parameters

hr
[in] Any HRESULT return code from XACT, Direct3D 10, D3DX10, Direct3D9, D3DX9, Direct3D 8, D3DX8, DirectDraw, DirectInput, DirectMusic, DirectSound, or DirectShow.

Return Values

If successful, this function returns a pointer to a string that contains the name of the error code. If Unicode is set, the function returns a Unicode string. Otherwise, it returns an ANSI string.

Remarks

This function is designed to retrieve the text equivalent of a DirectX error message from an XACT, Direct3D 10, D3DX10, Direct3D9, D3DX9, Direct3D 8, D3DX8, DirectDraw, DirectInput, DirectMusic, DirectSound, or DirectShow method. For example, if you set hr to 0x88760686, this function returns D3DERR_DEVICELOST.

If an error code maps to more than one text string, DXGetErrorString returns a generic string. For example, there are several DirectX error codes, such as D3DERR_OUTOFVIDEOMEMORY, that indicate that the system is out of memory and all map to the same value. If you set hr to any of these codes, DXGetErrorString returns E_OUTOFMEMORY.

This function handles standard Win32 errors and all DirectX components, including XACT, Direct3D 10, D3DX10, Direct3D9, D3DX9, Direct3D 8, D3DX8, DirectDraw, DirectInput, DirectMusic, DirectSound, and DirectShow.

This function supports Unicode and ANSI strings.

This function supports the Win32 error codes that are defined in Winerror.h.

Requirements

Header: Declared in Dxerr.h.


DXTrace

Displays a message box and passes the error code to DXGetErrorString.

HRESULT DXTrace(
  CHAR * strFile,
  DWORD dwline,
  HRESULT hr,
  CHAR * strMsg,
  BOOL bPopMsgBox
);

Parameters

strFile
[in] Pointer to the name of the current file. You can set this parameter easily with the __FILE__ macro.
dwline
[in] Line number. You can set this parameter easily with the __LINE__ macro.
hr
[in] HRESULT containing an error code. This value will be passed to DXGetErrorString and converted to the equivalent name.
strMsg
[in] Pointer to an optional message that will be displayed, along with the file name, line number, and HRESULT.
bPopMsgBox
[in] Specifies whether a message box should be displayed. If bPopMsgBox is set to TRUE, a message box is displayed containing the values of the first four parameters. If bPopMsgBox is set to FALSE, the message box is not displayed.

Return Values

Returns the HRESULT that was assigned to hr.

Requirements

Header: Declared in Dxerr.h.


DirectX Error Handling Macros

The macros described in this section simplify using the DXTrace function.

Macro | Description
DXTRACE_ERR | Outputs a debug message and the failed return value for a failed function call.
DXTRACE_ERR_MSGBOX | Displays a message box with error information.
DXTRACE_MSG | Outputs a debug message for a failed function call.


DXTRACE_ERR

Output a debug message and the failed return value for a failed function call.

#define DXTRACE_ERR(str,hr)

Parameters

str
[in] Type is char*. Pointer to a string to be passed to the debugger.
hr
[in] Type is HRESULT. HRESULT containing an error code. This value will be passed to DXGetErrorString and converted to the equivalent name.

Return Values

Returns the HRESULT that was assigned to hr.

Remarks

For example, if you call DXTRACE_ERR with the following:

    DXTRACE_ERR( "Call failed", D3DERR_INVALIDCALL )

A function call that fails will output a debug message in the output window of the compiler similar to the following:

    c:\basichlsl\basichlsl.cpp(242): Call failed hr=D3DERR_INVALIDCALL (0x8876086c)

This error message identifies the file and line number of the function call that failed. If you are using the Visual Studio debugger, you can jump to the line of source code where the error occurred by double-clicking this message in the debug output window.

Note You must be running a debug build to see the error message.

If you are not interested in returning the error code, see DXTRACE_MSG.


DXTRACE_MSG

Output a debug message for a failed function call.

#define DXTRACE_MSG(str)

Parameters

str
[in] Type is char* *. Pointer to a user-supplied debug message that will be passed to the debugger.

Return Values

Returns zero if successful, or a nonzero value if not.

Remarks

For example, if you call DXTRACE_MSG with the following:

    DXTRACE_MSG( "Call failed" )

A function call that fails will output a debug message in the output window of the compiler similar to the following:

    c:\basichlsl\basichlsl.cpp(242): Call failed

This error message identifies the file and line number of the function call that fails. If you are using the Visual Studio debugger, you can jump to the line of source code where the error occurred by double-clicking this message in the debug output window.

Note You must be running a debug build to see the error message.

If you are interested in returning the error code also, see DXTRACE_ERR.


DXTRACE_ERR_MSGBOX

Displays a message box with error information.

#define DXTRACE_ERR_MSGBOX(str,hr)

Parameters

str
[in] Type is char*. Pointer to a string to be displayed in the message box.
hr
[in] Type is HRESULT. HRESULT containing an error code. This value will be passed to DXGetErrorString and converted to the equivalent name.

Return Values

Returns the HRESULT that was assigned to hr.

Remarks

For debug builds, the macro displays an error message that looks similar to the following:

c:\basichlsl\basichlsl.cpp(242):
    D3DXCreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
    OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial",
    NULL ) hr=D3DERR_INVALIDCALL (0x8876086c)

If you are using the Visual Studio debugger, you can jump to the line of source code where the error occurred by double-clicking this message in the debug output window.

If you don't want to use a message box to debug, you can send error messages to the debug output window in Visual Studio using DXTRACE_ERR or DXTRACE_MSG.


DirectX Diagnostic Tool Reference

The DirectX Diagnostic Tool exposes a COM interface to allow developers to programmatically query the information gathered by the tool.

  • DXDiag Interfaces
  • DxDiag_Structures

Examples using the diagnostic tool can be found in:

  • DirectX SDK root\Samples\C++\Misc\DXDiagReport\
  • DirectX SDK root\Samples\C++\Misc\DXDiagOutput\


DXDiag Interfaces

This section contains reference material for the interfaces exposed by the DirectX Diagnostic Tool.

  • IDXDiagContainer
  • IDxDiagProvider


IDXDiagContainer

Applications use the methods of the IDXDiagContainer interface to query objects and properties exposed by the Microsoft DirectX Diagnostic tool.

Method | Description
IDXDiagContainer::EnumChildContainerNames | Enumerates the name of the IDXDiagContainer object at the specified index.
IDXDiagContainer::EnumPropNames | Enumerates the name of the property at the specified index.
IDXDiagContainer::GetChildContainer | Retrieves a pointer to the specified child container.
IDXDiagContainer::GetNumberOfChildContainers | Returns the number of IDXDiagContainer objects in this container.
IDXDiagContainer::GetNumberOfProps | Retrieves the number of properties in this container.
IDXDiagContainer::GetProp | Retrieves an instance of the specified property.


IDXDiagContainer::EnumChildContainerNames

Enumerates the name of the IDXDiagContainer object at the specified index.

HRESULT EnumChildContainerNames(
  DWORD dwIndex,
  LPWSTR pwszContainer,
  DWORD cchContainer
);

Parameters

dwIndex
[in] Zero-based index of the container object that specifies which child container name to retrieve. If this is outside of the allowable range, E_INVALIDARG is returned.
pwszContainer
[out] Address of a string buffer that receives the unique name of the child container. This should be at least 256 elements. If the buffer is too small, it returns DXDIAG_E_INSUFFICIENT_BUFFER.
cchContainer
[in] Specifies the size of the pwszContainer buffer in characters.

Return Values

Returns S_OK if successful. Otherwise, returns one of the following values: E_INVALIDARG or DXDIAG_E_INSUFFICIENT_BUFFER.

Requirements

Header: Declared in Dxdiag.h.


IDXDiagContainer::EnumPropNames

Enumerates the name of the property at the specified index.

HRESULT EnumPropNames(
  DWORD dwIndex,
  LPWSTR pwszPropName,
  DWORD cchPropName
);

Parameters

dwIndex
[in] Zero-based index of the container object that specifies which property name to retrieve. If this is outside the allowable range, then E_INVALIDARG is returned.
pwszPropName
[out] Receives the unique name of the property. It should be at least 256 elements. If the buffer is too small, it returns DXDIAG_E_INSUFFICIENT_BUFFER.
cchPropName
[in] Specifies the size of the pwszPropName buffer in characters.

Return Values

If the function fails, returns one of the following values: E_INVALIDARG or DXDIAG_E_INSUFFICIENT_BUFFER.

Requirements

Header: Declared in Dxdiag.h.


IDXDiagContainer::GetChildContainer

Retrieves a pointer to the specified child container.

HRESULT GetChildContainer(
  LPCWSTR pwszContainer,
  IDXDiagContainer ** ppInstance
);

Parameters

pwszContainer
[in] Specifies the NULL-terminated name of the container.
ppInstance
[out] Receives an instance of the child IDXDiagContainer specified by pwszContainer.

Return Values

If unsuccessful, returns one of the following values: E_INVALIDARG or E_OUTOFMEMORY.

Requirements

Header: Declared in Dxdiag.h.


IDXDiagContainer::GetNumberOfChildContainers

Returns the number of IDXDiagContainer objects in this container.

HRESULT GetNumberOfChildContainers(
  DWORD * pdwCount
);

Parameters

pdwCount
[out] Receives the number of IDXDiagContainer objects in the container.

Return Values

Returns S_OK if successful. Otherwise, returns the following value: E_INVALIDARG.

Requirements

Header: Declared in Dxdiag.h.


IDXDiagContainer::GetNumberOfProps

Retrieves the number of properties in this container.

HRESULT GetNumberOfProps(
  DWORD * pdwCount
);

Parameters

pdwCount
[out] Receives the number of properties in this container.

Return Values

Returns S_OK if successful. Otherwise, returns the following value: E_INVALIDARG.

Requirements

Header: Declared in Dxdiag.h.


IDXDiagContainer::GetProp

Retrieves an instance of the specified property.

HRESULT GetProp(
  LPCWSTR pwszPropName,
  VARIANT * pvarProp
);

Parameters

pwszPropName
[in] Specifies the NULL-terminated name of the property.
pvarProp
Receives an instance of the property specified in pwszPropName. Check the method's return value and call VariantClear only if the method succeeds.

Return Values

Returns S_OK if successful. Otherwise, returns one of the error codes for VariantCopy or the following value: E_INVALIDARG.

Requirements

Header: Declared in Dxdiag.h.


IDxDiagProvider

Applications use the methods of the IDxDiagProvider interface to create the root IDXDiagContainer object.

Method | Description
IDxDiagProvider::GetRootContainer | Creates and initializes an IDXDiagContainer object to be the root container.
IDxDiagProvider::Initialize | Initializes an IDxDiagProvider object.


IDxDiagProvider::GetRootContainer

Creates and initializes an IDXDiagContainer object to be the root container.

HRESULT GetRootContainer(
  IDXDiagContainer ** ppInstance
);

Parameters

ppInstance
[in, out] Receives an instance of IDXDiagContainer.

Return Values

If unsuccessful, returns one of the following values: E_CO_UNINITIALIZED, E_OUTOFMEMORY, E_INVALIDARG, or E_NOINTERFACE.

Requirements

Header: Declared in Dxdiag.h.


IDxDiagProvider::Initialize

Initializes an IDxDiagProvider object.

HRESULT Initialize(
  DXDIAG_INIT_PARAMS * pParams
);

Parameters

pParams
[in] DXDIAG_INIT_PARAMS that specifies the initialization parameters.

Return Values

Returns S_OK if successful. Otherwise, returns one of the following values: E_POINTER, E_INVALIDARG, or E_OUTOFMEMORY

Requirements

Header: Declared in Dxdiag.h.


DxDiag_Structures

This section contains the structure exposed by the Microsoft DirectX Diagnostic tool.

Structures

  • DXDIAG_INIT_PARAMS


DXDIAG_INIT_PARAMS

Used by IDxDiagProvider::Initialize to initialize the IDxDiagProvider object.

typedef struct DXDIAG_INIT_PARAMS {
    DWORD dwSize;
    DWORD dwDxDiagHeaderVersion;
    BOOL bAllowWHQLChecks;
    VOID * pReserved;
} DXDIAG_INIT_PARAMS, *LPDXDIAG_INIT_PARAMS;

Members

dwSize
Specifies the size of the structure.
dwDxDiagHeaderVersion
Identifies whether the header is built against the correct version. This value must be DXDIAG_DX9__SDK_VERSION.
bAllowWHQLChecks
Specifies whether the DirectX Diagnostic tool is allowed to verify that the drivers are digitally signed by Microsoft Windows Hardware Quality Labs (WHQL). When doing this, the DirectX Diagnostic tool can connect to the Internet to download new WHQL certificates. The valid values are:
TRUE
Allow verification.
FALSE
Do not allow verification.
pReserved
Reserved. Must be NULL.


DirectSetup Reference

This section contains reference information for the API elements provided by DirectSetup. Reference material is divided into the following categories:

  • DirectSetup Functions
  • DirectSetup Structures
  • DirectSetup Enumerations
  • Return Values


DirectSetup Functions

This section contains information about the following global functions used with DirectSetup:

  • DirectXRegisterApplication
  • DirectXSetup
  • DirectXSetupCallbackFunction
  • DirectXSetupGetEULA
  • DirectXSetupGetVersion
  • DirectXSetupSetCallback
  • DirectXSetupShowEULA
  • DirectXUnRegisterApplication


DirectXRegisterApplication

Deprecated. Do not use.

int DirectXRegisterApplication(
  HWND hWnd,
  LPDIRECTXREGISTERAPP lpDXRegApp
);

Parameters

hWnd
lpDXRegApp

Return Values

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DirectXSetup

Installs DirectX components.

int DirectXSetup(
  HWND hWnd,
  LPSTR lpszRootPath,
  DWORD dwFlags
);

Parameters

hWnd
Handle of the parent window for the setup dialog boxes.
lpszRootPath
Address of a string that contains the root path of the DirectX component files. This string must specify a full path to the directory that contains the files Dsetup.dll and Dsetup32.dll, as well as the DirectX redistributable files. If this value is NULL, the current working directory is used.
dwFlags
This flag is ignored unless you use:
DSETUP_DIRECTX
Installs the core DirectX runtime components.
DSETUP_MANAGEDDX
Installs the Managed Code component. This requires that the Microsoft .NET Framework is installed.
DSETUP_TESTINSTALL
Performs a test installation. Does not install new components.

Return Values

If the function fails fails, it returns an error value (see DirectXSetup Return Values). If the function succeeds, it returns one of the following success codes: DSETUPERR_SUCCESS or DSETUPERR_SUCCESS_RESTART.

Remarks

Before using the DirectXSetup function in your setup program, you should first ensure that the system has enough available disk space. The maximum space that you need to set up DirectX 9 is 20 MB for computers running Windows 98 and Windows Millenium, and 25 MB for Windows 2000 and Windows XP.

Requirements

Header: Declared in Dsetup.h.

See Also

Installing DirectX with DirectSetup


DirectXSetupCallbackFunction

Optional callback function supplied by the setup program. If present, it is called once for each step in the setup process. The name, DirectXSetupCallbackFunction, is a placeholder name.

DWORD DirectXSetupCallbackFunction(
  DWORD Reason,
  DWORD MsgType,
  char * szMessage,
  char * szName,
  void * pInfo
);

Parameters

Reason
Reason for the callback. It can be one of the following values:
DSETUP_CB_MSG_BEGIN_INSTALL
DirectXSetup is about to begin installing DirectX components. The system will be checked for the DirectX version, operating system, system language, and disk space requirements.
DSETUP_CB_MSG_BEGIN_INSTALL_RUNTIME
DirectXSetup is about to begin installing DirectX components.
DSETUP_CB_MSG_INTERNAL_ERROR
An internal error has occurred. Setup of the DirectX component or device driver has failed.
DSETUP_CB_MSG_NOMESSAGE
No message to be displayed. The callback function should return.
DSETUP_CB_MSG_PROGRESS
Reporting the progress of the runtime installation, which includes initializing, extracting, copying, and finalizing DirectSetup files.
DSETUP_CB_MSG_WARNING_DISABLED_COMPONENT
DirectSetup has detected that one or more DirectX components are disabled.
MsgType
Flags that control the display of a message box. These flags can be passed as the uType parameter to the MessageBox function. An exception is when MsgType is 0. In that case, the setup program can display status information, but it should not wait for input from the user.
szMessage
Pointer to a localized character string containing error or status messages that can be displayed in a dialog box created with the MessageBox function.
szName
NULL and can be ignored.
pInfo
Pointer to the address of a structure containing upgrade information. When Reason is DSETUP_CB_MSG_PROGRESS, the setup program supplies the current state of installation. In this case, pInfo points to a DSETUP_CB_PROGRESS structure containing information about the phase of the installation.

Return Values

The return value should be IDOK, MB_OK, or MB_OK | MB_ICONERROR. If this function returns 0, the DirectXSetup function performs the default action.

Remarks

The actual name of this function is supplied by the setup program. The DirectXSetupSetCallback function is used to pass the address of the callback function to DirectSetup.

If MsgType is 0, the setup program can display status information, but it should not wait for user input. In this case, the function returns IDOK.

If Reason is DSETUP_CB_MSG_WARNING_DISABLED_COMPONENT, direct the user to the DirectX Diagnostic Tool for more information about enabling DirectX components. It is typical for components, such as Direct3D, to be disabled on computers running Windows Server.

Requirements

Header: Declared in Dsetup.h.

See Also

DirectXSetupSetCallback


DirectXSetupGetEULA

Gets the DirectX end-user license agreement (EULA) text for a specific language.

int DirectXSetupGetEULA(
  LPTSTR lpszEULA,
  UINT cchEULA,
  WORD LangID
);

Parameters

lpszEULA
[out] Points to a buffer that receives the EULA string. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. For more information, see Remarks.
cchEULA
[in] Specifies the size of the buffer pointed to by the lpszEULA parameter. If this value is zero, the function returns the required buffer size and makes no use of the lpszEULA buffer. If the compiler settings specify Unicode, the size is in Unicode characters; otherwise, the size is in ANSI characters.
LangID
[in] Specifies in which language the DirectX EULA is returned. Specify 0 for the system default language, or specify one of the following values:
MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED)
MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL)
MAKELANGID(LANG_CZECH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_DUTCH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_ENGLISH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_FRENCH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_GERMAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_ITALIAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_JAPANESE, SUBLANG_NEUTRAL)
MAKELANGID(LANG_KOREAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_POLISH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_PORTUGUESE, SUBLANG_NEUTRAL)
MAKELANGID(LANG_RUSSIAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_SPANISH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_SWEDISH, SUBLANG_NEUTRAL)

Return Values

If the function succeeds, and cchEULA is a nonzero value, the return value is the number of EULA characters (Unicode or ANSI) written to the buffer pointed to by lpszEULA. If the function succeeds, and cchEULA is 0, the return value is the required size, in ANSI or Unicode characters, for a buffer that can receive the EULA string.

If the function fails, the return value is 0. To get extended error information, call GetLastError.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to DirectXSetupGetEULAW. Otherwise, the function call resolves to DirectXSetupGetEULAA, because ANSI strings are being used.

If a LangID is passed that is not supported, the function fails and returns 0. In this case, the return value of GetLastError is ERROR_INVALID_PARAMETER. ERROR_INVALID_PARAMETER is also returned for the following reasons:

  • cchEULA is not large enough to receive the EULA.
  • cchEULA is a nonzero value, and lpszEULA is NULL.
  • lpszEULA is an invalid pointer.

The setup application must display the EULA in accordance with the DirectX SDK EULA.

The EULA must be displayed and accepted before continuing with the DirectSetup process.

Requirements

Header: Declared in Dsetup.h.


DirectXSetupGetVersion

Retrieves the version number of the DirectX core runtime components that are currently installed.

INT DirectXSetupGetVersion(
  DWORD * pdwVersion,
  DWORD * pdwRevision
);

Parameters

pdwVersion
Pointer to the address of a variable to receive the version number. This parameter can be NULL if the version number is not wanted.
pdwRevision
Pointer to the address of a variable to receive the revision number. This parameter can be NULL if the revision number is not wanted.

Return Values

If the function succeeds, it returns nonzero.

If it fails, it returns 0.

Remarks

The DirectXSetupGetVersion function can be used to retrieve the version and revision numbers before or after the DirectXSetup function is called. If it is called before DirectXSetup is invoked, it gives the version and revision numbers of the DirectX core runtime components that are currently installed. If it is called after DirectXSetup is called, but before the computer is restarted, it gives the version and revision numbers of the DirectX components that take effect after the computer is restarted.

The version number in the pdwVersion parameter is composed of the major version number and the minor version number. The major version number is in the 16 most significant bits of the DWORD when this function returns. The minor version number is in the 16 least significant bits of the DWORD when this function returns. The version numbers can be interpreted as follows:

DirectX version | Value pointed to by pdwVersion
DirectX 5 | 0x00040005
DirectX 6 | 0x00040006
DirectX 7 | 0x00040007
DirectX 8 | 0x00040008
DirectX 9 | 0x00040009

DirectX 9 supports only operating systems and DirectX versions later than Windows 98 and DirectX 5. This method will not return a value less than 0x00040005 for pdwVersion.

The version number in the pdwRevision parameter is composed of the release number and the build number. The release number is in the 16 most significant bits of the DWORD when this function returns. The build number is in the 16 least significant bits of the DWORD when this function returns.

All DirectX 8 releases have the same pdwVersion value. The pdwRevision parameter differentiates them. DirectX 8 versions do not install on Windows XP. Windows XP shipped with DirectX 8.1 and the DirectX 8.1a and DirectX 8.1b updates were included in Windows XP Service Pack 1. The following table lists the pdwRevision values for DirectX 8.

DirectX release | pdwRevision | Notes
DirectX 8 |  |
DirectX 8.1 | 0x0001032A | 4.08.01.0810. Windows XP version.
DirectX 8.1 | 0x00010371 | 4.08.01.0881. This is the DirectX 8.1 version for the down level operating systems. 0371 is the hex version for 0881 decimal revision value.
DirectX 8.1a | 0x00010385 | 4.08.01.0901. This release includes an update to Direct3D (D3d8.dll).
DirectX 8.1b | 0x00010385 | 4.08.01.0901. This update includes a fix to DirectShow on Windows 2000 (Quartz.dll).
DirectX 8.2 | 0x00020386 | 4.08.02.0134.

All DirectX 9 releases have the same pdwVersion value. The pdwRevision parameter differentiates them. The following table lists the pdwRevision values for DirectX 9 releases.

DirectX release | pdwRevision | Notes
DirectX 9 | 0x00000384 | 4.09.00.0900. This release includes many updates across all DirectX components.
DirectX 9a | 0x00000385 | 4.09.00.0901. This is an incremental update to DirectX 9, which include updates to DirectX for managed code, Graphics, and DirectSetup components.
DirectX 9b | 0x00000386 | 4.09.00.0902. This is an incremental update, which includes DirectX 9a updates, plus additional updates to the DirectShow and Direct3D components.
DirectX 9c | 0x00000387 | 4.09.00.0903. This is an incremental update, which includes DirectX 9b updates, plus additional updates for Windows XP Service Pack 2 (SP2). This is the default version for SP2.
DirectX 9c | 0x00000388 | 4.09.00.0904. This is the SP2 release for downlevel platforms.

Note There is no way to tell the difference between DirectX 8.1a and DirectX 8.1b with the pdwVersion and pdwRevision values. DirectX 8.1a updates only D3d8.dll. DirectX 8.1b includes the changes in DirectX 8.1a as well as updates to other files. Use GetFileVersionInfo to get version information for the following files.

On Windows 2000:

Quartz.dll | 6.03.01.0885
Stream.sys | 5.01.2600.0885
Mpg2splt.ax | 6.03.01.0885
D3d8.dll | 5.01.2600.0901
D3d8d.dll | 5.01.2600.0901

On Windows 95 or later:

Mpg2splt.ax | 6.03.01.0885
D3d8.dll | 4.08.01.0901
D3d8d.dll | 4.08.01.0901

The following sample code fragment demonstrates how the information returned by DirectXSetupGetVersion can be extracted and used.

DWORD dwVersion;
DWORD dwRevision;
if (DirectXSetupGetVersion(&dwVersion, &dwRevision))
{
    printf("DirectX version is %d.%d.%d.%d\n",
           HIWORD(dwVersion), LOWORD(dwVersion),
           HIWORD(dwRevision), LOWORD(dwRevision));
}

Version and revision numbers can be concatenated into a 64-bit quantity for comparison. The version number is in the 32 most significant bits and the revision number is in the 32 least significant bits.

Requirements

Header: Declared in Dsetup.h.

See Also

DirectXSetup


DirectXSetupSetCallback

Sets a pointer to a callback function that is periodically called by DirectXSetup. The callback function can be used for setup progress notification and to implement a custom user interface for an application's setup program. For more information about the callback function, see DirectXSetupCallbackFunction. If a setup program does not provide a callback function, DirectXSetupSetCallback is not invoked.

INT DirectXSetupSetCallback(
  DSETUP_CALLBACK Callback
);

Parameters

Callback
Address of a callback function.

Return Values

Currently returns 0.

Remarks

To set a callback function, DirectXSetupSetCallback must be called before DirectXSetup is called.

The name of the callback function passed to DirectXSetupSetCallback is supplied by the setup program. However, it must match the prototype given in DirectXSetupCallbackFunction.

Requirements

Header: Declared in Dsetup.h.

See Also

DirectXSetupCallbackFunction, DirectXSetup


DirectXSetupShowEULA

Displays the DirectX end-user license agreement (EULA) in the system's localized language.

int DirectXSetupShowEULA(
  HWND hWndParent
);

Parameters

hWndParent
Handle of the parent window for the EULA dialog boxes.

Return Values

IDYES is returned if the user accepts the EULA and the application can continue with DirectSetup. Otherwise, IDNO is returned and the application must cancel DirectSetup.

Remarks

Both the EULA and dialog box displaying the EULA are localized to the system language.

If hWndParent equals NULL then DirectSetup uses the desktop as the parent window.

DirectXSetupShowEULA should be called before proceeding with DirectSetup.

Even if the local language for the system is changed to another language, using, for example, a multilingual user interface package, this API displays the DirectX UI in the system language. To display the EULA for local languages other than the system language, use DirectXSetupGetEULA.

IDNO is returned if the user rejects the EULA or an internal setup error occurs.

Requirements

Header: Declared in Dsetup.h.


DirectXUnRegisterApplication

Deprecated. Do not use.

int DirectXUnRegisterApplication(
  HWND hWnd,
  LPGUID lpGUID
);

Parameters

hWnd
lpGUID

Return Values

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DirectSetup Structures

This section contains the structure exposed by the DirectX Diagnostic tool.

  • DIRECTXREGISTERAPP
  • DIRECTXREGISTERAPP2
  • DSETUP_CB_PROGRESS

Note The memory for all Microsoft DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use.


DIRECTXREGISTERAPP

Deprecated. Do not use.

typedef struct DIRECTXREGISTERAPP {
    DWORD dwSize;
    DWORD dwFlags;
    LPSTR lpszApplicationName;
    LPGUID lpGUID;
    LPSTR lpszFilename;
    LPSTR lpszCommandLine;
    LPSTR lpszPath;
    LPSTR lpszCurrentDirectory;
} DIRECTXREGISTERAPP, *LPDIRECTXREGISTERAPP;

Members

dwSize
dwFlags
lpszApplicationName
lpGUID
lpszFilename
lpszCommandLine
lpszPath
lpszCurrentDirectory


DIRECTXREGISTERAPP2

Deprecated. Do not use.

typedef struct DIRECTXREGISTERAPP2 {
    DWORD dwSize;
    DWORD dwFlags;
    LPSTR lpszApplicationName;
    LPGUID lpGUID;
    LPSTR lpszFilename;
    LPSTR lpszCommandLine;
    LPSTR lpszPath;
    LPSTR lpszCurrentDirectory;
    LPSTR lpszLauncherName;
} DIRECTXREGISTERAPP2, *LPDIRECTXREGISTERAPP2;

Members

dwSize
dwFlags
lpszApplicationName
lpGUID
lpszFilename
lpszCommandLine
lpszPath
lpszCurrentDirectory
lpszLauncherName


DSETUP_CB_PROGRESS

Passed as a parameter to the application-defined DirectXSetupCallbackFunction. It contains valid information only when the Reason parameter is DSETUP_CB_MSG_PROGRESS. Callback functions can use it to get status information on the upgrade that is about to be done.

typedef struct DSETUP_CB_PROGRESS {
    DWORD dwPhase;
    DWORD dwInPhaseMaximum;
    DWORD dwInPhaseProgress;
    DWORD dwOverallMaximum;
    DWORD dwOverallProgress;
} DSETUP_CB_PROGRESS, *LPDSETUP_CB_PROGRESS;

Members

dwPhase
Flag indicating the phase of the installation progress. Can be any of the DSETUP_CB_PROGRESS_PHASE flags.
dwInPhaseMaximum
Maximum number of files that need to be extracted or copied during the DSETUP_EXTRACTING or DSETUP_COPYING phases. This parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise, it is 0 and can be ignored.
dwInPhaseProgress
Current number of files that have been extracted or copied during the DSETUP_EXTRACTING or DSETUP_COPYING phases. This parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise, it is 0 and can be ignored.
dwOverallMaximum
Total number of files for both the DSETUP_EXTRACTING and DSETUP_COPYING phases that need to be performed. This parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise, it is 0 and can be ignored.
dwOverallProgress
Current number of files that have been extracted or copied in relation to the dwOverallMaximum value. This parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise, it is 0 and can be ignored.

See Also

DirectXSetupCallbackFunction


DirectSetup Enumerations

This section contains information on the following enumerations used with DirectSetup:

  • DSETUP_CB_PROGRESS_PHASE


DSETUP_CB_PROGRESS_PHASE

Specifies the progress phase of a DirectSetup installation.

typedef enum DSETUP_CB_PROGRESS_PHASE
{
    DSETUP_INITIALIZING,
    DSETUP_EXTRACTING,
    DSETUP_COPYING,
    DSETUP_FINALIZING,
} DSETUP_CB_PROGRESS_PHASE, *LPDSETUP_CB_PROGRESS_PHASE;

Constants

DSETUP_INITIALIZING
Initializing DirectSetup. Initialization includes version checking, an operating system check, and locale and disk space calculations.
DSETUP_EXTRACTING
Extracting files from the cabinet (.cab) files.
DSETUP_COPYING
Copying files onto the user's computer.
DSETUP_FINALIZING
Finalizing DirectSetup. This includes updating the registry and removing temporary files.


Return Values

The DirectXSetup function can return the following values.

typedef enum Return_Values
{
    DSETUPERR_SUCCESS = 0,
    DSETUPERR_SUCCESS_RESTART = 1,
    DSETUPERR_BADWINDOWSVERSION = -1,
    DSETUPERR_SOURCEFILENOTFOUND = -2,
    DSETUPERR_NOCOPY = -5,
    DSETUPERR_OUTOFDISKSPACE = -6,
    DSETUPERR_CANTFINDINF = -7,
    DSETUPERR_CANTFINDDIR = -8,
    DSETUPERR_INTERNAL = -9,
    DSETUPERR_UNKNOWNOS = -11,
    DSETUPERR_NOTADMIN = -15,
    DSETUPERR_UNSUPPORTEDPROCESSOR = -16,
    DSETUPERR_CABDOWNLOADFAIL = -19,
    DSETUPERR_DXCOMPONENTFILEINUSE = -20,
    DSETUPERR_UNTRUSTEDCABINETFILE = -21,
} Return Values;

Constants

DSETUPERR_SUCCESS
Setup was successful, and no restart is required.
DSETUPERR_SUCCESS_RESTART
Setup was successful, and a restart is required.
DSETUPERR_BADWINDOWSVERSION
Microsoft DirectX does not support the version of Microsoft Windows on the computer.
DSETUPERR_SOURCEFILENOTFOUND
One of the required source files could not be found.
DSETUPERR_NOCOPY
A file's version could not be verified or was incorrect.
DSETUPERR_OUTOFDISKSPACE
The setup program ran out of disk space during installation.
DSETUPERR_CANTFINDINF
A required information (.inf) file could not be found.
DSETUPERR_CANTFINDDIR
The setup program could not find the working directory.
DSETUPERR_INTERNAL
An internal error occurred.
DSETUPERR_UNKNOWNOS
The operating system is unknown.
DSETUPERR_NOTADMIN
The current user does not have administrative privileges. On Windows 2000, the user may need administrative privileges for some setup operations.
DSETUPERR_UNSUPPORTEDPROCESSOR
The processor type is unsupported. DirectX supports only Intel Pentium, AMD K6, and compatible processors with equivalent or higher performance.
DSETUPERR_CABDOWNLOADFAIL
The cabinet (.cab) file failed to load.
DSETUPERR_DXCOMPONENTFILEINUSE
The cabinet (.cab) file was in use.
DSETUPERR_UNTRUSTEDCABINETFILE
The cabinet (.cab) file is not signed.


IUnknown

All Component Object Model (COM) objects support an interface called IUnknown. This interface provides Microsoft DirectX with control of the object's lifetime and the ability to retrieve other interfaces implemented by the object. IUnknown has three methods.

IUnknown Members

Method | Description
IUnknown::AddRef | Increases the interface's reference count by 1.
IUnknown::QueryInterface | Reference identifier of the interface being requested.
IUnknown::Release | Decreases the reference count of the interface by 1.

Remarks

The IUnknown::AddRef and IUnknown::Release methods maintain an object's reference count. For example, if you create a Microsoft Direct3D object, the object's reference count is set to 1. Every time that a function returns a pointer to an interface for that object, the function must call IUnknown::AddRef through that pointer to increment the reference count. Match each IUnknown::AddRef call with a call to IUnknown::Release. You must call IUnknown::Release through that pointer before the pointer can be destroyed. After an object's reference count reaches 0, the object is destroyed, and all interfaces to it become invalid.

The IUnknown::QueryInterface method determines whether an object supports a specific interface. If an object supports an interface, IUnknown::QueryInterface returns a pointer to that interface. You then can use the methods of that interface to communicate with the object. If IUnknown::QueryInterface successfully returns a pointer to an interface, it implicitly calls IUnknown::AddRef to increment the reference count; so, your application must call IUnknown::Release to decrement the reference count before destroying the pointer to the interface.

Note The reference pages for IUnknown are included with this documentation as a convenience for users of the stand-alone DirectX Help. Refer to the Microsoft Platform Software Development Kit (SDK) documentation for the most complete and up-to-date information about this interface.


IUnknown::AddRef

Increases the interface's reference count by 1.

ULONG AddRef();

Parameters

None.

Return Values

Returns the new reference count. This value is for diagnostic and testing purposes only.

Remarks

When the interface is created, its reference count is set to 1. Every time that an application obtains an interface to the object or calls the IUnknown::AddRef method, the interface's reference count is increased by 1. Use the IUnknown::Release method to decrease the interface's reference count by 1.

Requirements

Header: Declared in Unknwn.h.


IUnknown::QueryInterface

Determines whether the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately.

HRESULT QueryInterface(
  REFIID riid,
  LPVOID * ppvObj
);

Parameters

riid
Reference identifier of the interface being requested.
ppvObj
Address of a pointer to fill with the interface pointer, if the query succeeds.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value may be E_NOINTERFACE. Some components also have their own definitions of these error values in their header files.

Remarks

If the application does not need to use the interface retrieved by a call to this method, it must call the IUnknown::Release method for that interface to free it. The IUnknown::QueryInterface method makes it possible to extend objects without interfering with functionality.

Requirements

Header: Declared in Unknwn.h.


IUnknown::Release

Decreases the reference count of the interface by 1.

ULONG Release();

Parameters

None.

Return Values

Returns the new reference count. This value is for diagnostic and testing purposes only.

Remarks

The object that exports the interface deallocates itself when its total reference count reaches 0. Use the IUnknown::AddRef method to increase the interface's reference count by 1.

Applications must call this method to release only those interfaces that were explicitly created in a previous call to IUnknown::AddRef, IUnknown::QueryInterface, or a creation function, such as Direct3DCreate9.

Requirements

Header: Declared in Unknwn.h.


Further Information

There are many places to go for further information about DirectX in general, or any of the components in DirectX, or even COM programming background.

For the latest information, see the Microsoft DirectX Development Center. This Web site contains pointers to many sources of information, including: the latest documentation and technical articles, code samples, downloads, and links to newsgroups and other online DirectX communities.

  • Graphics Information
  • Sound and Music Information
  • Developing for Microsoft Platforms
  • Security Information

Graphics Information

Here are some references for more information about graphics topics:

  • Akenine-Möller, T., and Haines, E. Real-Time Rendering. Second ed. Reading, MA: Addison-Wesley, 1991.
  • Blinn, Jim. Jim Blinn's Corner: A Trip Down the Graphics Pipeline. San Francisco, CA: Morgan Kaufmann Publishers, 1996.
  • Eberly, David H. 3D Game Engine Design: A Practical Approach to Real-Time Computer Graphics. San Francisco, CA: Morgan Kaufmann Publishers, 2000.
  • Engel, Wolfgang F. Direct3D ShaderX2: Introductions & Tutorials with DirectX 9. Plano, TX: Wordware Publishing, 2003.
  • Engel, Wolfgang F. Direct3D ShaderX2: Shader Programming Tips & Tricks With Directx 9. Plano, TX: Wordware Publishing, 2003.
  • Foley, James D., et al. Computer Graphics: Principles and Practice. Second ed. in C. Reading, MA: Addison-Wesley, 1995.
  • Gray, Kris. DirectX 9 Programmable Graphics Pipeline. Redmond, WA: Microsoft Press, 2003.
  • Hearn, Donald, and M. Pauline Baker. Computer Graphics. Second ed. Englewood Cliffs, NJ: Prentice-Hall, 1994.
  • Shirley, Peter. Fundamentals of Computer Graphics. Natick, MA: AK Peters, 2002.
  • Walsh, Peter. The Zen of Direct3D Game Programming. Roseville, CA: Prima Publishing, 2001.
  • Watt, Alan. 3D Computer Graphics. Third ed. Harlow, England; Reading, MA: Addison-Wesley, 2000.
  • Watt, Alan, and Fabio Policarpo. 3D Games: Real-Time Rendering and Software Technology. Volumes 1 and 2. Reading, MA: Addison-Wesley, 2003.
  • Watt, Alan, and Mark Watt. Advanced Animation and Rendering Techniques: Theory and Practice. New York, NY: ACM Press; Wokingham, England; Reading, MA: Addison-Wesley, 1992.

Sound and Music Information

You can find more information about sound and music in the following books:

  • Begault, Durand R. 3D Sound for Virtual Reality and Multimedia. Academic Press, 1994.
  • Dodge, Charles, and Thomas A. Jerse. Computer Music: Synthesis, Composition, and Performance. Second ed. Schirmer Books, 1997.
  • Kientzle, Tim. A Programmer's Guide to Sound. Addison-Wesley Developers Press, 1998.

Developing for Microsoft Platforms

  • Brockschmidt, Kraig. Inside OLE 2. Second ed. Microsoft Press, 1995.
  • Miller, Tom. Managed DirectX 9 Graphics and Game Programming, Kick Start. Sams, 2003
  • Nathan, Adam. .NET and COM: The Complete Interoperability Guide. Pearson Education, 2002.
  • Petzhold, Charles. Programming Windows with C#. Microsoft Press, 2001.
  • Richter, Jeffrey. Applied Microsoft .NET Framework Programming. Microsoft Press, 2002.
  • Robbins, John. Debugging Applications for Microsoft .NET and Microsoft Windows. Microsoft Press, 2003.
  • Rogerson, Dale E. Inside COM. Microsoft Press, 1997.
  • Russinovish, M.E., and Solomon, D.A. Inside Microsoft Windows Internals, Covering Windows 2000, Windows XP, Windows Server 2003. Microsoft Press, 2005.
  • Troelsen, Andrew. C# and the .NET Platform. APress, 2003.

Security Information

For general security topics, such as avoiding buffer overruns and running with special privileges, see Security Developer Center.

For more information about writing secure code, see:

  • Howard, Michael, and David LeBlanc. Writing Secure Code. Redmond, WA: Microsoft Press, 2002.


DirectX Documentation Conventions

The following conventions are used in the syntax of methods, functions, and other API elements, as well as typographic conventions used in explanatory material and sample code.

Convention | Meaning
FULL BOLD CAPITALS | Used for most type and structure names.
FULL CAPITALS | Used for enumeration values, flags, and constants.
Bold text | Denotes a function, procedure, structure, macro, interface, method, data type, or other keyword in the programming interface or language.
Italic text | Denotes a placeholder or variable. You must provide the actual value. For example, the statement SetCursorPos(x,y) requires you to substitute values for the x and y parameters.
monospace
 Used for code examples, syntax spacing, and user input.
[] Encloses optional parameters.
... Specifies that the preceding item may be repeated or represents an omitted portion of text or sample.
... Represents an omitted portion of a sample application.

Obtaining Code Syntax and Help in Visual Studio .NET

You can search the help files within Visual Studio .NET as follows:

  • Place the cursor over a DirectX object in code, and prototype syntax will appear.
  • Place the cursor over a DirectX object in code, then press F1, and a help page will open on that topic.
  • In a line of code, type in a DirectX method or function name, then an open parenthesis, and required parameters and their types will appear to assist completion of the method or function call.

    Code syntax display in Visual Studio .NET

Printing Help Files

To print the SDK Help files, complete the following steps.

  1. Open the Help file.
  2. From the File menu, click Print. The Print Topics dialog box appears.

    Print Topics dialog box

  3. Click either Print the selected topic or Print the selected heading and all subtopics.
  4. Click OK.

To print C++ graphics files, for example, the Help files can be opened from Start, All Programs, Microsoft DirectX SDK, DirectX Documentation for C++, or by double-clicking the SDK Help file at the following location:

(SDK root)\Documentation\DirectX9\

If the pages are being cut off on the right side when printing, decrease the font size so that the text does not exceed the right page margin. You can do this by clicking the Font button one or more times to choose a smaller font size before opening the Print Topics dialog box.

Location of the Font button

Using the Index

When using the Help file, click the Index tab at the left and then use this typical procedure:

  1. In the index text entry box, type the name of the DirectX method you seek. The index list will display topics that match what you have typed, along with their associated interfaces in parentheses. For example, if you type "lock", then Lock Method (IDirect3DVertexBuffer9) will be one of several Lock methods listed.
  2. Double-click the appropriate entry to open its documentation.

Searching the Help Files

To begin a search in the Help file, click the Search tab. Type in the word or phrase you are looking for. To do partial word searches, use the * wildcard. For example, a search for D3DXLoad* returns all references to functions that begin with D3DXLoad.


DirectX Audio

  • Microsoft Cross-Platform Audio Creation Tool (XACT)
  • DirectSound


Microsoft Cross-Platform Audio Creation Tool (XACT)

This section provides information about the Microsoft Cross-Platform Audio Creation Tool (XACT). This tool and its associated APIs allow developers and content providers to work together and bring vibrant sounds to a game.

Infomation is presented in the following sections:

XACT Features
Describes the key features of the XACT framework for sound designers and game programmers.
XACT Best Practices
Best practices for designing and programming with XACT.
XACT Concepts and Terminology
An introduction to key concepts and terms used in XACT.
XACT Audio Authoring
A guide to creating audio content using XACT.
XACT Programming
A guide to programming the XACT engine for use in an application.
XACT Tutorials and Samples
A set of tutorials and samples that demonstrate how to use XACT.


XACT Features

Microsoft Cross-Platform Audio Creation Tool (XACT) is a production-ready environment for integrating audio resources into game titles. It is expected that audio designers will use one of the many linear audio editing packages that are available commercially to develop the core audio elements (waves) for the game. The designer will then use XACT to package those audio resources to aid the programmer in making them an interactive part of gameplay.

This topic describes the benefits of XACT as pertains to each partner in the development process for title audio:

  • For Audio Designers
  • For Title Programmers

For Audio Designers

The XACT authoring tool allows the designer to group waves into cues and sequences, which include settings for volume and pitch levels.

These are the key features of the XACT authoring tool:

  • Audio File Formats
  • Speaker Channels
  • Organizing
  • Auditioning

Audio File Formats

XACT supports a variety of audio file formats, including:

  • WAV — the standard audio file format for Microsoft® Windows® environments.
  • AIFF — the standard audio file format for Apple® Macintosh® environments.
  • ADPCM — compressed form of PCM data.

    Note ADPCM is currently only available for Windows, including XNA Game Studio Express Windows deployments.

  • XMA — a file format based on Microsoft WMA.

    Note XMA is currently only available for Xbox 360, including XNA Game Studio Express Xbox 360 deployments.

The XACT authoring tool supports both 16-bit and 8-bit PCM data.

XACT will also recognize and properly act on loop points embedded within WAV and AIFF files. This means that loop markers created with commercially available linear audio design tools will be honored by XACT.

Speaker Channels

XACT supports stereo and 5.1 channel speaker arrangements. Currently no other speaker arrangements are supported.

Organizing

XACT provides the audio designer with a variety of ways to bundle audio elements into collections and group them into sequences for events in the game.

  • Wave banks allow the designer to package collections of multiple audio files into single files. These files are identified by the .XWB extension.

    This feature simplifies management of audio data for the programmer. Rather than trying to manage many audio files, titles can now load a more manageable set of wave banks that bundle the waves necessary for a section of the game.

    XACT wave banks can optionally compress wave files to Microsoft ADPCM.

  • Sound banks allow the designer to package collections of cues, waves and settings for ready playback by a game title. A sound bank file is identified by its .XSB extension.

Auditioning

XACT provides the designer with the ability to preview audio content on the game platform. An audio console application that executes on the game platform is provided with Microsoft development kits that accepts information from the Windows-based XACT running on the development system, and allows controlled playback of audio sequences.

Designers can also perform "in-game" auditioning with XACT. When a game title is built with special development-only libraries, a designer can adjust the audio settings while the game application is running. This allows the designer to test and discover what works best under conditions of actual gameplay.

For Title Programmers

The XACT API functions allow the programmer to integrate the designer's work into the game title flexibly and efficiently.

The XACT run-time libraries:

  • Ease the integration of wave, sound and cue information from the audio designer.
  • Support in-memory and streaming wave banks with minimal programmer intervention.
  • Free the game title developer to focus on gameplay rather than feeding audio hardware.
  • Allow audio resources to be invoked by cue name rather than by specific components.
  • Provide notification of audio events to the game title.
  • Provide a powerful feature called zero-latency streaming that solves the problem of fitting waves within allocated memory. This feature is discussed in more detail in XACT Streaming Wave Banks.

See Also

XACT Overviews, XACT Reference, XACT Audio Authoring


XACT Best Practices

Before You Get Started

When creating audio resources for a game title, it is important to understand which aspects are in the hands of the programmer and which are the responsibility of the composer or sound designer. To help avoid confusion and collisions as each pursues their tasks, the Microsoft Cross-Platform Audio Creation Tool (XACT) provides a single way to perform most tasks. Properties and behaviors that are specified in content cannot generally be overridden by the programmer. Similarly, the composer does not control the management of memory or other resources.

At the project start, the sound designer and the programmer decide jointly on important cues, or trigger points, in the game. The composer creates a sound (or perhaps multiple sounds, one of which will be chosen randomly to play) that will be played when the cue event occurs. Using the audio resources that the composer has created and organized with the XACT, the programmer will ensure that the sound is played at the right time in the game.

Designer Responsibilities

The sound designer or composer will use the XACT to organize the audio as follows:

  • Grouping the audio wave files he/she has created into collections of wave banks.
  • Defining the program cues that designer and programmer have agreed upon as XACT data.
  • Assigning the audio to cues, and organizing these relationships into sound banks.
  • Assigning playback settings to each cue event, which is included in the sound bank information. This can include volume and pitch, adjustments to hardware envelopes, starting and stopping low-frequency oscillators, and sweeping filters.
  • Defining the variables that the programmer will need to control the audio elements within the game software.
  • Defining run-time parameter controls that allow the programmer to vary the audio, in order to create dynamic, interactive audio content.
  • Build the project to produce the data files the programmer will need to integrate the audio resources into game.

Programmer Responsibilities

The programmer will use the data files received from the sound designer with the XACT API libraries to:

  • Launch the calls that will play the cues.
  • Manage software resources (such as memory, free hardware voices, and content loading and unloading).
  • Manage all dynamic sound management (pause/resume, 3D positioning, and so on).

See Also

XACT Overviews, XACT Reference, XACT Audio Authoring


XACT Concepts and Terminology

Working with the Microsoft Cross-Platform Audio Creation Tool (XACT) requires a working knowledge of some general terminology and concepts. This section discusses these terms as they apply to the XACT.

An XACT project is composed of three top-level collections of information, Wave Banks, Sound Banks and Global Settings. Each of these components will be represented by a data file, to be conveyed to the title programmer, once the project is built.

Icon | XACT Term
 | Wave Banks (file extension .xwb)
 | Waves
 | Sound Banks (file extension .xsb)
 | Sounds
 | Tracks
 | Events
 | Cues
[no icon] | Global Settings (file extension .xgs)
 | Categories
 | Variables
 | Runtime Parameter Controls
 | DSP Effect Path Presets
 | Compression Presets

Wave Banks

A wave bank is a collection of waves logically grouped into a single file by an audio designer. When an XACT project is built for integration into a game title, each wave bank is represented by a file with the extension .xwb.

For example, user interface waves that are always resident in memory may be stored in one wave bank, while waves used for sound effects are stored in another.

Figure 1. XACT Wave Banks

Wave Bank Modes

XACT supports two types of wave banks, in-memory and streaming:

In-Memory

In-memory wave banks are, as the name implies, held in active memory and delivered to the audio output as gameplay proceeds. This is typically used for small audio resources, such as sound effects or pieces of dialogue.

Streaming

Streaming wave banks are transferred directly from the DVD to the audio output through an intermediate memory buffer. This mode is typically used for large audio resources, like background music or ongoing soundtrack, which would otherwise require a great deal of system memory.

For more information on streaming wave banks, see XACT Streaming Wave Banks.

Waves

Waves are audio data files that are used whole or as building blocks for creating sound effects. XACT supports the following audio formats for waves:

  • Windows audio waves (WAV)
  • The native format (XMA), based on Windows Media Audio (WMA)
  • Audio interchange file format (AIFF)

You can use any of several commercially available applications to create waves.

Sound Banks

A Sound Bank is a collection of sounds and cues logically grouped by the sound designer. When an XACT project is built for integration into a game title, each sound bank is represented by a file with the extension .xsb.

A sound bank file does not contain wave data; wave data reside in wave banks. A sound bank references the waves that are bundled in wave banks, and houses the information on how they are to be played.

The components of a sound bank are sounds and cues.

  • Sounds
  • Cues

The diagram below illustrates how a sound bank designed for a game title might define its cues and sounds, and how sounds might be mapped to individual waves:

Figure 2. XACT Sound Banks

Sounds

A sound specifies how one or more waves should be played. A sound also has specific properties such as volume and pitch. These properties can be adjusted by the sound designer.

Sounds are composed of tracks and events.

  • Tracks
  • Events

Tracks

A Track is a grouping of events that, together, define a sound. A sound is composed of one or more tracks.

Each track can contain a single Play Wave event, as well as any number of other events (such as markers and volume changes). Each track of a sound plays only a single wave at any given time. For sounds that require wave files to be played concurrently, you may create multiple tracks, each with its own Play Wave event (and again, each with as many other event types as you wish).

Events

Events are actions to be performed within the body of a track. A track must have at least one event. The simplest event type is a Play Wave event, which plays a wave.

The simplest style of a Play Wave event is one that plays a single wave. However, a play event may also play a wave from a wave variation list, which can play waves in sequence, or randomly selected.

Other events control or constrain the manner in which the wave is played. They may include the following:

Stop
Playing of the track or the entire sound is halted.
Marker
Provides a notification to the program when a marked position in the track is reached. This allows the program to synchronize action to an audio event. Markers are a core part of controlling the way XACT Interactive Audio cues transition from variation to variation.
Set Volume
Sets a level, or variable ramp or sweep.
Set Pitch
Sets a fixed or variable pitch.
Set Variable
Not currently supported.
Branch/Wait
Not currently supported.

Cues

Cues are what programmers use to play sounds. (Sometimes playing a cue is called "triggering" a cue.) Cues are typically played when certain game events, such as footsteps or gunshots, occur. A cue is composed of one or more sounds, so when the cue is triggered, the set of associated sounds is heard.

A cue can be associated with a sound variation list instead of a single sound, and the audio designer may specify that sounds in the list are to be played in strict sequence, shuffled or randomly selected.

A sound designer can easily reassign sounds to a cue without programmer intervention. For example, a sound designer can try various gunshot waves associated with a particular game event without requiring the programmer to change their code or rename sounds.

Global Settings

Some settings are considered global, which means they are not tied exclusively to a wave bank or sound bank. These are defined within the Global Settings (XGS) file that is generated when the XACT project is built. These global settings are the following:

  • Categories
  • Variables
  • Run-Time Parameter Controls
  • DSP Effect Path Presets
  • Compression Presets

Categories

Categories are a way of sorting audio resources into common behaviors.

Assigning sounds to categories allows the programmer to collectively change settings for similarly associated sounds. It can also ensure that a sound assigned to a category behaves according to a common set of rules, including a limit on the number of playing instances of sounds belonging to that category.

For example, a sound designer of a role-playing game might group all dialogue spoken by antagonists into a single category, so that all voices are played at a common volume, paused and restarted in unison, or limited to no more than three active at once.

XACT also allows categories to belong to other categories (also known as subcategories). For example, a category of "Dialogue" may be further broken down into "Allies" and "Enemies."

A sound may be assigned to only one category. XACT supports up to 255 categories.

XACT provides three predefined categories:

Global
The top-level category, to which all XACT sounds belong. This category allows for master volume set, pause or resume.
Default
The set of all sounds not explicitly assigned to a category.
Music
Available for all sounds that are part of the game's background score. The presence of this category avoids conflicts with user-customized soundtracks. When XMP is playing, all sounds in this category are muted automatically. Subcategories of this predefined category are permissible.

Variables

Variables are the programmer's control mechanism for Run-Time Parameter Controls (RPCs). They can also be used to control branch/wait events.

The sound designer defines the name of the variable, its allowable range and the initial value.

Variables may be global, which may be responded to by multiple cues, or cue instance, which are associated only with a single instance of a cue.

Variables may be marked public, which are accessible by the game program, or private, which are controlled by and respond to the content alone as part of a Set Variable or Conditional event.

Run-Time Parameter Controls

Run-Time Parameter Controls (RPCs), also known as "sliders", allow a sound to be varied under program control.

To illustrate, consider the case of an automobile simulation. Audio waves and pitches for the car's engine need to adjust as gear and RPM change. The developer could figure out what values need to be changed to achieve the desired effect and develop code to change them. But, with an RPC, this is not necessary. Using the XACT, the sound designer can provide the programmer with the control that dictates how the content responds.

DSP Effect Path Presets

DSP Effect Path Presets (DSPs) enable special digital signal processing effects, such as reverb, to be applied to sounds.

Compression Presets

Compression Presets enable the sound designer to define specific compression attributes that may be applied to individual waves or an entire wave bank.

See Also

XACT Overviews, XACT Reference, XACT Audio Authoring


XACT Audio Authoring

This section contains information about authoring sound using the Microsoft Cross-Platform Audio Creation Tool (XACT).

In This Section

XACT Introduction
An introduction to the XACT authoring tool interface.
Auditioning with XACT for Windows
The Audio Console application allows users of XACT for Windows to audition audio created using the XACT tool.
XACT Audition Monitor
A guide to working with the XACT audition monitor.
Building an XACT Wave Bank
How to build a wave bank using XACT.
Working With XACT Sound Banks
How to build a sound bank, sounds, tracks and cues using XACT.
XACT Events
Details on types of XACT events that compose tracks and their properties.
XACT Sound and Wave Variations
How to use sound and wave variations to vary audio playback using XACT.
Making XACT Categories
How to create categories using XACT.
XACT Variables
How to create XACT audio variables that reflect activity in the game.
XACT Runtime Parameter Controls
How to create runtime-parameter controls (a.k.a. "sliders") that modify audio output as conditions in the game change.
XACT Time Variables
How to create attack and release envelopes for wave playback.
XACT DSP Presets
How to create and attach DSP effects to sounds.
XACT Reverb
How to manipulate the DSP reverberation effect.
XACT Interactive Audio
Introductory information on the Interactive Audio feature of XACT.
Project Build Wizard
Describes the XACT project build wizard.
XACT Reports
Describes the XACT report feature.
XACT Property Grid
Provides a quick reference for the XACT property grid.

Related Topics

For related topics about XACT, see:

XACT Concepts and Terminology

XACT Features


XACT Introduction

The Microsoft Cross-Platform Audio Creation Tool (XACT) is the Windows®-based graphical interface that offers a convenient way to organize audio resources. It is intended for use by audio designers as a tool for packaging audio resources, which can then be accessed by titles via the XACT APIs.

It is expected that audio designers will use one of the many linear audio editing packages that are available commercially to develop the core audio elements (waves) for the game.

When those core audio elements are ready, designers use XACT to build XACT projects, which ultimately take the form of data files that can be given to the title programmer. With the data files produced by the XACT, the programmer can make those audio resources an interactive part of gameplay.

This topic contains the following sections:

  • Launch the Authoring Tool
  • XACT Workspace

Launch the Authoring Tool

The authoring tool is installed as part of the installation process of the full SDK.

To start the authoring tool

  1. Click Start.

  2. Select All Programs, Microsoft DirectX SDK, DirectX Utilities, and finally Microsoft Cross-Platform Audio Creation Tool (XACT).

Figure 1. The XACT graphical interface, with a project in progress

Note XACT will generate an unhandled exception when a user without administrative rights tries to use the tool.

XACT Workspace

The workspace of the XACT graphical interface is headed by the menu bar and the toolbar. The remainder of the workspace is divided into three other display regions:

  • Project Tree
  • Property Grid
  • Project Workspace

Project Tree

The project tree region of the XACT graphical interface lists all of the content in the currently open project. This includes:

  • Wave banks
  • Sound banks
  • Settings (categories, variables, RPCs, DSP Presets, Compression Presets)

Figure 2. The project tree region of the authoring tool

You can create a new wave bank, sound bank, or global setting by using any of the following methods:

  • By selecting the appropriate command on the Wave Bank, Sound Bank, or Global Settings menus.
  • By clicking the icons that are presented when the authoring tool has determined that creation of one of these resources is permitted.
  • By right-clicking in the project tree the type of resource that you want to create, which presents an option to create the resource.

Property Grid

The property grid displays all editable properties for objects currently selected in the project tree or the project workspace. This dockable frame is docked by default, but may be undocked by selecting Properties from the View menu.

Figure 3. The authoring tool's property window

See the XACT Property Grid section for more information.

Project Workspace

The project workspace is where the wave banks and sound banks are viewed and edited. The conventional insert, delete, copy, and paste functions are supported.

Items selected within one of the child windows of this workspace display their properties in the property grid, and properties can be edited within that region.

Child windows of this workspace typically support drag-and-drop actions as shortcuts to commonly performed tasks. For example, dragging a wave from a wave bank window into the sounds frame of the sound bank window will create a new sound that uses that wave.

Figure 4. The project workspace region of the authoring tool

See Also

XACT Audio Authoring, XACT Overviews, XACT Reference


Auditioning with XACT for Windows

This topic gives step-by-step instructions for auditioning content on Microsoft Cross-Platform Audio Creation Tool (XACT) for Windows using the Audio Console application (AudConsole.exe). Follow these steps to begin auditioning.

  1. Launch the Audio Console Application
  2. Connect to the Audio Console Application with XACT
  3. Begin Auditioning

Launch the Audio Console Application

The Audio Console application (AudConsole.exe) is a program that supports auditioning of sounds by the XACT tool. You may use this tool to audition your sounds with XACT.

Note The Audio Console application is provided as a means to get up and running with XACT early in the development process. Title applications may support auditioning by linking with an appropriate XACT library. For more information, see XACT Libraries.

To launch the Audio Console application

  1. Click Start.

  2. Select All Programs, Microsoft DirectX SDK, DirectX Utilities, and finally Audio Console.

Once the Audio Console has started, it will display a message indicating that it is waiting for the XACT Tool to connect. Once this message is displayed, proceed to the next step.

Connect to the Audio Console Application with XACT

Once the audio console application is running, you may connect to it using the XACT authoring tool.

To start the XACT authoring tool

  1. Click Start.

  2. Select All Programs, Microsoft DirectX SDK, DirectX Utilities, and finally Microsoft Cross-Platform Audio Creation Tool (XACT) .

  3. Once the XACT authoring tool is running, load a project containing the wave resources to audition.

  4. From the View menu, click View Windows Properties.

  5. From the Audition menu, click Connect to Default Windows Machine.

    Figure 1. XACT's Audition menu

  6. When XACT has successfully connected to the development kit, the Audio Console Application will display a message indicating success.

Begin Auditioning

Once the XACT authoring tool on the PC and the Audio Console Application are connected, auditioning may begin.

The toolbar in the main XACT window contains a set of auditioning controls that allow you to play, repeat, and stop waves, sounds, and cues.

To start playback of a wave, sound, or cue

Figure 2. Play Button

  1. Select the sound, wave, or cue you wish to play by left-clicking on it in the appropriate sound bank or wave bank.
  2. Click the Play button on the Auditioning Toolbar.

- OR -

  1. Right-click the sound, wave, or cue you wish to play, and select "Play" from the menu that appears.

Note If the XACT authoring tool was not properly connected to the auditioning server, you will receive the message "Could not connect to a Windows auditioning server." If this occurs, you will need to verify the steps listed in the section above: Connect to the Audio Console Application with XACT.

Auditioning items may be played once, or repeated continuously.

To repeat playback continuously

Figure 3. Repeat Playback Button

  1. Select the sound, wave, or cue you wish to play continuously by left-clicking on it in the appropriate sound bank or wave bank.
  2. Click the Repeat Playback button on the Auditioning Toolbar so that the button remains depressed.
  3. Click the Play button on the Auditioning Toolbar.

- OR -

  1. Right-click the sound, wave, or cue you wish to play, and select the "Repeat Playback" item from the menu that appears so that a check appears next to it.
  2. Right-click the same sound, wave, or cue again and select the "Play" item from the menu.

More than one sound, wave, or cue may be playing at a time. A playing sound, wave, or cue will be denoted by a lit icon in its corresponding sound bank or wave bank.

At any point you may choose to stop the playback of one or more auditioning items.

To stop a single sound, wave, or cue

Figure 4. Stop Button

  1. Select a sound, wave, or cue that is currently playing by left-clicking on it in the appropriate sound bank or wave bank.
  2. Click the Stop button on the Auditioning Toolbar.

- OR -

  1. Right-click the currently playing sound, wave, or cue you wish to stop, and select "Stop" from the menu that appears.

With this stop mode, certain settings on cues and sounds may prevent playback from stopping immediately:

  • Sounds that use release time variables will apply the variables as they stop rather than stopping immediately. See XACT Time Variables.
  • Any Play events on a sound that have the PlayRelease property set to True will play to the end of the wave before stopping. See XACT Event, Play Wave.
  • Any cues that are interactive will stop using their Stop transition, if one is assigned. See XACT Interactive Audio.

To stop a single sound, wave, or cue immediately

Figure 5. Stop Immediately Button

  1. Select a sound, wave, or cue that is currently playing by left-clicking on it in the appropriate sound bank or wave bank.
  2. Click the Stop Immediately button on the Auditioning Toolbar.

These first two Stop options only apply to a selected sound, cue, or wave. You can stop all playing items by clicking the Stop All Button.

To stop all playing sounds, waves, and cues

Figure 6. Stop All Button

  1. Click the Stop All button on the Auditioning Toolbar.

Stop Auditioning

To stop auditioning, press the 'Q' key from the Audio Console application window. This will stop any auditioning in progress and close the Audio Console.

See Also

XACT Audio Authoring, XACT Overviews, XACT Reference


XACT Audition Monitor

In order to track resource usage, audio output levels, and activity in the engine, the Microsoft Cross-Platform Audio Creation Tool (XACT) provides an optional interface called the audition monitor. The audition monitor is designed to report information in real time while auditioning audio data. This information may then be saved to a text file for later review.

In this overview, the following subjects are discussed:

  • Launching the Audition Monitor
  • Exploring the Interface
  • Tracking Audition Information
  • Saving Audition Information

Launching the Audition Monitor

To launch the audition monitor, select Audition Monitor from the View in the main XACT menu. The audition monitor window will appear:

Figure 1. The audition monitor window, populated with audition data.

The monitor can be in either a running state, or a stopped state. In the running state, the monitor is actively collecting audition data from the XACT engine. When the monitor is stopped, you may continue to audition as you would normally, but the monitor will not collect data. The monitor is in the running state by default.

Exploring the Interface

The audition monitor interface consists of a main menu and several panes containing audition information. These interface components are discussed in the following sections:

  • Main Menu
  • Voice Count
  • Object Count
  • Memory Usage
  • Level Meters
  • Event Log

Main Menu

The following options are available under the main menu:

  • File

    • Start — Starts the audition monitor, placing the monitor in a running state. While running, the monitor will collect audition data.

    • Stop — Stops the audition monitor. While stopped, you may continue to audition, but the audition monitor will not collect audition data.

    • Save Log As — Saves information collected by the audition monitor to a text file.

    • Exit — Closes the audition monitor window.

  • Edit

    • Copy — Copies any selected rows to the clipboard.

    • Select All — Selects all rows in the currently active pane (Voice Count, Object Count, Memory Usage, or Event Log).

    • Clear Log — Erases data from the event log.

    • Clear Max Values — Erases the max values (Voice Count, Object Count, and Memory Usage).

    • Clear Clip LED's — Resets the LED's clip state.

    • Clear All — Erases Voice Count, Object Count, Memory Usage, Event Log, and resets the LED's clip state.

  • View

    • Always On Top — Prevents the audition monitor window from falling behind the XACT main window.

    • Event Filter — Opens the Event Filter window. This window allows you to select which events will be captured during auditioning, as well as the color of the event text as is appears in the Event Log pane.

    • Variable Window — Opens the XACT variable window (see XACT Variables for more information).

Go back to Exploring the Interface.

Voice Count

This pane shows the current and maximum voice counts of the playing content.

Go back to Exploring the Interface.

Object Count

This pane shows the current and maximum number of active objects.

Go back to Exploring the Interface.

Memory Usage

This pane shows the current and maximum amount of memory used. It does not include additional memory overhead required for auditioned content.

Go back to Exploring the Interface.

Level Meters

The level meters show the current Peak or RMS levels of the playing content. To switch between Peak and RMS, select the Peak or RMS buttons respectively.

Go back to Exploring the Interface.

Event Log

This pane shows all recorded events. You may choose which events you want to log and the color of the text by selecting Event Filter from the View menu.

Go back to Exploring the Interface.

Tracking Audition Information

To track audition information:

  1. Open the audition monitor by selecting Audition Monitor from the View menu in XACT.

  2. Make sure that the audition monitor is running. When the monitor is running, the word Running will appear in the title bar. If it does not, select Start from the File menu in the audition monitor window.

  3. Audition your media in XACT as you normally would.

Saving Audition Information

When you've finished tracking audition information, you may wish to save the data. To save audition information:

  1. Select Save Log As from the File menu in the audition monitor window. You will then be prompted to provide a file name for the audition information.

See Also

XACT Audio Authoring


Building an XACT Wave Bank

A wave bank is a collection of wave files bundled together into a single larger file. You must also specify the mode of the wave bank, whether it is meant to be used in-memory or streamed.

To build a Microsoft Cross-Platform Audio Creation Tool (XACT) wave bank, complete the following steps:

  • Create a Wave Bank
  • Set Wave Bank Properties
  • Add a Wave File

You may perform additional actions with wave banks:

  • Rescan a Wave Bank
  • Update Wave Source Paths

Create a Wave Bank

When you begin a new XACT project, there are no wave banks available. You must create each one you wish to use. You may create as many wave banks as you require.

To create a new wave bank

  1. Navigate to the Wave Banks menu, and click New Wave Bank.

    The new wave bank is listed under the Wave Banks branch of the project tree.

    Figure 1. Creating a new wave bank using the menu toolbar

    This new wave bank has the default name "Wave Bank".

  2. Select the new wave bank.

  3. Press F2 and enter a more descriptive name for the wave bank, or change the Name property of the wave bank in the property grid of the audio creation authoring tool.

Creating a new wave bank, or double-clicking an existing wave bank in the project tree opens a child window within the project workspace. Figure 2 shows a wave bank window with some waves assigned.

Figure 2. Wave bank window with data assigned

Set Wave Bank Properties

When the wave bank is selected in the project tree, its properties are displayed in the property grid, and may be changed. For a list of wave bank properties, see the Wave Bank Properties section.

Add a Wave File

Once you have created a wave bank, it is empty and ready to receive waves. You may add as many wave files to the wave bank as you need.

To add a wave file

  1. Open the wave bank by double-clicking the wave bank in the project tree.

    If the wave bank is already open, select the wave bank window by clicking on its title bar.

  2. Click Insert Wave File(s) on the Wave Banks menu (or, alternately, press Ctl+W).

    Figure 3. Adding a wave to the wave bank using the menu toolbar

  3. Select one or more wave files to add to your wave bank, and then click Open.

    The wave files you selected are added to the wave bank.

Or

  • Simply drag one or more wave files from Windows Explorer into the wave bank window.

Wave Properties

When the wave is selected in the wave bank window, its properties are displayed in the property grid, and may be changed. For a list of wave bank properties, see the Wave Properties section.

Rescan a Wave Bank

If you have modified a wave file used in a wave bank, you can rescan the wave bank that holds it to update XACT to the new wave's updated length, file size, and data.

To rescan waves in a wave bank

  • Right-click on the wave bank in the project tree that you wish to rescan, and select Rescan Wave Bank Entries.

Update Wave Source Paths

During development of a title, you may move wave files around on disk. To continue using the wave banks that reference these moved wave files, you can update XACT to use the new file location, either by individual wave or by an entire wave bank.

To update the source path for an individual wave

  1. Double-click the wave bank in the project tree that contains the wave you wish to modify. The wave bank window will open.
  2. In the wave bank window, right-click on the wave you wish to modify and select Update Source Path...
  3. From the folder selection dialog box that appears, choose the folder that contains the wave file, and click OK.

To update the source path for a wave bank

  1. Right-click on the wave bank in the project tree that you wish to modify, and select Update Source Path...
  2. From the folder selection dialog box that appears, choose the folder that contains the wave files that are held in the wave bank, and click OK.

Note When updating the path for a wave bank, the same folder will be applied to each wave in the wave bank individually. If a wave file cannot be found, a dialog box will appear and prompt for the correct path.

See Also

XACT Audio Authoring, XACT Overviews, XACT Reference


Working With XACT Sound Banks

A sound bank is a collection of instructions about how and when to play sounds. The programmer invokes sounds by their cues, and does not need to know anything about the sound or sounds that a cue uses.

This section steps through the process of building a sound bank using the Microsoft Cross-Platform Audio Creation Tool (XACT), which includes specifying the tracks that compose a sound, the events that compose tracks, and how to build cues from the sounds you define. For more information on the elements of sound banks, see XACT Concepts.

To build an XACT sound bank, complete the following steps:

  • Create a Sound Bank
  • Create Sounds
  • Build Tracks
  • Create Cues
  • Edit Transitions

Create a Sound Bank

When you begin a new XACT project, there are no sound banks available. You must create each one you wish to use. You may create as many sound banks as you require.

To create a sound bank

  1. Navigate to the Sound Banks menu and click New Sound Bank.

    The new sound bank is listed under the Sound Banks branch of the project tree, and the properties for the sound bank are shown in the Property Grid.

    Figure 1. Creating a new sound bank using the menu toolbar

    This new sound bank has the default name "Sound Bank".

  2. Select the new sound bank.

  3. Press F2 and enter a more descriptive name for the sound bank. You can also rename the sound bank by changing the Name property of the sound bank in the properties frame.

Sound Bank Window

Double-click the sound bank in the project tree to open the Sound Bank window.

Figure 2. Sound Bank window (with data assigned)

The Sound Bank window is divided into two halves, upper and lower, for sounds and cues, respectively. Each of these is further divided in half, right and left, to display the data associated with each (tracks that compose the sound and sounds associated to cues).

The upper left area is the sounds frame where the sounds defined in the sound bank are displayed. The upper right area is the tracks frame where the tracks that compose the selected sound are displayed. The lower left area is the cues frame where the cues defined in the sound bank are displayed. The lower right area is the associations frame where the sounds associated with the selected cue are displayed.

Sound Bank Properties

When the sound bank is selected in the project tree, its properties are displayed in the property grid, and may be changed. For a list of wave bank properties, see the Sound Bank Properties section.

Create Sounds

Once you have created a sound bank, it is empty and ready to construct sounds and associate them with cues. You may create as many sounds and cues in a sound bank as you need.

Before creating any sounds, however, you should first build your wave banks that will hold the wave files your sounds will use. Otherwise, the wave files your sounds need to reference will not be available when they need to be played.

To create a sound

  1. Open the sound bank by double-clicking the sound bank in the project tree.

    If the sound bank is already open, select the sound bank window by clicking on its title bar.

  2. On the Sound Banks menu, click New Sound. You can also create a new sound by pressing CTRL+D.

    Figure 3. Creating a new sound bank using the menu toolbar

    This creates a sound with the default name "New Sound".

  3. Select the new sound.

  4. Press F2 and enter a more descriptive name for the sound. You can also rename a sound by changing the Name property of the sound in the properties frame.

Once you have followed this procedure, you'll have a sound, but it will have no content. The next step is to construct the sound, and its behavior, from a wave or multiple waves.

Sound Properties

When the sound is selected in the project tree, its properties are displayed in the property grid, and may be changed. For a list of sound properties, see the Sound Properties section.

Build Tracks

A sound is composed of one or more tracks. Each track can contain a single "Play Wave" event, as well as any number of other events (such as markers and level settings). Each track of a sound plays only a single wave at any given time. For more complex sounds, you can create multiple tracks, each with its own "Play Wave" event (and again, each with as many other non-"Play Wave" events as you wish).

Because the Audio Console Application limits the number of concurrent streams coming from the hard drive to 50, no more than 50 tracks should be added to a sound.

To create a track

  1. On the Sound Banks menu, click New Track. You can also create a new track by pressing CTRL+K.

    Figure 4. Creating a new track using the menu toolbar

    This creates an empty track with the default name "Track N".

At this point, you have a track that is empty. You must now add events to the track, which will define what the track does. Each track may contain a single "Play Wave" event, and this will typically be the basis of all other events that are assigned to the track.

To add an event to the track

  1. Right-click the track's entry in the tracks frame of the Sound Bank window.

    Figure 5. Adding a new event to the track

  2. Select one of the event types to add.
  3. Set the event's properties in the property grid.

The events that are available, along with their properties, are described in XACT Events.

A "Play Wave" event may be created this way. To associate a wave file with the event, simply drag and drop a wave from a wave bank onto the "Play Wave" event.

Note You may associate multiple waves to a single "Play Wave" event. Doing so introduces variations to the event. See the XACT Sound and Wave Variations section for more information.

In addition to the steps listed above, XACT provides two alternatives to using the menu to create "Play Wave" events.

To create a "Play Wave" event

  1. Open the wave bank where the wave you wish to play resides.

  2. Drag the icon for the wave file from the Wave Bank window to the track in the tracks frame of the Sound Bank window.

    This creates a "Play Wave" event that will play the dragged wave when the track is executed.

XACT also provides a drag-and-drop shortcut to create a track that contains a "Play Wave" event.

To create a track with a "Play Wave" event

  1. Open the wave bank where the wave you wish to play resides.

  2. Drag the icon for the wave file from the Wave Bank window to an empty space in the tracks frame of the Sound Bank window.

    This creates a track with a "Play Wave" event that will play the dragged wave. The track has the default name "Track N".

  3. Add more events to the track as you require.

Create Cues

The cues are what the developer will invoke to play the sound.

To create a cue

  1. On the Sound Banks menu, click New Cue. You can also create a new cue by pressing CTRL+U.

    Figure 6. Creating a new cue using the menu toolbar

    This creates an empty cue with the default name "New Cue".

  2. Select the new cue.

  3. Press F2 and enter a more descriptive name for the cue. You can also rename a cue by changing the Name property of the cue in the properties frame.

To assign a sound to a cue

  1. Select the sound in the sound frame (upper left).

  2. Drag the selection to the associations frame (lower right).

XACT also provides some drag-and-drop shortcuts that combine creation and assignment of cues:

  • Drag a sound from the sound frame into the cues frame (lower right), and the XACT will automatically create a cue associated with that sound. Make sure you drag it into an empty area, because this same drag action is used to replace the sound associated with an existing cue.
  • Drag a wave from the wave bank into the cues frame. This creates both a sound that plays the wave and a cue that plays the sound.

Cue Properties

When the cue is selected in the project tree, its properties are displayed in the property grid, and may be changed. For a list of cue properties, see the Cue Properties section.

Edit Transitions

For cues that are interactive (see the Cue Properties section above), an Edit Transitions menu item is made available in the cue context menu. Right-click on the cue and select Edit Transitions to open the Interactive Audio window.

You may choose to view elements by source or by target, with source being the default. Selecting an item in the tree reveals a new set of properties in the property grid. These are the transition properties of the selected cue. For a list of transition properties, see the Transition Properties section.

For more information on transitions, see the XACT Interactive Audio section.

See Also

XACT Audio Authoring, XACT Events, XACT Overviews, XACT Reference


XACT Events

An Microsoft Cross-Platform Audio Creation Tool (XACT) sound is composed of one or more tracks, which are in turn defined by a collection of events. An event can be a "Play Wave" event, which plays a wave file, or a type of event that controls the playback of the wave, such as markers or level settings.

These events are available to the XACT audio designer.

Icon | Event Type
 | Play Wave
 | Stop
 | Marker
 | Set Volume
 | Set Pitch

Common Event Properties

All events, no matter what type, are provided a core set of properties. If any of the properties are not applicable to an event, they are either not presented or disabled.

Event Properties

The event properties specify the fundamental information for all events, such as its "friendly name" and comments.

Property Name | Description
EventType | Displays the type of event. Display only.
Name | The default name of an event is its event type (for example, Play Wave). You can rename the event by changing this selection, or by selecting the name displayed in the sound bank window.
Comment | Comments from the designer.

Timing Properties

The timing properties hold the relative time information that the event may use to execute its playback, repeats, or notifications.

Property Name | Description
TimeStamp | Time, relative to when the sound is played, when the event is to occur.
RandomOffset | Random time, relative to when the sound is played, when the event is to occur. Random time takes into account the TimeStamp property. If TimeStamp is set to three seconds, and RandomOffset is set to four, the event will occur at some random interval between three and seven seconds.
RelativeToStartEnd | Currently unsupported.

Repeat Properties

The repeat properties specify how often and in what manner the event is to automatically repeat itself.

Property Name | Description
RepeatEvent

The following options are available:

  • None
  • Finite
  • Infinite

Sub-properties are made available depending on this setting.
NumberOfRepeats

The number of additional times the event should repeat. A value of 1 will cause the event to occur two times.

If RepeatEvent is set to Infinite, this property does not appear.
RepeatFrequency | The amount of time, in FrequencyUnits, to pause between event repeats.
FrequencyUnits

The units for RepeatFrequency. Options are:

Seconds
Default.
Beats Per Minute
Provided as a shortcut for rhythmic event repeats.
LastRepeat | If an event is recurring, this property shows the last time the event will occur.

See Also

XACT Audio Authoring, XACT Overviews, XACT Reference


XACT Event, Play Wave

The Play Wave event causes a wave to commence playback. It also allows the audio designer to specify that the wave is to be repeated, or specify a list of waves that can be cycled through either in sequence or at random.

Properties

Event Properties

The common set of event properties that specify the event name and hold comments.

Level Variations

Property Name | Description
VolumeVariation | Randomized volume is used when the event is played.
PitchVariation | Randomized pitch is used when the event is played.
RangeMinimum | Minimum value to set when choosing a random value.
RangeMaximum | Maximum value to set when choosing a random value.
NewValueOnLoop | Determines whether a new variation should be selected each time the play event loops.
OperationToPerform

How the new setting should behave relative to other parameter settings the track may already have.

  • Replace current
  • Add to current
  • Subtract from current
  • Multiply by current

Play Wave Properties

Property Name | Description
LoopEvent

Number of times to repeat the wave entry.

  • No
  • Finite
  • Infinite
LoopCount | Specifies the number of additional times the event should play. For instance, setting the loop count to 1 means the event will play a total of two times.
NewVariationOnLoop | When the play event loops, whether to repeat the identical wave or choose a new variation (in wave, pitch, volume, and so on)
PlayRelease | For cues that use looping sounds, this setting determines how a sound will be stopped. If set to True, a cue will stop looping and play to the end of the wave. If set to False, the sound will stop immediately. An exception is made in the case of a sound that is looping and has a Release RPC attached. In that case, the sound will fade out as the Release RPC specifies while continuing to loop.

Speaker Positioning Properties

Property Name | Description
EnableSpeakerPositioning

Determines whether to position the speaker at a random location around the user (true) or to use authored speaker assignment properties (false).
UseCenterSpeaker | Determines whether the center speaker is used for positioning.
SpeakerPositionAngle Angle used for speaker positioning, in degrees:
  • 0 degrees — ahead
  • 90 degrees — right
  • 180 degrees — behind
  • 270 degrees — left
SpeakerPositionArcSize | For a random speaker position, the size of the arc that will contain the position.
NewPositionOnLoop | When the play event loops, whether to pick a new pick a new position, or keep using the same position.

Timing Properties

The common set of timing properties that hold relative time information for playback and repeats.

Variation Playlist Properties

Property Name Description
PlayListType

When there is a wave variation list associated with the sound, this property determines the play order each time the sound is played.

  • Ordered
  • Ordered from random
  • Random
  • Random (no immediate repeats)
  • Shuffle
Variations

A variation contains the following properties.

Property | Description
Wave | Wave attached to the variation.
Weight | Weight for the variation (how frequently it will be chosen, while abiding the playlist restrictions).

See Also

XACT Events, XACT Audio Authoring, XACT Overviews, XACT Reference


XACT Event, Stop

The Stop event allows the audio designer to specify the time that playback of a wave is to terminate. For example, the audio designer may wish to have an in-memory looping wave or sound play for three seconds and then stop. The Stop event allows the audio designer (rather than the title programmer) to control this behavior.

The Stop event may halt wave playback abruptly, but it doesn't have to. The audio designer may define a release envelope that specifies the volume and/or pitch of the wave to fade out slowly. The Stop event permits the audio designer to associate a release envelope with the track and to specify when it is to be invoked.

Properties

Event Properties

The common set of event properties that specify the event name and hold comments.

Repeat Properties

The common set of repeat properties that specify how often and in what manner the event is to automatically repeat itself.

Stop Wave Properties

Property Name | Description
StopEntireCue | Stop the cue instance, allow for a release envelope.
StopImmediately | Stop the sound immediately, no release envelope.

Timing Properties

The common set of timing properties that hold relative time information for playback and repeats.

See Also

XACT Events, XACT Audio Authoring, XACT Overviews, XACT Reference


XACT Event, Marker

A Marker event specifies that the Microsoft Cross-Platform Audio Creation Tool (XACT) engine must generate a marker notification to the title program when the track has progressed to the designated point. The programmer can use this notification to know when to perform some required action. It should be noted that markers play a significant role in deciding how interactive cues transition from variation to variation.

A Marker event can be set up to provide a single notification, or to recur on a timed interval.

Properties

Event Properties

The common set of event properties that specify the event name and hold comments.

Repeat Properties

The common set of repeat properties that specify how often and in what manner the event is to automatically repeat itself.

Marker Properties

Property Name | Description
MarkerID | Integer value used to identify this marker event when it occurs.

Timing Properties

The common set of timing properties that hold relative time information for playback and repeats.

See Also

XACT Events, XACT Audio Authoring, XACT Overviews, XACT Reference


XACT Event, Set Volume and Set Pitch

The Set Volume event is used to set and optionally fade the playback volume of a wave.

The Set Pitch event is used to set and optionally fade the playback pitch of a wave.

The properties of Volume and Pitch events are the same for each.

Properties

Event Properties

The common set of event properties that specify the event name and hold comments.

Repeat Properties

The common set of repeat properties that specify how often and in what manner the event is to automatically repeat itself.

Set Volume Properties

Property Name Description
SettingType

May be one of the following settings:

  • Ramp – A ramping event provides for a gradual change in a sound's property without the need to set an event to be recurring with an equation.
  • Equation – An instant change to a sound's property to a specific value or an adjustment to the current value based upon a modifier.

Ramp SettingType Properties

Property Name | Description
Duration | Defines how long the ramp will occur, in seconds.
StartVolume | Starting volume/pitch setting when the event occurs.
EndVolume | Volume/pitch setting when the event ends.
Curvature | How steep the curve from start to end value is.

Equation SettingType Properties

Property Name Description
EquationType

May be one of the following settings:

  • Constant – The property is adjusted by a fixed amount.
  • Random from Range – The property is adjusted by a random amount between RangeMinimum and RangeMaximum.

Timing Properties

The common set of timing properties that hold relative time information for playback and repeats.

See Also

XACT Events, XACT Audio Authoring, XACT Overviews, XACT Reference


XACT Sound and Wave Variations

When creating cues and tracks using Microsoft Cross-Platform Audio Creation Tool (XACT), developers may want to add variability to what sounds or waves are being played. By using variations, you can assign multiple sounds to a cue, or multiple waves to a track, that will be played randomly when the cue or track is played. Both methods allow for weighting and play options to modify how the sounds or waves are chosen at random.

Variations require that at least one sound bank and one wave bank have been created in an XACT project. See Working With XACT Sound Banks and Building an XACT Wave Bank to learn how to create sound banks and wave banks.

There are two types of variations in XACT: sound variations, which are linked to a cue and vary the sound played when the cue is triggered, and wave variations, which are linked to a track and vary the wave played when the track is played.

  • Wave Variations
  • Sound Variations
  • Random Weighting
  • Variation Playlists

Wave Variations

Wave variations are the simpler of the two types of variations; all that is required to create a wave variation for any given track is a wave bank with two or more waves in it, and a sound bank.

To create a wave variation

  1. From the Wave Bank window, click and drag a wave into the Sound Bank window.

    Figure 1. The wave and sound bank windows, prior to creating the new sound

    A new sound will be created for the wave, and a Play event will be added to the sound automatically.

  2. Select the new sound in the Sound Bank window.

    Figure 2. The wave and sound bank windows, after selecting the newly-created sound

    The details of the automatically-generated Play event will be shown in the tracks frame of the Sound Bank window.

  3. From the Wave Bank window, click and drag a second wave, different than the first wave, to the sound in the sound bank window. Do not release the mouse button yet. As you drag the wave over the sound, the tracks in the sound will appear. Continue to drag the wave over to "Play Wave" event in the tracks frame, and release.

    Figure 3. The wave and sound bank windows, after adding the second wave.

    The new wave should appear below the old wave. Both waves will be displayed with a percentage value next to their names. This indicates the chance that the wave will be played when the track is played. Both waves have a fifty-percent chance of being played.

This final step can be repeated as many times as desired to add additional waves to the track that will play randomly. Each additional wave will reduce the percentage chance that each wave has of being played, unless certain waves are weighted more heavily than others. Weighting is discussed in the Random Weighting section.

The default behavior of a wave variation is to play waves randomly but with no immediate repeats, that is, no wave that was just played will be played a second time, even if it is the wave that is randomly chosen. There are other modes of selecting which wave to play. See the Variation Playlists section for details.

Sound Variations

Sound variations are the second type of variation, and are used to link multiple possible sounds to play when a specific cue is triggered. This allows for a greater level of variation, as the sounds that are played can then have wave variations within their tracks.

To create a sound variation, you must have two or more sounds in a sound bank.

Note For performance reasons, a cue should have no more than 100 sound varations associated with it.

To create a sound variation

  1. Select the Sound Bank window. Right-click in the lower-left pane of the Sound Bank window, and select New Cue.

    Figure 4. Sound bank window, after creating a cue

    A new cue will be created and will appear in the lower-left pane of the Sound Bank window.

  2. Click and drag a sound from the upper-left pane of the Sound Bank window onto the newly-created cue.

    Figure 5. The sound bank window, after dragging a sound onto the new cue

    The sound will be added to the lower-right pane of the Sound Bank window.

  3. Click and drag a second sound, different from the first sound, from the upper-left pane of the Sound Bank window onto the cue.

    Figure 6. The sound bank window, after adding the second sound to the cue.

    The second sound should appear below the first sound in the bottom-right pane of the sound bank window. One of these sounds will be played randomly when the cue is triggered.

This final step can be repeated as many times as desired to add additional sounds to the cue that will play randomly. Each additional sound will reduce the percentage chance that each sound has of being played, unless certain sounds are weighted more heavily than others. Weighting is discussed in the Random Weighting section.

The default behavior of a sound variation is to play sounds randomly but with no immediate repeats, that is, no sound that was just played will be played a second time, even if it is the sound that is randomly chosen. There are other modes of selecting which sound to play. See the Variation Playlists section for details.

Random Weighting

In the case of both sound and wave variations, an initial weight is applied to each sound or wave that makes it no more likely to be chosen randomly than any of the other sounds or waves that could also be chosen. This may not be the desired result in all cases. In order to make certain sounds or waves more or less likely to be chosen, a developer may change the random weight of a sound or wave.

Note Weighting only effects variations with "random" playlist types (Random, Random (no immediate repeats), and Shuffle). Ordered playlist types will not be affected by weighting. See Variation Playlists.

Weighting Waves and Sounds

Waves and sounds are weighted by a single number that represents how frequently they will be chosen versus the other waves or sounds in the track.

To modify a wave weight

These instructions assume that you have a sound bank prepared that contains a sound that uses wave variations. See the Wave Variations section to learn how to create wave variations.

  1. Select the sound bank window.

  2. In the upper-left pane of the sound bank window, click on a sound that contains a track that uses wave variations. The track and the waves that the track contains will be shown in the upper-right pane of the sound bank window.

  3. In the upper-right pane of the sound bank window, click on the wave that you wish to weight. The property grid, which is on the lower left of the XACT window, will display properties about the selected wave.

  4. In the property grid, under the Variation Properties heading, edit the Weight property. You may click in the text box corresponding to the Weight property to type in a number from 0 to 255, or you may click the downward-pointing arrow to the right of the box to display a slider, which you can manipulate to change the value of the property. The percentage value that the number corresponds to will be shown.

    Figure 7. The property grid, during editing of the Weight property of a wave.

    The waves in the track will update to show the new percentage amounts. These amounts correspond to the updated percentage chance that they will be chosen at random to play when the track is played.

To modify a sound weight

These instructions assume that you have a sound bank prepared that contains a non-interactive cue that uses sound variations (interactive cues override weighting behavior, so the weights will have no effect). See the Sound Variations section to learn how to create sound variations.

  1. Select the sound bank window.

  2. In the lower-left pane of the sound bank window, click on a cue that is using sound variations (i.e., has more than one sound associated with it). The sounds associated with the cue will be shown in the lower-right pane of the sound bank window.

  3. In the lower-right pane of the sound bank window, click on the sound that you wish to weight. The property grid, which is on the lower left of the XACT window, will display properties about the selected sound.

  4. In the property grid, under the Variation Properties heading, edit the Weight property. You may click in the text box corresponding to the Weight property to type in a number from 0 to 255, or you may click the downward-pointing arrow to the right of the box to display a slider, which you can manipulate to change the value of the property. The percentage value that the number corresponds to will be shown.

    Figure 8. The property grid, during editing of the Weight property of a sound.

Variation Playlists

The default behavior of a sound variation is to play sounds randomly but with no immediate repeats, that is, no sound that was just played will be played a second time, even if it is the sound that is randomly chosen. There are other modes of selecting which sound to play:

Property Value | Description
Random (no immediate repeats) | The default behavior. Items will be chosen at random, but the immediate repeat of a previously played item will not occur.
Random | Random selection that does not track the previously played item. The immediate repeat of a previously played item is possible with this setting.
Ordered | Items are played in order. This order will be made visible when this playlist type is chosen, and you may drag and drop sounds in relation to each other to change this order. See Using The Ordered Playlist Type.
Ordered from Random | From a random starting position (no weighting used), plays all entries in order, using the same logic as the ordered type.
Shuffle | Items are chosen randomly, but no item will be played twice until all items in the list have been played.

This behavior is set by a property that is accessed differently for wave variations than it is for sound variations. Both are covered below.

Changing Wave Variation Behavior

These instructions assume that you have a sound bank prepared that contains a sound that uses wave variations. See the Wave Variations section to learn how to create wave variations.

To modify wave variation behavior

  1. Select the sound bank window.

  2. In the upper-left pane of the sound bank window, click on a sound that contains a track that uses wave variations. The track and the waves that the track contains will be shown in the upper-right pane of the sound bank window.

  3. In the upper-right pane of the sound bank window, click on the Play Wave event for the list of waves you wish to modify. The property grid, which is on the lower left of the XACT window, will display properties about the selected event.

  4. In the property grid, under the Variation Playlist Properties heading, edit the PlayListType property. Click the downward-pointing arrow to the right of the PlayListType property box to display a list of available behaviors. Clicking on a behavior type will set the waves associated with the sound to play using that behavior.

Changing Sound Variation Behavior

These instructions assume that you have a sound bank prepared that contains a cue that uses sound variations. See the Sound Variations section to learn how to create sound variations.

To modify sound variation behavior

  1. Select the sound bank window.

  2. In the lower-left pane of the sound bank window, click on a cue that is using sound variations (i.e., has more than one sound associated with it). The property grid, which is on the lower left of the XACT window, will display properties about the selected cue.

  3. In the property grid, under the Variation Playlist Properties heading, edit the PlayListType property. Click the downward-pointing arrow to the right of the PlayListType property box to display a list of available behaviors. Clicking on a behavior type will set the sounds associated with the cue to play using that behavior.

Using The Ordered Playlist Type

The Ordered and Ordered From Random playlist types behave differently than the other playlist types. The sounds are not played randomly, but in an order that you can define by dragging and dropping sounds in relation to one another.

These instructions assume that you have a sound bank prepared that contains a cue that uses sound variations. See the Sound Variations section to learn how to create sound variations.

To define a playlist order using the Ordered playlist type

  1. Select the sound bank window.

  2. In the lower-left pane of the sound bank window, click on a cue that is using sound variations (i.e., has more than one sound associated with it). The property grid, which is on the lower left of the XACT window, will display properties about the selected cue.

  3. In the property grid, under the Variation Playlist Properties heading, edit the PlayListType property. Choose Ordered or OrderedFromRandom.

  4. The sound list for the cue in the sound bank will change to show a column called Order. This shows the order that the sounds will play in when the cue is played.

    Figure 9. Cue and sounds in sound bank, showing order

  5. Drag and drop a sound above or below another sound in the cue's sound list to change its order in the list.

See Also

Working With XACT Sound Banks, Building an XACT Wave Bank


Making XACT Categories

Categories are a way of sorting audio resources into common behaviors.

Assigning sounds to categories allows the programmer to collectively change settings for similarly associated sounds. It can also ensure that a sound assigned to a category behaves according to a common set of rules, including a limit on the number of instances of sounds belonging to that category.

These are the steps to making and assigning Microsoft Cross-Platform Audio Creation Tool (XACT) categories.

  • Create a Category
  • Create a Subcategory
  • Assign a Category to a Sound

Create a Category

Categories are a type of global setting, along with variables and run-time parameter controls. They are listed in the project tree at the same hierarchy level as wave banks and sound banks.

An XACT project is automatically provided with two top-level categories, the Default category, which is assigned to all sounds not explicitly assigned to any other category, and the Music category, which is intended for streamed background music.

An audio designer may create new top-level categories as required.

To create a new category

  1. Navigate to the Global Settings menu, and select New Category. You can also create a new category by pressing Ctl+T.

    Figure 1. Creating a new category using the menu toolbar.

    The new category is listed under the Categories branch of the project tree. This new category has the default name "Category".

  2. Select the new category.

  3. Press F2 and enter a more descriptive name for the category. You can also rename a category by changing its Name property in the properties frame.

Properties

When the category is selected in the project tree, its properties are displayed in the property grid, and may be changed. The following table describes the properties of a category as they appear in the property grid.

Category Properties

When the category is selected in the project tree, its properties are displayed in the property grid, and may be changed.

Property Name | Description
Name | The default name of a category is Category. You can rename the catagory by changing this selection, or by selecting the name displayed in the project tree frame.
Notes | Comments from the designer.
Volume | The master volume level for all sounds assigned to this category. The range is from -96 dB to 6 dB.
Public | If set to True, this category of sounds is available to the sound programmer (the default). If set to False, access to this category of sounds is restricted, intended for internal use by the creator of the content.

Instance-Limiting Properties

Property Name | Description
LimitInstances | If set to True, the number of playing instances permitted at one time within the category is limited to MaximumInstances.
MaximumInstances | Specifies how many playing instances are permitted at one time within the category, if LimitInstances is set to True.
BehaviorAtMax

Specifies the action to take once the limit you specify is reached within the category. If LimitInstances is set to False, these properties are ignored. The property offers the following selection of behaviors:

  • FailToPlay — Inhibits playing of any other instances once the limit is reached. Also, the function that tried to initiate the new instance will receive a failure error code.

  • Queue — Stores the instance in a last-in-first-out queue to begin playing once any of the active instances completes.

  • Replace — Begins playing the instance in place of an active instance that meets the selected condition.
InstanceToReplace

If LimitInstances is set to True and BehaviorAtMax is set to Replace, XACT will replace the instance according to one of the following selected criteria:

  • Lowest Priority (default)
  • Oldest
  • Quietest
HowToReplace

Specifies the style of fade of a replaced instance.

  • Linear
  • Logarithmic
  • Equal Power
FadeOutDuration

The period in seconds to fade out the replaced sound.
FadeInDuration

The period in seconds to fade in the replacing sound.

Create a Subcategory

Categories may be created that are subordinate to another category.

To create a subcategory

  1. Right-click on the desired category in the project tree and select New Subcategory.

    Figure 2. Creating a subcategory under an existing top-level category.

    The new subcategory is listed under the parent category. This new category has the default name "Category". All properties for the new subcategory are set to the defaults (properties are not copied from the parent category).

  2. Select the new subcategory.

  3. Press F2 and enter a more descriptive name for the subcategory. You can also rename a subcategory by changing its Name property in the properties frame.

Assign a Category to a Sound

Categories are useful only once they have been assigned to sounds. Once categories are assigned, they will ensure that the sounds assigned to them operate within the same functional boundaries.

For information on how to create sounds, see Working With XACT Sound Banks.

To assign a category to a sound

  1. Double-click the sound bank in the project tree to open the Sound Bank window.

  2. Drag and drop the sound you want to associate onto the desired category in the project tree.

- OR -

  1. Double-click the sound bank in the project tree to open the Sound Bank window.

  2. Select the sound you want to assign to the category.

    The sound's properties are displayed in the XACT properties frame.

  3. In the Sound Properties section, select the drop-down list of the Category property.

    The list of available categories are displayed in the drop-down list.

  4. Choose one of the available categories to set this property.

See Also

XACT Audio Authoring, XACT Overviews, XACT Reference


XACT Variables

The Microsoft Cross-Platform Audio Creation Tool (XACT) variables allow a title to control its audio output (for example, volume levels) through parameters that reflect the activity taking place in the title.

This topic covers the essential information you need to know about variables, and the steps to create them.

  • XACT Variable Types
  • Creating a Variable
  • Deleting a Variable

XACT Variable Types

Understanding some terminology is essential for working effectively with XACT variables. Variables have a scope that is either global or specific to a cue, as well as being implicitly or explicitly part of an XACT project.

Global and Cue-Instance Variables

All variables must be declared as either global or cue-instance.

Global Variables

Global variables are accessible to every cue and persistent throughout the title.

Programmers can set or read these values through the IXACTEngine::SetGlobalVariable and IXACTEngine::GetGlobalVariable functions.

Cue-Instance Variables

Cue-Instance variables are limited in scope to the created cue and they exist only for the life of that cue instance. Cue-instance variables are useful when multiple instantiations of a single cue (and its associated sounds) are required (for example, a "car" cue where there may be more than one car at any given time). While a global variable allows multiple audio elements to be controlled in unison, a cue instance variable grants discrete control of each instance of a cue, even for each copy of the same cue.

Programmers can set or read these values per instance through the IXACTCue::GetVariableIndex and IXACTCue::GetVariable methods.

Implicit and Explicit Variables

Variables that are automatically included with every XACT project are called implicit variables. Variables that you create are called explicit variables. Both implicit and explicit variables can be declared to be global or cue-instance, although the audio designer can change this setting only for explicit variables.

Implicit Variables

Implicit variables are inherent within the XACT engine and available to the sound designer for use.

Variable Name | Type | Description
NumCueInstances | Cue Instance | Contains the number of currently playing instances of the cue.
AttackTime | Cue Instance | Counts the amount of time elapsed since the start of playback. This counter begins at zero and continues to increment until the cue is stopped.
ReleaseTime | Cue Instance | Counts the amount of time elapsed since a non-immediate request to stop playback. A stop request can occur either from programmer control or from a Stop event. This counter begins at zero and continues to increment until the cue is retriggered.
Distance | Cue Instance | Represents the current distance from the sound source to the listener. If the cue instance has no distance associated with it, the value of Distance is 0. Set by XACT3DApply.
OrientationAngle | Cue Instance | Represents a cue instance's orientation to the listener, expressed in degrees from -180 to 180. Set by XACT3DApply.
DopplerPitchScalar | Cue Instance | Represents the amount of pitch modification on a cue instance created by doppler shift between the cue instance and the listener, expressed as a number between 0 and 4. Set by XACT3DApply.
SpeedOfSound | Global | Speed of sound constant used in doppler shift calculations, expressed as a number between 0 and 1,000,000. Used by XACT3DCalculate in doppler shift calculations.

For more information on AttackTime and ReleaseTime, see XACT Time Variables.

For more information on Distance, OrientationAngle, DopplerPitchScalar, and SpeedOfSound, see Using X3DAudio with XACT.

Explicit Variables

Explicit variables are those that are created by the sound designer. For example, the designer may define a variable EngineRPM, to control engine volume based on the speed of the car.

Creating a Variable

While you cannot create new implicit variables, you can create new explicit variables.

To create a new explicit variable

  1. Right-click the Variables item in the XACT project tree.

  2. Select either the New Global Variable or New Cue Instance Variable option that is presented.

    Figure 1. Creating a new explicit variable

    A new global variable has the default name "Global." A new cue-instance variable has the default name "Cue Instance."

  3. Select the new variable.

  4. Press F2 and enter a more descriptive name for the variable, or if you prefer, change the Name property of the variable in the properties frame of the authoring tool.

Variable Properties (Settings)

When a new variable is created or an existing variable is selected in the project tree, its properties are displayed in the property grid. The same values, however, may also be set in the Variable Settings dialog box, which is displayed when you double-click the name of the new variable.

Figure 2. Variable Settings dialog box

The Variable Settings dialog box allows you to change the following settings:

Name
The Name property of the variable. This property can be changed within this setting dialog box.
Scope
Specifies whether the variable is either a global or a cue-instance variable.
Control
Local

Local variables can be set using the XACT GUI, and their values are visible to the GUI user. This is the default setting when the variable is created.

Monitored

Monitored (external) variables can NOT be set using the XACT GUI. Control of this variable is presumed to be done by the game. The values of monitored variables are updated or visible to the GUI user.

Non-monitored

Non-monitored (external) variables can NOT be set using the XACT GUI. Control of this variable is presumed to be done by the game. The values of non-monitored variables are NOT updated or visible to the GUI user. This is the default when the XACT GUI is connected to an application other than Audio Console.

Use of non-monitored global variables minimizes network traffic for improved performance.

Value
The current value held by the variable.
Min
The minimum value of the variable's possible range. Min is a free form floating point input value. The default is 0.
Max
The maximum value of the variable's possible range. Max is a free form floating point input value. The default is 100.
Type
Public
A public variable is available to the game programmer using the IXACTCue::SetVariable method.
Private
Private variables are only accessible to XACT content and are not visible to the game programmer.

Deleting a Variable

To delete a variable, right-click the variable as it is displayed in the project tree, then select Delete. Alternatively, you may select the variable and press the DEL key, or click Delete Variable in the Variable Settings dialog box.

If the variable is in use (for example, assigned to a run-time parameter control), a delete action is disallowed.

See Also

XACT Audio Authoring, XACT Overviews, XACT Reference


XACT Runtime Parameter Controls

Some kinds of sounds inherently require run-time control to function correctly. For example, the sound of a car engine needs to have its volume and pitch adjusted according to gear and engine speed. Runtime parameter controls (RPCs) give the content creator control over how audio elements respond to changing conditions. With the Microsoft Cross-Platform Audio Creation Tool (XACT), the designer creates these controls and transfers them to the programmer for use in the title.

These controls are also known as sliders, because they mimic the function of slider controls on an audio mixing board.

To create and define an RPC, complete the following steps:

  • Creating a Runtime Parameter Control
  • Building a Runtime Parameter Control
  • Associating Sounds with Runtime Parameter Controls
  • Adjusting the Cursor in the RPC Editor
  • Deleting a Runtime Parameter Control

See Also

Microsoft Cross-Platform Audio Creation Tool (XACT), XACT Overviews, XACT Reference


Creating a Runtime Parameter Control

When you begin a new Microsoft Cross-Platform Audio Creation Tool (XACT) project, there are no RPCs available. You must create each that you want to use. You may create as many RPCs as you require, but you do not need to create any RPCs if you do not need them.

To create a new RPC

  1. Right-click RPC Presets in the XACT project tree.

  2. Click New RPC Preset on the shortcut menu.

    Figure 1. Creating a new runtime parameter control using the menu bar

    The new item has the default name RPC Preset.

  3. Select the new RPC.

  4. Press F2 and enter a more descriptive name for the RPC or if you prefer, change the Name property of the variable in the properties frame of the authoring tool.

RPC Preset Properties

When the RPC is selected in the project tree, its properties are displayed in the property grid, and can be changed. The following table describes the properties of an RPC as they appear in the property grid.

Property Name | Description
Name | The given name of the RPC Preset. You can rename the RPC Preset by changing this selection, or by selecting the name displayed in the project tree frame.
Notes | Comments about the object. This information is visible to the author only and is not stored in generated banks.
NumberofAttachedSounds | Display only. The count of sounds currently attached to this RPC.
AttachedSounds | A list of all the sounds associated with the RPC. The Sound level below this property displays the properties of the sound currently selected in the drop-down list box.

See Also

XACT Runtime Parameter Controls, Microsoft Cross-Platform Audio Creation Tool (XACT), XACT Overviews, XACT Reference


Building a Runtime Parameter Control

Once you have created an RPC preset, you need to define the variables that control it and how the levels will change to correspond to changes in those variables.

Double-clicking an RPC preset in the XACT project tree opens the RPC Preset dialog box; the example shown in Figure 1 already has data in it.

Figure 1. An RPC Preset dialog box showing preset data

The RPC Preset dialog box allows you to perform the following tasks:

  • Curve Editing Basics
  • Adding a New RPC Curve
  • Selecting an RPC Curve
  • Defining an RPC Curve
  • Deleting an RPC Curve

A new RPC has a single blank entry. To create a curve in the graphical editor, select a variable, object and parameter. The curve is initially displayed as a straight line with two points; you can add and adjust points on the curve to yield the desired behavior when the variable reaches a particular value. For example, when the variable OrientationAngle shown in Figure 1 reaches 41.5, the pitch will be set to 5.0. You should change the settings by moving the points, defining your own levels for each curve to match your requirements. The data points for the curve are displayed in the Points table.

The curve settings portion of the dialog box allows you to change the following settings:

View

Clicking this check box makes the graph line for this curve visible. Note that the selected curve will always be shown.

Color

Clicking this allows you to select the color used to display the graph line for this parameter.

Variable

Specifies the variable that controls the output parameter. The drop-down list offers the variables you have created, as well as the implicit variables that the Microsoft Cross-Platform Audio Creation Tool (XACT) automatically provides. To specify attack or release envelopes, use the corresponding implicit variables.

Value (Variable)

Sets the current value of the variable. This value is also known as the cursor position; for information about adjusting the cursor position, see Adjusting the Cursor in the RPC Editor.

Object

Specifies the object the curve is tied to. This can be a sound, a track or an effect (based on the RPC type).

Parameter

Specifies the output parameter to be changed by the variable. These parameters can vary, depending on the object they're affecting:

  • For sound and track objects, Pitch and Volume are available.
  • For sound objects, Reverb Send is also available.
  • For effect objects, individual effect parameters are available.

    Note Currently, Microsoft Reverb is the only available effect.

Value (Parameter)

Display only. Shows the value of the output parameter at the current cursor position.

Curve Editing Basics

The curve edit control supports a rich set of mouse and key combinations that make curve manipulation easier. These combinations are listed in the following table:

Operation | Target | Effect
Click | None | Deselect all points
Click | Non-selected point | Deselect all points and selects the point and curve under mouse cursor
Ctrl + Click | Point on selected curve | Toggles point under to selected points list
Ctrl + Shift + Click | Selected point | Deletes the point under the mouse cursor
Double Click | None | Adds a new point to the selected curve
Click + Drag | None | Drag the view
Click + Drag | Selected Point | Move the selected point(s)
Ctrl + Click + Drag | None | Drag a highlight box to select points
Shift + Click + Drag | None | Drag a box to zoom a region
MouseWheel In | None | Zoom in
MouseWheel Out | None | Zoom Out

Adding a New RPC Curve

An RPC may be as complex as you require, with several levels being controlled by different variables, each with its own curve. For example, you can specify that the volume and pitch of the first track changes according to a variable you have defined called EngineRPM, while the master volume of the cue is controlled by the implicit variable Distance.

The list of curves at the top always contains an empty entry at the bottom. To add a new curve, simply fill in the information for the new variable.

Selecting an RPC Curve

Only one curve is active at a time; only the active curve can be modified. The settings for the active curve are in bold text, its data points are listed in the Points table, and the cursor for the curve is displayed in the graphical editor. To select the active curve, select a point in the curve by clicking on it. Modifying a curve setting also sets that curve as the active curve.

Defining an RPC Curve

If View is selected in the curve settings, the curve is displayed in the drawing region of the RPC dialog box. Initially, only two points are defined on the curve. To define any curve other than a simple straight-line ramp, you must add curve points that you can use to define a more complex shape. You can place curve points in arbitrary positions; there is no rule that says a curve has to constantly move up or down.

To add a curve point

  • Double-click on the curve.

    -or-

  • In the Points table, right-click the point before which you want to add a point and then click Insert Point.

To move a curve point

  • Drag the point to a new position.

    -or-

  • In the Points table, double-click the value you want to change and then enter the new value.

To delete curve points

  1. In the graphical editor or the Points table, select the curve points to delete. You can select multiple points by holding down the CTRL key and then either dragging a box around the points or clicking each point in turn.

  2. Do one of the following:

    • Press DELETE.

      -or-

    • Right-click within the graphical editor or the Points table and then click Delete Point(s).

Deleting an RPC Curve

You can delete any curve that you no longer need.

To delete a curve

  1. Select the curve you want to delete.

  2. Right-click within the graphical editor and then select Delete Curve.

Note You can also delete a curve by right-clicking one of the curve's settings at then clicking Delete Curve.

See Also

XACT Runtime Parameter Controls, Microsoft Cross-Platform Audio Creation Tool (XACT), XACT Overviews, XACT Reference


Associating Sounds with Runtime Parameter Controls

A runtime parameter control can be associated with a single sound or even several sounds at once. Association with multiple sounds means that the same control applies to them all as the controlling variables change.

To apply an RPC to a sound or a set of sounds

  1. Double-click the sound bank under the Sound Banks heading of the project tree where the sound you wish to link to the RPC resides.
  2. Drag the sound from the Sounds frame of the sound bank to the RPC under the RPC Presets heading of the project tree.
  3. Repeat the above step for each sound you wish to associate with the RPC.

To more efficiently associate a group of sounds with an RPC, you can select multiple sounds in the sound bank by holding down the SHIFT key while clicking to select items, and then dragging the selections to the RPC in the project tree.

The sounds associated with an RPC are displayed in the property grid when the RPC is selected. These sounds also appear in the Attached Sounds table in the RPC editor.

See Also

XACT Runtime Parameter Controls, Microsoft Cross-Platform Audio Creation Tool (XACT), XACT Overviews, XACT Reference


Adjusting the Cursor in the RPC Editor

A vertical line displayed as part of the RPC graph is called a cursor. The color of the cursor is identical to color of the curve(s) it is associated with (and can be multi-colored), and its position represents the current value of the variable. The cursor associated with the selected curve is highlighted. This value will fall between the variable's MinimumValue and MaximumValue.

Figure 1. A curve with the Distance variable selected.

In the example above, the blue curve represents attenuation ranging from 0.00 dB at Distance 0.00 to −96.00 dB at Distance 5280.00. The current value (cursor position) of Distance is 723.29. The volume attenuation for the cursor location is displayed in the Value box to the right of the parameter name; here we see that the value will be −40.90 dB at this distance. This represents what you will actually hear if you play a sound that has this RPC attached to it.

Setting the position of the cursor simply requires setting the current value of the variable associated with it. This can be done during auditioning to verify that the sound or sounds will play as expected given a particular variable value. For shorter sounds, it may be useful to loop the sound during playback for testing purposes. You can also drag the cursor in the graphical editor to change its position.

Figure 2. A curve with the EngineRPM variable selected.

In this next example, the purple curve represents pitch ranging from roughly −2.00 semitones at 0.00 RPM to +12.00 semitones at 15000.00 RPM. The value of EngineRPM is at 13500 RPM, yielding a pitch shift of +6.20 semitones.

See Also

Microsoft Cross-Platform Audio Creation Tool (XACT), XACT Overviews, XACT Reference


Deleting a Runtime Parameter Control

If an RPC is no longer used, you may delete it. If the RPC is still in use, the attempt to delete it is disallowed.

To delete an RPC

  • Right-click the name of the RPC in the project tree, and then select DELETE.

    Note You can also select the RPC and then press DELETE.

See Also

XACT Runtime Parameter Controls, Microsoft Cross-Platform Audio Creation Tool (XACT), XACT Overviews, XACT Reference


XACT Time Variables

The Microsoft Cross-Platform Audio Creation Tool (XACT) engine provides a set of implicit variables that are available solely for use with runtime parameter controls to specify the behavior of attack and release envelopes for playback of a wave.

Variable Name | Type | Description
AttackTime | Cue-Instance | Counts the amount of time elapsed since the start of playback. This counter begins at zero and continues to increment until the cue is stopped.
ReleaseTime | Cue-Instance | Counts the amount of time elapsed since a non-immediate request to stop playback. A stop request can occur either from programmer control or from a Stop event. This counter begins at zero and continues to increment until the cue is retriggered.

These "time" variables are implicit for each instance of the cue. Unlike other implicit variables (such as NumCueInstances and Distance), they do not appear in the project tree. They are only accessible through the Variable column of the Runtime Parameter Control dialog box. They cannot be set or queried by the programmer, and they are not accessible through the XACT APIs.

Implement Envelopes

The default behavior for playing a wave is to play it at a constant volume and pitch level, and to stop playback immediately when requested to stop.

The implicit time-related variables AttackTime and ReleaseTime can be used to define envelopes for volume and/or pitch levels, and override the default behavior. Levels controlled by envelopes are additive to the setting in the track; that is, from -96.00 dB to +6.00 dB for volume and -12 to 12 semitones for pitch.

For example, the audio designer might create a Runtime Parameter Control (RPC) that defines attack and release envelopes as shown in Figure 1.

Figure 1. Example RPC configuration

In a curve using the AttackTime variable, the leftmost point marks the start of playback, and the initial level for that setting. Remember that this is a relative level to the track's setting for that level. In this way, a volume level of 0 means the same as the track's volume level, while -96dB equates to silence.

The rightmost point of a curve using the AttackTime variable defines the sustain envelope, or the relative level at which the setting is held throughout the remainder of playback.

In a curve using the ReleaseTime variable, the leftmost point represents the initial request to stop playback (either from the program or a Stop event) and the initial amount to add to the sustain envelope's level. Therefore, this should always begin at zero for a smooth transition.

The rightmost point of a curve using the ReleaseTime variable represents the point at which playback is completely stopped. Note that a ReleaseTime curve will have no effect if either the program or the Stop event uses the IMMEDIATE flag.

It is possible for the content creator to create multiple curves for the same time variable and level, either within a single RPC or in several RPCs assigned to the same sound. This is not desirable, however, as it makes the behavior of stopping the wave ambiguous. If a conflict occurs for a volume release envelope, the shortest envelope takes precedence, although all others are still be applied. This is likely to produce unexpected results, and applying only a single envelope per level to a sound is recommended.

See Also

XACT Audio Authoring, XACT Overviews, XACT Reference


XACT DSP Presets

Sounds can be associated with Digital Signal Processing (DSP) presets. DSPs change the way sounds render; effects like reverb are possible using DSPs.

To use a DSP in your project, complete the following steps:

  • Create a DSP Preset
  • Set DSP Parameters
  • Attach and Detach Sounds and DSP Presets

Additionally, you may perform other actions with DSP presets:

  • Modify DSP Levels
  • Delete a DSP

Create a DSP Preset

You must first create a preset that can then be associated with sounds.

Note As of this release, only one preset type, Microsoft Reverb, is available for use.

To create a new DSP preset

  1. Right-click on the DSP Effect Path Presets heading of the project tree.

  2. Select the new DSP preset you wish to create from the drop-down list.

Figure 1. The project tree, showing the DSP Effect Path Presets heading selected

Note Only one preset of each type may be created. If a preset of a given type already exists, you will not be allowed to create another preset of that type.

Set DSP Parameters

Once a DSP preset has been created, various parameters of the preset can be set to change how the preset affects the sounds it is associated with.

To set DSP preset parameters

  1. Double-click on the DSP preset you wish to modify parameters for under the DSP Effect Path Presets heading of the project tree.

- OR -

  1. Right-click on the DSP preset you wish to modify parameters for under the DSP Effect Path Presets heading of the project tree.

  2. Select "Edit Parameters..." from the drop-down list that appears.

Figure 2. The DSP preset parameter window showing various parameters

Attach and Detach Sounds and DSP Presets

A DSP can apply (be "attached") to multiple sounds. Likewise, any sound can be attached to multiple DSPs. Depending on what associations you wish to make between DSPs and sounds, you may attach a DSP to multiple sounds, or sounds to multiple DSPs:

To attach a DSP preset to sounds

  1. Right-click the DSP you wish to attach in the project tree, and select Attach/Detach Sounds...
  2. A new dialog box will appear, showing two lists. The list on the left shows sounds that are not attached to the selected DSP. The list on the right shows sounds that are attached. Use the Attach and Detach buttons to control the attachment of sounds to the DSP.
  3. To complete the attachment, click OK.

To attach a sound to DSP Presets

  1. Right-click the sound you wish to attach in the sound bank, and select Attach/Detach DSP Effect Presets...
  2. A new dialog box will appear, showing two lists. The list on the left shows DSP presets that are not attached to the selected sound. The list on the right shows DSP presets that are attached. Use the Attach and Detach buttons to control the attachment of DSPs to the sound.
  3. To complete the attachment, click OK.

Modify DSP Levels

Using Runtime Parameter Curves (RPCs), you can control the parameters of a DSP Preset at runtime by associating changes in the parameter values with changes in variables.

To use RPC to modify DSP preset parameters

  1. Create a new global variable by right-clicking on the Variables heading under the project tree and selecting "New Global Variable" from the drop-down list that appears. You may use an existing global variable, if you have previously created one.
  2. Right-click on the preset you wish to modify under the DSP Effect Path Presets heading in the project tree and select "Open RPC..." from the drop-down list that appears.
  3. Edit RPC curves on parameters to achieve the desired effect. For information on editing RPC curves, see XACT Runtime Parameter Controls.

Figure 3. The RPC window, showing various Microsoft Reverb parameters

Note The RPC that controls the parameters of a DSP preset is created automatically when the DSP preset is created, and has the same name as the DSP preset.

You can also control the level of input (called the "Send Level") of any DSP preset to sounds. This affects how much the preset affects the sounds it is associated with as a whole, without changing individual DSP preset parameters.

To use RPC to modify DSP send level

  1. Create a new global variable by right-clicking on the Variables heading under the project tree and selecting "New Global Variable" from the drop-down list that appears. You may use an existing global variable, if you have previously created one.
  2. Create a new RPC Preset by right-clicking on the RPC Presets heading under the project tree and selecting "New RPC Preset" from the drop-down list that appears.
  3. Double-click the newly-created RPC Preset. The RPC Settings dialog box will appear.
  4. In the RPC Settings dialog box, click the text box under the Parameter heading. A drop-down list will appear.
  5. Select the "Send Level" parameter corresponding to the DSP preset type you are modifying.
  6. Edit the RPC curve to achieve the desired effect.

Figure 4. The RPC window, showing the Reverb Send Level parameter selected

Note The units given in the RPC curve for DSP effects are in decibels (dB).

Delete a DSP

If a DSP preset is no longer used, you may delete it.

To delete a DSP preset

  • Right-click the name of the DSP preset in the project tree, and then select Delete.

    Note You can also select the DSP preset and then press the DELETE key.

See Also

XACT Audio Authoring, XACT Overviews, XACT Reference


XACT Reverb

The Microsoft Cross-Platform Audio Creation Tool (XACT) features a standard DSP reverberation effect with stereo input and four-channel output. The provided reverberation effect itself (the Princeton Digital 2016/360 reverb, based on the same algorithms as the 2016 reverb from Eventide, with some enhancements) is identical across both Windows and Xbox 360 acoustically, though CPU performance may vary.

The XACT Property Grid provides an easy way to adjust and set each of the reverb parameters, listed below. Adjustments may be made to the settings through a series of knobs in the DSP Preset Properties interface. Additionally, you may select an effect preset which will adjust the settings for you.

Reverb Parameters

XACT reverb parameters fall into the following three categories:

  • Delay Times
  • Indexed Parameters
  • Direct Parameters

Delay Times

Delay Times | Description
Reflections Delay | An adjustable delay introduced before the effect. It is a pre-delay that adjusts the delay time of the first reflection relative to the direct path. This delay allows the reverb effect to be delayed relative to the input (direct) signal. This parameter delays both the early reverb field (early reflections) and the late field (reverb decay). Permitted range is from 0 to 300 milliseconds.
Reverb Delay | An adjustable delay of the late field relative to the early field. The delay is measured from the start of the early reflections to the start of the late field. Permitted range is from 0 to 85 milliseconds.
Rear Delay | Rear Delay introduces a pair of adjustable delays for the left rear output and right rear output. The Rear Delay is relative to the front left and front right outputs. Permitted range is from 0 to 5 milliseconds.

Indexed Parameters

Indexed Parameters | Description
Position Left | Position Left positions the Left input within the simulated space relative to the listener. With Position Left set to minimum, the left input is placed close to the listener with early reflections dominant and the reverb decay set back in the sound field and reduced in amplitude. With Position Left set to maximum, the left input is placed at a maximum distance from the listener within the simulated room. Position Left does not affect the reverb decay time (liveness of the room), only the apparent position of the source relative to the listener. Permitted range is from 0 to 30 (no units).
Position Right | Same as Position Left, but affecting only the right input. Permitted range is from 0 to 30 (no units).
Position Matrix Left | Permitted range is from 0 to 30 (no units).
Position Matrix Right | Same as Position Matrix Left, but affecting only the right input. Permitted range is from 0 to 30 (no units).
Early Diffusion | Early Diffusion and Late Diffusion have been combined. Diffusion controls the character of the individual wall reflections. Set to minimum value to simulate a hard flat surface and to maximum value to simulate a diffuse surface. Permitted range is from 0 to 15 (no units).
Late Diffusion | Early Diffusion and Late Diffusion have been combined. Diffusion controls the character of the individual wall reflections. Set to minimum value to simulate a hard flat surface and to maximum value to simulate a diffuse surface. Permitted range is from 0 to 15 (no units).
Low EQ Gain Low EQ Gain adjusts the decay time of low frequencies relative to the decay time at 1 kHz. The values correspond to dB of gain as follows:
Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12
Gain (dB) | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 | 0 | +1 | +2 | +3 | +4

Note that a Low EQ Gain value of 8 results in the decay time of low frequencies equals the decay time at 1 kHz. Permitted range is from 0 to 12 (no units).
Low EQ Cutoff Low EQ Cutoff sets the corner frequency of the low pass filter that is controlled by the Low EQ Gain parameter. The values correspond to frequency in Hz as follows:
Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Frequency (Hz) | 50 | 100 | 150 | 200 | 250 | 300 | 350 | 400 | 450 | 500

Permitted range is from 0 to 9 (no units).
High EQ Gain High EQ Gain adjusts the decay time of high frequencies relative to the decay time at 1 kHz. When set to zero high frequencies decay at the same rate as 1 kHz. When set to maximum value, high frequencies decay at a much faster rate than 1 kHz.
Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
Gain (dB) | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 | 0

Permitted range is from 0 to 8 (no units).
High EQ Cutoff High EQ Cutoff sets the corner frequency of the high pass filter that is controlled by the High EQ Gain parameter. The values correspond to frequency in kHz as follows:
Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14
Frequency (kHz) | 1 | 1.5 | 2 | 2.5 | 3 | 3.5 | 4 | 4.5 | 5 | 5.5 | 6 | 6.5 | 7 | 7.5 | 8

Permitted range is from 0 to 14 (no units).

Direct Parameters

Direct Parameters | Description
Room Filter Frequency | Room Filter Frequency sets the corner frequency of the low pass filter for the room effect (i.e. both the early and late reverberation). Permitted range is from 20 to 20,000 Hz.
Room Filter Main | Room Filter Main sets the pass band intensity level of the low-pass filter for both the early reflections and the late field reverberation. Permitted range is from -100 to 0 dB.
Room Filter HF | Room Filter HF sets the intensity level of the low-pass filter for both the early reflections and the late field reverberation at the corner frequency (Room Filter Frequency). Permitted range is from -100 to 0 dB.
Reflections Gain | Reflections Gain adjusts the intensity/level of the early reflections. Permitted range is from -100 to 20 dB.
Reverb Gain | Reverb Gain adjusts the intensity/level of the late field. Permitted range is from -100 to 20 dB.
Decay Time | Reverberation decay time at 1 kHz. This is the time that a full scale input signal decays by 60 dB. Permitted range is from 0.1 to infinity seconds.
Density | Density controls the modal density in the late field reverberation. For colorless spaces Density should be set at max (1). As Density is decreased, the sound becomes hollow (comb filtered); an effect than can be useful if you're trying to model a silo. Permitted range is from 0 to 1, representing percentage.
Room Size | Room Size controls the apparent size of the acoustic space, with a value of 1 being smallest and 12 largest. Permitted range is from 1 to 12 meters.

See Also

XACT Audio Authoring


Compression Presets

Compression presets allow compression of wave files in XACT wave banks to reduce wave bank size.

Introduction

When authoring an XACT project, you may choose to apply compression presets to waves in the project's wave banks. Compression reduces the overall file size of the wave bank files when the project is built, but requires more CPU time to decode when the waves are played, and may result in lower quality audio playback.

Currently, one type of compression is available: ADPCM Compression. This compression method requires that waves adhere to certain conditions if they are to be played continuously. For more information, see ADPCM Compression.

To use compression presets in your XACT project, follow these steps:

  • Create A Compression Preset
  • Set Compression Properties
  • Apply Compression to Waves/Wave Banks

You may perform additional actions with compression presets:

  • Delete a Compression Preset

Create A Compression Preset

Compression Presets are a global setting in the project tree. You may create as many presets as you wish.

To create a compression preset

  1. Right-click on the Compression Presets heading of the project tree.

  2. From the drop-down list that appears, select "New Compression Preset".

    Figure 1. Creating a New Preset

Set Compression Properties

A created compression preset has properties associated with it that control the compression settings.

To modify compression properties

  1. Left-click on the compression property you wish to modify in the project tree.

  2. The properties pane below the project tree will show the compression properties.

    Figure 2. Properties Pane Showing Compression Properties

    Note There are two categories of properties, shown in the properties pane as Windows Properties and Xbox 360 Properties. Windows-only developers should set the compression properties in the Xbox 360 Properties section to None.

Apply Compression to Waves/Wave Banks

Once created, a compression preset can be applied to entire wave banks or individual waves.

To apply a compression preset to an entire wave bank

  1. Left-click on the wave bank you wish to apply compression to in the project tree.

  2. The properties pane below the project tree will show the wave bank properties.

  3. In the properties pane, left-click on the compression preset property, and choose the compression preset you want to apply from the drop-down list, or <None> if you wish to remove compression from a wave.

Figure 3. Wave Bank Properties Showing Compression Preset

Note Applying a compression preset to a wave bank may generate one or more errors or warnings if the individual waves do not meet compression requirements. If errors or warnings occur, they will be listed in a dialog box.

To apply a compression preset to an individual wave

  1. Double-click on the wave bank that contains your target wave in the project tree. The wave bank will open.

  2. In the wave bank window, click on the wave you wish to compress.

  3. The properties pane below the project tree will show the wave properties.

  4. In the properties pane, left-click on the compression preset property, and choose the compression preset you want to apply from the drop-down list. In addition to the compression settings, two additional settings are available:

    Option | Meaning
    <None> | No compression will be used on this wave.
    (Use Wavebank Settings) | This wave will use the compression type that is used by the wave bank that contains it.

Figure 4. Wave Properties Showing Compression Preset

Note Applying a compression preset may generate a warning or an error if certain compression requirements are not met. If an error or warning occurs, a dialog box will be shown.

Viewing Compression Results

When waves in a wave bank are compressed, you can compare the compressed and uncompressed file sizes, as well as the compression ratio to estimate your file size savings. The wave bank window has two columns that contain this data:

Column Name | Meaning
Size | The size of the uncompressed wave file, in bytes.
PC Compressed | The size of the compressed wave file, in bytes.
PC Ratio | A percentage number from 0-100% expressing the ratio of the compressed file size to the uncompressed file size; a value of 25% would indicate a compression rate of 4:1.

Figure 5. Wave Bank Showing Compressed File Ratios

Delete a Compression Preset

If a compression preset is no longer needed, you may delete it.

To delete a compression preset

  • Right-click the compression preset in the project tree, and then select Delete.

    Note You can also select the compression preset and then press the DELETE key.


ADPCM Compression

Description

The ADPCM compression preset is a lossy compression, which means that some data is altered and lost during compression, that can be applied to waves in wave banks to achieve compression ratios of up to 4:1. The compression sample block size is variable to allow a desirable tradeoff between size, quality, and resolution (for placing loop points).

XACT uses the Microsoft ADPCM codec. This means that a title could theoretically use XACT solely to bundle waves into wave banks, and feed these ADPCM-compressed waves to an Microsoft ADPCM codec for playback, without using the XACT engine.

Parameters

SamplesPerBlock

ADPCM compression works by separating the waveform into "blocks" and predicting the variation of the waveform samples within each block. The size of the blocks is measured in samples, and can be modified by editing this parameter in Compression Presets. The smallest block size is 32 samples, the highest is 512 samples.

Larger "blocks" will allow better compression, resulting in smaller file sizes, but at the expense of sound quality and resolution for aligning loop points.

In general, you will get the following tradeoffs as you modify the SamplesPerBlock value:

If SamplesPerBlock... | File Compression | Sound Quality | Loop Point Resolution
Increases (up to max 512) | Increases | Decreases | Decreases
Decreases (down to min 32) | Decreases | Increases | Increases

Restrictions

Because ADPCM uses sample "blocks" that are aligned one after the other, a wave compressed with ADPCM may have an unfinished, "partial" block at its end. The ADPCM decoder generates silence for the remainder of this partial block which will cause the wave to not loop seamlessly.

To properly loop waves using ADPCM compression in XACT, the wave length and any loop points in the wave data must be aligned to the sample block size. Many wave authoring packages allow you to sample block align wave lengths and loop points.

Depending on the value of the SamplesPerBlock parameter of the compression preset you are using, you may have more or less resolution with which to align the end of the wave data and/or loop points.

If you attempt to apply compression to a non-aligned wave, you will either get an error or a warning, depending on whether the wave is being used in any looping Play events. You may not compress a wave used in any looping Play events. Remove it from the looping Play events and re-apply compression.

If you apply ADPCM compression to a properly aligned wave, then re-author the wave so that it becomes non-aligned, XACT will remove the ADPCM compression from the wave without warning. Additionally, if you re-author a wave file to be properly block-aligned and reload the XACT project that contains the wave file, you may get a warning that ADPCM compression will still not properly apply. Rescan the wave in the wave bank to restore proper functionality.

If the wave is to be used exclusively in non-looping mode, this restriction does not apply. If changes are made in the XACT tool that make the wave part of a looping Play event, a warning will appear and the loop will not be allowed until the compression is removed from that wave, or the wave is re-authored to be sample block aligned.

See Also

Compression Presets


XACT Interactive Audio

Interactive Audio is a feature of the Microsoft Cross-Platform Audio Creation Tool (XACT) which enables controlled transitions between sounds or music. A complex set of music transitions can be controlled at run-time with a single trigger variable, set by the game, which causes sound transitions to occur. The transition states, effects, delays, and so on, are handled automatically by the XACT engine. Multiple interactive cues can be playing at one time, based from the same or different trigger variables, enabling a rich combination of transitions. For example, crowd noises could transition between frantic cheering, booing, and stunned silence, while the background music transitions between scores, both based on the ebb and flow of a battle scene.

Enabling Interactive Audio

To enable Interactive Audio, set the IsInteractive property of a cue to True. Cue properties can be set by selecting the cue in the Sound Bank window, then selecting the property in the property pane.

Transitions

A transition occurs when the XACT engine picks a new variation to play from an interactive audio cue. Note that if the same variation is picked again, no transition occurs and the variation continues playing uninterrupted. To edit transitions, right-click on a cue and select Edit Transitions. This will open the Interactive Audio window. You may then choose to view the transition properties by source or by target. The following properties appear in the property grid.

Transition Property Description Possible Values
TransitionSource When in the currently playing sound to begin the transition.

Immediate (default) - Stop this sound at any point and start transition.

First Marker within Range - Wait to leave this sound until the first marker in the specified range (low, high) is reached. If no marker is reached in the range, transition immediately.

Random Marker from Range - Wait to leave this sound until a randomly chosen marker in this range is reached. If no marker is reached in the range, transition immediately.

End of Loop - Play to the end of the loop (either looping play event or loop start event) then start the transition. If no loop play to the end of the sound.

End of Sound - Play to the end of the sound then start the transition. If the sound playing loops infinitely, the transition will occur immediately.
SourceMarkerMin The minimum value of the marker range.

0 to 4,294,967,295
SourceMarkerMax The maximum value of the marker range.

0 to 4,294,967,295
FadeOutDuration The duration, in milliseconds, to fade out the source sound.

0 to 65.535
TransitionDestination When in the destination sound to begin playing.

Beginning (default) — Start the destination sound from the beginning (timestamp 0.0).

AlignedTime — Jump to the same time in the destination that we were at in the source (effectively allow for smooth crossfading between several potential mixes).

AlignedMarker — Jump to the same instance of a marker that shares the same value as the marker we left the source sound at.

FirstAlignedMarker — Jump to the first instance of a marker that shares the same value as the marker we left the source sound at. If there is no matching marker, start from the beginning.

FirstMarkerInRange — Start playing at the first marker encountered in the destination sound in the specified range. If none is found, start from beginning.

RandomMarkerInRange — Start playing at a randomly chosen marker within the specified range. If none is found, start from beginning.
DestinationMarkerMin The minimum value of the marker range.

0 to 4,294,967,295
DestinationMarkerMax The maximum value of the marker range.

0 to 4,294,967,295
FadeInDuration The duration, in milliseconds, to fade in the destination sound.

0 to 65.535
TransitionType How to get from the source to the destination.

See Transition Behavior.
TransitionSound The sound to play between the source and destination.

<none> or the name of the sound to play.
CrossfadeType How the destination should replace the source sound.

Linear — Crossfade should be linear.

Logarithmic — Crossfade should be logarithmic.

EqualPower — Crossfade should be equal power.

Transition Behavior

The following tables display the possible source, destination and transition values and their defined behavior for the Transition Type property defined in the previous table.

Transition Effect | Description | Parameters
None (default) | No transition, just start the Destination as specified. | None.
Crossfade | Crossfade the Source and the Destination based on the parameters. | Source Fade Out — The time to fade the Source, in seconds. Destination Fade In — The time to fade in the Destination, in seconds.
Transitional Sound | Play the transitional sound specified when the Source stops. When the transitional sound stops, start the Destination sound, possibly overlapped with a crossfade listed below. | Transitional Sound — The sound chosen to be played between the end of the Source and the beginning of the Destination. Simultaneous — True or False. If True, play the transitional sound and the Destination at the same time.
Crossfade to Transitional Sound | Crossfade from the Source to the transitional sound. When the transition sound is done, begin playing the Destination. | Source Fade Out — The time to fade the Source, in seconds. Transitional Sound — The sound chosen to be played between the end of the Source and the beginning of the Destination.
Crossfade from Transitional Sound | Begin the transition sound once the Source has stopped. Crossfade from the transition sound to the Destination. (No change for simultaneous start; destination can still crossfade in, even though transition does not.) | Destination Fade In — The time to fade in the Destination, in seconds. Transitional Sound — The sound chosen to be played between the end of the Source and the beginning of the Destination.
Crossfade to/from transitional sound | Crossfade from the Source to the transitional sound and from the transitional sound to the Destination. | Source Fade Out — The time to fade the Source, in seconds. Transitional Sound — The sound chosen to be played between the end of the Source and the beginning of the Destination. Destination Fade In — The time to fade in the Destination, in seconds.

Auditioning

To audition a cue with interactive audio properties, simply select the cue in the sound bank and click on the play button in the XACT toolbar. To change the variable value while auditioning, open the variables window and adjust the slider for the interactive audio variable. For now when you try to edit transition properties while auditioning, the auditioning will stop (transition table has to be regenerated). Play the cue when the Transition window has focus by clicking the play button on the toolbar.

See Also

XACT Overviews


Project Build Wizard

Once you have designed your audio using the Microsoft Cross-Platform Audio Creation Tool (XACT), you must build the project to generate the resource files that the title programmer needs to integrate the audio design into the title. The XACT provides a project build wizard that automates creation of these resource files.

This topic outlines the process for building an XACT project.

  • Set the Project Properties
  • Set the Wave Bank and Sound Bank Build Properties
  • Run the Build Wizard

Set the Project Properties

The types of files generated by the build wizard, as well as the names and locations of the generated files, are set in the properties of the project.

To display the project properties

  1. Navigate to the root node at the base of the project tree.

  2. Select the root node, which is your project.

    The properties should now be displayed in the property grid (shown in Figure 1).

    Figure 1. XACT display of project properties

Build Properties

The Build Properties of the project specify the file names and paths for the header file (.h), global settings file (.xgs) and the cue list. These properties are described in the following table.

Property Name | Description
BuildProjectHeader | When set to True, the build wizard will generate the header (.h) file required by the game programmer.
ProjectHeaderFile | The name of the header file generated when BuildProjectHeader is set to True.
ProjectHeaderPath | The path of where to place the header file generated when BuildProjectHeader is set to True.
BuildCueList | When set to True, the build wizard will generate the text (.txt) file that contains the cue list.
CueListFile | The name of the cue list file generated when BuildCueList is set to True.
CueListPath | The path of where to place the cue list file generated when BuildCueList is set to True.
Name (read only) | The file name of the project.
Path (read only) | Location where the XACT file is stored. Note Source wave paths may be relative to this path, so the project file and source content can be moved.
WindowsGlobalSettingsFile | The name of the Windows version of the XACT global settings file.
WindowsGlobalSettingsPath | The location where the Windows version of the XACT global settings file should be placed.

Set the Wave Bank and Sound Bank Build Properties

Each wave bank has its own set of properties that identify the file name and path for the wave bank (.xwb) file generated by the build wizard.

Similarly, each sound bank has its own set of properties that identify the file name and path for the sound bank (.xsb) file generated by the build wizard.

Note that it is possible for each wave bank or sound bank to be written in a different location on your hard drive if the properties are set that way.

Run the Build Wizard

When you have saved the project or specified the properties for your XACT project and for its wave and sound banks, you can run the build wizard to create the resource files. The XACT provides several ways to run the build wizard.

To launch the project build wizard from the toolbar

  • Click the build icon [image] on the toolbar.

To launch the project build wizard from the menu bar

  • From the File menu, click Build.

To launch the project build wizard using the keyboard

  • Press F7.

To launch the project build wizard using the mouse

  • Right-click the root project node and select Build from the pop-up context menu.

Once you have launched the build wizard, the XACT displays the dialog box shown in Figure 2.

Figure 2. The XACT build wizard dialog

Click Finish to complete the build and exit the project build wizard. The generated files should now reside in the paths designated in the properties, which you can verify by locating them in Windows Explorer.

If the project has changed since the last build, you will be prompted to save the project.

See Also

XACT Audio Authoring, XACT Overviews, XACT Reference


XACT Shared Settings

Titles have grown in complexity and this increase often requires several audio designers and composers to work on the same project. To help manage this complexity, the Microsoft Cross-Platform Audio Creation Tool (XACT) supports project sharing. Project sharing makes it possible for different sound designers to create and/or access the same XACT global properties.

If many sound designers are collaborating on multiple projects, several XACT objects must be shared across all the projects in order for XACT to work properly. These shared objects include:

  • Global variables
  • Local variables
  • Categories
  • DSP presets
  • Compression presets
  • RPC presets

Because any member of the design team for a game can change any of these shared properties, be very careful when changing properties of shared objects.

Import and Export of Shared Settings

The XACT File menu includes the following items to support shared settings:

  • Import Shared Settings — Allows an XACT user to specify an output file that will contain all the global properties of their project. The file is stored in a simple .xap format.
  • Export Shared Settings — Allows an XACT user to import and merge a global settings file that had previously been exported. If the imported file contains any non-global properties or objects, the import fails and an error message informs the user that the selected file is not an XACT Global Settings file.

Note Only global (shared) data is exported to a global settings file, and only global data is read in when importing. Therefore, any non-global data, such as wave bank or sound bank information, is lost when syncing a shared settings file. Non-global data is lost from the shared settings file, not the current project.


XACT Reports

As part of the build process, the Microsoft Cross-Platform Audio Creation Tool (XACT) can optionally generate a report that details information about the cues, sounds banks, variables, and more. You can then use this information to help play back XACT content. This report may be generated in verbose, long text format, or a concise, tab-delimited text format.

Generating Reports

After selecting Build from the File menu, the Build Project dialog is displayed.

You may opt to generate a verbose report, a concise report, or no report at all. If you choose to generate a report, you must specify a filename. The file generated will be in text format.

After a filename has been specified, select Finish to build the project and generate the report, or Cancel to abort.

Report Format

The outline below shows the type of information that will be generated in verbose report. Concise reports provide similar information, but the formatting is tab delimited and easily read by Excel.

General:
 Project Path
 Build Platform
 Build Timestamp
 Content Version (not individual file versions)
Variables (count of used variables):
 Name
 Type (cue instance / global)
 Min Value
 Max Value
 Default Value
 ...
Categories (count of used categories):
 Name
 Parent Category
 Instance Limit
 Instance Limit Behavior
 ...
Cues (count of used cues):
 Name
 Sound Bank
 Interactive (interactive / non-interactive)
 Looping (looping / non-looping)
 Instance Limit
 Instance Limit Behavior
 Dependant Wave Banks
 Cue Instance Variables
 Global Variables
 Notes
 ...
Wave Banks (count of used wave banks):
 Name
 Type (in-memory / streaming)
 Wave Names (omitted / included)
 Num Waves
 Dependant Sound Banks
 ...
Sound Banks (count of all sound banks):
 Name
 Cue Names (omitted / included)
 Dependant Wave Banks
 ...
Unused Waves (count of unused waves):
 Wave Bank
 Name
 Path
 ...
Unused Sounds (count of unused sounds):
 Sound Bank
 Name
 ...
Unused Wave Banks (count of unused wave banks):
 Name
 ...
Unused Variables (count of unused variables):
 Name
 ...
Unused Categories (count of unused categories):
 Name
 ...
Unused RPC Presets (count of unused RPC presets):
 Name
 ...
Unused DSP Presets (count of unused DSP Presets):
 Name
 ...
Invalid Cues (count of invalid cues):
 Sound Bank
 Name
 ...
Invalid Sounds (count of invalid sounds):
 Sound Bank
 Name
 ...

See Also

XACT Audio Authoring, XACT Command-Line Tool


XACT Property Grid

The Microsoft Cross-Platform Audio Creation Tool (XACT) features a dockable property grid. This grid displays the properties of the currently selected object in the XACT interface. Selected objects can include waves, sounds, cues, wave banks, sound banks, or any other object that has its own set of properties.

The property grid appears in the lower left corner of the XACT interface, just below the project tree. By default the grid is docked, but may be undocked by selecting Properties from the View menu. The docked state of the grid may also be toggled by pressing CTRL+P.

These sections provide a quick reference guide to each of the property sets available in the XACT interface:

  • Project Properties
  • Wave Bank Properties
  • Wave Properties
  • Sound Bank Properties
  • Sound Properties
  • Cue Properties
  • Track Properties
  • Play Wave Event Properties
  • Stop Event Properties
  • Volume Event Properties
  • Pitch Event Properties
  • Marker Event Properties
  • Wave Variation Properties
  • Sound Variation Properties
  • Category Properties
  • Variable Properties
  • RPC Preset Properties
  • DSP Preset Properties
  • Compression Preset Properties
  • Transition Properties

See Also

XACT Audio Authoring


Project Properties

This section shows the property grid displaying project properties.

Property | Description
Project Path | Full path that specifies the XACT project file name and location. Note Source wave paths can be relative to this path, to allow the project file and source content to be moved.
Shared Settings | Full path that specifies the shared settings file name and location.
Project Header | Full path that specifies the project header name and location.
Cue List | Full path that specifies the generated cue list name and location.
Xbox 360 Global Settings | Full path that specifies the Xbox 360 version of the XACT global settings file name and location.
Windows Global Settings | Full path that specifies the Windows version of the XACT global settings file name and location.

See Also

XACT Property Grid


Wave Bank Properties

This section shows the property grid displaying wave bank properties.

Property | Description
Name | The name of the wave bank.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Type | Whether the XACT engine maps an entire wave bank into memory at once or streams just the needed portions of the wave bank.
Size | The wave bank data segment size.
Friendly Names | Friendly names for entries in the built wave banks. This feature is not used by the XACT engine. You should select this option only if you plan to load wave banks manually.
Sync In-Game Data | Synchronize wave bank data in the game. Note This has no effect if you use the Audio Console application.
Compression Preset | Compression to apply to waves while they are built in wave banks.
Header Path | Full path that specifies the generated wave bank header name and location.
Xbox 360 Build Path | Full path that specifies the Xbox 360 version of the generated wave bank name and location.
Windows Build Path | Full path that specifies the Windows version of the generated wave bank name and location.

See Also

XACT Property Grid


Wave Properties

This section shows the property grid displaying wave properties.

Property | Description
Name | The friendly name of this wave.
Notes | Comments about this object. Note Notes are visible to the author only and are not stored in generated banks.
Source Path | The source wave file's location. Note Source waves are not modified by XACT.
Compression Preset | Apply this compression to waves as they are built in wave banks.
Size | The size of the wave in its original format.
Format | The original format of the wave.
PC Format | The target format of the wave as it will be played on a Windows machine.
PC Size (Ratio) | The size of the wave in its Windows target format, and the ratio to the original size.
Xbox 360 Format | The target format of the wave as it will be played on an Xbox 360.
Xbox 360 Size (Ratio) | The size of the wave in its Xbox 360 format, and the ratio to the original size.
Xbox 360 Quality | The quality level for XMA encoding. Higher values increase quality, lower values decrease file size.
Additional Information | Indicates if the wave is not in use by any sounds, or if the wave has been authored with a loop point. Blank if the wave is used by at least one sound and contains no loop points.

See Also

XACT Property Grid


Sound Bank Properties

This section shows the property grid displaying sound bank properties.

Property | Description
Name | The name of the sound bank.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Include Cue Names | Store the text names of cues in the built bank. This can be removed for optimization purposes, if the programmer sets cues to play by index.
Header Path | Full path that specifies the generated sound bank header name and location.
Xbox 360 Build Path | Full path that specifies the Xbox 360 version of the generated sound bank name and location.
Windows Build Path | Full path that specifies the Windows version of the generated sound bank name and location.

See Also

XACT Property Grid


Sound Properties

This section shows the property grid displaying sound properties.

Property | Description
Name | The name of the sound.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Category | The category that the sound belongs to.
Volume | The overall volume for the sound, in dB.
Pitch | The overall pitch for the sound, in semitones.
Priority | This priority of the sound. Used to determine playback behavior if the XACT engine is using all allocated voices. A value of 0 indicates lowest priority, and 255 the highest.
Loop Count | The number of additional times that the wave events that are associated with the event play. For instance, setting the loop count to 1 means that all events play twice.
Infinite | Whether the events associated with the sound loop continuously.
New Wave on Loop | When the play event loops, whether to repeat the identical wave or choose a new wave variation.
Play Release | When the play events that are associated with this sound loop, whether to play any release envelopes or fades.
Property | Description
Enable (Vol Variation) | Whether randomized volume is used when the sound's play events are played.
New on Loop (Vol Variation) | Whether a new volume is selected each time this sound's play events loop.
Range (Vol Variation) | Minimum and maximum values to use when choosing a random value for this sound's play events.
Operation (Vol Variation) | How the new setting behaves relative to other parameter settings that the sound's tracks may already have.
Enable (Pitch Variation) | Whether randomized pitch is used when this sound's play events are played.
New on Loop (Pitch Variation) | Whether a new pitch is selected each time this sound's play events loop.
Range (Pitch Variation) | Minimum and maximum values to use when choosing a random value for this sound's play events.
Operation (Pitch Variation) | How the new setting behaves relative to other parameter settings that the sound's tracks may already have.
Enable (360 Pan) | When this sound's play events play, whether to position them at random locations around the user (checked) or to use the authored speaker assignment properties (unchecked). Note Random positioning cannot be used in conjunction with programmer-controlled positioning, nor with speaker events.
New on Loop (360 Pan) | When the sound's play events loop, whether to keep the chosen position (unchecked) or select a new value (checked).
Pan | Position the sounds from play wave events randomly between one angle and another (specified in degrees). Straight ahead is 0 degrees, to the right is 90 degrees, behind is 180 degrees, and to the left is 270 degrees.
Use Center Speaker | Whether the center channel is used for positioning.
Property | Description
RPC(s) | A scrollable list of all Runtime Parameter Controls (RPCs) that the sound uses. Use the Detach button to detach the RPCs that are selected in the list, or the Detach All button to detach all the listed RPCs.
Effect(s) | A scrollable list of all DSP Effects Path Presets that the sound uses. Use the Detach button to detach the effects that are selected in the list, or the Detach All button to detach all the listed effects.

See Also

XACT Property Grid


Cue Properties

This section shows the property grid displaying cue properties.

Property | Description
Name | The name of the cue.
Notes | Comments about the object. Note Notes are visible only to the author. They are not stored in generated banks.
Playlist Type | How to determine which variation to play.
Variations | The variations for this cue.
Limit Instances | Whether XACT should limit the number of instances of this cue that can be played at any given time.
Maximum | The maximum number of instances to allow for this cue.
Fade In (sec) | Length of time to fade in the new instance.
Fade Out (sec) | Length of time to fade out the old (stopping) instance.
Behavior At Max | How to handle play requests if the maximum number of instances is reached.
Replace Instance | Which playing instance to replace with the new instance.
How To Replace | How the new instance should replace the old (stopping) instance.

See Also

XACT Property Grid


Track Properties

This section shows the property grid displaying track properties.

Property | Description
Name | The name of the track.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Volume | The overall volume for the track, in dB.

See Also

XACT Property Grid


Play Wave Event Properties

This section shows the property grid displaying play wave event properties.

Property | Description
Name | The name of the event.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Time Stamp (sec) | The earliest time at which this event can occur, in seconds.
Random Offset (sec) | Randomly delay playback of the event by up to this much time, in seconds.
Loop Count | The number of additional times that the wave events that are associated with the event play. For instance, setting the loop count to 1 means that all events play twice.
Infinite | Specifies whether the event should loop continuously.
New Wave on Loop | When the play event loops, whether to repeat the identical wave or choose a new wave variation.
Play Release | When the track is stopped, whether to break out of the loop and play to the end of the file, including the release portion if present.
Property | Description
Enable (Vol Variation) | Whether randomized volume is used when the sound's play events are played.
New on Loop (Vol Variation) | Whether a new volume is selected each time this sound's play events loop.
Range (Vol Variation) | Minimum and maximum values to use when choosing a random volume for this play event.
Operation (Vol Variation) | How this new setting should behave relative to other parameter settings that this track may already have.
Enable (Pitch Variation) | Whether randomized pitch is used when this event is played.
New on Loop (Pitch Variation) | Whether a new pitch is selected each time this play event loops.
Range (Pitch Variation) | Minimum and maximum values to use when choosing a random pitch for this play event.
Operation (Pitch Variation) | How this new setting should behave relative to other parameter settings the track may already have.
Enable (360 Pan) | When this event plays, whether to position it at a random location around the user (checked) or to use the authored speaker assignment properties (unchecked). Note Random positioning cannot be used in conjunction with programmer-controlled positioning, nor with speaker events.
New on Loop (360 Pan) | When the play event loops, whether to keep the chosen position (unchecked) or select a new value (checked).
Pan | Position the event randomly between one angle and another (specified in degrees). Straight ahead is 0 degrees, to the right is 90 degrees, behind is 180 degrees, and to the left is 270 degrees.
Use Center Speaker | Whether the center channel is used for positioning.
Property | Description
Playlist Type | How to determine which variation to select to play.

See Also

XACT Property Grid


Stop Event Properties

This section shows the property grid displaying stop event properties.

Property | Description
Name | The name of the event.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Time Stamp (sec) | The earliest time at which this event can occur, in seconds.
Random Offset (sec) | Randomly delay playback of the event by up to this much time, in seconds.
Behavior on Stop | Whether to cut off the wave immediately upon stop, or play any release envelopes or fades before stopping.
Object to Stop | Whether the stop event affects only the wave that plays on this track, or stops the entire cue (all tracks of this sound).

See Also

XACT Property Grid


Volume Event Properties

This section shows the property grid displaying volume event properties.

Property | Description
Name | The name of the event.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Time Stamp (sec) | The earliest time at which this event can occur, in seconds.
Random Offset (sec) | Randomly delay playback of the event by up to this much time, in seconds.
Property | Description
Setting Type | Whether this setting is a one-shot, single value or a ramp (sweep across a range of values). Note Repeats (bottom of this section) must be 0 if the setting type is Ramp, and Ramp will disable repeat properties.
Equation Type | Whether the parameter is to be adjusted using a constant value, a random value from a specified range, or based on an XACT variable.
Operation | How this new setting should behave relative to other parameter settings the track may already have.
Value | A static value to use when adjusting the parameter.
Property | Description
Start | The starting volume of this volume ramp.
End | The ending volume of this volume ramp.
Seconds | The duration of this volume ramp, in seconds.
Curve | The curve shape of this volume ramp.
Property | Description
Range | The volume will be a randomly chosen value between these values, inclusive.
Property | Description
Repeats | The number of additional times the event plays. For instance, setting the repeat count to "1" means that the event plays twice.
Infinite | Whether this event repeats infinitely.
Frequency | The amount of time between repeats of this event.
Frequency Units | The units for repeat frequency. Note Beats per minute is provided as a shortcut for rhythmic event repeats.
Last Repeat (sec) | The time the last repeat occurs, relative to the time stamp start of this event.

See Also

XACT Property Grid


Pitch Event Properties

This section shows the property grid displaying pitch event properties.

Property | Description
Name | The name of the event.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Time Stamp (sec) | The earliest time at which this event can occur, in seconds.
Random Offset (sec) | Randomly delay playback of the event by up to this much time, in seconds.
Property | Description
Setting Type | Whether this setting is a one-shot, single value or a ramp (sweep across a range of values). Note Repeats (bottom of this section) must be 0 if the setting type is Ramp, and Ramp will disable repeat properties.
Equation Type | Whether the parameter is to be adjusted using a constant value, a random value from a specified range, or based on an XACT variable.
Operation | How this new setting should behave relative to other parameter settings the track may already have.
Value | A static value to use when adjusting the parameter.
Property | Description
Start | The starting pitch of this pitch ramp.
End | The ending pitch of this pitch ramp.
Seconds | The duration of this pitch ramp, in seconds.
Curve | The curve shape of this pitch ramp.
Property | Description
Range | The pitch will be a randomly chosen value between these values, inclusive.
Property | Description
Repeats | The number of additional times the event plays. For instance, setting the repeat count to "1" means that the event plays twice.
Infinite | Whether this event repeats infinitely.
Frequency | The amount of time between repeats of this event.
Frequency Units | The units for repeat frequency. Note Beats per minute is provided as a shortcut for rhythmic event repeats.
Last Repeat (sec) | The time the last repeat occurs, relative to the time stamp start of this event.

See Also

XACT Property Grid


Marker Event Properties

This section shows the property grid displaying marker event properties.

Property | Description
Name | The name of the event.
Notes | Comments about the object. Note Notes are visible only to the author. They are not stored in generated banks.
Time Stamp (sec) | The earliest time at which this event can occur, in seconds.
Random Offset (sec) | Randomly delay playback of the event by up to this much time, in seconds.
Marker ID | The value that is communicated as part of marker notifications. Markers are also used in some Interactive Audio transitions.
Repeats | The number of additional times the event plays. For instance, setting the repeat count to "1" means that the event plays twice.
Infinite | Whether this event repeats infinitely.
Frequency | The amount of time between repeats of this event.
Frequency Units | The units for repeat frequency. Note Beats per minute is provided as a shortcut for rhythmic event repeats.
Last Repeat (sec) | The time the last repeat occurs, relative to the time stamp start of this event.

See Also

XACT Property Grid


Wave Variation Properties

This section shows the property grid displaying wave variation properties.

Property | Description
Wave Name | Name of the wave attached to this variation.
Path | Location of the wave attached to this variation.
Wave Bank | Wave bank containing this wave.
Weight | Weight for this variation, indicating how frequently it will be chosen while abiding by playlist restrictions.

See Also

XACT Property Grid


Sound Variation Properties

This section shows the property grid displaying sound variation properties.

Property | Description
Sound | Sound attached to this variation.
Sound Bank | Sound bank containing this sound.
Weight | Weight for this variation, indicating how frequently it will be chosen while abiding by playlist restrictions.

See Also

XACT Property Grid


Category Properties

This section shows the property grid displaying category properties.

Property | Description
Name | The name of this category.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Visibility | Whether this category is visible to a game (public) or not (private).
Volume | The overall volume for this category, in dB.
Limit Instances | Whether XACT should limit the number of instances of this category that can play at any given time.
Maximum | The maximum number of instances to allow for this category.
Fade In (sec) | Length of time to fade in the new instance.
Fade Out (sec) | Length of time to fade out the old (stopping) instance.
Behavior At Max | How to handle play requests if the maximum number of instances is reached.
Replace Instance | Which playing instance to replace with the new instance.
How To Replace | How the new instance should replace the old (stopping) instance.

See Also

XACT Property Grid


Variable Properties

This section shows the property grid displaying variable properties.

Property | Description
Name | The name of the variable.
Notes | Comments about the object. Note Notes are visible only to the author. They are not stored in generated banks.
Scope | Whether the variable is seen by all XACT objects as a single value (global), or each cue instance gets its own copy of the variable (cue instance).
Visibility | Whether the variable can be viewed and adjusted by the programmer (public) or only by the content (private).
Initial Value | The default value when this variable is created, either when XACT is initialized (scope is global) or when a cue instance is created (scope is cue instance).
Variable Range | The minimum and maximum allowed values for the variable.
Control | Whether the authoring tool (local) or the application (external) can change the variable's value. If controlled by the application, whether updates are sent to the authoring tool (monitored) or not (non-monitored).
Value | The currently auditioning value of the variable.
RPC(s) | A scrollable list of all Runtime Parameter Controls (RPCs) that use the variable.
Sound(s) | A scrollable list of all sounds that use the variable. Note Sounds using an RPC that uses the variable are also displayed.

See Also

XACT Property Grid


RPC Preset Properties

This section shows the property grid displaying RPC preset properties.

Property | Description
Name | The name of this RPC preset.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Attached Sound(s) | A scrollable list of all sounds that use this RPC. Use the Detach button to detach the sounds selected in the list, or the Detach All button to detach all of the listed sounds.

See Also

XACT Property Grid


DSP Preset Properties

This section shows the property grid displaying DSP preset properties.

Property | Description
Name | Name of this DSP Effects Path preset.
Property | Description
Effect Preset | Parameters for this DSP effect. See XACT Reverb for a description of each of the parameters that may be adjusted for reverb.
Property | Description
Sound(s) | A scrollable list of all sounds using this DSP. Use the Detach button to detach the sounds selected in the list, or the Detach All button to detach all of the listed sounds

See Also

XACT Property Grid


Compression Preset Properties

This section shows the property grid displaying compression preset properties.

Property | Description
Name | Name of this compression preset.
Notes | Comments about this object. Note Notes are visible only to the author. They are not stored in generated banks.
Format (Xbox 360) | The file format generated by this compression preset.
Quality (Xbox 360) | Quality level for XMA encoding. Higher values increase quality, while lower values decrease file size.
Format (Windows) | The file format generated by this compression preset.
Samples Per Block (Windows) | Number of samples in a compressed ADPCM block.

See Also

XACT Property Grid


Transition Properties

This section shows the property grid displaying transition properties.

Property | Description
Source | When in the currently playing sound to begin the transition.
Destination | When in the destination sound to begin playing.
Range | Minimum and maximum values of the marker range. When transitioning, this specifies the minimum and maximum marker values to be used as a transition point from the source.
Transition Type | How to get from the source to the destination.
Property | Description
Sound | Sound attached to this variation.
Sound Bank | Sound bank containing this sound.
Range | Minimum and maximum variable value for which this sound will play.
Linger | Keep playing the currently chosen sound as long as the variable driving interactive audio is within its range. In other words, do not choose a new variation every time the variable changes unless necessary.

See Also

XACT Property Grid


XACT Command-Line Tool (XACTBld)

XACTBld (xactbld.exe) is the command-line version of the XACT. This tool generates wave bank (.xwb), sound bank (.xsb), C/C++ header, and cue list files from an XACT project (.xap) file.

USAGE: xactbld [/L] [/F] [/N] [/R:VERBOSE] [/R:CONCISE] [/X:WAVEBANK]
  [/X:SOUNDBANK] [/X:HEADER] [/X:CUELIST] [/X:REPORT] [/WIN32]
  project [project2...] [path]
Option Description

/L

Do not print the banner or status.

/F

Force a rebuild of all files.

/N

Do not overwrite files if they already exist.

/R:VERBOSE

Build a verbose report (overrides /R:CONCISE). Default is project specific.

/R:CONCISE

Build a concise report. Default is project specific.

/X:WAVEBANK

Do not build wave banks.

/X:SOUNDBANK

Do not build sound banks.

/X:HEADER

Do not build the C/C++ header.

/X:CUELIST

Do not export the cue list.

/X:REPORT

Do not generate a report.

/WIN32

Build for the Microsoft® Win32® architecture (PowerPC is the default).

Enabling this option causes XACTBld to generate data for little-endian targets, as used by the x86 processor.

project

Specifies the project file to build.

project2...

Specifies additional projects to import and build. Up to 1023 additional projects can be specified.

When you specify multiple projects, xactbld.exe loads the first project, and then imports additional projects into the first before building. Any categories, layers, or groups with the same name (assuming they are the same type) are merged. Conflicting sound bank or wave bank names or paths cause an error. This is the same functionality as the Import Project command in the XACT GUI, except that no merged project file is saved.

path

Specifies the path to which output files should be written. If a path is not specified, the paths stored in the project file are used.

To write sound banks and wave banks to separate directories, run xactbld.exe twice using the /X:WAVEBANK and /X:SOUNDBANK switches.

See Also

XACT Reference, XACT Audio Authoring


XACT Programming

This section provides information about programming using the Microsoft Cross-Platform Audio Creation Tool (XACT) engine.

Infomation is presented in the following sections:

XACT Overviews
XACT Reference


XACT Overviews

The Microsoft Cross-Platform Audio Creation Tool (XACT) and its associated application programming interface (APIs) are the high-level tools used by designers and programmers to develop audio.

XACT provides a framework for organizing and managing a title's audio resources that eases the collaboration between audio designers and title programmers.

In this section

XACT Programming Guide
Important information for programmers using XACT.
XACT Code-Driven API
An introduction to the XACT code-driven APIs.
XACT Files
The file types produced by the XACT authoring tool.
XACT Libraries
Describes the different versions of the XACT libraries for development and final builds.
Managing XACT Resources and Notifications
Discussion of XACT resource and notification management.
XACT Streaming Wave Banks
Streaming wave banks and how to use them under different circumstances with XACT.
Using X3DAudio with XACT
How to use X3DAudio with XACT to add 3D positioning effects to your title.
XACT Differences from Version 1.0
Differences between this version of XACT and v1.0 of XACT.

See Also

XACT Reference, XACT Audio Authoring


XACT Programming Guide

This topic discusses the Microsoft Cross-Platform Audio Creation Tool (XACT) from the programmer's perspective.

  • XACT Scope
  • XACT Integration

XACT Scope

The XACT APIs drive the low-level audio software engine functions to render sound. This is intended to be transparent to both the designer and the programmer.

In most cases, game title developers will find that the XACT and its functions provide a simple and elegant solution for their audio needs. However, developers who prefer to manage their audio data at a lower level will find no obstacle to accessing the functions of their audio engine directly.

Figure 1. Relationship of XACT to the audio engine

XACT Integration

The game programmer will receive from the audio designer the files that result from the XACT build process. It is then the responsibility of the programmer to initialize the XACT, load the data when it is needed within the game and trigger cues at the appropriate junctures as gameplay progresses. The programmer is also responsible for allocation and management of the memory resources needed by the XACT.

The following sections outline the most common procedures for integrating game audio resources with XACT.

  • Initialization
  • Work Loop
  • Creating Wave Banks and Sound Banks
  • Playing Cues

Initialization

To start the XACT audio engine, you must first call IXACTEngine::Initialize. As the following example demonstrates, you may invoke this function with an empty set of initialization parameters, which indicates that default settings are desired. This function needs to be called only once at the beginning of your application.

XACT_RUNTIME_PARAMETERS Params;

memset(&Params, 0, sizeof(Params));

pXACTEngine->Initialize(&Params);

Work Loop

Applications must continuously call IXACTEngine::DoWork. This function is typically called every 30 to 100 milliseconds (about once every one to four frames). The following example illustrates calling IXACTEngine::DoWork in an applications main execution loop:

bool fDone = false;

do {
   // update all the game action
   Update();

   // render graphic elements to the screen
   Render();

   // drive audio
   pXACTEngine->DoWork();

} while (!fDone)

Creating Wave Banks and Sound Banks

The game title must allocate the memory for the wave and sound bank data, then read the files into that memory. The program must then instantiate the wave and sound bank objects that will control that data. Once these banks are no longer needed, the program is responsible for destroying the objects and freeing the memory.

These procedures will typically occur at the beginning and end of a scene in the game.

The following example illustrates creation of an in-memory wave bank. For streaming wave banks, see XACT Streaming Wave Banks.

IXACTWaveBank * pWaveBank;
IXACTSoundBank * pSoundBank;

// Load Wave Bank file from media into memory, pointed to by pbWaveBank, dwWaveBankSize
// Load Sound Bank file from media into memory, pointed to by pbSoundBank, dwSoundBankSize

 // Ready to create engines for wave banks and sound banks
 if ( SUCCEEDED( pXACTEngine->CreateInMemoryWaveBank( pbWaveBank, dwWaveBankSize, 0, 0, &pWaveBank ) ) )
 {
    if ( SUCCEEDED( pXACTEngine->CreateSoundBank( pbSoundBank, dwSoundBankSize, 0, 0, &pSoundBank ) ) )
    {
      // Ready to do work
    }
}

Playing Cues

Cues in the sound bank are referenced by index. However, the method IXACTSoundBank::GetCueIndex is provided so that the program can look up the cue index from the "friendly name," or text string given the cue by the audio designer (if friendly names were included when built).

XACTINDEX XCueIndex_gs1;

// Look up the cue index from the friendly name
XCueIndex_gs1 = pSoundBank->GetCueIndex("Gunshot1");

// Play the cue
hr = pSoundBank->Play(XCueIndex_gs1, 0, NULL);

For further information, see Managing XACT Resources and Notifications

See Also

XACT Overviews, XACT Reference, XACT Audio Authoring


XACT Code-Driven API

The Microsoft Cross-Platform Audio Creation Tool (XACT) has traditionally been a content-driven system. Content creators use tools to create binary content. Then the XACT API is used to play back that content as a black box. Many developers have requested two main features—run-time visibility into the content, and APIs for a more code-driven system.

The code-driven API set expands the usefulness of XACT, by allowing game developers to take advantage of the underlying XACT architecture for such things as disk streaming, data bundling, and abstraction of complex formats such as XMA.

The XACT code-driven API provides an easy to use set of methods for playback of audio data. Audio files can either reside in wavebanks, as created by the XACT GUI, or can simply be manipulated as .wav files.

Note XMA has a variable block size, which can be set if you use the command-line encoder. If you use the XACT code-driven APIs, you must encode the data by using a 64 KB block size.

Using Programmatic APIs with Wavebanks

To use the programmatic APIs with wavebanks, create a wavebank as usual. For details, see the IXACTEngine wavebank creation methods. After the wavebank object is created, there are two ways to play a wave—prepare and play or fire and forget.

To play a wave from the wavebank by using the prepare and play method, create an IXACTWave object by using IXACTEngine::PrepareWave. For in-memory waves, IXACTEngine::PrepareWave is instantaneous. For streaming waves, IXACTEngine::PrepareWave may take some time, because the wave data must be retrieved from disk. After the wave is prepared, its properties—such as pitch and volume—can be set. To play the wave, call IXACTWave::Play.

To play a wave from a wavebank by using fire and forget, simply call IXACTWaveBank::Play. The wave then plays.

Note that if you wish to set the volume or other properties before playback begins, you must use the prepare and play method.

Using Programmatic APIs Without Wavebanks
Using a .wav File

The programmatic APIs can be used to play in-memory or streaming waves directly, by using the .wav file format. To play a wave directly, create a IXACTWave object by using the IXACTEngine::PrepareWave method. Either the IXACTWave object is read completely into memory, or it is designated for streaming. A fully prepared wave is returned from these methods. IXACTEngine::PrepareWave is asynchronous. Use a notification or IXACTWave::GetState to determine if the wave is prepared.

It may take some time to prepare the wave data while it is retrieved from disk. After creating the wave, you can set wave properties, such as pitch and volume. Call IXACTWave::Play to play the wave, IXACTWave::Stop to stop the wave, and IXACTWave::Pause to pause the wave.

Using Raw Wave Data

The programmatic APIs can be used to play in-memory or streaming waves from raw data, either in memory or as part of a larger wad file. To use raw data or a wad file, create an IXACTWave object by using either IXACTEngine::PrepareInMemoryWave or IXACTEngine::PrepareStreamingWave. Properties such as pitch and volume of the wave can be set, and the wave can be played by calling IXACTWave::Play.

Code-Driven vs. Content-Driven Methods

Methods that are available in the XACT API fall into one of three categories— code-driven, content-driven, or both. The following table summarizes the methods that are part of the code-driven API set. It also summarizes methods that are considered code-driven and content-driven.

Method | Category
IXACTEngine::CreateInMemoryWaveBank | Both
IXACTEngine::CreateStreamingWaveBank | Both
IXACTEngine::DoWork | Both
IXACTEngine::GetFinalMixFormat | Both
IXACTEngine::PrepareInMemoryWave | Code-driven
IXACTEngine::PrepareStreamingWave | Code-driven
IXACTEngine::PrepareWave | Code-driven
IXACTWave::Destroy | Code-driven
IXACTWave::GetProperties | Code-driven
IXACTWave::GetState | Code-driven
IXACTWave::Pause | Code-driven
IXACTWave::Play | Code-driven
IXACTWave::SetMatrixCoefficients | Code-driven
IXACTWave::SetPitch | Code-driven
IXACTWave::SetVolume | Code-driven
IXACTWave::Stop | Code-driven
IXACTWaveBank::GetNumWaves | Code-driven
IXACTWaveBank::GetWaveIndex | Code-driven
IXACTWaveBank::GetWaveProperties | Code-driven
IXACTWaveBank::Play | Code-driven
IXACTWaveBank::Prepare | Code-driven
IXACTWaveBank::Stop | Code-driven

See Also

XACT Overviews


XACT Files

This section describes the file types produced by the Microsoft Cross-Platform Audio Creation Tool (XACT), and how they are to be used by the developer to integrate them into the game title. XACT maintains the definition of the project in a single file and outputs other files for use by title developers.

Project File (.xap)

An XACT project is preserved in a text file with the extension XAP. This file can be opened and read using a text editor. However, it is not recommended that changes be made to this file directly. Instead, XACT should be used to change the project.

This file contains the intermediate form of the information produced by XACT, and should not be used directly by any other application.

You may import (or merge) project information from an existing project into the current project by selecting Import from the File menu. The imported file will remain unmodified.

Output Files

This section describes the files that are the product of the "Build Project" process of XACT. These output files are to be provided to the programmer to integrate the audio resources into the game title.

Wave Bank (.xwb)

The data in this file describes a single wave bank. This is the collection of waves that will either reside in memory or be streamed from the DVD or hard drive.

Sound Bank (.xsb)

The data in this file describes a single sound bank. This is the collection of instructions for playing waves and the cues that the title program uses to invoke them.

Global Settings (.xgs)

The data in this file describes all of the remaining definitions by the sound designer, including the categories, variables, and run-time parameter controls.

Header (.h)

XACT supports the option to build three types of C/C++ header files:

  • Project header file containing the indices for all wave bank entries, sound cues, and categories. This header can be used by a title to reference cues more optimally.

  • Wave bank header file containing the indices for all wave bank entries in a specific wave bank.

  • Sound bank header file containing the indices for all sounds in a specific sound bank.

Cue List (.txt)

The cue list text file contains a list of all sound cues and associated notes included in the project.

See Also

XACT Overviews, XACT Reference


XACT Libraries

Microsoft Cross-Platform Audio Creation Tool (XACT) functionality is available to titles via the libraries outlined below. Regardless of which library your title is using, XACT requires that X3DAUDIO.LIB be linked as well. The following table outlines these libraries and the features that each one supports.

Library | Supports Auditioning | Debug Information | Debugging Support File
XactEngine2_0.dll | No | No | XactEngine2_0.pdb
XactEngineD2_0.dll | No | Yes | XactEngineD2_0.pdb
XactEngineA2_0.dll | Yes | Yes | XactEngineA2_0.pdb

XactEngine2_0.dll contains no additional overhead for auditioning. Shipping titles should link with this library for the best performance and smallest memory footprint.

Linking to a specific library determines if auditioning and debug information will be available but does not enable them. To turn auditioning and debug information on their respective flags XACT_FLAG_API_AUDITION_MODE and XACT_FLAG_API_DEBUG_MODE must be used in the call to XACTCreateEngine.

XactengineA2_0.dll and XactengineD2_0.dll are located in the following directory:

<Installed SDK Location>\Utilities\Bin\x86 or x64

The debugging support files (.pdb) are located in the following directory:

<Installed SDK Location>\Extras\Symbols\retail\x86 or x64\dll

X3DAudio

Debug and retail versions of the X3DAudio library are available:

Retail | X3DAudio1_0.dll
Debug | X3DAudioD1_0.dll

The X3DAudioD1_0.dll file is located in the following directory:

<Installed SDK Location>\Utilities\Bin\x86 or x64

See Also

XACT Overviews, XACT Reference, XACT Audio Authoring


Managing XACT Resources and Notifications

The Microsoft Cross-Platform Audio Creation Tool (XACT) has always provided a great deal of freedom and flexibility with regard to resource management and notifications. With the July 2005 XDK release, XACT resources and notifications can be managed more easily than ever before.

  • IXACTSoundBank, IXACTWaveBank, and IXACTCue no longer support AddRef and Release methods. Instead, titles should free resources by calling these interfaces' respective Destroy methods. Destroy calls will synchronously destroy the object (stopping the playback immediately) and free up the resources allocated for that object.

    • Destroying a cue will immediately stop the playback (if it's playing) and delete all its contained sounds, etc.

    • Destroying a soundbank will destroy all its cues.

    • Destroying a wavebank will cause any cues that were using this wavebank to be destroyed.

  • XACTDestroyNotification, XACTFlushNotification, and XACTGetNotification have been removed. Instead, titles should implement an XACT_NOTIFICATION_CALLBACK routine and pass the function pointer to IXACTEngine::Initialize as a member of the XACT_RUNTIME_PARAMETERS structure.

  • Notification callbacks take place as soon as the event that needs the notification takes place. Titles should minimize the amount of time spent in these callbacks to avoid glitching.

  • XACT no longer makes allocations for notifications and hence titles do not need to call destroy notification APIs to free them. This means that it's no longer safe for a title to keep the notification pointers passed in the callbacks. As soon as the callback returns, the pointer is invalid.

  • The IXACTEngine::RegisterNotification and IXACTEngine::UnRegisterNotification APIs will return failure if the notification callback function pointer was not passed in the XACT_RUNTIME_PARAMETERS structure during XACT initialization.

  • Certain API calls (any that allocate/deallocate memory) are not allowed to be called from the notification callbacks. See the tables listed under XACT_NOTIFICATION_CALLBACK that enumerate all the APIs that are allowed or prohibited from the notification callbacks.

  • Interface pointers sent to titles in notifications are for reference only. Titles can make some calls on these interfaces in the callback, but should not depend on these pointers being valid after the callback returns.

  • Notification callbacks can take place on any thread, DoWork, ProcessEvents or the application thread.

    • Callbacks for Cue Prepared notification occur on the ProcessEvents thread.

    • Callbacks for Cue Destroyed notification can occur on either DoWork or the application thread. (Fire and forget cues are destroyed on the DoWork thread as soon as they finish playing).

    • Callbacks for Cue playing and Cue Stopped notification will take place on the ProcessEvents thread.

    • Callbacks for Sound Bank Destroyed notification will occur on the application thread when either IXACTSoundBank::Destroy or IXACTEngine::ShutDown is called.

    • Callbacks for Wave Bank Prepared notification will occur on either the DoWork thread or on the application thread when IXACTEngine::CreateInMemoryWaveBank or IXACTEngine::CreateStreamingWaveBank is called.

    • Callbacks for Wave Bank Destroyed notification will occur on the application thread when either IXACTWaveBank::Destroy or IXACTEngine::ShutDown is called.

    • Callbacks for Local Variable Changed and Global Variable Changed notification will occur on the ProcessEvents or the application thread (when IXACTCur::SetVariable or IXACTEngine::SetGlobalVariable APIs are called).

    • Callbacks for GUI connected and GUI disconnected notifications take place only when auditioning is enabled and take place on the auditioning thread or the application thread (when IXACTEngine::Shutdown is called).

    • Callbacks for Wave Playing and Wave Stopped can take place on the ProcessEvents thread, the renderer callback thread (notifying packet completion) or on the application thread when IXACTEngine::Shutdown or IXACTWaveBank::Destroy is called.

See Also

XACT Overviews, XACT Reference, XACT Audio Authoring,

IXACTCue::GetState, IXACTSoundBank::GetState, IXACTWaveBank::GetState,

IXACTCue::Destroy, IXACTSoundBank::Destroy, IXACTWaveBank::Destroy


XACT Streaming Wave Banks

This section discusses streaming wave banks and how to use them under different circumstances with Microsoft Cross-Platform Audio Creation Tool (XACT).

  • What is Streaming?
  • When Should Waves Be Streamed?
  • Programming for XACT Streaming
  • Memory Usage

What is Streaming?

Wave banks may be designated as in-memory, which means that their waves are to be loaded entirely into local memory from the storage medium (DVD or hard drive) for later playback through audio hardware. For waves played directly from memory there are no inherent timing or latency issues.

Wave banks may also be designated as streamed, which means that their wave data remains on the storage medium. The audio data is delivered from the DVD or hard drive to the audio hardware for playback through a set of work buffers. This is often necessary for audio (such as background music) that is too large to load into working memory.

To better understand streaming audio, it will help to become familiar with some important concepts:

Latency

Latency is wasted time. On a storage medium such as DVD or hard drive, latency is the substantial amount of time the device takes to position the proper sector under the read/write head. Latency can cause delays in playback of streamed audio, or even intermittent breaks if a slow-reading disk fails to feed data to the audio output fast enough for continuous sound.

The inherent latency of DVD and that of a hard drive can be quite substantial. While the worst-case latency of a hard drive might be around 100 milliseconds, the worst-case latency of a DVD can be a full second or more.

Latency on a DVD can be minimized when audio files are strategically placed on the disc so that the data to be streamed is contiguous. If the read head does not have to move far to retrieve the next block of data, delays will remain small.

Zero-Latency Streaming

One of the biggest challenges for game audio is trying to fit all the desired sounds within the available memory. To do so, an audio designer might reduce the sampling rate, compress the data, or both. However, this can reduce the fidelity of the sounds.

The XACT solution to this problem is zero-latency streaming, sometimes called "primed streaming." Zero-latency streaming allows a game title to make use of large, high-quality wave banks, tens of megabytes or larger, without crowding out other needs for memory while supporting smooth, uninterrupted playback.

For each wave streamed, the XACT allocates a set of memory buffers that are considerably smaller than the total size of the file. The XACT gives itself a head-start by loading a small portion of the wave file's beginning into the allocated memory; the rest remains on the storage disk. Once playback begins, the XACT will continue to reload subsequent portions of the wave into the memory buffers as they become free. If the buffer is appropriately sized, the inherent latency of the storage media will not interrupt playback.

When Should Waves Be Streamed?

In general, it is preferable to designate wave banks as in-memory. Playback from memory always occurs without error or delay.

That is not always possible, especially when wave files are large and memory resources are limited. In those circumstances, the audio designer may choose to designate a wave bank as streaming. This can be done through the XACT design tool, setting the "Streaming" property of the wave bank.

Examples of types of audio that may be appropriate for streaming are (but not limited to):

  • Background music
  • Atmospheric soundtrack
  • Extended dialogue
  • Cut-scene audio

Also, if your title has a large number of speech phrases, it may be most efficient to place them all in one large streaming wave bank.

The audio designer should consult with the game title programmer to determine if streaming is appropriate. Under the XACT, the audio designer does not need to be concerned with the details of how the audio is streamed, or what settings will work best. Implementing streaming, determining what size memory buffers need to be and managing resources are entirely under the control of the programmer.

Programming for XACT Streaming

Using a streaming wave bank, in most respects, follows the process discussed in the XACT Programming Guide. You will use the function IXACTEngine::CreateStreamingWaveBank to instantiate a wave bank object.

For cues that use streamed waves, the latency of the storage medium produces a gap of time between the request to play the cue and the moment the audio is played. On a DVD, this is typically around 100 milliseconds, but can be substantially more (see above section on latency.) If this is acceptable to gameplay, then these cues can be triggered using the IXACTSoundBank::Play method. No other support is needed.

XACTINDEX bg_music_index;

// Look up the cue's index
bg_music_index = pSoundBank->GetCueIndex( "Gunshot_1" );
// Now trigger the cue
pSoundBank->Play( bg_music_index, 0, NULL );

Programming for Zero-Latency Playback

In some cases, the programmer may need to synchronize sound to gameplay, such as speech for animations. This can be difficult without knowing the exact latency of the streamed sound. The XACT provides the programmer with a way to address this problem:

Using the Prepare Method

The game title can prime the sound cue using the IXACTSoundBank::Prepare method. This service reads a bit of the beginning of the wave into memory. After the XACT completes its priming, it notifies the program. Once the cue is primed, it can be played with zero latency and synchronized with the animation.

When the function IXACTEngine::CreateStreamingWaveBank is called to instantiate the streamed wave bank it is passed information a XACT_WAVEBANK_STREAMING_PARAMETERS structure that will identify the wave bank file and establish resources for streaming. The packetSize member specifies the amount of memory, in media sectors, for each memory buffer (or "packet") used to stream the waves in the wave bank.

When the game title wishes to trigger the cue that uses a streamed wave, it may use the Prepare method to prime the cue. This method will return the IXACTCue object for the cue. When the Play method of the primed cue is invoked, the title can expect the sound to begin immediately and commence the animation without any additional wait.

The initialization portion of the title might appear as the code sample suggests.

XACT_WAVEBANK_STREAMING_PARAMETERS  XStreaming_Params = {0};

XStreaming_Params.fh = fh_MyStreamingWaveBankFile;
XStreaming_Params.packetSize = 4;			// Four DVD sectors = 8192 bytes

// Ready to create engines for wave banks and sound banks
if ( SUCCEEDED( hr = pEngine->CreateStreamingWaveBank( &XStreaming_Params, &pWaveBank ) ) )
{
  pEngine->CreateSoundBank( pbSoundBank, dwSoundBankSize, 0, 0, &pSoundBank );
}

When the game title wishes to trigger the cue for synchronization with animation, the following sequence may be used:

XACTINDEX cue_anim_index;
IXACTCue * pCue_lips;
DWORD dwState;

// Look up the cue's index
cue_anim_index = pSoundBank->GetCueIndex( "Lips_Moving1" );
// Prime the cue
pSoundBank->Prepare( cue_anim_index, 0, &pCue_lips );
bool fDone= false;
while (!fDone)
{ // Wait for the cue to finish being prepared
  pCue_lips->GetState( &dwState );
  if( dwState & XACT_CUESTATE_PREPARED )
  {
     fDone = true;
     continue;
  }
  Sleep(1);
}

// Now trigger the cue
pCue_lips->Play();

Memory Usage

How much system memory a particular streaming wave uses for buffering depends on the value of the packetSize member of the XACT_WAVEBANK_STREAMING_PARAMETERS structure passed to IXACTEngine::CreateStreamingWaveBank. A non-looping sound uses three buffers; a looping sound uses four. The size of each buffer is specified in packetSize, as the number of sectors. The number of bytes in a packet depends on the storage media sector size (512 bytes for hard drive wave banks, 2048 bytes for DVD).

You will want to determine the ideal value for packetSize from the samples-per-second resolution of the audio and the amount of playback time you wish to buffer. The following examples show how this is done, and what memory usage would result:

Example 1

To begin, we must compute the number of DVD sectors we will need to set as packetSize for a streaming wave bank with a single 44.1-kHz, 16-bit, non-looping wave entry. Assume that we have chosen to buffer 100 milliseconds of wave data.

Therefore, we would compute the amount of memory we need for one buffer as:

44,100 (samples per second) × 2 (bytes per sample) × .100 (milliseconds) = 8820 bytes

Converting this to the number of sectors, would be calculated by:

8820 (buffer size in bytes) / 2048 (bytes per DVD sector) = 4.3 sectors

The value of 4.3 sectors must be rounded up to 5 sectors, so the effective lines of code would read:

XACT_WAVEBANK_STREAMING_PARAMETERS  XStreaming_Params = {0};

XStreaming_Params.fh = fh_MyStreamingWaveBankFile;
XStreaming_Params.packetSize = 5;			// Five DVD sectors = 10,240 bytes

The amount of memory allocated for a single buffer would be 10 KB. Because non-looping waves use 3 buffers per wave, the actual amount of memory used in this case would be 30 KB (3 × 10 KB). Since there is only one wave in this sound bank, that's all the memory that will ever be used.

Note that the amount of system RAM required does not depend on the length of the sound. It depends only on the format and the value specified in packetSize.

Example 2

Let us examine another case, a streaming wave bank that contains 200 looping wave entries. As in the example above, each wave is 44.1-kHz and 16-bit format. If the average length of each wave is 3 seconds, then the approximate size of the wave bank would be 52 MB.

If we decide that we need to buffer 100 milliseconds as in the above example, this means that our value for packetSize remains the same (5 DVD sectors), and each buffer requires 10 KB.

Because looping waves use 4 buffers (instead of 3 in the above example which specified non-looping), the actual amount of memory used per wave will be 40 KB (4 × 10 KB).

If we would like to support up to 40 concurrently playing streamed waves, then the actual amount of memory used would be computed as:

40 Kbytes (per wave) × 40 (concurrent waves) = 1.6MB of memory.

In this example, streaming the wave bank will require only 30 percent of the memory that would be required if the 52 MB wave bank were designated as in-memory.

See Also

XACT Overviews, XACT Reference, XACT Audio Authoring


Using X3DAudio with XACT

XACT supports 3D audio ouput on cues using the X3DAudio library. This section describes how to get started using X3DAudio and its associated XACT helper functions to add 3D positioning to an XACT-enabled title.

Introduction

The X3DAudio library is a 3D audio geometry library that provides positional audio calculation between sound emitters and sound listeners. XACT uses X3DAudio to calculate and apply 3D positional information to cues and their associated sound playback, so that users will hear sounds, in stereo or 5.1 configurations, with realistic positioning effects.

XACT also uses the 3D information to set the values of implicit variables on cues, so that the audio designer can create effects based on positional information, such as attenuation of volume based on distance between emitter and listener, etc.

X3DAudio is strictly a 3D math library with no signal processing capability. In order to easily integrate the X3DAudio library into XACT so that positional information can be calculated and applied to cues, XACT provides two helper functions:

  • XACT3DCalculate, which calculates positional information between a single emitter and a single listener,
  • XACT3DApply, which applies a calculation received from XACT3DCalculate to a cue, so that the cue will play with positional effects.

To use X3DAudio to apply 3D sounds to an XACT cue, follow these steps:

  1. Initialize X3DAudio Structures
  2. Set Up Emitters/Listener
  3. Call XACT3DCalculate and XACT3DApply

Initialize X3DAudio Structures

To calculate 3D positional information, X3DAudio must be given initial data about the configuration of the sound channels held by the sound emitter, and the number of sound channels held by the listener. These two values, stored in the X3DAUDIO_DSP_SETTINGS structure as SrcChannelCount and DstChannelCount determine how the calculations will be mapped to the listener's sound output format (such as stereo or 5.1 sound).

Once the count has been set, a matrix of coefficients must be allocated. The matrix must be large enough to hold the mapping data from the source channels to the destination channels. This matrix is one-dimensional, and must contain a number of elements equal to SrcChannelCount x DstChannelCount. The matrix should not be filled in with values manually, as this will be done when XACT3DCalculate is called.

The following code configures a X3DAUDIO_DSP_SETTINGS structure with mappings for either stereo or 5.1 destination sound, from either a mono or stereo source:

UINT32 srcChannelCount;  // number of points on the emitter. (DSPSettings.SrcChannelCount)
UINT32 speakerconfig;   // either SPEAKER_STEREO or SPEAKER_5POINT1 (Should match the speaker configuration of the user's system)

// Set up DSP settings based on your desired speaker configuration and emitter channel count
X3DAUDIO_DSP_SETTINGS DSPSettings;

// Set source channel and matrix coeeficients
DSPSettings.SrcChannelCount = srcChannelCount;

switch( speakerconfig )
{
 case SPEAKER_STEREO:
  //Set destination
  //Destination channels must be 2 for stereo
  DSPSettings.DstChannelCount = 2;    // must match number of channels of SpeakerChannelMask sent to XACT3DCalculate
  DSPSettings.pMatrixCoefficients = new FLOAT32[DSPSettings.SrcChannelCount * DSPSettings.DstChannelCount];
  break;

 case SPEAKER_5POINT1:
  //Set destination
  //Destination channels must be 6 for 5.1 sound
  DSPSettings.DstChannelCount = 6;  // must match number of channels of SpeakerChannelMask sent to XACT3DCalculate
  DSPSettings.pMatrixCoefficients = new FLOAT32[DSPSettings.SrcChannelCount * DSPSettings.DstChannelCount];

 default:
  // HANDLE FAILURE
  break;
}

Note that this code only handles 1- or 2-channel sources. In more complicated scenarios, source material may be 5.1 format, and so the source channel count may be 6, increasing the size of the matrix.

Set Up Emitters/Listener

X3DAudio functions by calculating positional information between emitters and listeners. The XACT implementation of X3DAudio uses one emitter and one listener for every call to XACT3DCalculate.

Your title will need to provide the positioning information that will be used to fill in the emitter and listener structures. The following code sets up a simple emitter and listener:

// generic listener that's not moving
X3DAUDIO_LISTENER listener = {
        Z_AXIS_VECTOR,      // z axis {0,0,1}, orient front
        Y_AXIS_VECTOR,      // y axis {0,1,0}, orient top
        POSITION_VECTOR,    // user defined vector for position
        ZERO_VECTOR };      // {0,0,0}, listener not moving

// Audio cone.  Ignored in multi-point emitters (channel count > 1)
X3DAUDIO_CONE cone = {  X3DAUDIO_PI/2.0f,   // InnerAngle
                            X3DAUDIO_PI,        // OuterAngle
                            2.0f,               // InnerVolume
                            1.0f,               // OuterVolume
                            0.0f,               // InnerLPF
                            0.0f,               // OuterLPF
                            0.0f,               // InnerReverb
                            0.0f };             // OuterReverb

//set up emitter
X3DAUDIO_EMITTER emitter;

emitter.pCone = &cone;

// the following need to be orthonormal
emitter.OrientFront = Z_AXIS_VECTOR;
emitter.OrientTop = Y_AXIS_VECTOR;

emitter.Position = ZERO_VECTOR;
emitter.Velocity = ZERO_VECTOR; // needs to not be zero if you want to hear Doppler effect
emitter.ChannelCount = pDSPSettings->SrcChannelCount;   // emitter ChannelCount and DSP Setting's SrcChannelCount must match
emitter.ChannelRadius = 0.0f;   // this will be set by XACT3DCalculate if ChannelCount > 1.

// will be set by XACT3DCalculate
emitter.pChannelAzimuths = NULL;

// will be set by XACT3DCalculate
emitter.pVolumeCurve = emitter.pLFECurve
        = emitter.pLPFDirectCurve
        = emitter.pLPFReverbCurve
        = emitter.pReverbCurve
        = NULL;

emitter.CurveDistanceScaler = FLT_MIN;
emitter.DopplerScaler = 1.0f;

Note that several fields of the emitter are set to NULL to use default values, or values provided by the XACT3DCalculate function.

The X3DAUDIO_CONE structure used in the above example is optional. On a single-channel emitter, setting the pCone value to NULL will result in an omnidirectional emitter.

Call XACT3DCalculate and XACT3DApply

The final steps are to call XACT3DCalculate to calculate the final channel mapping that will be applied, and then to call XACT3DApply to then apply this mapping to a cue, and copy over 3D information, such as distance, to the cue's implicit variables.

The following code assumes the XACT engine is initialized, and a cue is available:

// call calculate and apply.  It doesn't matter if the cue is already playing or just prepared.
hr = XACT3DCalculate(speakerconfig, &listener, &emitter, &DSPSettings, g_pEngine);

if(S_OK == hr)
{
 hr = XACT3DApply( &DSPSettings, pCue);
}

Implicit Variable Settings

When a call to XACT3DApply is successful, the cue that is the target of the call will be updated by XACT with values for several of its implicit variables:

Variable | Meaning
Distance | The distance from the emitter to the listener. Corresponds with the value of X3DAUDIO_DSP_SETTINGS.EmitterToListenerDistance returned by XACT3DCalculate.
OrientationAngle | The interior angle from emitter to listener, expressed in degrees with respect to the emitter's front orientation. Corresponds with the value of X3DAUDIO_DSP_SETTINGS.EmitterToListenerAngle returned by XACT3DCalculate, converted to degrees.
DopplerPitchScalar | The doppler shift factor between the source and the emitter. Corresponds with the value of X3DAUDIO_DSP_SETTINGS.DopplerFactor returned by XACT3DCalculate.

If XACT's 3D functionality is to be used in a title, the audio designer can use RPCs to relate the changes in these implicit variables to values of sound parameters such as pitch or volume.

See Also

X3DAudio Reference


XACT Differences from Version 1.0

Microsoft Cross-Platform Audio Creation Tool (XACT) 2.0 is a unified system for development of games to run on Windows® and Xbox 360 platforms. This is intended to allow designers to author their audio resources once for multiple platforms, just as a game title can be built for multiple platforms. For programmers, the XACT API set is equivalent on each platform, wherever possible.

  • Interfaces are instantiated to manage Wave Banks, Sound Banks and Cues. The SoundSources API that was available in XACT 1.0 is no longer available.
  • XACT no longer supports Windows Media Audio (WMA) playlists, and the WmaPlayList API is no longer available. Playlists and their associated audio files are now managed exclusively through Media Player (XMP).
  • XACT now supports multiple instances of cues.
  • Functions for 2D and 3D audio are unified within the XACT API.
  • The XACT graphical design tool now generates a Global Settings (XGS) file that contains information on categories, variables, and run-time parameter controls.
  • Zero-latency streaming remains a feature of XACT, but is no longer exposed to the audio designer. The decision to use zero-latency methods with streamed audio is now entirely within the jurisdiction of the game title programmer.

See Also

XACT Overviews, XACT Reference, XACT Audio Authoring


XACT Reference

This section contains the reference pages for the Microsoft Cross-Platform Audio Creation Tool (XACT) application programming interface (API). Reference material is divided into the following categories.

  • XACT Interfaces
  • XACT Functions
  • XACT Structures
  • XACT Callbacks
  • X3DAudio Reference
  • XACT Error Codes
  • XACT Project File Format (.xap)


XACT Interfaces

This section contains information about the interfaces used with Microsoft Cross-Platform Audio Creation Tool (XACT).

Interface | Description
IXACTEngine | Applications use the methods of the IXACTEngine interface to instantiate and manipulate core XACT objects.
IXACTCue | Applications use the methods of the IXACTCue interface to manipulate an XACT cue object.
IXACTSoundBank | Applications use the methods of the IXACTSoundBank interface to manipulate an XACT sound bank object.
IXACTWave | Applications use the methods of the IXACTWave interface to manipulate an XACT wave object.
IXACTWaveBank | Applications use the methods of the IXACTWaveBank interface to manipulate an XACT wave bank object.

See Also

XACT Reference


IXACTEngine

This section contains information about the methods used with the IXACTEngine interface.

Method | Description
AddRef | Adds a reference to this interface.
CreateInMemoryWaveBank | Creates an in-memory wave bank for use by the XACT engine.
CreateSoundBank | Creates a sound bank for use by the XACT engine.
CreateStreamingWaveBank | Creates an IXACTWaveBank instance.
DoWork | Performs periodic work required by the XACT engine.
GetCategory | Retrieves the sound category index that corresponds to a friendly name string.
GetFinalMixFormat | Retrives the final mix format.
GetGlobalVariable | Retrieves the value of a global variable by its index.
GetGlobalVariableIndex | Retrieves the corresponding index for a global variable name string.
GetRendererCount | Returns the total number of audio rendering devices that are available on the system. Xbox 360: This method is not supported on the Xbox 360 platform.
GetRendererDetails | Retrieves information about a specific renderer. Xbox 360: This method is not supported on the Xbox 360 platform.
Initialize | Initializes the XACT engine.
Pause | Pauses or resumes playback of a category.
PrepareInMemoryWave | Creates an in-memory IXACTWave object from data that is already resident in memory.
PrepareStreamingWave | Creates a streaming wave object for the file handle passed in.
PrepareWave | Prepares a wave object from a standard PCM, XMA (Xbox 360) file.
QueryInterface | Retrieves a pointer to an interface.
RegisterNotification | Registers an event notification.
Release | Releases this interface from memory.
SetGlobalVariable | Stores a new value to a global variable, which is referenced by its index.
SetVolume | Sets the volume of a sound category.
ShutDown | Shuts down the XACT engine and frees any resources in use.
Stop | Stops a sound category.
UnRegisterNotification | Cancel registration of an event notification.


IXACTEngine::AddRef

Adds a reference to this interface.

[Content-driven]

ULONG AddRef();

Parameters

None.

Return Values

Returns the new reference count. This return value is for diagnostic and testing purposes only.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::CreateInMemoryWaveBank

Creates an in-memory wave bank for use by the XACT engine.

[Code-driven][Content-driven]

HRESULT CreateInMemoryWaveBank(
  const void *pvBuffer,
  DWORD dwSize,
  DWORD dwFlags,
  DWORD dwAllocAttributes,
  IXACTWaveBank **ppWaveBank
);

Parameters

pvBuffer
[in] Pointer to the data that is used to create the wave bank.

Xbox 360: Memory for this member must be allocated by using Unknown Topic when you specify the XACT_FLAG_API_CREATE_MANAGEDATA flag.

Xbox 360 wavebanks must be created with caching enabled. The PAGE_WRITECOMBINE and PAGE_NOCACHE flags must not be used when calling Unknown Topic.

Windows: Memory for this member must be allocated by using CoTaskMemAlloc when you specify the XACT_FLAG_API_CREATE_MANAGEDATA flag.

dwSize
[in] Value that indicates the size of the data used to create the wave bank.
dwFlags
[in] Flag values that indicate how the wave bank is created. This parameter can be zero or the value shown in the following table.
Value | Description
XACT_FLAG_API_CREATE_MANAGEDATA | Indicates that XACT frees the buffer that the pvBuffer parameter points to, when the wave bank data is released. Note XACT does not attempt to free the memory if the buffer allocation fails.
dwAllocAttributes
[in] Flag values that indicate the attributes of the memory buffer that the pvBuffer parameter points to.

Xbox 360: This parameter is needed only if XACT_FLAG_API_CREATE_MANAGEDATA is specified in dwFlags. This is so that XMemFree can receive the correct values when the XACT engine frees the buffer. Otherwise, dwAllocAttributes is ignored.

These flags should match the XALLOC_ATTRIBUTES values that were specified to XMemAlloc when the memory buffer that pvBuffer points to was allocated.

Windows: This parameter has no relevance and is ignored.

ppWaveBank
[out] Pointer to an IXACTWaveBank object that is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::CreateSoundBank

Creates a sound bank for use by the XACT engine.

[Content-driven]

HRESULT CreateSoundBank(
  const void *pvBuffer,
  DWORD dwSize,
  DWORD dwFlags,
  DWORD dwAllocAttributes,
  IXACTSoundBank **ppSoundBank
);

Parameters

pvBuffer
[in] Pointer to the data that is used to create the sound bank.

Xbox 360: Memory for this member must be allocated by using Unknown Topic when specifying the XACT_FLAG_API_CREATE_MANAGEDATA flag.

Windows: Memory for this member must be allocated by using CoTaskMemAlloc when specifying the XACT_FLAG_API_CREATE_MANAGEDATA flag.

dwSize
[in] Value that indicates the size of the data that is used to create the sound bank .
dwFlags
[in] Flag values that indicate how the sound bank is created. This parameter can be zero or the value shown in the following table.
Value | Description
XACT_FLAG_API_CREATE_MANAGEDATA | Indicates that XACT should free the buffer that the pvBuffer parameter points to, when the sound bank data is released. Note XACT does not attempt to free the memory if the buffer allocation fails.
dwAllocAttributes
[in] Flag values that indicate the attributes of the memory buffer that the pvBuffer parameter points to.

Xbox 360: This parameter is needed only if XACT_FLAG_API_CREATE_MANAGEDATA is specified in dwFlags. This is so that XMemFree can receive the correct values when the XACT frees the buffer. Otherwise, dwAllocAttributes is ignored.

These flags should match the XALLOC_ATTRIBUTES values that were specified to XMemAlloc when the memory buffer that pvBuffer points to was allocated.

Windows: This parameter has no relevance and is ignored.

ppSoundBank
[out] Pointer to an IXACTSoundBank object that is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::CreateStreamingWaveBank

Creates an IXACTWaveBank instance.

[Code-driven][Content-driven]

HRESULT CreateStreamingWaveBank(
  const XACT_WAVEBANK_STREAMING_PARAMETERS *pParms,
  IXACTWaveBank **ppWaveBank
);

Parameters

pParms
[in] Pointer to an XACT_WAVEBANK_STREAMING_PARAMETERS structure that describes the streaming wave bank to create.
ppWaveBank
[out] Pointer to the location of the handle for the newly created IXACTWaveBank instance.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

Do not use a sound that is associated with a streaming wave bank unless you know that the wave bank is prepared.

To ascertain that the wave bank is prepared, do one of the following:

  • Create an XACTNOTIFICATIONTYPE_WAVEBANKPREPARED notification by using IXACTEngine::RegisterNotification.

    • –or–

  • Issue a query about the state of the wave bank by using IXACTWaveBank::GetState. When the XACT_WAVEBANKSTATE_PREPARED bit is set, you can use the wave bank.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::DoWork

Performs periodic work required by the XACT engine.

[Code-driven][Content-driven]

HRESULT DoWork();

Parameters

None.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

This method drives the XACT engine and is typically called every 30 to 100 milliseconds (about once every one to four frames).

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::GetCategory

Retrieves the sound category index that corresponds to a friendly name string.

[Content-driven]

XACTCATEGORY GetCategory(
  PCSTR szFriendlyName
);

Parameters

szFriendlyName
[in] Pointer to a buffer that contains the zero-terminated string that describes the category's friendly name.

Return Values

Returns a category index for the friendly name if successful. Otherwise, XACTCATEGORY_INVALID.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine | IXACTEngine::Pause, IXACTEngine::SetVolume, IXACTEngine::Stop


IXACTEngine::GetFinalMixFormat

Retrives the final mix format.

[Code-driven][Content-driven]

HRESULT GetFinalMixFormat(
  WAVEFORMATEXTENSIBLE *pFinalMixFormat
);

Parameters

pFinalMixFormat
[out] Pointer to a WAVEFORMATEXTENSIBLE structure that returns the final mix format.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::GetGlobalVariable

Retrieves the value of a global variable by its index.

[Content-driven]

HRESULT GetGlobalVariable(
  XACTVARIABLEINDEX nIndex,
  XACTVARIABLEVALUE *nValue
);

Parameters

nIndex
[in] Assigned index of the global variable to retrieve.
nValue
[out] Pointer to the location for the value currently held by the global variable.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::GetGlobalVariableIndex

Retrieves the corresponding index for a global variable name string.

[Content-driven]

XACTVARIABLEINDEX GetGlobalVariableIndex(
  PCSTR szFriendlyName
);

Parameters

szFriendlyName
[in] String that contains the friendly name of the global variable, as specified in the XACT engine.

Return Values

The index of the global variable if it exists. Otherwise, XACTVARIABLEINDEX_INVALID.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::GetRendererCount

Returns the total number of audio rendering devices that are available on the system.

Xbox 360: This method is not supported on the Xbox 360 platform.

[Content-driven]

HRESULT GetRendererCount(
  XACTINDEX *pnRendererCount
);

Parameters

pnRendererCount
Pointer to an XACTINDEX value that represents the count of audio devices.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

This method returns the total number of audio rendering devices that are available on the system. Because renderer indices are zero-based, the index of the last device is the number of devices minus one. For example, if there are two devices on the system, the index of the first device is 0 and the index of the last device is 1.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::GetRendererDetails

Retrieves information about a specific renderer.

Xbox 360: This method is not supported on the Xbox 360 platform.

[Content-driven]

HRESULT GetRendererDetails(
  XACTINDEX nRendererIndex,
  LPXACT_RENDERER_DETAILS pRendererDetails
);

Parameters

nRendererIndex
Index of the renderer to retrieve information from.
pRendererDetails
Pointer to an XACT_RENDERER_DETAILS structure that contains details of the renderer.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::Initialize

Initializes the XACT engine.

[Content-driven]

HRESULT Initialize(
  const XACT_RUNTIME_PARAMETERS *pParams
);

Parameters

pParams
[in] Pointer to an XACT_RUNTIME_PARAMETERS structure that contains the XACT engine initialization parameters.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

This function creates the XACT engine and data structures. It should be called in an application only once per IXACTEngine instance.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::Pause

Pauses or resumes playback of a category.

[Content-driven]

HRESULT Pause(
  XACTCATEGORY nCategory,
  BOOL fPause
);

Parameters

nCategory
[in] Index of the category (XACTCATEGORY) to pause, as returned by IXACTEngine::GetCategory.
fPause
[in] Action to take. If TRUE, playback is paused. If FALSE, playback resumes.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

A stopping or stopped cue cannot be paused.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine | IXACTEngine::GetCategory

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


IXACTEngine::PrepareInMemoryWave

Creates an in-memory IXACTWave object from data that is already resident in memory.

[Code-driven]

HRESULT PrepareInMemoryWave(
  DWORD dwFlags,
  WAVEBANKENTRY entry,
  DWORD *pdwSeekTable,
  BYTE *pbWaveData,
  DWORD dwPlayOffset,
  XACTLOOPCOUNT nLoopCount,
  IXACTWave **ppWave
);

Parameters

dwFlags
Flags that affect wave preparation:
Value | Description
XACT_FLAG_BACKGROUND_MUSIC | Marks the waves as background music. Xbox 360: This flag is supported only on the Xbox 360 platform.
XACT_FLAG_UNITS_MS | Indicates that the units that are passed in are measured in milliseconds.
XACT_FLAG_UNITS_SAMPLES | Indicates that the units that are passed in are in samples.
entry
WAVEBANKENTRY structure that describes the format, play region, and loop region for the wave. Set the play region length to be the buffer size, in bytes.
pdwSeekTable
Pointer to the seek table. The first DWORD in this table must be the count of entries in the seek table.
pbWaveData
Pointer to wave data. The size of the wave data is determined by the length of the play region that is described in the WAVEBANKENTRY structure that is passed in.

Xbox 360: PCM data should be in big endian format.

dwPlayOffset
Play offset to use as the start of the wave. The offset can be described in milliseconds or in samples. The dwFlags argument determines the offset units.
nLoopCount
Loop count for the wave.
ppWave
Pointer to an IXACTWave object that is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

The application must make sure that the any buffers passed in (data, seek table) are valid through the lifetime of this wave.

Xbox 360: If this API is used to prepare XMA content, the content must be encoded with 64K block size. When using XMAEncode, specify "/b 64" on the command line to create 64K blocks.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::PrepareStreamingWave

Creates a streaming wave object for the file handle passed in.

[Code-driven]

HRESULT PrepareStreamingWave(
  DWORD dwFlags,
  WAVEBANKENTRY entry,
  XACT_STREAMING_PARAMETERS streamingParams,
  DWORD dwAlignment,
  DWORD *pdwSeekTable,
  DWORD dwPlayOffset,
  XACTLOOPCOUNT nLoopCount,
  IXACTWave **ppWave
);

Parameters

dwFlags
Flags that affect wave preparation:
Value | Description
XACT_FLAG_BACKGROUND_MUSIC | Marks the waves as background music. Xbox 360: This flag is supported only on the Xbox 360 platform.
XACT_FLAG_UNITS_MS | Indicates that the units passed in are measured in milliseconds.
XACT_FLAG_UNITS_SAMPLES | Indicates that the units passed in are in samples.
entry
WAVEBANKENTRY structure that describes the format, play region, and loop region for the wave.
streamingParams
XACT_STREAMING_PARAMETERS structure with a valid file handle, packet size, etc.
dwAlignment
Alignment of wave data on the media from which it is streamed. This must be at least 2048. Otherwise, it must be a multiple of 2048.
pdwSeekTable
The seek table for XMA content. The first DWORD must be the count of entries in the table that follows it.
dwPlayOffset
Play offset to use as the start of the wave. The offset can be described in milliseconds or in samples. The dwFlags argument determines the offset units.
nLoopCount
Loop count for the wave.
ppWave
Pointer an IXACTWave object that is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

If this API is used to prepare XMA content, the content must be encoded with 64K block size. ADPCM files are currently not supported.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::PrepareWave

Prepares a wave object from a standard PCM, XMA (Xbox 360) file.

[Code-driven]

HRESULT PrepareWave(
  DWORD dwFlags,
  PCSTR szWavePath,
  WORD wStreamingPacketSize,
  DWORD dwAlignment,
  DWORD dwPlayOffset,
  XACTLOOPCOUNT nLoopCount,
  IXACTWave **ppWave
);

Parameters

dwFlags
Flags that affect wave preparation:
Value | Description
XACT_FLAG_BACKGROUND_MUSIC | Marks the waves as background music. Xbox 360: This flag is supported only on the Xbox 360 platform.
XACT_FLAG_UNITS_MS | Indicates that the units passed in are measured in milliseconds.
XACT_FLAG_UNITS_SAMPLES | Indicates that the units passed in are in samples.
szWavePath
Path to the wave file.
wStreamingPacketSize
Packet Size, in 2 KB increments. If wStreamingPacketSize is 0, the file is an in-memory wave. A fully prepared wave is returned. For streaming waves, the client needs to call IXACTWave::GetState to ensure that the wave is prepared before playback. Loop region information is read from the wave file.
dwAlignment
Alignment of wave data on the media from which it is streamed. This must be at least 2048. Otherwise, it must be a multiple of 2048.
dwPlayOffset
Play offset to use as the start of the wave. The offset can be described in milliseconds or in samples. The dwFlags argument determines the offset units.
nLoopCount
Number of times to loop this file. If there is no loop region, but the loop count is nonzero, the entire wave is looped.
ppWave
Pointer to an IXACTWave object that is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

If this API is used to prepare XMA content, the content must be encoded with 64K block size.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::QueryInterface

Retrieves a pointer to an interface.

[Content-driven]

HRESULT QueryInterface(
  REFIID riid,
  void **ppvObj
);

Parameters

riid
The REFIID that identifies the interface to query for.
ppvObj
[out] Address of a pointer that receives the interface.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::RegisterNotification

Registers an event notification.

[Content-driven]

HRESULT RegisterNotification(
  const XACT_NOTIFICATION_DESCRIPTION *pNotificationDesc
);

Parameters

pNotificationDesc
[in] Pointer to an XACT_NOTIFICATION_DESCRIPTION structure that describes the notification to register.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::Release

Releases this interface from memory.

[Content-driven]

ULONG Release();

Parameters

None.

Return Values

Returns the new reference count. This return value is for diagnostic and testing purposes only.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::SetGlobalVariable

Stores a new value to a global variable, which is referenced by its index.

[Content-driven]

HRESULT SetGlobalVariable(
  XACTVARIABLEINDEX nIndex,
  XACTVARIABLEVALUE nValue
);

Parameters

nIndex
[in] Assigned index of the global variable in which to store nValue.
nValue
[in] Value to store in the global variable.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::SetVolume

Sets the volume of a sound category.

[Content-driven]

HRESULT SetVolume(
  XACTCATEGORY nCategory,
  XACTVOLUME nVolume
);

Parameters

nCategory
[in] Index of the category (XACTCATEGORY) for which to set the volume, as returned by IXACTEngine::GetCategory.
nVolume
[in] Volume level to set.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine | IXACTEngine::GetCategory

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


IXACTEngine::ShutDown

Shuts down the XACT engine and frees any resources in use.

[Content-driven]

HRESULT ShutDown();

Parameters

None.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

This method destroys all existing cues, sound banks, and wave banks. It blocks until all cues are destroyed. The method also flushes all pending notifications and unregisters all notification descriptions. No XACT API or method calls can be made after calling this function.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTEngine::Stop

Stops a sound category.

[Content-driven]

HRESULT Stop(
  XACTCATEGORY nCategory,
  DWORD dwFlags
);

Parameters

nCategory
[in] Index of the category (XACTCATEGORY) to stop, as returned by IXACTEngine::GetCategory.
dwFlags
[in] Flag that specifies how the category is stopped. By default, the sounds complete whatever release phase the content has set up.
Value | Description
XACT_FLAG_API_STOP_IMMEDIATE | Category stops immediately, ignoring any release phase or transition specified in the content.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine | IXACTEngine::GetCategory

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


IXACTEngine::UnRegisterNotification

Cancel registration of an event notification.

[Content-driven]

HRESULT UnRegisterNotification(
  const XACT_NOTIFICATION_DESCRIPTION *pNotificationDesc
);

Parameters

pNotificationDesc
[in] Pointer to an XACT_NOTIFICATION_DESCRIPTION structure that describes the notification to unregister.

Note Attempting to unregister a notification that has not been registered has no effect.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTEngine


IXACTCue

This section contains information about the methods used with the IXACTCue interface.

Method | Description
Destroy | Destroys the cue.
GetChannelMap | Retrieves the current channel map.
GetChannelVolume | Retrieves the current volumes of a group of channel map entries.
GetState | Retrieves the state of a cue.
GetVariable | Retrieves the value of a variable by its index.
GetVariableIndex | Retrieves the corresponding index for a variable name string.
Pause | Pause or resume playback of a cue instance.
Play | Plays a prepared cue.
SetChannelMap | Sets the map used to route data from an input buffer to an output buffer.
SetChannelVolume | Sets the current volumes of a group of channel map entries, adjusting as necessary.
SetMatrixCoefficients | Sets channel volume mapping values.
SetVariable | Stores a new value to a variable, referenced by its index.
Stop | Stops a cue.


IXACTCue::Destroy

Destroys the cue.

[Content-driven]

HRESULT Destroy();

Parameters

None.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

IXACTCue::Destroy will synchronously destroy the cue, stopping the playback immediately, and frees resources allocated for the cue.

For further information on using this method, see Managing XACT Resources and Notifications.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::GetChannelMap

Retrieves the current channel map.

Windows: GetChannelMap is unsupported. Use IXACTCue::SetMatrixCoefficients.

Xbox 360: GetChannelMap is supported, but it is recommended that tiles use IXACTCue::SetMatrixCoefficients instead.

[Content-driven]

HRESULT GetChannelMap(
  LPXACTCHANNELMAP pChannelMap,
  DWORD BufferSize,
  LPDWORD pRequiredSize
);

Parameters

pChannelMap
[out, optional] Pointer to an XACTCHANNELMAP structure that receives the channel map.
BufferSize
[in, optional] Size, in bytes, of the channel map.
pRequiredSize
[out, optional] Size, in bytes, of the buffer required to store the channel map.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

This function must be called twice, first to determine the size of the buffer required to receive the channel map, and then to retrieve the channel map.

To allocate a buffer of the size required to receive the channel map
  1. Set pChannelMap to NULL.
  2. Set BufferSize to 0.
  3. Declare a temporary variable to pass its address as pRequiredSize.
  4. Call GetChannelMap with these settings.

  5. Allocate a memory block of the size (in bytes) returned in pRequiredSize.

    Xbox 360: The function XMemAlloc may be used to allocate the memory.

To retrieve the channel map
  1. Set pChannelMap to the address of the memory block allocated in the prior procedure.
  2. Set BufferSize to the value returned in pRequiredSize by the prior procedure.
  3. Set pRequiredSize to NULL.
  4. Call GetChannelMap with these settings.
  5. The channel map returned in pChannelMap can then be referenced as an XACTCHANNELMAP structure

It is not valid to call GetChannelMap with BufferSize set to a nonzero value that is smaller than the size returned in pRequiredSize.

Example

The following example shows correct procedure for using GetChannelMap.

// Query how much memory is needed for the channel map
DWORD dwChannelMapBufferSize;
pCue->GetChannelMap( NULL, 0, &dwChannelMapBufferSize );

// Now allocate the memory with our version of malloc()
LPXACTCHANNELMAP pChannelMap = (LPXACTCHANNELMAP) MyMalloc (dwChannelMapBufferSize) ;

// Retrieve the channel map for the cue
pCue->GetChannelMap( pChannelMap, dwChannelMapBufferSize, NULL );

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::GetChannelVolume

Retrieves the current volumes of a group of channel map entries.

Windows: GetChannelVolume is unsupported. Use IXACTCue::SetMatrixCoefficients.

Xbox 360: GetChannelVolume is supported, but it is recommended that tiles use IXACTCue::SetMatrixCoefficients instead.

[Content-driven]

HRESULT GetChannelVolume(
  LPXACTCHANNELVOLUME pVolume
);

Parameters

pVolume
[out] Pointer to an XACTCHANNELVOLUME structure in which to return the volume information.

Return Values

Returns S_OK if successful, an error code otherwise.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::GetProperties

Retrieves the properties of the cue.

[Content-driven]

HRESULT GetProperties(
  LPXACT_CUE_INSTANCE_PROPERTIES *ppProperties
);

Parameters

ppProperties
[out] Pointer to an XACT_CUE_INSTANCE_PROPERTIES structure that contains the cue properties.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

GetProperties will allocate memory for the XACT_CUE_INSTANCE_PROPERTIES structure using CoTaskMemAlloc. The caller should free the memory using CoTaskMemFree. As an example:

LPXACT_CUE_INSTANCE_PROPERTIES pCueProperties = NULL;
if ( FAILED( pCue->GetProperties( &pCueProperties ) ) )
{
    // Error
}
CoTaskMemFree( (void*)pCueProperties );

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::GetState

Retrieves the current operating state of a cue.

[Content-driven]

HRESULT GetState(
  DWORD *pdwState
);

Parameters

pdwState
Flags indicating the state of the cue. The flags are as follows:
Value | Description
XACT_CUESTATE_CREATED | Created, but nothing else
XACT_CUESTATE_PREPARING | Preparing to play
XACT_CUESTATE_PREPARED | Prepared, but not yet played
XACT_CUESTATE_PLAYING | Playing, but can be paused
XACT_CUESTATE_STOPPING | Stopping
XACT_CUESTATE_STOPPED | Stopped
XACT_CUESTATE_PAUSED | Paused

Note States represented by these flags are not necessarily mutually exclusive. Therefore, test states using the & (and) operation rather than the == (equals) operation.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

This function informs the caller what activity the cue is performing at the moment the call is made. The state returned from GetState indicates only the current condition.

Only XACT_CUESTATE_PAUSED is used in combination with other state flags. In other words, the GetState might return a state value with XACT_CUESTATE_PREPARING set or XACT_CUESTATE_PLAYING set, but never with both (since both conditions cannot both be true at the same time). However, GetState may return a state value with both XACT_CUESTATE_PLAYING and XACT_CUESTATE_PAUSED flags set, to signify that the cue is paused while playing.

For more information on using this method, see Managing XACT Resources and Notifications.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::GetVariable

Retrieves the value of a variable by its index.

[Content-driven]

HRESULT GetVariable(
  XACTVARIABLEINDEX nIndex,
  XACTVARIABLEVALUE *nValue
);

Parameters

nIndex
[in] Assigned index of the variable to retrieve.
nValue
[out] Pointer to where to store the value currently held by the variable.

Return Values

Returns S_OK if successful, an error code otherwise.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::GetVariableIndex

Retrieves the corresponding index for a variable name string.

[Content-driven]

XACTVARIABLEINDEX GetVariableIndex(
  PCSTR szFriendlyName
);

Parameters

szFriendlyName
[in] String containing the "friendly name" of the variable, as specified in the XACT.

Return Values

The index of the variable if it exists, or XACTVARIABLEINDEX_INVALID otherwise.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::Pause

Pause or resume playback of a cue instance.

[Content-driven]

HRESULT Pause(
  BOOL fPause
);

Parameters

fPause
[in] Action to take. If TRUE, playback is paused. If FALSE, playback resumes.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

A stopping or stopped cue cannot be paused.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::Play

Plays a prepared cue.

[Content-driven]

HRESULT Play();

Parameters

None.

Return Values

Returns S_OK if successful, an error code otherwise.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::SetChannelMap

Sets the map used to route data from input channels to output channels.

Windows: SetChannelMap is unsupported. Use IXACTCue::SetMatrixCoefficients.

Xbox 360: SetChannelMap is supported, but it is recommended that tiles use IXACTCue::SetMatrixCoefficients instead.

[Content-driven]

HRESULT SetChannelMap(
  LPCXACTCHANNELMAP pChannelMap
);

Parameters

pChannelMap
[in, optional] Pointer to an XACTCHANNELMAP structure containing the channel map data.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

Calling this method will override any volume scaling set by IXACTCue::SetChannelVolume.

This effect processes all channel map entries in the order they are passed to IXACTCue::SetChannelMap.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::SetChannelVolume

Sets the current volumes of a group of channel map entries, adjusting as necessary.

Windows: SetChannelVolume is unsupported. Use IXACTCue::SetMatrixCoefficients.

Xbox 360: SetChannelVolume is supported, but it is recommended that tiles use IXACTCue::SetMatrixCoefficients instead.

[Content-driven]

HRESULT SetChannelVolume(
  LPCXACTCHANNELVOLUME pVolume
);

Parameters

pVolume
[in] Pointer to an XACTCHANNELVOLUME structure to set all desired volumes.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

Call IXACTCue::SetChannelMap to set the channel map entries prior to calling SetChannelVolume.

Note The channel volume entries passes to SetChannelVolume must be those passed to IXACTCue::SetChannelMap.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::SetMatrixCoefficients

Sets the volume matrix coefficient table for the cue.

[Content-driven]

HRESULT SetMatrixCoefficients(
  UINT32 uSrcChannelCount,
  UINT32 uDstChannelCount,
  float *pMatrixCoefficients
);

Parameters

uSrcChannelCount
[in] Number of source channels. This must equal the number of emitter channels.
uDstChannelCount
[in] Number of destination channels. This must equal the number of final mix channels.
pMatrixCoefficients
[in] Matrix coefficient table. This is an array that represents the volume level of each source channel present in each destination channel. The source channels are the column index and the destination channels are the row index of the table. The table must have at least uSrcChannelCount * uDstChannelCount elements.

Return Values

Returns S_OK if successful, an error code otherwise.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::SetVariable

Stores a new value to a variable, referenced by its index.

[Content-driven]

HRESULT SetVariable(
  XACTVARIABLEINDEX nIndex,
  XACTVARIABLEVALUE nValue
);

Parameters

nIndex
[in] Assigned index of the variable in which to store nValue.
nValue
[in] Value to store in the variable.

Return Values

Returns S_OK if successful, an error code otherwise.

If the variable is private or read-only, SetVariable returns XACTENGINE_E_INVALIDVARIABLEINDEX.

If nValue falls outside of it's assigned range (or XACTVARIABLEVALUE_MIN to XACTVARIABLEVALUE_MAX), SetVariable returns E_FAIL. In this case, the variable is clamped within valid range and a warning message is sent to the debugger.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTCue::Stop

Stops a cue.

[Content-driven]

HRESULT Stop(
  DWORD dwFlags
);

Parameters

dwFlags
[in] Flag specifying how the cue should be stopped. The flag value may be 0 or the following:
Value | Description
XACT_FLAG_CUE_STOP_IMMEDIATE | Indicates the cue should stop immediately, ignoring any release phase or transition specified in the content.

Note Specifying a value of 0 causes Stop to account for the release phase and/or transition specified in the XACT.

Return Values

Returns S_OK if successful, an error code otherwise.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTCue


IXACTSoundBank

This section contains information about the methods used with the IXACTSoundBank interface.

Method | Description
Destroy | Destroys the sound bank.
GetCueIndex | Retrieves a sound cue index based on a string that represents the friendly name of the cue.
GetCueProperties | Retrieves the properties of a cue.
GetNumCues | Retrieves the number of cues in the soundbank.
GetState | Retrieves the current state of the sound bank.
Play | Plays a cue. Optionally, returns an instance handle to the cue object for further control.
Prepare | Prepares a cue instance for playback.
Stop | Stops a cue.


IXACTSoundBank::Destroy

Destroys the sound bank.

[Content-driven]

HRESULT Destroy();

Parameters

None.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

IXACTSoundBank::Destroy synchronously destroys all cues that are associated with the sound bank. It stops the playback immediately, and frees resources that were allocated to the sound bank.

For further information on using this method, see Managing XACT Resources and Notifications.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTSoundBank


IXACTSoundBank::GetCueIndex

Retrieves a sound cue index based on a string that represents the friendly name of the cue.

[Content-driven]

XACTINDEX GetCueIndex(
  PCSTR szFriendlyName
);

Parameters

szFriendlyName
[in] NULL-terminated string that represents the friendly name of a cue in the sound bank.

Note This string is case sensitive.

Return Values

Returns the cue index that is associated with szFriendlyName. If the cue index is not found, XACTINDEX_INVALID is returned.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTSoundBank


IXACTSoundBank::GetCueProperties

Retrieves the properties of a cue.

[Content-driven]

HRESULT GetCueProperties(
  XACTINDEX nCueIndex,
  LPXACT_CUE_PROPERTIES pProperties
);

Parameters

nCueIndex
Index of the cue to query.
pProperties
Pointer to an XACT_CUE_PROPERTIES structure that receives the cue properties.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTSoundBank


IXACTSoundBank::GetNumCues

Retrieves the number of cues in the soundbank.

[Content-driven]

HRESULT GetNumCues(
  XACTINDEX *pnNumCues
);

Parameters

pnNumCues
Pointer to an XACTINDEX that returns the number of cues.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTSoundBank


IXACTSoundBank::GetState

Retrieves the current state of the sound bank.

[Content-driven]

HRESULT GetState(
  DWORD *pdwState
);

Parameters

pdwState
[out] Flags that indicate the state of the sound bank. The flags are as follows:
Value | Description
XACT_SOUNDBANKSTATE_INUSE | Indicates that the sound bank is referenced by at least one valid cue instance or other client. For example, the game itself might reference the sound bank.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

For information on using this method, see Managing XACT Resources and Notifications.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTSoundBank


IXACTSoundBank::Play

Plays a cue. Optionally, returns an instance handle to the cue object for further control.

[Content-driven]

HRESULT Play(
  XACTINDEX nCueIndex,
  DWORD dwFlags,
  XACTTIME timeOffset,
  IXACTCue **ppCue
);

Parameters

nCueIndex
[in] Value that indicates the index of the cue to be played.
dwFlags
[in] Flags to pass to IXACTSoundBank::Prepare for cue playback.
timeOffset
[in] Time offset into the cue to start from, in milliseconds.
ppCue
[out, optional] Pointer to the IXACTCue object that is returned. If NULL is specified, no cue instance object is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTSoundBank


IXACTSoundBank::Prepare

Prepares a cue instance for playback.

[Content-driven]

HRESULT Prepare(
  XACTINDEX nCueIndex,
  DWORD dwFlags,
  XACTTIME timeOffset,
  IXACTCue **ppCue
);

Parameters

nCueIndex
[in] Value that indicates the index of the cue to be prepared.
dwFlags
[in] Unused. Should be 0.
timeOffset
[in] Time offset into the cue to start from, in milliseconds.
ppCue
[out] Pointer to the IXACTCue object that is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

This method returns a valid cue instance that is ready to be played. All allocations and stream priming, if necessary, are performed by this method.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTSoundBank


IXACTSoundBank::Stop

Stops a cue.

[Content-driven]

HRESULT Stop(
  XACTINDEX nCueIndex,
  DWORD dwFlags
);

Parameters

nCueIndex
[in] Index of the cue to be stopped.

Note All instances of the cue that are specified by nCueIndex are stopped.

dwFlags
[in] Flags affecting how the cue will be stopped. By default, the sound completes the release phase that the content has set up.
Value | Description
XACT_FLAG_SOUNDBANK_STOP_IMMEDIATE | Cue stops immediately. It ignores any release phase or transition that is specified in the content.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTSoundBank


IXACTWave

This section contains information about the methods used with the IXACTWave interface.

Method | Description
Destroy | Destroys a wave object.
GetProperties | Retrieves the properties of the wave object.
GetState | Returns the state of the wave object.
Pause | Pauses playback of a wave.
Play | Starts the playback for this wave.
SetMatrixCoefficients | Sets the volume value for each output of a wave.
SetPitch | Sets the pitch of a wave.
SetVolume | Sets the volume of a wave.
Stop | Stops the wave.


IXACTWave::Destroy

Destroys a wave object.

[Code-driven]

HRESULT Destroy();

Parameters

None.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

This method is synchronous.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWave


IXACTWave::GetProperties

Retrieves the properties of the wave object.

[Code-driven]

HRESULT GetProperties(
  LPXACT_WAVE_INSTANCE_PROPERTIES pProperties
);

Parameters

pProperties
Pointer to an XACT_WAVE_INSTANCE_PROPERTIES structure that is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWave


IXACTWave::GetState

Returns the state of the wave object.

[Code-driven]

HRESULT GetState(
  DWORD *pdwState
);

Parameters

pdwState
Pointer to a DWORD that receives the current wave state:
Value | Description
XACT_STATE_CREATED | Created, but nothing else.
XACT_STATE_PREPARING | In the middle of preparing.
XACT_STATE_PREPARED | Prepared, but not yet played.
XACT_STATE_PLAYING | Playing, but can be paused.
XACT_STATE_STOPPING | Stopping.
XACT_STATE_STOPPED | Stopped.
XACT_STATE_PAUSED | Paused. Can be combined with some of the other state flags.
XACT_STATE_INUSE | Object is in use. Used by wavebanks and soundbanks.
XACT_STATE_PREPAREFAILED | Object preparation failed.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWave


IXACTWave::Pause

Pauses playback of a wave.

[Code-driven]

HRESULT Pause(
  BOOL fPause
);

Parameters

fPause
Boolean value that specifies if the wave is paused (TRUE) or unpaused (FALSE).

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWave


IXACTWave::Play

Starts the playback for the wave.

[Code-driven]

HRESULT Play();

Parameters

None.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWave


IXACTWave::SetMatrixCoefficients

Sets the volume value for each output of a wave.

[Code-driven]

HRESULT SetMatrixCoefficients(
  UINT32 uSrcChannelCount,
  UINT32 uDstChannelCount,
  float *pMatrixCoefficients
);

Parameters

uSrcChannelCount
Number of source channels.
uDstChannelCount
Number of destination channels.
pMatrixCoefficients
Matrix coefficient table. This is an array that represents the volume level of each source channel that is present in each destination channel. The source channels are represented by the column index of the table. The destination channels are represented by the row index of the table. The table must have at least uSrcChannelCount×uDstChannelCount elements.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

The final output volume of any channel is the matrix coefficient volume multiplied by the value that is specified by IXACTWave::SetVolume.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWave


IXACTWave::SetPitch

Sets the pitch of a wave.

[Code-driven]

HRESULT SetPitch(
  XACTPITCH pitch
);

Parameters

pitch
XACTPITCH value that is used to set the pitch for playback of this wave.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWave


IXACTWave::SetVolume

Sets the volume of a wave.

[Code-driven]

HRESULT SetVolume(
  XACTVOLUME volume
);

Parameters

volume
XACTVOLUME value that is used to set the volume for playback of this wave.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWave


IXACTWave::Stop

Stops the wave.

[Code-driven]

HRESULT Stop(
  DWORD dwFlags
);

Parameters

dwFlags
Flags that affect how the wave is stopped:
Value | Description
XACT_FLAG_STOP_RELEASE | Plays the wave to completion, then stops. For looping waves, this flag plays the current iteration to completion, then stops (ignoring any subsequent iterations). In either case, any release (or tail) is played. To stop the wave immediately, use the XACT_FLAG_STOP_IMMEDIATE flag.
XACT_FLAG_STOP_IMMEDIATE | Stops the playback immediately.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWave


IXACTWaveBank

This section contains information about the methods used with the IXACTWaveBank interface.

Method | Description
Destroy | Destroys the wave bank.
GetNumWaves | Returns the number of wave entries in the wave bank.
GetState | Retrieves the current state of the wave bank.
GetWaveIndex | Returns the wave index for the friendly name of a wave in a wave bank.
GetWaveProperties | Gets the properties of a specific wave in a wave bank.
Play | Starts the playback for a wave that is indicated by the wave index.
Prepare | Prepares a wave for playback at a specified time offset.
Stop | Stops the playback for the waves that were fired using IXACTWaveBank::Play method.


IXACTWaveBank::Destroy

Destroys the wave bank.

[Content-driven]

HRESULT Destroy();

Parameters

None.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

IXACTWaveBank::Destroy synchronously destroys any cues that are using the wavebank. It stops playback immediately, and frees resources that were allocated to the wavebank.

For further information on using this method, see Managing XACT Resources and Notifications.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWaveBank


IXACTWaveBank::GetNumWaves

Returns the number of wave entries in the wave bank.

[Code-driven]

HRESULT GetNumWaves(
  XACTINDEX *pnNumWaves
);

Parameters

pnNumWaves
Pointer to an XACTINDEX that returns the number of waves in the wave bank.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWaveBank


IXACTWaveBank::GetState

Retrieves the current state of the wave bank.

[Content-driven]

HRESULT GetState(
  DWORD *pdwState
);

Parameters

pdwState
[out] Flags that indicate the state of the wave bank. The flags are as follows:
Value | Description
XACT_WAVEBANKSTATE_INUSE | Indicates that the wave bank is referenced by at least one valid cue instance or other client. For example, the game itself might reference the wave bank.
XACT_WAVEBANKSTATE_PREPARED | Indicates that the wave is prepared for use by a cue instance.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

For information on using this method, see Managing XACT Resources and Notifications.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWaveBank


IXACTWaveBank::GetWaveIndex

Returns the wave index for the friendly name of a wave in a wave bank.

[Code-driven]

XACTINDEX GetWaveIndex(
  PCSTR szFriendlyName
);

Parameters

szFriendlyName
Friendly name for the wave within the wave bank.

Return Values

Wave index for the friendly name of a wave within a wave bank.

If the wave bank does not contain the friendly name, or if an entry does not exist for the name that is passed in, the method returns XACTINDEX_INVALID .

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWaveBank


IXACTWaveBank::GetWaveProperties

Gets the properties of a specific wave in a wave bank.

[Code-driven]

HRESULT GetWaveProperties(
  XACTINDEX nWaveIndex,
  LPXACT_WAVE_PROPERTIES pWaveProperties
);

Parameters

nWaveIndex
Index of the wave for which to get properties.
pWaveProperties
Pointer to an XACT_WAVE_PROPERTIES structure that is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWaveBank


IXACTWaveBank::Play

Starts the playback for a wave that is indicated by the wave index.

[Code-driven]

HRESULT Play(
  XACTINDEX nWaveIndex,
  DWORD dwFlags,
  DWORD dwPlayOffset,
  XACTLOOPCOUNT nLoopCount,
  IXACTWave **ppWave
);

Parameters

nWaveIndex
Index of the wave.
dwFlags
Flags that affect wave preparation:
Value | Description
XACT_FLAG_BACKGROUND_MUSIC | Marks the waves as background music. Xbox 360: This flag is supported only on the Xbox 360 platform.
XACT_FLAG_UNITS_MS | Indicates that the units that are passed in are measured in milliseconds.
XACT_FLAG_UNITS_SAMPLES | Indicates that the units that are passed in are in samples.
dwPlayOffset
Play offset to use as the start of the wave. The offset can be described in milliseconds or in samples. The dwFlags argument determines the offset units.
nLoopCount
Number of loops for playback.
ppWave
Pointer to an IXACTWave object that is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWaveBank


IXACTWaveBank::Prepare

Prepares a wave for playback at a specified time offset.

[Code-driven]

HRESULT Prepare(
  XACTINDEX nWaveIndex,
  DWORD dwFlags,
  DWORD dwPlayOffset,
  XACTLOOPCOUNT nLoopCount,
  IXACTWave **ppWave
);

Parameters

nWaveIndex
Index of the wave.
dwFlags
Flags that affect wave preparation:
Value | Description
XACT_FLAG_BACKGROUND_MUSIC | Marks the waves as background music. Xbox 360: This flag is only supported only on the Xbox 360 platform.
XACT_FLAG_UNITS_MS | Indicates that the units that are passed in are measured in milliseconds.
XACT_FLAG_UNITS_SAMPLES | IIndicates that the units that are passed in are in samples.
dwPlayOffset
Play offset to use as the start of the wave. The offset can be described in milliseconds or in samples. The dwFlags argument determines the offset units.
nLoopCount
Number of loops for playback.
ppWave
Pointer to an IXACTWave object that is returned.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWaveBank


IXACTWaveBank::Stop

Stops the playback for waves that were started by using IXACTWaveBank::Play method.

[Code-driven]

HRESULT Stop(
  XACTINDEX nWaveIndex,
  DWORD dwFlags
);

Parameters

nWaveIndex
Index of the wave to stop.
dwFlags
Flags that affect how the wave is stopped:
Value | Description
XACT_FLAG_STOP_RELEASE | Breaks the loop for a looping wave and stops after playing through the release section of the wave.
XACT_FLAG_STOP_IMMEDIATE | Stops the playback immediately.

Return Values

Returns S_OK if successful. Otherwise, an error code.

Remarks

Any instance of a wave entry that is playing as part of a cue instance is not stopped by this method.

Requirements

Header: Declared in Xact.h.

Library: Use Xact.lib.

See Also

IXACTWaveBank


XACT Functions

This section contains information about the functions used with the Microsoft Cross-Platform Audio Creation Tool (XACT).

Function | Description
XACT3DApply | Applies a 3D calculation returned by XACT3DCalculate to a cue.
XACT3DCalculate | Calculates 3d positional audio information between an X3DAUDIO_LISTENER and an X3DAUDIO_EMITTER.
XACTCreateEngine | Creates an instance of the IXACTEngine interface, which is used to create and manipulate other XACT objects.

See Also

XACT Reference


XACT3DApply

Applies a 3D calculation returned by XACT3DCalculate to a cue.

HRESULT XACT3DApply(
  X3DAUDIO_DSP_SETTINGS* pDSPSettings,
  IXACTCue* pCue
);

Parameters

pDSPSettings
[in] Pointer to the 3D calculation data generated by a call to XACT3DCalculate.
pCue
[in] The cue to apply the parameters in pDSPSettings to.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

XACT3DApply performs the following:

  • Applies speaker coefficients to the playing cue instance to position it in 3D space.
  • Applies the Doppler setting to the playing cue instance (though the sound designer can exaggerate this by using the DopplerPitchScalar variable).
  • Updates the cue instance variables of this cue instance (Distance, OrientationAngle, DopplerPitchScalar).

The following elements of X3DAudio are not applied or used when content can be used to drive behavior. The library's calculations of that behavior are ignored by XACT.

  • X3DAUDIO_DISTANCE_CURVE— In particular, distance-based attenuation is provided by the content creator, not by way of a programmatic curve passed to X3DAudio.
  • X3DAUDIO_CONE— Orientation-based behavior is similarly driven by content.

Requirements

Header: Declared in Xact3d.h.

See Also

XACT Functions


XACT3DCalculate

Calculates 3D positional audio information between an X3DAUDIO_LISTENER and an X3DAUDIO_EMITTER.

HRESULT XACT3DCalculate(
  X3DAUDIO_HANDLE X3DInstance,
  const X3DAUDIO_LISTENER* pListener,
  X3DAUDIO_EMITTER* pEmitter,
  X3DAUDIO_DSP_SETTINGS* pDSPSettings
);

Parameters

X3DInstance
[in] X3DAudio instance (returned from XACT3DInitialize).
pListener
[in] Defines the listener object that will be used to calculate positional audio effects.
pEmitter
[in] Defines the emitter object that will be used to calculate positional audio effects.
pDSPSettings
[out] Pointer that receives the 3D calculation data. This value can be applied to a cue by calling XACT3DApply.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

If the pChannelAzimuths parameter of pEmitter is set to NULL, XACT will automatically calculate the azimuth values of the emitter if the number of channels is 2, 3, 4, 6, or 8. Otherwise, the function will fail.

Requirements

Header: Declared in Xact3d.h.

Library: Use X3daudio.lib.

See Also

XACT Functions


XACT3DInitialize

Initializes the 3D application programming interfaces.

HRESULT XACT3DInitialize(
  IXACTEngine* pEngine,
  X3DAUDIO_HANDLE X3DInstance
);

Parameters

pEngine
[in] Pointer to the XACT engine.
X3DInstance
[out] Handle to the X3DAudio instance.

Return Values

Returns S_OK if successful, an error code otherwise.

Remarks

This method only needs to be called once.

Requirements

Header: Declared in Xact3d.h.

See Also

XACT Functions


XACTCreateEngine

Creates an instance of the IXACTEngine interface, which is used to create and manipulate other XACT objects.

HRESULT XACTCreateEngine(
  DWORD dwCreationFlags,
  IXACTEngine **ppEngine
);

Parameters

dwCreationFlags
[in] Flags that specify how the engine should be created.
Value | Description
XACT_FLAG_API_AUDITION_MODE | Specifies that auditioning should be enabled.
XACT_FLAG_API_DEBUG_MODE | Specifies that debug mode should be enabled.
ppEngine
[out] Address that will receive a pointer to the created engine.

Return Values

Returns S_OK if successful, an error code otherwise.

Requirements

Header: Declared in Xact.h.

See Also

XACT Functions


XACT Structures

This section contains information about the structures used with the Microsoft Cross-Platform Audio Creation Tool (XACT).

Structure | Description
WAVEBANKDATA | Contains the data from an XACT wave bank.
WAVEBANKENTRY | Contains the entry information from an XACT wave bank.
WAVEBANKENTRYCOMPACT | Contains compact entry metadata.
WAVEBANKHEADER | Contains the header information from an XACT wave bank.
WAVEBANKMINIWAVEFORMAT | Contains the mini-wave format for an XACT wave bank.
WAVEBANKREGION | Contains the region information for an XACT wave bank.
WAVEBANKSAMPLEREGION | Contains the sample region information for an XACT wave bank.
XACT_CUE_INSTANCE_PROPERTIES | Returns the properties of an active cue instance.
XACT_CUE_PROPERTIES | Reports cue properties back to the client.
XACT_FILEIO_CALLBACKS | File I/O Callbacks
XACT_NOTIFICATION | General XACT notification structure.
XACT_NOTIFICATION_CUE | Notification structure for all XACT cue notifications.
XACT_NOTIFICATION_DESCRIPTION | Provides descriptions for registering, unregistering, and flushing notifications.
XACT_NOTIFICATION_GUI | Notification structure for all GUI notifications.
XACT_NOTIFICATION_MARKER | Notification structure for all marker notifications.
XACT_NOTIFICATION_SOUNDBANK | Notification structure for all sound bank notifications.
XACT_NOTIFICATION_VARIABLE | Notification structure for all variable notifications.
XACT_NOTIFICATION_WAVE | Notification structure for all wave notifications.
XACT_NOTIFICATION_WAVEBANK | Notification structure for all wave bank notifications.
XACT_RENDERER_DETAILS | Returns information about a particular renderer.
XACT_RUNTIME_PARAMETERS | Runtime parameters for initialization of the XACT engine.
XACT_SOUND_PROPERTIES | Returns the properties for a sound that is referenced by the active variation.
XACT_SOUND_VARIATION_PROPERTIES | Returns the properties of the sound variation that is currently active in a cue instance.
XACT_STREAMING_PARAMETERS | Streaming parameters for a wave bank.
XACT_TRACK_PROPERTIES | Returns the properties of a track in an active sound variation in a cue instance.
XACT_VARIATION_PROPERTIES | Returns the properties for the variation that is currently active in a cue instance.
XACT_WAVE_INSTANCE_PROPERTIES | Returns the properties specific to a wave instance.
XACT_WAVE_PROPERTIES | Returns the properties that are common to all waves.
XACTCHANNELMAP | Defines the entire map of how a router effect moves data from one frame buffer to another, or how it moves channel data in a single frame buffer.
XACTCHANNELMAPENTRY | One entry in the map used by the router effect.
XACTCHANNELVOLUME | Groups a collection of audio channel volume entries.
XACTCHANNELVOLUMEENTRY | One entry in the collection of channel volumes.
XACTCUEPROPERTIES | Contains the properties of a cue. Xbox 360: This structure is specific to the Xbox 360 platform.

See Also

XACT Reference


WAVEBANKDATA

Contains the data from an XACT wave bank.

typedef struct WAVEBANKDATA {
    DWORD dwFlags;
    DWORD dwEntryCount;
    CHAR szBankName[WAVEBANK_BANKNAME_LENGTH];
    DWORD dwEntryMetaDataElementSize;
    DWORD dwEntryNameElementSize;
    DWORD dwAlignment;
    WAVEBANKMINIWAVEFORMAT CompactFormat;
    FILETIME BuildTime;
} WAVEBANKDATA, *LPWAVEBANKDATA;

Members

dwFlags
Wave bank type and data flags. Specifies one of the following wave bank types.
Value | Description
WAVEBANK_TYPE_BUFFER | Indicates that the data for this wave bank uses an in-memory buffer. When this flag is specified, the WAVEBANK_TYPE_STREAMING flag may not be specified.
WAVEBANK_TYPE_STREAMING | Indicates that the data for this wave bank uses a streaming buffer. When this flag is specified, the WAVEBANK_TYPE_BUFFER flag may not be specified.
Additionally, dwFlags may contain a combination of the following wave bank flags.
Value | Description
WAVEBANK_FLAGS_ENTRYNAMES | Indicates that the wave bank includes entry names. The names will be an array of strings found in the WAVEBANK_SEGIDX_ENTRYNAMES section of the wave bank.
WAVEBANK_FLAGS_COMPACT | Indicates that the wave bank is a compact streaming bank.
dwEntryCount
Number of elements found in the WAVEBANK_SEGIDX_ENTRYMETADATA section (and if names are included, the number of elements in the WAVEBANK_SEGIDX_ENTRYNAMES section).
szBankName
Name of the wave bank.
dwEntryMetaDataElementSize
Size of each entry metadata element, in bytes.
dwEntryNameElementSize
Size of each entry name element, in bytes.
dwAlignment
Entry alignment, in bytes. Can be one of the following values:
Value | Description
WAVEBANK_ALIGNMENT_MIN | Indicates alignment for in-memory wave banks.
WAVEBANK_ALIGNMENT_DVD | Indicates alignment for DVD streamed wave banks.
CompactFormat
WAVEBANKMINIWAVEFORMAT structure containing the mini-wave format for the wave bank. This member is valid only if dwFlags contains WAVEBANK_FLAGS_COMPACT.
BuildTime
Build timestamp.

Requirements

Header: Declared in Xact2wb.h.

See Also

XACT Structures


WAVEBANKENTRY

Contains the entry information from an XACT wave bank.

typedef struct WAVEBANKENTRY {
    union {
        struct {
            DWORD dwFlags : 4;
            DWORD Duration : 28;
        };
        DWORD dwFlagsAndDuration;
    };
    WAVEBANKMINIWAVEFORMAT Format;
    WAVEBANKREGION PlayRegion;
    WAVEBANKSAMPLEREGION LoopRegion;
} WAVEBANKENTRY, *LPWAVEBANKENTRY;

Members

dwFlags
Flags for the wave bank entry. Can be the following values.
Value | Description
WAVEBANKENTRY_FLAGS_READAHEAD | Indicates stream read-ahead is enabled.
WAVEBANKENTRY_FLAGS_LOOPCACHE | Indicates one or more looping sounds use this wave.
WAVEBANKENTRY_FLAGS_REMOVELOOPTAIL | Indicates removal of data after the end of the loop region.
Duration
Duration of the wave, in units of one sample. For instance, a ten second long wave sampled at 48KHz would have a duration of 480,000. This value is not affected by the number of channels, the number of bits per sample, or the compression format of the wave.
dwFlagsAndDuration
DWORD value representing both the flags and duration.
Format
WAVEBANKMINIWAVEFORMAT structure describing the mini-wave format for the wave bank entry.
PlayRegion
WAVEBANKREGION structure that describes the region within the wave data segment that contains this entry.
LoopRegion
WAVEBANKSAMPLEREGION structure that describes the region within the wave data (in samples) that should loop.

Requirements

Header: Declared in Xact2wb.h.

See Also

XACT Structures


WAVEBANKENTRYCOMPACT

Contains compact entry meta-data.

typedef struct WAVEBANKENTRYCOMPACT {
    DWORD dwOffset : 21;
    DWORD dwLengthDeviation : 11;
} WAVEBANKENTRYCOMPACT, *LPWAVEBANKENTRYCOMPACT;

Members

dwOffset
Data offset, in sectors.
dwLengthDeviation
Data length deviation, in bytes.

Requirements

Header: Declared in Xact2wb.h.

See Also

XACT Structures


WAVEBANKHEADER

Contains the header information from an XACT wave bank.

typedef struct WAVEBANKHEADER {
    DWORD dwSignature;
    DWORD dwVersion;
    DWORD dwHeaderVersion;
    WAVEBANKREGION Segments[WAVEBANK_SEGIDX_COUNT];
} WAVEBANKHEADER, *LPWAVEBANKHEADER;

Members

dwSignature
File signature. In a valid file, this will equal WAVEBANK_HEADER_SIGNATURE.
dwVersion
Version of the tool that created the file. The version is XACT_CONTENT_VERSION, and is defined in XACT.h.
dwHeaderVersion
Version of the wave bank file format. The current file format version is WAVEBANK_HEADER_VERSION.
Segments
Array of WAVEBANKREGION structures representing the segment lookup table. The indices into this array are defined in WAVEBANKSEGIDX. For example, you would use the WAVEBANK_SEGIDX_BANKDATA index to find the bank data region.

Requirements

Header: Declared in Xact2wb.h.

See Also

XACT Structures


WAVEBANKMINIWAVEFORMAT

Contains the mini-wave format for an XACT wave bank.

typedef union WAVEBANKMINIWAVEFORMAT {
    struct {
        DWORD wFormatTag : 1;
        DWORD nChannels : 3;
        DWORD nSamplesPerSec : 27;
        DWORD wBitsPerSample : 1;
    };
    DWORD dwValue;
} WAVEBANKMINIWAVEFORMAT, *LPWAVEBANKMINIWAVEFORMAT;

Members

wFormatTag
Format of the wave file. Can be one of the following values.
Value | Description
WAVEBANKMINIFORMAT_TAG_PCM | Specifies PCM wave format.
WAVEBANKMINIFORMAT_TAG_XMA | Specifies XMA format.
nChannels
Number of channels in the wave file. Can be a value from 1 to 6.
nSamplesPerSec
Sampling rate of the wave file.
wBitsPerSample
Bit depth of the wave file. Can be one of the following values.
Value | Description
WAVEBANKMINIFORMAT_BITDEPTH_8 | Specifies 8-bit data. (PCM only)
WAVEBANKMINIFORMAT_BITDEPTH_16 | Specifies 16-bit data. (PCM or XMA)
dwValue
This member is unused.

Requirements

Header: Declared in Xact2wb.h.

See Also

XACT Structures


WAVEBANKREGION

Contains the region information for an XACT wave bank.

typedef struct WAVEBANKREGION {
    DWORD dwOffset;
    DWORD dwLength;
} WAVEBANKREGION, *LPWAVEBANKREGION;

Members

dwOffset
Region offset in bytes.
dwLength
Region length in bytes.

Requirements

Header: Declared in Xact2wb.h.

See Also

XACT Structures


WAVEBANKSAMPLEREGION

Contains the sample region information for an XACT wave bank.

typedef struct WAVEBANKSAMPLEREGION {
    DWORD dwStartSample;
    DWORD dwTotalSamples;
} WAVEBANKSAMPLEREGION, *LPWAVEBANKSAMPLEREGION;

Members

dwStartSample
Start sample for the region.
dwTotalSamples
Region length in samples.

Requirements

Header: Declared in Xact2wb.h.

See Also

XACT Structures


XACTCHANNELMAP

Defines the entire map of how a router effect moves data from one frame buffer to another, or how it moves channel data in a single frame buffer.

typedef struct XACTCHANNELMAP {
    XACTCHANNEL EntryCount;
    XACTCHANNELMAPENTRY *paEntries;
} XACTCHANNELMAP, *LPXACTCHANNELMAP;

Members

EntryCount
Number of entries in the map.
paEntries
Pointer to an array of XACTCHANNELMAPENTRY structures containing the mapping information.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACTCHANNELMAPENTRY

One entry in the map used by the router effect.

typedef struct XACTCHANNELMAPENTRY {
    XACTCHANNEL InputChannel;
    XACTCHANNEL OutputChannel;
    XACTVOLUME Volume;
} XACTCHANNELMAPENTRY, *LPXACTCHANNELMAPENTRY;

Members

InputChannel
Channel index to read from the input frame buffer.
OutputChannel
Channel index to write to the output frame buffer.
Volume
Volume level of the data to be written to the output frame buffer.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACTCHANNELVOLUME

Groups a collection of audio channel volume entries.

typedef struct XACTCHANNELVOLUME {
    XACTCHANNEL EntryCount;
    XACTCHANNELVOLUMEENTRY *paEntries;
} XACTCHANNELVOLUME, *LPXACTCHANNELVOLUME;

Members

EntryCount
Number of elements in the paEntries array.
paEntries
Pointer to an array of XACTCHANNELVOLUMEENTRY structures of channel volume entries.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACTCHANNELVOLUMEENTRY

One entry in the collection of channel volumes.

typedef struct XACTCHANNELVOLUMEENTRY {
    XACTCHANNEL EntryIndex;
    XACTVOLUME Volume;
} XACTCHANNELVOLUMEENTRY, *LPXACTCHANNELVOLUMEENTRY;

Members

EntryIndex
Channel index to which this setting applies.
Volume
Volume level setting for the data to output.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACTCUEPROPERTIES

Contains the properties of a cue.

typedef struct XACTCUEPROPERTIES {
    XACTCATEGORY ActiveSoundCategory;
    BYTE ActiveSoundTrackCount;
    BYTE ActiveSoundPriority;
    XACTINDEX FirstTrackWaveIndex;
    DWORD FirstTrackWaveDuration;
    XACTCHANNEL MaxTrackChannelCount;
    BYTE MaxTrackLoopCount;
} XACTCUEPROPERTIES, *LPXACTCUEPROPERTIES;

Members

ActiveSoundCategory
Category of the active sound.
ActiveSoundTrackCount
Number of tracks in the active sound.
ActiveSoundPriority
Priority of the active sound.
FirstTrackWaveIndex
Index of the currently selected wave variation in the first track.
FirstTrackWaveDuration
Estimated duration, in milliseconds, of the selected wave in the first track.

Note This does not account for pitch changes.

MaxTrackChannelCount
Highest number of channels in any track.
MaxTrackLoopCount
Highest loop count of any track (255 is infinite).

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_CUE_INSTANCE_PROPERTIES

Returns the properties of an active cue instance.

typedef struct XACT_CUE_INSTANCE_PROPERTIES {
    DWORD allocAttributes;
    XACT_CUE_PROPERTIES cueProperties;
    XACT_SOUND_VARIATION_PROPERTIES activeVariationProperties;
} XACT_CUE_INSTANCE_PROPERTIES, *LPXACT_CUE_INSTANCE_PROPERTIES;

Members

allocAttributes
Buffer allocation attributes.
cueProperties
Properties of the cue that are shared by all instances. These properties are represented in an XACT_CUE_PROPERTIES structure.
activeVariationProperties
Properties of the currently active variation. These properties are represented in an XACT_SOUND_VARIATION_PROPERTIES structure.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_CUE_PROPERTIES

Reports cue properties back to the client.

typedef struct XACT_CUE_PROPERTIES {
    CHAR friendlyName[XACT_CUE_NAME_LENGTH];
    BOOL interactive;
    XACTINDEX iaVariableIndex;
    XACTINDEX numVariations;
    XACTINSTANCELIMIT maxInstances;
    XACTINSTANCELIMIT currentInstances;
} XACT_CUE_PROPERTIES, *LPXACT_CUE_PROPERTIES;

Members

friendlyName
Friendly name of the cue. If the soundbank does not contain of friendly names, an empty string is returned.
interactive
TRUE if the cue is an interactive audio cue. Otherwise, FALSE.
iaVariableIndex
For interactive audio cues, the index of the variable to control the cue.
numVariations
Number of sound variations for this cue.
maxInstances
Maximum number of instances that are allowed for this cue.
currentInstances
Number of currently active instances of this cue.

Remarks

This structure returns the non-instance specific cue properties for a cue. That is, it returns the properties that are shared across all instances of a cue.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_FILEIO_CALLBACKS

File I/O Callbacks

typedef struct XACT_FILEIO_CALLBACKS {
    XACT_READFILE_CALLBACK readFileCallback;
    XACT_GETOVERLAPPEDRESULT_CALLBACK getOverlappedResultCallback;
} XACT_FILEIO_CALLBACKS, *PXACT_FILEIO_CALLBACKS;

Members

readFileCallback
Pointer to the client (title) implementation of the XACT_READFILE_CALLBACK callback function.
getOverlappedResultCallback
Pointer to the client (title) implementation of the XACT_GETOVERLAPPEDRESULT_CALLBACK callback function.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_NOTIFICATION

General XACT notification structure.

typedef struct XACT_NOTIFICATION {
    XACTNOTIFICATIONTYPE type;
    LONG timeStamp;
    PVOID pvContext;
    union {
        XACT_NOTIFICATION_CUE cue;
        XACT_NOTIFICATION_MARKER marker;
        XACT_NOTIFICATION_SOUNDBANK soundBank;
        XACT_NOTIFICATION_WAVEBANK waveBank;
        XACT_NOTIFICATION_VARIABLE variable;
        XACT_NOTIFICATION_GUI gui;
    };
} XACT_NOTIFICATION, *LPXACT_NOTIFICATION;

typedef const XACT_NOTIFICATION *LPCXACT_NOTIFICATION;

Members

type
Notification type. Can be one of the following values:
Notification Type | Member Used
XACTNOTIFICATIONTYPE_CUEPREPARED | cue
XACTNOTIFICATIONTYPE_CUEPLAY | cue
XACTNOTIFICATIONTYPE_CUESTOP | cue
XACTNOTIFICATIONTYPE_CUEDESTROYED | cue
XACTNOTIFICATIONTYPE_MARKER | marker
XACTNOTIFICATIONTYPE_SOUNDBANKDESTROYED | soundBank
XACTNOTIFICATIONTYPE_WAVEBANKDESTROYED | waveBank
XACTNOTIFICATIONTYPE_LOCALVARIABLECHANGED | variable
XACTNOTIFICATIONTYPE_GLOBALVARIABLECHANGED | variable
XACTNOTIFICATIONTYPE_GUICONNECTED | gui
XACTNOTIFICATIONTYPE_GUIDISCONNECTED | gui
XACTNOTIFICATIONTYPE_WAVEPLAY | wave
XACTNOTIFICATIONTYPE_WAVESTOP | wave
XACTNOTIFICATIONTYPE_WAVEBANKPREPARED | waveBank
timeStamp
Timestamp of notification, in milliseconds.
pvContext
User context (optional).
cue
XACT_NOTIFICATION_CUE structure that contains information about the cue notification.
marker
XACT_NOTIFICATION_MARKER structure that contains information about the marker notification.
soundBank
XACT_NOTIFICATION_SOUNDBANK structure that contains information about the sound bank notification.
waveBank
XACT_NOTIFICATION_WAVEBANK structure that contains information about the wave bank notification.
variable
XACT_NOTIFICATION_VARIABLE structure that contains information about the variable notification.
gui
XACT_NOTIFICATION_GUI structure that contains information about the GUI notification.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_NOTIFICATION_CUE

Notification structure for all XACT cue notifications.

typedef struct XACT_NOTIFICATION_CUE {
    XACTINDEX cueIndex;
    IXACTSoundBank *pSoundBank;
    IXACTCue *pCue;
} XACT_NOTIFICATION_CUE, *LPXACT_NOTIFICATION_CUE;

typedef const XACT_NOTIFICATION_CUE *LPCXACT_NOTIFICATION_CUE;

Members

cueIndex
Cue index. XACTINDEX_INVALID signifies an invalid cue index.
pSoundBank
Pointer to the IXACTSoundBank instance. This pointer is invalid when the notification type is XACTNOTIFICATIONTYPE_CUEDESTROYED.
pCue
Pointer to the IXACTCue instance. This pointer is invalid when the notification type is XACTNOTIFICATIONTYPE_CUEDESTROYED.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_NOTIFICATION_DESCRIPTION

Notification description used for registering, unregistering, and flushing notifications.

typedef struct XACT_NOTIFICATION_DESCRIPTION {
    XACTNOTIFICATIONTYPE type;
    BYTE flags;
    IXACTSoundBank *pSoundBank;
    IXACTWaveBank *pWaveBank;
    IXACTCue *pCue;
    IXACTWave *pWave;
    XACTINDEX cueIndex;
    XACTINDEX waveIndex;
    PVOID pvContext;
} XACT_NOTIFICATION_DESCRIPTION, *LPXACT_NOTIFICATION_DESCRIPTION;

typedef const XACT_NOTIFICATION_DESCRIPTION *LPCXACT_NOTIFICATION_DESCRIPTION;

Members

type
Notification type. Can be one of the following values:
Value | Supported Fields
XACTNOTIFICATIONTYPE_CUEPREPARED | None, sound bank, sound bank and cue index, cue instance
XACTNOTIFICATIONTYPE_CUEPLAY | None, sound bank, sound bank and cue index, cue instance
XACTNOTIFICATIONTYPE_CUESTOP | None, sound bank, sound bank and cue index, cue instance
XACTNOTIFICATIONTYPE_CUEDESTROYED | None, sound bank, sound bank and cue index, cue instance
XACTNOTIFICATIONTYPE_MARKER | None, sound bank, sound bank and cue index, cue instance
XACTNOTIFICATIONTYPE_SOUNDBANKDESTROYED | None, sound bank
XACTNOTIFICATIONTYPE_WAVEBANKDESTROYED | None, wave bank
XACTNOTIFICATIONTYPE_LOCALVARIABLECHANGED | None, sound bank, sound bank and cue index, cue instance
XACTNOTIFICATIONTYPE_GLOBALVARIABLECHANGED | None
XACTNOTIFICATIONTYPE_GUICONNECTED | None
XACTNOTIFICATIONTYPE_GUIDISCONNECTED | None
XACTNOTIFICATIONTYPE_WAVEPREPARED | None, wave bank and wave index, wave instance
XACTNOTIFICATIONTYPE_WAVEPLAY | None, sound bank, sound bank and cue index, cue instance, wave bank
XACTNOTIFICATIONTYPE_WAVESTOP | None, sound bank, sound bank and cue index, cue instance, wave bank
XACTNOTIFICATIONTYPE_WAVELOOPED | None, sound bank, sound bank and cue index, cue instance, wave bank, wave instance
XACTNOTIFICATIONTYPE_WAVEDESTROYED | None, wave bank and wave index, wave instance
XACTNOTIFICATIONTYPE_WAVEBANKPREPARED | None, wave bank
XACTNOTIFICATIONTYPE_WAVEBANKSTREAMING_INVALIDCONTENT | None, wave bank
flags
Flag indicating the notification behavior. Can be zero or one of the following:
Value | Description
XACT_FLAG_NOTIFICATION_PERSIST | Indicates that the notification should persist. If this flag is not set, the user will receive no more than one notification of the type registered.
pSoundBank
Pointer to the IXACTSoundBank instance. If this entry is set to NULL, then the notification applies to all sound banks.
pWaveBank
Pointer to the IXACTWaveBank instance (optional). This entry may be NULL if no wave bank applies.
pCue
Pointer to the IXACTCue instance (optional). This entry may be NULL if no cue applies.
pWave
Pointer to the IXACTWaveBank instance (optional). This entry may be NULL if no wave applies.
cueIndex
Cue index. If pSoundBank is NULL, then this entry should contain XACTINDEX_INVALID.
waveIndex
Wave index.
pvContext
User context (optional). This entry may be NULL if no user context applies.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_NOTIFICATION_GUI

Notification structure for all GUI notifications.

typedef struct XACT_NOTIFICATION_GUI {
    DWORD reserved;
} XACT_NOTIFICATION_GUI, *LPXACT_NOTIFICATION_GUI;

typedef const XACT_NOTIFICATION_GUI *LPCXACT_NOTIFICATION_GUI;

Members

reserved
Reserved for future use.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_NOTIFICATION_MARKER

Notification structure for all marker notifications.

typedef struct XACT_NOTIFICATION_MARKER {
    XACTINDEX cueIndex;
    IXACTSoundBank *pSoundBank;
    IXACTCue *pCue;
    DWORD marker;
} XACT_NOTIFICATION_MARKER, *LPXACT_NOTIFICATION_MARKER;

typedef const XACT_NOTIFICATION_MARKER *LPCXACT_NOTIFICATION_MARKER;

Members

cueIndex
Cue index. XACTINDEX_INVALID signifies an invalid cue index.
pSoundBank
Pointer to the IXACTSoundBank instance.
pCue
Pointer to the IXACTCue instance.
marker
Marker value.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_NOTIFICATION_SOUNDBANK

Notification structure for all sound bank notifications.

typedef struct XACT_NOTIFICATION_SOUNDBANK {
    IXACTSoundBank *pSoundBank;
} XACT_NOTIFICATION_SOUNDBANK, *LPXACT_NOTIFICATION_SOUNDBANK;

typedef const XACT_NOTIFICATION_SOUNDBANK *LPCXACT_NOTIFICATION_SOUNDBANK;

Members

pSoundBank
Pointer to the IXACTSoundBank instance. This pointer is invalid when the notification type is XACTNOTIFICATIONTYPE_SOUNDBANKDESTROYED.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_NOTIFICATION_VARIABLE

Notification structure for all variable notifications.

typedef struct XACT_NOTIFICATION_VARIABLE {
    XACTINDEX cueIndex;
    IXACTSoundBank *pSoundBank;
    IXACTCue *pCue;
    XACTVARIABLEINDEX variableIndex;
    XACTVARIABLEVALUE variableValue;
    BOOL local;
} XACT_NOTIFICATION_VARIABLE, *LPXACT_NOTIFICATION_VARIABLE;

typedef const XACT_NOTIFICATION_VARIABLE *LPCXACT_NOTIFICATION_VARIABLE;

Members

cueIndex
Cue index.
pSoundBank
Soundbank instance.
pCue
Cue instance.
variableIndex
Variable index.
variableValue
Variable value.
local
TRUE if a local variable.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_NOTIFICATION_WAVE

Notification structure for all wave notifications.

typedef struct XACT_NOTIFICATION_WAVE {
    IXACTWaveBank *pWaveBank;
    XACTINDEX waveIndex;
    XACTINDEX cueIndex;
    IXACTSoundBank *pSoundBank;
    IXACTCue *pCue;
    IXACTWave *pWave;
} XACT_NOTIFICATION_WAVE, *LPXACT_NOTIFICATION_WAVE;

typedef const XACT_NOTIFICATION_WAVE *LPCXACT_NOTIFICATION_WAVE;

Members

pWaveBank
Pointer to the IXACTWaveBank instance.
waveIndex
Wave index.
cueIndex
Cue index. XACTINDEX_INVALID signifies an invalid cue index.
pSoundBank
Pointer to the IXACTSoundBank instance.
pCue
Pointer to the IXACTCue instance.
pWave
Pointer to the IXACTWaveBank instance.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_NOTIFICATION_WAVEBANK

Notification structure for all wave bank notifications.

typedef struct XACT_NOTIFICATION_WAVEBANK {
    IXACTWaveBank *pWaveBank;
} XACT_NOTIFICATION_WAVEBANK, *LPXACT_NOTIFICATION_WAVEBANK;

typedef const XACT_NOTIFICATION_WAVEBANK *LPCXACT_NOTIFICATION_WAVEBANK;

Members

pWaveBank
Pointer to the IXACTWaveBank instance. This pointer is invalid when the notification type is XACTNOTIFICATIONTYPE_WAVEBANKDESTROYED.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_RENDERER_DETAILS

Returns information about a particular renderer.

typedef struct XACT_RENDERER_DETAILS {
    WCHAR rendererID[XACT_RENDERER_ID_LENGTH];
    WCHAR displayName[XACT_RENDERER_NAME_LENGTH];
    BOOL defaultDevice;
} XACT_RENDERER_DETAILS, *LPXACT_RENDERER_DETAILS;

Members

rendererID
Wide character array containing the id of the renderer.
displayName
Wide character array that contains the name of the renderer.

Note The friendly name is useful in presenting the audio devices that are available to the end user. However, the renderer id can be passed in the XACT_RUNTIME_PARAMETERS structure—which is used during XACT initialization—to connect to the renderer.

defaultDevice
TRUE if this renderer is the default renderer. Otherwise, FALSE.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_RUNTIME_PARAMETERS

Runtime parameters for initialization of the XACT engine.

typedef struct XACT_RUNTIME_PARAMETERS {
    DWORD lookAheadTime;
    void *pGlobalSettingsBuffer;
    DWORD globalSettingsBufferSize;
    DWORD globalSettingsFlags;
    DWORD globalSettingsAllocAttributes;
    XACT_FILEIO_CALLBACKS fileIOCallbacks;
    XACT_NOTIFICATION_CALLBACK fnNotificationCallback;
    PWSTR pRendererID;
} XACT_RUNTIME_PARAMETERS, *LPXACT_RUNTIME_PARAMETERS;

typedef const XACT_RUNTIME_PARAMETERS *LPCXACT_RUNTIME_PARAMETERS;

Members

lookAheadTime
Interactive audio and branch event look-ahead time, in milliseconds. This specifies how far ahead the XACT engine will look ahead when determining when to transition to another sound. XACT_ENGINE_LOOKAHEAD_DEFAULT is a good default value to use for this member.
pGlobalSettingsBuffer
Buffer containing the global file data. This file is generated when you build an XACT project file. It contains category, variable, and RPC information.

Xbox 360: Memory for this member must be allocated using XMemAlloc when specifying the XACT_FLAG_API_CREATE_MANAGEDATA flag.

Windows: Memory for this member must be allocated using CoTaskMemAlloc when specifying the XACT_FLAG_API_CREATE_MANAGEDATA flag.

globalSettingsBufferSize
Size of the data buffer associated with pGlobalSettingsBuffer.
globalSettingsFlags
Flag values indicating how global file data should be handled by XACT. This member can be zero or the value shown in the following table.
Value | Description
XACT_FLAG_API_CREATE_MANAGEDATA | Indicates that XACT should free the buffer pointed to by pGlobalSettingsBuffer when initialization is complete. Note XACT will not attempt to free the memory if the buffer allocation fails.
globalSettingsAllocAttributes
Flag values that indicate the attributes of the memory buffer pointed to by pGlobalSettingsBuffer.

Xbox 360: This member is needed only if XACT_FLAG_API_CREATE_MANAGEDATA is specified in globalSettingsFlags, so that XMemFree can receive the correct values when XACT frees the buffer. Otherwise, globalSettingsAllocAttributes is ignored.

These flags should match the XALLOC_ATTRIBUTES values that were specified to XMemAlloc when the memory buffer pointed to by pGlobalSettingsBuffer was allocated.

Windows: This parameter has no relevance and is ignored.

fileIOCallbacks
File I/O callbacks.
fnNotificationCallback
Callback that receives notifications.
pRendererID
Pointer to the ID of the audio renderer that the engine should connect to.

Xbox 360: This parameter is undefined.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures, IXACTEngine::Initialize


XACT_SOUND_PROPERTIES

Returns the properties for a sound that is referenced by the active variation.

typedef struct XACT_SOUND_PROPERTIES {
    XACTCATEGORY category;
    BYTE priority;
    XACTPITCH pitch;
    XACTVOLUME volume;
    XACTINDEX numTracks;
    XACT_TRACK_PROPERTIES arrTrackProperties[1];
} XACT_SOUND_PROPERTIES, *LPXACT_SOUND_PROPERTIES;

Members

category
Category that this sound belongs to.
priority
Priority that is assigned to this sound.
pitch
Current pitch of the sound.
volume
Current volume of the sound.
numTracks
Number of tracks that are contained in this sound.
arrTrackProperties
A contiguous array of track properties, represented by XACT_TRACK_PROPERTIES structures. This array contains numTracks number of elements.

Remarks

The following is an example of iterating through the track properties represented by the arrTrackProperties member:

void EnumerateTrackProperties(LPXACT_SOUND_PROPERTIES pSoundProperties)
{
  for (XACTINDEX nIndex = 0; nIndex < pSoundProperties->numTracks; ++nIndex)
  {
    // Do something with pSoundProperties->arrTrackProperties[nIndex];
  }
}

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_SOUND_VARIATION_PROPERTIES

Returns the properties of the sound variation that is currently active in a cue instance.

typedef struct XACT_SOUND_VARIATION_PROPERTIES {
    XACT_VARIATION_PROPERTIES variationProperties;
    XACT_SOUND_PROPERTIES soundProperties;
} XACT_SOUND_VARIATION_PROPERTIES, *LPXACT_SOUND_VARIATION_PROPERTIES;

Members

variationProperties
Properties of the currently active variation, represented by an XACT_VARIATION_PROPERTIES structure.
soundProperties
Properties of the sound that the active variation references, represented by an XACT_SOUND_PROPERTIES structure.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_TRACK_PROPERTIES

Returns the properties of a track in an active sound variation in a cue instance.

typedef struct XACT_TRACK_PROPERTIES {
    XACTTIME duration;
    XACTINDEX numVariations;
    XACTCHANNEL numChannels;
    XACTINDEX waveVariation;
    XACTLOOPCOUNT loopCount;
} XACT_TRACK_PROPERTIES, *LPXACT_TRACK_PROPERTIES;

Members

duration
Duration of the track in milliseconds.
numVariations
Total number of wave variations in the track.
numChannels
Maximum number of channels that are required to play the track.
waveVariation
Index of the currently active wave variation.
loopCount
Current loop count on the track.

Remarks

These properties are timing dependent. They may change when the IXACTSoundBank::GetCueProperties call returns.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_VARIATION_PROPERTIES

Returns the properties for the variation that is currently active in a cue instance.

typedef struct XACT_VARIATION_PROPERTIES {
    XACTINDEX index;
    XACTVARIATIONWEIGHT weight;
    XACTVARIABLEVALUE iaVariableMin;
    XACTVARIABLEVALUE iaVariableMax;
    BOOL linger;
} XACT_VARIATION_PROPERTIES, *LPXACT_VARIATION_PROPERTIES;

Members

index
Index of the variation in the parent variation list.
weight
Weight that is assigned to the variation. This member is used by noninteractive variations only.
iaVariableMin
Lower bound of the interactive variable that controls the variation. This member is used by interactive variations only.
iaVariableMax
Upper bound of the interactive variable that controls the variation. This member is used by interactive variations only.
linger
Flag that indicates if the variation should linger. This member is used by interactive variations only.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_STREAMING_PARAMETERS

Streaming parameters for a wave bank.

typedef struct XACT_STREAMING_PARAMETERS {
    HANDLE file;
    DWORD offset;
    DWORD flags;
    WORD packetSize;
} XACT_STREAMING_PARAMETERS, *LPXACT_STREAMING_PARAMETERS, XACT_WAVEBANK_STREAMING_PARAMETERS, *LPXACT_WAVEBANK_STREAMING_PARAMETERS;

typedef const XACT_STREAMING_PARAMETERS *LPCXACT_STREAMING_PARAMETERS;

Members

file
File handle associated with wave bank data.

Windows: The file referenced by this handle must be opened with the following CreateFile flags: FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING.

offset
Offset within the wave bank data file. This offset must be DVD sector aligned.
flags
Flags. Reserved for future use. Set to 0.
packetSize
Stream packet size, in sectors, to use for each stream. The minimum value is 2.

The size of a DVD sector is 2048 bytes. Therefore, setting this value to 2 would result in a packet size of 4096 bytes. Setting it to 3 would specify packets of 6144 bytes, setting it to 4 would specify packets of 8192 bytes, and so on.

The optimal DVD size is a multiple of 16 (1 DVD block = 16 DVD sectors).

Remarks

Xact.h also includes the following constant declaration:

typedef const XACT_WAVEBANK_STREAMING_PARAMETERS *LPCXACT_WAVEBANK_STREAMING_PARAMETERS;

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures, IXACTEngine::CreateStreamingWaveBank


XACT_WAVE_INSTANCE_PROPERTIES

Returns the properties of a specific wave instance.

typedef struct XACT_WAVE_INSTANCE_PROPERTIES {
    XACT_WAVE_PROPERTIES properties;
    BOOL backgroundMusic;
} XACT_WAVE_INSTANCE_PROPERTIES, *LPXACT_WAVE_INSTANCE_PROPERTIES;

Members

properties
Static properties that are common to all wave instances.
backgroundMusic
TRUE, if the wave is tagged as background music. Otherwise, FALSE.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT_WAVE_PROPERTIES

Returns the properties that are common to all waves.

typedef struct XACT_WAVE_PROPERTIES {
    char friendlyName[WAVEBANK_ENTRYNAME_LENGTH];
    WAVEBANKMINIWAVEFORMAT format;
    DWORD durationInSamples;
    WAVEBANKSAMPLEREGION loopRegion;
    BOOL streaming;
} XACT_WAVE_PROPERTIES, *LPXACT_WAVE_PROPERTIES;

Members

friendlyName
Friendly name for the wave. An empty string if the wave bank has been stripped of friendly names.
format
Format for the wave.
durationInSamples
Duration of the wave, in samples.
loopRegion
Loop region that is defined in samples.
streaming
TRUE if the wave is streaming. Otherwise, FALSE.

Requirements

Header: Declared in Xact.h.

See Also

XACT Structures


XACT Enumerations

This section contains information about the enumerations used with the Microsoft Cross-Platform Audio Creation Tool (XACT).

Enumeration | Description
WAVEBANKSEGIDX | Wave bank segment identifiers.

See Also

XACT Reference


WAVEBANKSEGIDX

Wave bank segment identifiers.

typedef enum WAVEBANKSEGIDX
{
    WAVEBANK_SEGIDX_BANKDATA = 0,
    WAVEBANK_SEGIDX_ENTRYMETADATA,
    WAVEBANK_SEGIDX_SEEKTABLES,
    WAVEBANK_SEGIDX_ENTRYNAMES,
    WAVEBANK_SEGIDX_ENTRYWAVEDATA,
    WAVEBANK_SEGIDX_COUNT,
} WAVEBANKSEGIDX, *LPWAVEBANKSEGIDX;

Constants

WAVEBANK_SEGIDX_BANKDATA
Bank data.
WAVEBANK_SEGIDX_ENTRYMETADATA
Entry metadata.
WAVEBANK_SEGIDX_SEEKTABLES
Storage for seek tables for the encoded waves.
WAVEBANK_SEGIDX_ENTRYNAMES
Entry friendly names.
WAVEBANK_SEGIDX_ENTRYWAVEDATA
Entry wave data.
WAVEBANK_SEGIDX_COUNT
Number of WAVEBANK_SEGIDX types.

Requirements

Header: Declared in Xact2wb.h.

See Also

XACT Enumerations


XACT Callbacks

This section contains information about the callbacks used with the Microsoft Cross-Platform Audio Creation Tool (XACT).

Callback | Description
XACT_GETOVERLAPPEDRESULT_CALLBACK | Title-defined function called by XACT to determine the status of pending overlapped operations.
XACT_NOTIFICATION_CALLBACK | Title-defined function called by XACT to receive notifications.
XACT_READFILE_CALLBACK | Title-defined function called by XACT to read data from disk.

See Also

XACT Reference


XACT_GETOVERLAPPEDRESULT_CALLBACK

Title-defined function called by XACT to determine the status of pending overlapped operations.

typedef BOOL (__stdcall *XACT_GETOVERLAPPEDRESULT_CALLBACK)(
    HANDLE hFile,
    LPOVERLAPPED lpOverlapped,
    LPDWORD lpNumberOfBytesTransferred,
    BOOL bWait
);

Parameters

hFile
Handle to a file. This is the handle specified when the overlapped operation was started by a call to the title's read file callback.
lpOverlapped
Pointer to the OVERLAPPED structure specified when the overlapped operation was started.
lpNumberOfBytesTransferred
Pointer to a variable that receives the number of bytes transferred by a read or write operation.
bWait
Specifies whether the function should wait for the pending overlapped operation to be completed. If this value is TRUE, the function does not return until the operation has been completed. If this value is FALSE and the operation is still pending, the function returns FALSE and the GetLastError function returns ERROR_IO_INCOMPLETE.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

This function is analogous to the system GetOverlappedResult function. When determining the status of pending overlapped operations, the XACT engine calls the title's overlapped result callback instead of the system GetOverlappedResult function. The advantage of registering a callback is that the title can manage XACT's disk input to prioritize it along with the game's other I/O.

The simplest implementation of this callback function is to call GetOverlappedResult and return its return value.

The XACT makes extensive use of the HasOverlappedIoCompleted macro, which references the Internal member of the OVERLAPPED structure passed in lpOverlapped. Titles must properly set this flag to indicate the status of the overlapped operation. The HasOverlappedIoCompleted macro is defined as follows:

#define HasOverlappedIoCompleted( lpOverlapped ) ( (lpOverlapped)->Internal != STATUS_PENDING )

Requirements

Header: Declared in Xact.h.

See Also

XACT Callbacks


XACT_NOTIFICATION_CALLBACK

Title-defined function called by XACT to receive notifications.

typedef void (__stdcall *XACT_NOTIFICATION_CALLBACK)(
    const XACT_NOTIFICATION *pNotification
);

Parameters

pNotification
Pointer to an XACT_NOTIFICATION structure containing the notification data.

Return Values

None.

Remarks

Any XACT function or method that allocates or deallocates memory cannot be called from within this callback. The following tables detail which routines are allowed.

IXACTEngine Method | Allowed
IXACTEngine::CreateInMemoryWaveBank | No
IXACTEngine::CreateSoundBank | No
IXACTEngine::CreateStreamingWaveBank | No
IXACTEngine::DoWork | No
IXACTEngine::GetCategory | Yes
IXACTEngine::GetGlobalVariable | Yes
IXACTEngine::GetGlobalVariableIndex | Yes
IXACTEngine::Initialize | Yes*
IXACTEngine::Pause | Yes
IXACTEngine::RegisterNotification | No
IXACTEngine::SetGlobalVariable | No
IXACTEngine::SetVolume | Yes
IXACTEngine::ShutDown | No
IXACTEngine::Stop | No
IXACTEngine::UnRegisterNotification | No

* IXACTEngine::Initialize should be called only once per IXACTEngine instance in an application. Since you cannot receive callbacks without an already initialized engine, you may only call IXACTEngine::Initialize from a callback if you are initializing a different, uninitialized IXACTEngine than the one that is associated with the current callback.

IXACTCue Method | Allowed
IXACTCue::Destroy | No
IXACTCue::GetChannelMap | Yes
IXACTCue::GetChannelVolume | Yes
IXACTCue::GetState | Yes
IXACTCue::GetVariable | No
IXACTCue::GetVariableIndex | Yes
IXACTCue::Pause | Yes
IXACTCue::Play | Yes
IXACTCue::SetChannelMap | No
IXACTCue::SetChannelVolume | Yes
IXACTCue::SetVariable | No
IXACTCue::Stop | Yes
IXACTSoundBank Method | Allowed
IXACTSoundBank::Destroy | No
IXACTSoundBank::GetCueIndex | Yes
IXACTSoundBank::GetState | Yes
IXACTSoundBank::Play | No
IXACTSoundBank::Prepare | No
IXACTSoundBank::Stop | Yes
IXACTWaveBank Method | Allowed
IXACTWaveBank::Destroy | No
IXACTWaveBank::GetState | Yes

Requirements

Header: Declared in Xact.h.

See Also

XACT Callbacks


XACT_READFILE_CALLBACK

Title-defined function called by XACT to read data from disk.

typedef BOOL (__stdcall *XACT_READFILE_CALLBACK)(
    HANDLE hFile,
    LPVOID lpBuffer,
    DWORD nNumberOfBytesToRead,
    LPDWORD lpNumberOfBytesRead,
    LPOVERLAPPED lpOverlapped
);

Parameters

hFile
Handle to the file to be read.
lpBuffer
Pointer to the buffer to contain the data read from the file.
nNumberOfBytesToRead
Number of bytes to be read from the file.
lpNumberOfBytesRead
Pointer to the variable that receives the number of bytes read.
lpOverlapped
Pointer to an OVERLAPPED structure. This structure is required if hFile was created with FILE_FLAG_OVERLAPPED.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

This function is analogous to the system ReadFile function. When reading data from disk, the XACT engine calls the title's read file callback instead of the system ReadFile function. The advantage of registering a callback is that the title can manage XACT's disk input to prioritize it along with the game's other I/O.

The simplest implementation of this callback function is to call ReadFile and return its return value, but doing so provides no benefit. The title will want to extend or modify read behavior when registering this callback.

ReadFile sets the lpNumberOfBytesRead variable to zero before doing any work or error checking, so the title callback should do the same.

XACT makes extensive use of the HasOverlappedIoCompleted macro, which references the Internal member of the OVERLAPPED structure passed in lpOverlapped. Titles must properly set this flag to indicate the status of the overlapped operation. The HasOverlappedIoCompleted macro is defined as follows:

#define HasOverlappedIoCompleted( lpOverlapped ) ( (lpOverlapped)->Internal != STATUS_PENDING )

Requirements

Header: Declared in Xact.h.

See Also

XACT Callbacks


X3DAudio Reference

This section contains the reference pages for the Microsoft® X3DAudio application programming interface (API). Reference material is divided into the following categories.

  • X3DAudio Functions
  • X3DAudio Structures


X3DAudio Functions

This section contains information about the functions used with the X3DAudio API.

Function | Description
X3DAudioCalculate | Calculates DSP settings with respect to 3D parameters.
X3DAudioInitialize | Sets all global 3D audio constants.

See Also

X3DAudio Reference


X3DAudioCalculate

Calculates DSP settings with respect to 3D parameters.

void __stdcall X3DAudioCalculate(
  X3DAUDIO_HANDLE Instance,
  X3DAUDIO_LISTENER *pListener,
  X3DAUDIO_EMITTER *pEmitter,
  UINT32 Flags,
  X3DAUDIO_DSP_SETTINGS *pDSPSettings
);

Parameters

Instance
[in] Handle to an instance of X3DAudio, returned by calling X3DAudioInitialize.
pListener
[in] Pointer to an X3DAUDIO_LISTENER representing the point of reception.
pEmitter
[in] Pointer to an X3DAUDIO_EMITTER representing the sound source.
Flags
[in] Flags used to control which DSP settings are calculated:
Value | Description
X3DAUDIO_CALCULATE_MATRIX | Enable matrix coefficient table calculation.
X3DAUDIO_CALCULATE_DELAY | Enable delay time array calculation (stereo only).
X3DAUDIO_CALCULATE_LPF_DIRECT | Enable LPF direct-path coefficient calculation.
X3DAUDIO_CALCULATE_LPF_REVERB | Enable LPF reverb-path coefficient calculation.
X3DAUDIO_CALCULATE_REVERB | Enable reverb send level calculation.
X3DAUDIO_CALCULATE_DOPPLER | Enable doppler shift factor calculation.
pDSPSettings
[in, out] Pointer to an X3DAUDIO_DSP_SETTINGS structure that receives the calculation results.

Return Values

None.

Requirements

Header: Declared in X3daudio.h.

Library: Use X3daudio.lib.

See Also

X3DAudio Functions


X3DAudioInitialize

Sets all global 3D audio constants.

void __stdcall X3DAudioInitialize(
  UINT32 SpeakerChannelMask,
  FLOAT32 SpeedOfSound,
  X3DAUDIO_HANDLE Instance
);

Parameters

SpeakerChannelMask
[in] Assignment of channels to speaker positions. XACT currently only supports stereo and 5.1 speaker arrangements. The following #define values in X3DAudio.h can be used to easily set up these configurations:
SPEAKER_STEREO | Stereo Sound (Equivalent to SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT)
SPEAKER_5POINT1 | 5.1 Sound (Equivalent to SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT)
SpeedOfSound
[in] Speed of sound, in user-defined world units per second. This value is used only for doppler calculations and must be greater than or equal to FLT_MIN.
Instance
[out] Handle to this instance of X3DAudio.

Return Values

None.

Requirements

Header: Declared in X3daudio.h.

Library: Use X3daudio.lib.

See Also

X3DAudio Functions


X3DAudio Structures

This section contains information about the structures used with Microsoft® X3DAudio.

Structure | Description
X3DAUDIO_CONE | Specifies directionality for a single-channel non-LFE emitter by scaling DSP behaviour with respect to the emitter's orientation.
X3DAUDIO_DISTANCE_CURVE | Defines an explicit piecewise curve made up of linear segments, directly defining DSP behavior with respect to normalized distance.
X3DAUDIO_DISTANCE_CURVE_POINT | Defines a DSP setting at a given normalized distance.
X3DAUDIO_DSP_SETTINGS | Receives the results from a call to X3DAudioCalculate to be sent to the low-level audio rendering API for 3D signal processing .
X3DAUDIO_EMITTER | Defines a single or multi-point 3D audio source used with an arbitrary number of sound channels.
X3DAUDIO_LISTENER | Defines a point of 3D audio reception.

See Also

X3DAudio Reference


X3DAUDIO_CONE

Specifies directionality for a single-channel non-LFE emitter by scaling DSP behaviour with respect to the emitter's orientation.

typedef struct X3DAUDIO_CONE {
    FLOAT32 InnerAngle;
    FLOAT32 OuterAngle;
    FLOAT32 InnerVolume;
    FLOAT32 OuterVolume;
    FLOAT32 InnerLPF;
    FLOAT32 OuterLPF;
    FLOAT32 InnerReverb;
    FLOAT32 OuterReverb;
} X3DAUDIO_CONE, *LPX3DAUDIO_CONE;

Members

InnerAngle
Inner cone angle in radians. This value must be within 0.0f to X3DAUDIO_2PI.
OuterAngle
Outer cone angle in radians. This value must be within InnerAngle to X3DAUDIO_2PI.
InnerVolume
Volume scaler on/within inner cone. This value must be within 0.0f to 2.0f.
OuterVolume
Volume scaler on/beyond outer cone. This value must be within 0.0f to 2.0f.
InnerLPF
LPF direct-path or reverb-path coefficient scaler on/within inner cone. This value must be within 0.0f to 1.0f.
OuterLPF
LPF direct-path or reverb-path coefficient scaler on/beyond outer cone. This must be within 0.0f to 1.0f.
InnerReverb
Reverb send level scaler on/within inner cone. This must be within 0.0f to 2.0f.
OuterReverb
Reverb send level scaler on/beyond outer cone. This must be within 0.0f to 2.0f.

Requirements

Header: Declared in X3daudio.h.

See Also

X3DAudio Structures


X3DAUDIO_DISTANCE_CURVE

Defines an explicit piecewise curve made up of linear segments, directly defining DSP behavior with respect to normalized distance.

typedef struct X3DAUDIO_DISTANCE_CURVE {
    X3DAUDIO_DISTANCE_CURVE_POINT *pPoints;
    UINT32 PointCount;
} X3DAUDIO_DISTANCE_CURVE;

Members

pPoints
X3DAUDIO_DISTANCE_CURVE_POINT array. The array must have no duplicates and be sorted in ascending order with respect to distance.
PointCount
Number of distance curve points. There must be two or more points since all curves must have at least two endpoints defining values at 0.0f and 1.0f normalized distance, respectively.

Requirements

Header: Declared in X3daudio.h.

See Also

X3DAudio Structures


X3DAUDIO_DISTANCE_CURVE_POINT

Defines a DSP setting at a given normalized distance.

typedef struct X3DAUDIO_DISTANCE_CURVE_POINT {
    FLOAT32 Distance;
    FLOAT32 DSPSetting;
} X3DAUDIO_DISTANCE_CURVE_POINT, *LPX3DAUDIO_DISTANCE_CURVE_POINT;

Members

Distance
Normalized distance. This must be within 0.0f to 1.0f.
DSPSetting
DSP control setting.

Requirements

Header: Declared in X3daudio.h.

See Also

X3DAudio Structures


X3DAUDIO_DSP_SETTINGS

Receives the results from a call to X3DAudioCalculate to be sent to the low-level audio rendering function for 3D signal processing.

typedef struct X3DAUDIO_DSP_SETTINGS {
    FLOAT32 *pMatrixCoefficients;
    FLOAT32 *pDelayTimes;
    UINT32 SrcChannelCount;
    UINT32 DstChannelCount;
    FLOAT32 LPFDirectCoefficient;
    FLOAT32 LPFReverbCoefficient;
    FLOAT32 ReverbLevel;
    FLOAT32 DopplerFactor;
    FLOAT32 EmitterToListenerAngle;
    FLOAT32 EmitterToListenerDistance;
    FLOAT32 EmitterVelocityComponent;
    FLOAT32 ListenerVelocityComponent;
} X3DAUDIO_DSP_SETTINGS, *LPX3DAUDIO_DSP_SETTINGS;

Members

pMatrixCoefficients

Matrix coefficient table. This is an array representing the volume level of each source channel present in each destination channel, with the source channels being the column index and the destination channels being the row index of the table. It must have at least (SrcChannelCount × DstChannelCount) elements.

For example, when rendering two-channel stereo input into 5.1 output that is weighted toward the front channels—but is absent from the center and low-frequency channels—the matrix might be as shown in the following table.

Output | Left Input | Right Input
Left | 1.0 | 0.0
Right | 0.0 | 1.0
Front Center | 0.0 | 0.0
LFE | 0.0 | 0.0
Rear Left | 0.8 | 0.0
Rear Right | 0.0 | 0.8

Note that the left and right channels are fully mapped to the output left and right channels; 80 percent of the left and right input is mapped to the rear left and right channels.

pDelayTimes

Delay time array, which receives delays for each destination channel in milliseconds. This array must have at least DstChannelCount elements. X3DAudio doesn't actually perform the delay. It simply returns the coefficients that may be used to adjust a delay DSP effect placed in the effect chain.

Note This member is only returned when X3DAudio is initialized for stereo output. For typical Xbox 360 usage, it will not return any data at all.

SrcChannelCount
Number of source channels. This must match the number of channels on the respective emitter.
DstChannelCount
Number of destination channels. This must match what was passed into X3DAudioInitialize or XACT3DCalculate for the speaker channel mask. For SPEAKER_STEREO, the value must be 2. For SPEAKER_5POINT1, the value must be 6 (5 speakers + LFE).
LPFDirectCoefficient
LPF direct-path coefficient.
LPFReverbCoefficient
LPF reverb-path coefficient.
ReverbLevel
Reverb send level.
DopplerFactor

Doppler shift factor. Scales the resampler ratio for Doppler shift effect, where:
effective_frequency = DopplerFactor × original_frequency

EmitterToListenerAngle
The emitter-to-listener interior angle, expressed in radians with respect to the emitter's front orientation.
EmitterToListenerDistance
Distance in user-defined world units from the listener to the emitter base position.
EmitterVelocityComponent
Component of emitter velocity vector projected onto emitter-to-listener vector in user-defined world units per second. Calculated only for Doppler.
ListenerVelocityComponent
Component of listener velocity vector projected onto the emitter->listener vector in user-defined world units per second. Calculated only for Doppler.

Remarks

The following members must be initialized before passing this structure to the X3DAudioCalculate function:

  • pMatrixCoefficients
  • pDelayTimes
  • SrcChannelCount
  • DstChannelCount

The following members are returned by passing this structure to the X3DAudioCalculate function:

  • pMatrixCoefficients
  • pDelayTimes
  • LPFDirectCoefficient
  • LPFReverbCoefficient
  • ReverbLevel
  • DopplerFactor
  • EmitterToListenerDistance
  • EmitterToListenerAngle
  • EmitterVelocityComponent
  • ListenerVelocityComponent

Note For pMatrixCoefficients and pDelayTimes, X3DAudioCalculate does not allocate additional memory. X3DAudioCalculate merely modifies the values at the memory locations allocated for these pointers.

Requirements

Header: Declared in X3daudio.h.

See Also

X3DAudio Structures


X3DAUDIO_EMITTER

Defines a single or multi-point 3D audio source used with an arbitrary number of sound channels.

typedef struct X3DAUDIO_EMITTER {
    X3DAUDIO_CONE *pCone;
    X3DAUDIO_VECTOR OrientFront;
    X3DAUDIO_VECTOR OrientTop;
    X3DAUDIO_VECTOR Position;
    X3DAUDIO_VECTOR Velocity;
    FLOAT32 InnerRadius;
    FLOAT32 InnerRadiusAngle;
    UINT32 ChannelCount;
    FLOAT32 ChannelRadius;
    FLOAT32 *pChannelAzimuths;
    X3DAUDIO_DISTANCE_CURVE *pVolumeCurve;
    X3DAUDIO_DISTANCE_CURVE *pLFECurve;
    X3DAUDIO_DISTANCE_CURVE *pLPFDirectCurve;
    X3DAUDIO_DISTANCE_CURVE *pLPFReverbCurve;
    X3DAUDIO_DISTANCE_CURVE *pReverbCurve;
    FLOAT32 CurveDistanceScaler;
    FLOAT32 DopplerScaler;
} X3DAUDIO_EMITTER, *LPX3DAUDIO_EMITTER;

Members

pCone
Pointer to a sound cone. Used only with single-channel non-LFE emitters.
OrientFront
Orientation of the front direction. This value must be orthonormal with OrientTop.
OrientTop
Orientation of the top direction. This value must be orthonormal with OrientFront.
Position
Position in user-defined world units. This value does not affect Velocity.
Velocity
Velocity vector in user-defined world units/second. This value is used only for doppler calculations. It does not affect Position.
InnerRadius
Value to be used for the inner radius calculations. If InnerRadius is 0, then no inner radius is used, but InnerRadiusAngle may still be used. This value must be between 0.0f and MAX_FLT.
InnerRadiusAngle
Value to be used for the inner radius angle calculations. This value must be between 0.0f and X3DAUDIO_PI/4.0.
ChannelCount
Number of sound channels. Must be greater than 0.
ChannelRadius
Channel radius. Must be greater than or equal to 0.0f.
pChannelAzimuths
Position of channel expressed as an azimuth in radians along the channel radius with respect to the front orientation vector in the plane orthogonal to the top orientation vector, or X3DAUDIO_2PI to specify a LFE channel. This value must be within 0.0f to X3DAUDIO_2PI.
pVolumeCurve
Volume level distance curve, which is used only for matrix calculations. NULL specifies a specialized default curve that conforms to the inverse square law, such that:

When distance is between 0.0f and 1.0f, no attenuation is applied. When distance is greater than 1.0f, the amplification factor is 1/distance. At a distance of 2.0f, the sound will be at half volume or -6 dB, at a distance of 4.0f, the sound will be at one quarter volume or -12 dB, and so on.

CurveDistanceScaler is ignored when this parameter is NULL.

pLFECurve
LFE roll-off distance curve, or NULL to use default curve: [0.0f, 1.0f], [1.0f, 0.0f].
pLPFDirectCurve
LPF direct-path coefficient distance curve, or NULL to use default curve: [0.0f, 0.0f], [1.0f, 1.0f].
pLPFReverbCurve
LPF reverb-path coefficient distance curve, or NULL to use default curve: [0.0f, 0.25f], [1.0f, 0.25f].
pReverbCurve
Reverb send level distance curve, or NULL to use default curve: [0.0f, 1.0f], [1.0f, 0.0f].
CurveDistanceScaler
Curve distance scaler used to scale normalized distance curves to user-defined world units and/or exaggerate their effect. This does not affect any other calculations. The value must be within the range FLT_MIN to FLT_MAX.
DopplerScaler
Doppler shift scaler used to exaggerate doppler shift effect. This does not affect any other calculations. The value must be within 0.0f to FLT_MAX.

Remarks

The parameter type X3DAUDIO_VECTOR is typed to D3DVECTOR, to provide x, y, and z floating-point values.

X3DAudio uses a left-handed Cartesian coordinate system with values on the x-axis increasing from left to right, on the y-axis from bottom to top, and on the z-axis from near to far. Azimuths are measured clockwise from a given reference direction.

For user-defined distance curves, the distance field of the first point must be 0.0f and the distance field of the last point must be 1.0f.

If an emitter moves beyond a distance of (CurveDistanceFactor * 1.0f), the last point in the curve will be used to compute the volume output level. The last point is determined by the following:

X3DAUDIO_DISTANCE_CURVE.pPoints[PointCount-1].DSPSetting)
Inner Radius and Inner Radius Angle

InnerRadius is used to specify an area of smooth transition around the origin point as a sound travels directly through, above or below the listener. Elevation is accounted for by specifying an InnerRadiusAngle, whereby a sound whose elevation increases or decreases, will eventually start to bleed the sound into more than just two speakers.

Requirements

Header: Declared in X3daudio.h.

See Also

X3DAudio Structures


X3DAUDIO_LISTENER

Defines a point of 3D audio reception.

typedef struct X3DAUDIO_LISTENER {
    X3DAUDIO_VECTOR OrientFront;
    X3DAUDIO_VECTOR OrientTop;
    X3DAUDIO_VECTOR Position;
    X3DAUDIO_VECTOR Velocity;
    X3DAUDIO_CONE *pCone;
} X3DAUDIO_LISTENER, *LPX3DAUDIO_LISTENER;

Members

OrientFront
Orientation of front direction, used only for matrix and delay calculations. This value must be orthonormal with OrientTop when used.
OrientTop
Orientation of top direction, used only for matrix and delay calculations. This value must be orthonormal with OrientFront when used
Position
Position in user-defined world units. This value does not affect Velocity.
Velocity
Velocity vector in user-defined world units per second, used only for doppler calculations. This value does not affect Position.
pCone
Pointer to an X3DAUDIO_CONE structure for this listener. Providing a listener cone will specify that additional calculations are performed when determining the volume and filter DSP parameters for individual sound sources. If pCone is NULL then no cone processing is applied.

Remarks

The parameter type X3DAUDIO_VECTOR is typed to D3DVECTOR, to provide x,y and z floating-point values.

Requirements

Header: Declared in X3daudio.h.

See Also

X3DAudio Structures


XACT Error Codes

The following chart lists the HRESULT codes returned by Microsoft Cross-Platform Audio Creation Tool (XACT) APIs, and their meanings.

Error Code | Meaning
XACTENGINE_E_OUTOFMEMORY | The system has run out of memory.
XACTENGINE_E_INVALIDARG | One or more arguments to a function or method are invalid.
XACTENGINE_E_NOTIMPL | The called function or method has not been implemented.
XACTENGINE_E_FAIL | A failure of an unspecified type has occured.
XACTENGINE_E_ALREADYINITIALIZED | The engine has already been initialized.
XACTENGINE_E_NOTINITIALIZED | The engine has not yet been initialized.
XACTENGINE_E_EXPIRED | The engine is a pre-release version and has expired.
XACTENGINE_E_NONOTIFICATIONCALLBACK | No notification callback has been registered with the engine.
XACTENGINE_E_NOTIFICATIONREGISTERED | A notification callback has already been registered.
XACTENGINE_E_INVALIDUSAGE | The method or function called cannot be used in the manner requested.
XACTENGINE_E_INVALIDDATA | The data used by the method or function is invalid.
XACTENGINE_E_INSTANCELIMITFAILTOPLAY | A sound or cue has reached an instance limit and cannot be played.
XACTENGINE_E_NOGLOBALSETTINGS | Global settings have not been loaded.
XACTENGINE_E_INVALIDVARIABLEINDEX | The specified variable index is invalid.
XACTENGINE_E_INVALIDCATEGORY | The specified category is invalid.
XACTENGINE_E_INVALIDCUEINDEX | The specified cue index is invalid.
XACTENGINE_E_INVALIDWAVEINDEX | The specified wave index is invalid.
XACTENGINE_E_INVALIDTRACKINDEX | The specified track index is invalid.
XACTENGINE_E_INVALIDSOUNDOFFSETORINDEX | The specified sound offset or index is invalid.
XACTENGINE_E_READFILE | An error has occured while attempting to read a file.
XACTENGINE_E_UNKNOWNEVENT | The event specified could not be found.
XACTENGINE_E_INCALLBACK | An invalid method or function was called during a callback function.
XACTENGINE_E_NOWAVEBANK | No wavebank exists for the requested operation.
XACTENGINE_E_SELECTVARIATION | A variation could not be selected.
XACTENGINE_E_AUDITION_WRITEFILE | An error has occured while writing a file during auditioning.
XACTENGINE_E_AUDITION_NOSOUNDBANK | A required sound bank is missing.
XACTENGINE_E_AUDITION_INVALIDRPCINDEX | A required wave bank is missing.
XACTENGINE_E_AUDITION_MISSINGDATA | A required set of data is missing for the requested audition command.
XACTENGINE_E_AUDITION_UNKNOWNCOMMAND | The audition command requested is not known.


XACT Project File Format (.xap)

The Xbox Audio Creation Tool Project File format (.xap), read and written by the XACT authoring tool (xact.exe), and utilized by the command-line build environment (xactbld.exe), contains all of the instructions necessary to generate XACT content. It is a complete description of all XACT wave banks, sound banks, and global settings.

The project file format was intentionally designed to be human-readable text, which should allow for straightforward parsing (content analysis, custom data structures, and portability for translating the content creator's wishes to other audio platforms) as well as generation (creating XACT content from a title's custom, tightly integrated tools, or programmatically generated content).

Because ongoing XACT engine work can cause the binary file formats to change from release to release (and some crucial information is stripped out when the binary files are built), the XACT project file is the recommended file to work from when doing any parsing, translation, or generation to and from other game elements or other audio engine platforms.

Note The XACT project file format is subject to change from release to release of the Xbox and DirectX Development Kits. While most changes will tend to be additive (e.g. adding new features as exposed by the engine and authoring tool), some may cause larger XACT project file format changes.


XACT Project File Format Layout

This document describes the file layout of the XACT Project File Format (.xap).

Syntax

Signature = XACT2;
Version	= #;

Options
{
}

Global Settings
{
}

Wave Bank
{
}

Sound Bank
{
}

Elements

Element | Type | Comment
Signature | String | Must be XACT2.
Version | Number | Version number.
Options | Section (zero or one) | General Options. Not currently supported.
Global Settings | Section (zero or one) | Project settings, paths, variables, RPCs, categories.
Wave Bank | Section (zero or one) | Wave banks associated with the project.
Sound Bank | Section (zero or one) | Sound banks associated with the project.

See Also

XACT Project File Format (.xap)


XAP File Format: Branch Event

Not supported.


XAP File Format: Cache

Parent: Wave

Syntax

Cache
{
Name = string;
File = string;
Format Tag = 0 - x;
Channel = #;
Sampling Rate = #;
Bits Per Sample = 1 / 0;

Play Region Offset = #;
Play Region Length = #;
Loop Region Offset = #;
Loop Region Length = #;
File Type = 0 - x;
Last Modified Low = #;
Last Modified High = #;
}

Elements

Element | Type | Comments
Name | String | Cache name
File | String | Cache filename
Format Tag | Number |
Channel | Number | Number of channels
Sampling Rate | Number |
Bits Per Sample | Boolean 0/1 | 0: 8 bits, 1: 16 bits
Play Region Offset | Number |
Play Region Length | Number |
Loop Region Offset | Number |
Loop Region Length | Number |
File Type | Number |
Last Modified Low | Number | Date last modified
Last Modified High | Number | Date last modified


XAP File Format: Category

Parent: Global Settings

Syntax

Category
{
Name = string;

Parent
{
}

Instance Limit
{
}

}

Note If you choose to edit the XAP file and change the order in which categories appear, parent categories must come before nested categories. Nested categories that appear before their parent categories will not appear correctly in the Microsoft Cross-Platform Audio Creation Tool (XACT) interface.

Elements

Element | Type | Comment
Name | String |
Parent | Section |
Instance Limit | Section |


XAP File Format: Clip

Not supported.


XAP File Format: Clip Entry

Not supported.


XAP File Format: Codec Preset

Parent: Global Settings

Syntax

Codec Preset
{
Name = string;
Format Tag = #;
Target Sample Rate = #;
Quality = #;
Find Best Quality = 0/1;
High Freq Cut = 0/1;
Loop = 0/1;
}

Elements

Element | Type | Comment
Name | String |
Format Tag | Number | WAVE_FORMAT_XXX tag
Quality | Number | XMA Encoding Only
Find Best Quality | Boolean 0/1 | XMA Encoding Only
High Freq Cut | Boolean 0/1 | XMA Encoding Only
Loop | Boolean 0/1 | XMA Encoding Only


XAP File Format: Conditional

Parent: Branch Event

Syntax

Conditional
{
Type = 0 - 4;

Operand	 // Operand A
{
}

Operand	 // Operand B
{
}

Operand	 // Operand C (optional)
{
}

Operand	 // Operand D (optional)
{
}

Operator1 = 0 - 6;
Operator2 = 0 - 6;	// optional

}

Elements

Element | Type | Comment
Type | Number (0-3) | 0: (A ? B), 1: (A ? B) && (C $ D), 2: (A ? B) || (C $ D), 3: (A ? B) ^ (C $ D)
Operand | Section | Operand A
Operand | Section | Operand B
Operand | Section (Optional) | Operand C
Operand | Section (Optional) | Operand D
Operator1 | Number (0-5) | 0: <, 1: <=, 2: >, 3: >=, 4: ==, 5: !=
Operator2 | Number (0-5) (Optional) | 0: <, 1: <=, 2: >, 3: >=, 4: ==, 5: !=


XAP File Format: Crossfade

Parent: Transition, Instance Limit

Syntax

Crossfade
{
Fade In	= #;
Fade Out = #;
Crossfade Type = 0 - 3;
}

Elements

Element | Type | Comment
Fade In | Number | Fade in time in milliseconds
Fade Out | Number | Fade out time in milliseconds
Crossfade Type | Number (0-2) | 0: Linear, 1: Logarithmic, 2: Equal Power


XAP File Format: Cue

Parent: Sound Bank

Syntax

Cue
{
    Name = string;		// no default (name of cue)

// Optional Variation
Variation
{
}

// One or more sound variation entries (complex or interactive)
Sound Entry  (complex, non-interactive)
{
}

Sound Entry  (interactive)
{
}

// Transitions: there are exactly (n+1) * n entries, where n = number of sound
//   entries.  The first n entries represent coming from the "stopped" state,
// transitioning to each variation.  The transition entries are stored in the same order as the variation sound entry table, thus the first entry corresponds to transitioning from "stopped" to the first variation.  After the "stopped" entries, all variation to variation transitions are stored.  In a cue with 2 sounds, this would give
// (n+1) * n = (2+1) * 2 = 6 entries:
// stop-> variation 1
// stop -> variation 2
// variation 1 -> stop
// variation 1 -> variation 2
// variation 2 -> stop
// variation 2 -> variation 1

Transition (Interactive cues only)
{
}

// one instance limit
Instance Limit
{
}

}

Elements

Element | Type | Comment
Variation | Section (Optional) |
Sound Entry | Section (One or More) |
Transition | Section (See Syntax Comments) |
Instance Limit | Section |


XAP File Format: Effect

Parent: Global Settings

Syntax

Effect
{
Name = string;
Global = 1/0;
Comment = string;

// Zero or more Effect Parameters
Effect Parameter
{
}

}

Elements

Element | Type | Comment
Name | String | Name of effect
Global | Boolean 0/1 (Default 1) | 0: Instance effect, 1: Global effect
Comment | String |
Effect Parameter | Section (Zero or More) |


XAP File Format: Effect Entry

Parent: Sound

Syntax

Effect Entry
{
Effect Name = string;
Effect Index = #;
}

Elements

Element | Type | Comment
Effect Name | String |
Effect Index | Number |


XAP File Format: Effect Parameter

Parent: Effect

Syntax

Effect Parameter
{
Name = string;
Minimum = #;
Maximum = #;
Value = #;
Type = #(0-1);
}

Elements

Element | Type | Comment
Name | String |
Minimum | Number | Minimum parameter value
Maximum | Number | Maximum parameter value
Value | Number | Current parameter value
Type | Number (0-1) | 0: Float, 1: Integer


XAP File Format: Effect Parameter Entry

Parent: RPC Curve

Syntax

Effect Parameter Entry
{
Effect Name = string;
Effect Index = #;
Parameter Name = string;
Parameter Index = #;
}

Elements

Element | Type | Comment
Effect Name | String |
Effect Index | Number |
Parameter Name | String |
Parameter Index | Number |


XAP File Format: Equation

Parent: Set Pitch Event, Set Variable Event, Set Volume Event

Syntax

Equation
{

Operator = 0 - 3;

Operand
{
}

}

Elements

Element | Type | Comment
Operator | Number (0-3) | 0: =, 1: +=, 2: -=, 3: *=
Operand | Section |


XAP File Format: Event Header

Parent: Branch Event, Play Sound Event, Play Wave Event, Set Effect Param, Set Marker Event, Set Pitch Event, Set Variable Event, Set Volume Event, Stop Event, Wait Event

Syntax

Event Header
{
Timestamp = #;
Relative = 1 / 0;
Relative Event Index = #;
Relative to Start = 1 / 0;
Random Offset = #;
Random Recurrence = 1 / 0;
}

Elements

Element | Type | Comment
Timestamp | Number (Default 0) | Timestamp relative on track
Relative | Boolean 0/1 (Default 0) | 0: Absolute event, 1: Relative event
Relative Event Index | Number | Event index of relative event. Required if Relative == 0, must be less than current event's index.
Relative to Start | Boolean 0/1 (Default 0) | 0: Relative to end, 1: Relative to start
Random Offset | Number (Default 0) | Random offset for each event recurrence
Random Recurrence | Boolean 0/1 (Default 0) | 0: Random recurrence only first time, 1: Random offset per recurrence


XAP File Format: Global Settings

Parent: XACT Project File Format Layout

Syntax

Global Settings
{
File = string;
Xbox File = string;
Windows File = string;
Shared Settings File = string;
Exclude Category Names = 1 / 0;
Exclude Variable Names = 1 / 0;
Last Modified Low = #;
Last Modified High = #;

// Zero or more Categories
Category
{
}

// Zero or more variables
Variable
{
}

// Zero or more RPCs
RPC
{
}

// Zero or more Effects
Effect
{
}

// Zero or more CodecPresets
Codec Preset
{
}

}

Elements

Element | Type | Comment
File | String | Path to the global settings file *.xgs (deprecated)
Xbox File | String | Path to the Xbox format global settings file *.xgs
Windows File | String | Path to the Windows format global settings file *.xgs
Exclude Category Names | Boolean 0/1 (default 0) | 0: Include Category Names, 1: Exclude Category Names
Exclude Variable Names | Boolean 0/1 (default 0) | 0: Include Variable Names, 1: Exclude Variable Names
Last Modified Low | Number | Date file last modified
Last Modified High | Number | Date file last modified
Category | Section (zero or more) | Categories associated with the project.
Variable | Section (zero or more) | Global and per-instance variables.
RPC | Section (zero or more) | Runtime Parameter Controls.
Effect | Section (zero or more) | Global and per-instance effects.
Codec Preset | Section (zero or more) | Codec presets associated with the project.


XAP File Format: Instance Limit

Parent: Category, Cue

Syntax

Instance Limit
{
Max Instances = #;
Transition Type = 0 / 1;
Behavior = 0 - 11;

Crossfade
{
}

}

Elements

Element | Type | Comment
Max Instances | Number |
Transition Type | Number (0-1) | 0: Crossfade, 1: Pause/Resume (not currently supported)
Behavior | Number (0-11) | 0: Fail to play, 1: Queue, 2: Replace newest, 3: Replace Oldest, 4: Replace quietest, 5: Replace loudest, 6: Replace lowest priority, 7: Replace highest priority, 8: Replace most distant (currently not supported), 9: Replace closest (currently not supported), 10: Replace most instances (currently not supported), 11: Replace least instances (currently not supported)
Crossfade | Section |


XAP File Format: Operand

Parent: Conditional, Equation

Syntax

Operand
{
// Only one of the following three "values" can exist

//value 1
Variable Entry
{
}

//value 2
Constant = #;

//value 3
Min Random = #;
Max Random = #;
}

Elements

Element | Type | Comment
Variable Entry | Section |
Constant | Number (No default) |
Min Random | Number (No default) |
Max Random | Number (No default) |


XAP File Format: Options

Not supported.


XAP File Format: Parent

Parent: Category

Syntax

Parent
{
Name = string;
Index = #;
}

Elements

Element | Type | Comment
Name | String | Name of category
Index | Number | Index of category


XAP File Format: Pitch Variation

Parent: Play Wave Event

Syntax

Pitch Variation
{
Min = #;
Max = #;
Operator = 0 - 3;
New Variation On Loop = 0 / 1;
}

Elements

Element | Type | Comment
Min | Number | Minimum pitch range
Max | Number | Maximum pitch range
Operator | Operator | 0: =, 1: +=, 2: -=, 3: *=
New Variation On Loop | Boolean 0/1 | 0: Only select once, 1: New variation


XAP File Format: Play Sound Event

Parent: Track

Syntax

Play Sound Event
{

Event Header
{
}

// Optional Variation
Variation
{
}

// One or more sound entries
Sound Entry
{
}

}

Elements

Element | Type | Comment
Event Header | Section |
Variation | Section (Optional) |
Sound Entry | Section (One or More) |


XAP File Format: Play Wave Event

Parent: Track

Syntax

Play Wave Event
{

Event Header
{
}

Loop Count = #;
Offset = #;

// Optional Pitch Variation
Pitch Variation
{
}

// Optional Volume Variation
Volume Variation
{
}

// Optional Variation
Variation
{
}

// One or more wave entries
Wave Entry
{
}

}

Elements

Element | Type | Comment
Event Header | Section |
Loop Count | Number (Default 0) | Additional times to loop
Offset | Number (Default 0) | Offset into wave
Pitch Variation | Section (Optional) |
Volume Variation | Section (Optional) |
Variation | Section (Optional) |
Wave Entry | Section (One or More) |


XAP File Format: Ramp

Parent: Set Pitch Event, Set Volume Event

Syntax

Ramp
{
Initial Value = #;
Slope = #;
Slope Delta = #;
Duration = #;
}

Elements

Element | Type | Comment
Initial Value | Number | Starting value of the ramp
Slope | Number | Slope of ramp (per sample)
Slope Delta | Number | Rate of change of slope (per sample)
Duration | Number | Duration of ramp in audio frames (16 bits == 170 seconds @ 128 samples per frame)


XAP File Format: Recurrence

Parent: Branch Event, Play Sound Event, Play Wave Event, Set Effect Param, Set Marker Event, Set Pitch Event, Set Variable Event, Set Volume Event, Stop Event, Wait Event

Syntax

Recurrence
{
Count = #;
Frequency = #;
Beats Per Minute = 0 / 1;
}

Elements

Element | Type | Comment
Count | Number (No Default) | Number of recurrences
Frequency | Number (No Default) | Interval of recurrences (ms / bpm)
Beats Per Minute | Boolean 0/1 | 0: Frequency in ms, 1: Frequency in beats per minute


XAP File Format: RPC

Parent: Global Settings

Syntax

RPC
{
Name = string;
Comment = string;

Variable Entry
{
}

// One or more RPC Curves
RPC Curve
{
}

// Zero or one Effect Entry
Effect Entry
{
}

}

Elements

Element | Type | Comment
Name | String |
Comment | String |
Variable Entry | Section |
RPC Curve | Section (One or More) |
Effect Entry | Section (Zero or More) |


XAP File Format: RPC Curve

Parent: RPC

Syntax

RPC Curve
{

Name = string;
Property = 0 - 1;
Sound = 0 / 1;
Line Color = #;
Viewable = 0 / 1;

// Zero or one Effect Parameter Entry
Effect Parameter Entry
{
}

// Two or more RPC Points
RPC Point
{
}

}

Elements

Element | Type | Comment
Name | String |
Property | Number (0-1, Default 0) | 0: Volume, 1: Pitch
Sound | Boolean 0/1 | 0: Curve is a track curve, 1: Curve is a sound curve
Line Color | Number | RGB value for GUI representation of the curve
Viewable | Boolean 0/1 | 0: Curve is not viewable in GUI, 1: Curve is viewable in GUI
Effect Parameter Entry | Section (Zero or One) |
RPC Point | Section (Two or More) |


XAP File Format: RPC Curve Entry

Parent: Track

Syntax

RPC Curve Entry
{
RPC Name = string;
RPC Index = #;
RPC Curve Name = string;
RPC Curve Index = #;
}

Elements

Element | Type | Comment
RPC Name | String (No Default) |
RPC Index | Number (No Default) |
RPC Curve Name | String (No Default) |
RPC Curve Index | Number (No Default) |


XAP File Format: RPC Point

Parent: RPC Curve

Syntax

RPC Point
{
X = #;
Y = #;
Curve = 0 - 3;
}

Elements

Element | Type | Comment
X | Number | X coordinate: Variable
Y | Number | Y coordinate: Property
Curve | Number (0-3) | Curve Type - 0: Linear, 1: Exponential, 2: Logarithmic


XAP File Format: Set Effect Param

Parent: Track

Syntax

Set Effect Param
{

Event Header
{
}

Data Size = #;
Data = #;

}

Elements

Element | Type | Comment
Event Header | Section |
Data Size | Number |
Data | Number |


XAP File Format: Set Marker Event

Parent: Track

Syntax

Set Marker Event
{

Event Header
{
}

Data = #;

// Optional recurrence
Recurrence
{
}

}

Elements

Element | Type | Comment
Event Header | Section |
Data | Number |
Recurrence | Section (Optional) |


XAP File Format: Set Pitch Event

Parent: Track

Syntax

Set Pitch Event
{
Event Header
{
}

// Optional recurrence: If included, the event cannot have a Ramp
Recurrence
{
}

// Only one of the following two can exist
Ramp
{
}

Equation
{
}

}

Elements

Element | Type | Comment
Event Header | Section |
Recurrence | Section (Cannot Exist with Ramp) |
Ramp | Section (Cannot Exist with Recurrence) |
Equation | Section |


XAP File Format: Set Variable Event

Parent: Track

Syntax

Set Variable Event
{

Event Header
{
}

Variable Entry
{
}

Equation
{
}

// Optional recurrence
Recurrence
{
}

}

Elements

Element | Type | Comment
Event Header | Section |
Variable Entry | Section |
Equation | Section |
Recurrence | Section (Optional) |


XAP File Format: Set Volume Event

Parent: Track

Syntax

Set Volume Event
{
Event Header
{
}

// Optional recurrence: If included, the event cannot have a Ramp
Recurrence
{
}

// Only one of the two can exist
Ramp
{
}

Equation
{
}

}

Elements

Element | Type | Comment
Event Header | Section |
Recurrence | Section (Cannot Exist with Ramp) |
Ramp | Section (Cannot Exist with Recurrence) |
Equation | Section |


XAP File Format: Sound

Parent: Sound Bank

Syntax

Sound
{
Name = string;
Category = #;
Volume = #;
Pitch = #;
Priority = #;

// Zero or more Effect Entries
Effect Entry
{
}

// Zero or more Tracks
Track
{
}

// Zero or more RPCs
RPC Entry
{
}

}

Elements

Element | Type | Comment
Name | String (No Default) |
Category | Number (Default 0) |
Volume | Number (-9600 to 0, Default 0) |
Pitch | Number (Default 0) |
Priority | Number (Default 0) |
Effect Entry | Section (Zero or More) |
Track | Section (Zero or More) |
RPC Entry | Section (Zero or More) |


XAP File Format: Sound Bank

Parent: XACT Project File Format Layout

Syntax

Sound Bank
{
Name = string;
File = string;
Xbox File = string;
Windows File = string;
Exclude Cue Names = 1 / 0;
Header File = string;
Bank Last Modified Low  = #;
Bank Last Modified High = #;
Header Last Modified High = #;
Header Last Modified Low = #;

// Zero or more clips

Clip
{
}

// Zero or more sounds

Sound
{
}

// Zero or more cues

Cue
{
}

}

Elements

Element | Type | Comment
Name | String | Name of soundbank
File | String | Path to the soundbank file (*.xsb) (deprecated)
Xbox File | String | Path to the Xbox format soundbank file (*.xsb)
Windows File | String | Path to the Windows format soundbank file (*.xsb)
Exclude Cue Names | Boolean 0/1 (default 0) | 0: Include cue names, 1: Exckude cue names
Header File | String | Pathname of header file (*.h)
Bank Last Modified Low | Number | Date soundbank file last modified
Bank Last Modified High | Number | Date soundbank file last modified
Header Last Modified Low | Number | Date header file last modified
Header Last Modified High | Number | Date header file last modified
Clip | Section (zero or more) | Clips stored in the soundbank. Not currently supported.
Sound | Section (zero or more) | Sounds stored in the soundbank.
Cue | Section (zero or more) | Cues stored in the soundbank.


XAP File Format: Sound Entry

Parent: Cue

Note There are two types of sound entries, complex non-interactive entries, and interactive entries.

Syntax

Sound Entry  (complex, non-interactive)
{
Name = string;
Index = #;
Weight Min = (BYTE)#;
Weight Max = (BYTE)#;
}

Sound Entry  (interactive)
{
Name = string;
Index = #;
Variable Min = (float)#;
Variable Max = (float)#;
Linger = 0/1;
}

Elements

Complex, Non-Interactive

Element | Type | Comment
Name | Number | Name of sound
Index | Number | Sound offset in soundbank
Weight Min | Number (Byte) | Random range (Min)
Weight Max | Number (Byte) | Random range (Max)

Interactive

Element | Type | Comment
Name | String | Name of sound
Index | Number | Sound offset in soundbank
Variable Min | Number (Float) | Variation active when its controlling variable is in this range (Min)
Variable Max | Number (Float) | Variation active when its controlling variable is in this range (Max)
Linger | Boolean 0/1 | 1: Play currently chosen variation as long as its controlling variable is in range, 0: Choose a new variation every time the controlling variable changes


XAP File Format: Stop Event

Parent: Track

Syntax

Stop Event
{

Event Header
{
}

Immediate = 1 / 0;
Stop Cue = 1 / 0;

}

Elements

Element | Type | Comment
Event Header |  |
Immediate | Boolean 0/1 (Default 1) |
Stop Cue | Boolean 0/1 (Default 0) |


XAP File Format: Track

Parent: Sound

Syntax

Track
{

Volume = #;

// Zero or more RPC Curves
RPC Curve Entry
{
}

// One or more events
// Events must be in timestamp order, except for relative events
// which must be placed after the event they are relative to. Note that relative
// events do not need to immediately follow the event they are relative to,
// they just need to be after

// Zero or one "Play" event
Play Wave Event
{
}

Play Wave From Offset Event
{
}

Play Wave Variation Event
{
}

Play Sound Event
{
}

// Zero or more stop events
Stop Event
{
}

// Zero or more branch events
Branch Event
{
}

// Zero or more wait events
Wait Event
{
}

// Zero or more set effect param events
Set Effect Param
{
}

// Zero or more set variable events
Set Variable Event
{
}

// Zero or more set pitch events
Set Pitch Event
{
}

// Zero or more set volume events
Set Volume Event
{
}

// Zero or more marker events
Set Marker Event
{
}

// Zero or more set variable recurring events
Set Variable Recurring Event
{
}

// Zero or more set marker recurring events
Set Marker Recurring Event
{
}

// Clip entries are currently not supported.
Clip Entry
{
}

}

Elements

Element | Type | Comment
Volume | Number (-9600 to 0, Default 0) |
RPC Curve Entry | Section (Zero or More) |
Play Wave Event | Section (Zero or One) |
Play Wave From Offset Event | Section (Zero or One) |
Play Wave Variation Event | Section (Zero or One) |
Play Sound Event | Section (Zero or One) |
Stop Event | Section (Zero or More, See Comments Above) |
Branch Event | Section (Zero or More, See Comments Above) |
Wait Event | Section (Zero or More, See Comments Above) |
Set Effect Parameter | Section (Zero or More, See Comments Above) |
Set Variable Event | Section (Zero or More, See Comments Above) |
Set Pitch Event | Section (Zero or More, See Comments Above) |
Set Volume Event | Section (Zero or More, See Comments Above) |
Set Marker Event | Section (Zero or More, See Comments Above) |
Set Variable Recurring Event | Section (Zero or More, See Comments Above) |
Set Marker Recurring Event | Section (Zero or More, See Comments Above) |
Clip Entry | Section | Not supported.


XAP File Format: Transition

Parent: Cue

Syntax

Transition (Interactive cues only)
{

Sound Index = #;
Source Marker Min = (DWORD)#;
Source Marker Max = (DWORD)#;
Destination Marker Min = (DWORD)#;
Destination Marker Max = (DWORD)#;
Transition Type = 0 - 7;
Transition Source = 0 - 4;
Transition Destination = 0 - 5;
Crossfade
{
}

}

Elements

Element | Type | Comment
Sound Index | Number | Transition sound offset in soundbank, set to XACTOFFSET_INVALID if not used (see Transition Type for which transition types require transition sounds)
Source Marker Min | Number (DWORD) | Source marker range (Min)
Source Marker Max | Number (DWORD) | Source marker range (Max), must be >= Source Marker Min
Destination Marker Min | Number (DWORD) | Destination marker range (Min)
Destination Marker Max | Number (DWORD) | Destination marker range (Max), must be >= Destination Marker Min
Transition Type | Number (0-7) | 0: DirectWithoutTransition, 1:CrossfadeWithoutTransition, 2: DirectSequentialTransition, 3: CrossfadeToSequentialTransition, 4: CrossfadeFromSequentialTransition, 5: CrossfadeToAndFromSequentialTransition, 6: DirectConcurrentTransition, 7: CrossfadeConcurrentTransition
Transition Source | Number (0-4) | 0: Immediate, 1: FirstMarkerInRange, 2: RandomMarkerInRange, 3: EndOfLoop, 4: EndOfSound
Transition Destination | Number (0-5) | 0: Beginning, 1: AlignedTime, 2: AlignedMarker, 3: FirstAlignedMarker, 4: FirstMarkerInRange, 5: RandomMarkerInRange
Crossfade | Section |


XAP File Format: Variable

Parent: Global Settings

Syntax

Variable
{
Name = string;
Public = 0 / 1;
Global = 0 / 1;
Internal = 0 / 1;
External = 0 / 1;
Monitored = 0 / 1;
Reserved = 0 / 1;
Read Only = 0 / 1;
Time = 0 / 1;
Value = #;
Initial Value = #;
Min = #;
Max = #;
}

Elements

Element | Type | Comment
Name | String |
Public | Boolean 0/1 | 0: Private, 1: Public
Global | Boolean 0/1 | 0: Cue instance, 1: Global
Internal | Boolean 0/1 | 0: User, 1: Internal
External | Boolean 0/1 | Used by GUI
Monitored | Boolean 0/1 | Used by GUI
Reserved | Boolean 0/1 | 0: Non-Reserved, 1: Reserved
Read Only | Boolean 0/1 | 0: Read/Write, 1: Read Only
Time | Boolean 0/1 | 0: Time, 1: Normal
Value | Number | Current value of variable
Initial Value | Number | Initial value of variable
Min | Number | Minimum value of variable
Max | Number | Maximum value of variable


XAP File Format: Variable Entry

Parent: Operand, RPC, Set Variable Event

Syntax

Variable Entry
{
Name = string;
Index = #;
}

Elements

Element | Type | Comment
Name | String |
Index | Number |


XAP File Format: Variation

Parent: Cue, Play Sound Event, Play Wave Event

Syntax

Variation
{
Variation Type = 0 - 4;
Variation Table Type = 0 - 4;
New Variation on Loop = 0 - 1;
Variable Index = #;
}

Elements

Element | Type | Comment
Variation Type | Number (0-4) | 0: Ordered, 1: OrderedFromRrandom, 2: Random, 3: RandomNoImmediateRepeats, 4: Shuffle
Variation Table Type | Number (0-4) | 0: Wave, 1: Sound, 2: Clip, 3: Interactive, 4: CompactWave. Defines type of sound entries that can be expected. Non-interactive complex cues requiring a sound variation table (i.e. they have more than one sound) will have entries of type Sound. Interactive cues will always have a sound variation table with entries of type interactive.
New Variation On Loop | Boolean 0/1 | 1: Select new variation when looped, 0: Use same variation. Ignored by interactive cues.
Variable Index | Number | Variable index (used for interactive cues only; set to XACTVARIABLEINDEX_INVALID (0xffff) for all other variation table types).


XAP File Format: Volume Variation

Parent: Play Wave Event

Syntax

Volume Variation
{
Min = #;
Max = #;
Operator = 0 - 3;
New Variation On Loop = 0 / 1;
}

Elements

Element | Type | Comment
Min | Number | Minimum volume range
Max | Number | Maximum volume range
Operator | Number (0-3) | 0: =, 1: +=, 2: -=, 3: *=
New Variation On Loop | Boolean 0/1 | 0: Only select once, 1: New variation


XAP File Format: Wait Event

Parent: Track

Syntax

Wait Event
{

Event Header
{
}

Pause Playback = 1 / 0;

Conditional
{
}

}

Elements

Element | Type | Comment
Event Header | Section |
Pause Playback | Boolean 0/1 | 0: Pause events, 1: Pause events and playback
Conditional | Section |


XAP File Format: Wave

Parent: Wave Bank

Syntax

Wave
{
Name = string;
File = string;
Remove Loop Tail = 1 / 0;
Ignore Loop Region = 1 / 0;
Build Settings Last Modified Low = #;
Build Settings Last Modified High = #;

Cache
{
}

}

Elements

Element | Type | Comment
Name | String |
File | String |
Remove Loop Tail | Boolean 0/1 |
Ignore Loop Region | Boolean 0/1 |
Build Settings Last Modified Low | Number |
Build Settings Last Modified High | Number |
Cache | Section |


XAP File Format: Wave Bank

Parent: XACT Project File Format Layout

Syntax

Wave Bank
{
Name = string;
File = string;
Xbox File = string;
Windows File = string;
Seek Tables = #;
Header File = string;
Alignment = #;
Streaming = 1 / 0;
Entry Names = 1 / 0;
Compact = 1 / 0;
Audition Sync Disabled  = 1 / 0;
Bank Last Modified Low  = #;
Bank Last Modified High = #;
Header Last Modified High = #;
Header Last Modified Low = #;

Compression Preset Name = string;
Compression Preset ID = #;

// Zero or more waves

Wave
{
}
}

}

Elements

Element | Type | Comment
Name | String | Name of wavebank
File | String | Path to the wavebank file (*.xwb) (deprecated)
Xbox File | String | Path to the Xbox format wavebank file (*.xwb)
Windows File | String | Path to the Windows format wavebank file (*.xwb)
Header File | String | Pathname of header file (*.h)
Alignment | Number | Wavebank alignment
Streaming | Boolean 0/1 | 0: In-memory, 1: Streaming
Entry Names | Boolean 0/1 | 0: No entry names, 1: Include entry names
Compact | Boolean 0/1 | 0: Normal format, 1: Compact format
Audition Sync Disabled | Boolean 0/1 | 0: Bank will sync to audition engine, 1: Bank will not sync to audition engine
Bank Last Modified Low | Number | Date wavebank file last modified
Bank Last Modified High | Number | Date wavebank file last modified
Header Last Modified Low | Number | Date header file last modified
Header Last Modified High | Number | Date header file last modified
Compression Preset Name | String | Compression Preset attached to this bank
Compression Preset ID | Number | Compression Preset attached to this bank
Wave | Section (zero or more) | Waves stored in the wavebank.


XAP File Format: Wave Entry

Parent: Play Wave Event

Syntax

Wave Entry
{
Entry Name = string;
Entry Index = #;
Bank Name = string;
Bank Index = #;
Weight = #;
Weight Min = #;
}

Elements

Element | Type | Comment
Entry Name | String (No Default) |
Entry Index | Number (No Default) |
Bank Name | String (No Default) |
Bank Index | Number (No Default) |
Weight | Number (0-255) |
Weight Min | Number (0-255) | Minimum weight for range


XACT Tutorials and Samples

This section contains tutorials and sample code that demonstrate how to use the Microsoft Cross-Platform Audio Creation Tool (XACT) and associated APIs.

Infomation is presented in the following tutorials:

XACT Authoring Basics Tutorial
How to use the XACT. New users of the XACT should start here.
XACT API Basics Tutorial
The basic steps for using the XACT API. New users of the XACT API should start here.
XACT API Streaming Tutorial
How to use streaming audio.
XACT API Variables Tutorial
How to use variables and categories.
XACT Game Sample
A demonstration of a game using XACT and Direct3D.
XACT Code-Driven API Sample
How to use the XACT code-driven API.


XACT Authoring Basics Tutorial

The Microsoft Cross-Platform Audio Creation Tool (XACT) is typically used by the audio designer to create an XACT project file (.xap) which is used to build the data files which the programmer will need to integrate XACT audio resources into game. Once the programmer plugs the game into XACT, the authoring tool can then be used to dynamically alter the sounds while the game is playing.

Getting Started

To get started, start the authoring tool. It should look something like this:

Figure 1. Blank XACT Project

When you open the tool, the project is blank. There's nothing defined. To understand the XACT, you'll first need to understand some XACT terminology:

  1. A wave bank is a collection of waves logically grouped into a single file by an audio designer. When the XACT project is built for integration into a game title, each wave bank is represented by a file with the extension .xwb.
  2. A wave is just audio data. XACT supports WAV, and AIFF audio files.
  3. A sound bank is a collection of sounds and cues logically grouped by the sound designer. A sound bank file does not contain wave data; wave data resides in wave banks. A sound bank references the waves that are bundled in wave banks, and houses the information on how they are to be played. Each sound bank is represented by a file with the extension .xsb.
  4. A sound lives in a sound bank and specifies how one or more waves should be played. A sound also has specific properties such as volume and pitch. These properties can be adjusted by the sound designer. Sounds are composed of one or more tracks.
  5. A track is a grouping of events. One or more tracks define a sound. Each track can contain a single Play Wave event, as well as any number of other events (such as markers and volume changes).
  6. Events are actions to be performed within the body of a track. A track must have at least one event. The simplest event type is a Play Wave event, which plays a wave.
  7. Cues are what programmers use to play sounds. Cues are typically played when certain game events, such as footsteps or gunshots, occur. A cue is composed of one or more sounds, so when the cue is triggered, the set of associated sounds is heard.

Create Sound Banks and Wave Banks

To get started, you need to create a wave bank and a sound bank. To do this click in the menu "Wave Banks" | "New Wave Bank". A new wave bank will appear in the tree view under "Wave Banks" with the default name of "Wave Bank".

Then, create a new sound bank by clicking in the menu "Sound Banks" | "New Sound Bank". A new sound bank will appear in the tree view under "Sound Banks" with the default name of "Sound Bank". It should look like this:

Figure 2. New Sound and Wave Banks Created

Now to make things easy to see, click "Window" | "Tile Horizontally":

Figure 3. Windows Tiled Horizontally

Add a Wave

The wave bank window lists all the waves current inside the wave bank. Currently there are none so you will need to add some. Make sure the Wave Bank window is active by clicking on it and choose in the menu "Wave Banks" | "Insert Wave File(s)..." and insert 1 or more wave files into the wave bank. You could have also hit Ctrl-W or right clicked on the Wave Bank window for a popup menu. After you've added some wave files, they will be listed in the Wave Bank window.

Figure 4. Wave Files Added

Make a Sound and Cue

Now that there's a wave file in the wave bank, drag this wave from the wave bank to sound bank in the "Cue Name" panel. This will make XACT automatically create a new cue that's linked to a new sound that plays to this wave file.

Figure 5. New Cue Created

That's it! You have now setup your first complete but very simple XACT project. Now you can build this project and load the built XACT files with XACT API to play this cue in your game based on a game event. The cue we have set up will cause a single wave to be played but you can setup much more complex interactions when a cue is played.

To build the files, you will likely want to adjust build properties so the files are placed and named as you like. To do this, click on the "Wave Bank" in the tree view and adjust its "Build Name" and "Build Path" as you like and click on the "Sound Bank" in the tree view and adjust its "Build Name" and "Build Path" as you like. Then click File | "Build..." to create wave banks (*.xwb) and sound banks (*.xsb) based on the build settings.


XACT API Basics Tutorial

This tutorial covers the basics of the Microsoft Cross-Platform Audio Creation Tool (XACT) API, including understanding XACT components and file formats, and basic steps for using XACT, such as loading wave banks, using notifications, and playing cues.

Getting Started

The full working source code for this tutorial is in:

<Installed SDK Location>\Samples\C++\XACT\Tutorials\Tut01_PlayCue

XACT Components

Before we dive into programming, let's cover some of the basic background of XACT.

XACT is composed of three connected parts:

  • Content authoring and auditioning tool (XACT.exe). This is the tool used to create audio files that are used by the XACT runtime engine.
  • Runtime engine (XactEngine.lib). A highly optimized engine that exposes all of the run-time behavior that your game engine will interface with.
  • Audition engine (XactEngineA.lib). Beyond the run-time engine features, the audition engine allows sounds to be actively mixed, equalized, and edited while the game is running. Even if sounds are not being actively edited, the XACT authoring tool can be used to monitor resources and audio levels, and to display cue triggering events as they occur.

Dividing Up Responsibilities

When creating an audio solution for a game, it is important to understand which aspects are in the hands of the programmer and which are the responsibility of the composer or sound designer. To avoid confusion and potential responsibility "clashes," XACT attempts to provide a single way to perform most tasks. Properties and behaviors that are specified in content cannot generally be "overridden" programmatically, and conversely, the composer does not control resource management or dynamic pausing.

When initiating a project, the sound designer and the programmer decide on important cues, also known as "triggers" or "sound cues," in the game. The composer will then create a sound (or perhaps multiple sounds, one of which will be chosen randomly to play) that that cue plays, and the programmer makes the game plays those cues when the proper game events occur. This allows the programmer and the sound designer can go their separate ways.

To summarize, the programmer's responsibilities:

  • Program cue play calls into the game.
  • Manage resources (such as memory, content loading and unloading).
  • Manage all dynamic sounds (pause/resume, 3D positioning, and so on).

Meanwhile, the sound designer or composer:

  • Bundles up all source wave data into one or more wave banks.
  • Builds each of the individual sounds. A sound consists of one or more events on a timeline, which might consist of playing waves, and setting the volume and pitch possibly with variation.
  • Creates cues in the XACT tool corresponding to each programmed cue. Each cue can be assigned one or more sounds, one of which is chosen and played when the game calls for this cue.

XACT File Formats

XACT relies on two types of files for audio content: wave banks (*.xwb) and sound banks (*.xsb).

Wave banks are just bundled wave data, formatted for optimal playback performance. For in-memory wave banks, waves are DWORD aligned. For streamed wave banks, the individual waves are sector aligned (2048-byte boundaries for DVD streaming). All of this data formatting is managed automatically in the XACT build process, based on settings specified by the content author. These settings can be changed easily enough, but you should communicate with your content creator as to what kind of in-memory budget you have for audio, as well as how much streaming bandwidth you can grant to audio during game play.

Sound banks are where waves are assembled on a timeline into sounds by the content creator. The content creator then assigns a cue to play a sound (or in some cases, pick a random sound from a list). The developer then plays and stops these cues based on game events. Beyond controlling cues, the developer can also manipulate some properties on a category level. Each sound can be assigned to a category by the content creator. The developer can then globally adjust the relative volume of categories as well as pause or resume them.

While we're talking about file formats, let's also mention the XACT project file (*.xap). This is the file that contains all of the instructions for building the sound banks and wave banks for a project-every setting that the content creator has specified in the XACT authoring tool. Typically a developer will never have to actually read or edit this file. However, because the sound bank format could change in a future release, you should make sure to rebuild your sound banks with each new SDK, even if the content is no longer being edited. The command line tool xactbld.exe allows you to rebuild sound banks (and, optionally, wave banks) from the XACT project file without needing to open the editing tool. It's quite common to integrate this into a game's automated build process, rather than needing to remember to manually rebuild.

Basic Steps for Using XACT

Here is a quick overview of the basic steps to use XACT, and afterward we'll look each of these steps in detail.

  1. Initialize the XACT engine (IXACTEngine::Initialize). Here you can set some basic runtime parameters and set the notification callback.
  2. Create your wave bank(s) (IXACTEngine::CreateInMemoryWaveBank and/or IXACTEngine::CreateStreamingWaveBank). For in-memory wave banks, the binary .xwb image can just be loaded into memory. Remember to not free this file memory until the wave bank is destroyed by XACT. For streamed wave banks, use CreateFile with FILE_FLAG_OVERLAPPED and FILE_FLAG_NO_BUFFERING.
  3. Create your sound bank(s) (IXACTEngine::CreateSoundBank). As with in-memory wave banks, just load the binary .xsb sound bank into memory and point XACT at it.
  4. Look up the cue or cues that you want to play (IXACTSoundBank::GetCueIndex). This step is actually optional; XACT can build a header file that enumerates all of the cue indices, which saves you the run-time string lookup table size (and corresponding search hit). Note that specific indices and index ordering might change while the sound bank is being edited by the content creator, so this optimization is generally reserved for when cues are stabilized, and new cues are no longer being created.
  5. Optionally register for any notifications you want to handle (IXACTEngine::RegisterNotification). To keep things simple, you might just register for stop notifications (XACTNOTIFICATIONTYPE_CUESTOP) on your cues, so that you know when they finish playing.
  6. Play cues when game events happen (IXACTSoundBank::Play). There is often no need to get back a cue instance pointer if you won't need to stop the cue.
  7. Handle or flush pending notifications in the notification callback.
  8. During the main game loop, call IXACTEngine::DoWork. This allows XACT to processes notifications and streams.
  9. When game is done, shut down XACT (IXACTEngine::ShutDown).

Step 1: Initialize XACT

First, to initialize XACT it just requires making this call:

XACT_RUNTIME_PARAMETERS xrParams = {0};
xrParams.fnNotificationCallback = XACTNotificationCallback;
hr = pXACTEngine->Initialize( &xrParams );

The XACT_RUNTIME_PARAMETERS structure contains a number of advanced options such as the global settings file and look-ahead time which are out of the scope of this tutorial, but they can all be safely set to 0 to use the default settings. The fnNotificationCallback member is the callback function used to notify the application about XACT notifications. Notifications will be covered in detail later in this tutorial.

Steps 2-3: Create the XACT banks

Next, you need to create the wave banks and sound banks. In this tutorial, we only create one XACT wave bank and one XACT sound bank. For more complex games that have lots of sounds, they can break their sound effects into multiple wave and sound banks. This allows them to more easily partition the sound data by level, by character, by material, or however they desire to keep only the working set they desire loaded at the same time.

To create XACT wave banks and XACT sound banks you must use the following methods of IXACTEngine:

STDAPI IXACTEngine_CreateInMemoryWaveBank(
  void *pvBuffer,
  DWORD dwSize,
  DWORD dwFlags,
  DWORD dwAllocAttributes,
  IXACTWaveBank **ppWaveBank
);

STDAPI IXACTEngine_CreateStreamingWaveBank(
  const XACT_WAVEBANK_STREAMING_PARAMETERS *pParms,
  IXACTWaveBank **ppWaveBank
);

STDAPI IXACTEngine_CreateSoundBank(
  void *pvBuffer,
  DWORD dwSize,
  DWORD dwFlags,
  DWORD dwAllocAttributes,
  IXACTSoundBank **ppSoundBank
);

IXACTEngine::CreateStreamingWaveBank is slightly more advanced and will be discussed in the next tutorial.

Both IXACTEngine::CreateSoundBank and IXACTEngine::CreateInMemoryWaveBank need a pointer to the data to read and the size of the data in bytes. Typically this data will come from reading an XACT file but this does not have to be the case. For example, the data could be part of an exe resource or contained inside a bundled file format.

When reading a file, there are 2 primary methods of doing so. The most typical is to use ReadFile() to read the file into a buffer like so:

HANDLE hFile = CreateFile(str, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
DWORD dwFileSize = GetFileSize(hFile , NULL);
VOID* pSoundBankData = new BYTE [dwFileSize];
ReadFile(hFile, pSoundBankData, dwFileSize, &dwBytesRead, NULL))
HRESULT hr = pXACTEngine->CreateSoundBank(pSoundBankData, dwFileSize, 0, 0, &pSoundBank);

The other method is called memory-mapped files and uses MapViewOfFile to map a view of a file into the address space of the calling process. Memory-mapped files tend to be faster for most situations assuming you have enough virtual address space for a full map of the file thus our examples will use the faster memory mapped file method:

HANDLE hFile = CreateFile( str, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
DWORD dwFileSize = GetFileSize( hFile, NULL );
HANDLE hMapFile = CreateFileMapping( hFile, NULL, PAGE_READONLY, 0, dwFileSize, NULL );
VOID* pSoundBankData = MapViewOfFile( hMapFile, FILE_MAP_READ, 0, 0, 0 );
HRESULT hr = pXACTEngine->CreateSoundBank( pSoundBankData, dwFileSize, 0, 0, &pSoundBank );

The most important concept to understand is that you can not free the data block passed to these create functions until XACT has destroyed that wave bank or sound bank. The file data passed to these functions is not cached by XACT and is needed by XACT when sounds are played. Simply calling Release on the bank does not mean the bank is immediately destroyed and the memory can be freed because there could be sound(s) still playing when Release was called.

It is only safe to free the data after calling either IXACTEngine::ShutDown or a XACTNOTIFICATIONTYPE_SOUNDBANKDESTROYED or XACTNOTIFICATIONTYPE_WAVEBANKDESTROYED notification for the bank has been received. We will look at how to create and handle notifications shortly. Alternatively, if you set XACT_FLAG_API_CREATE_MANAGEDATA and do not use the memory-mapped file method then XACT will automatically free the file buffer when the bank is destroyed.

Step 4: Store XACT cue indices

After the wave and sound banks have been created, an XACT cue index is needed used by your game to play a cue event. There are a few methods for retrieving these index cues. The most common method is to use IXACTSoundBank::GetCueIndex like so:

iZapCueIndex = g_audioState.pSoundBank->GetCueIndex( "zap" );

Note that the string "zap" used here is just the friendly string name of the cue as you defined in the XACT project. Also note that if the cue does not exist in the sound bank, the index will be XACTINDEX_INVALID however this is not tragic especially during development as it will simply cause the IXACTCue::Play or IXACTSoundBank::Prepare call to fail.

Another method is to enable the BuildProjectHeader setting in XACT authoring tool. This will make the XACT project create a C style header which can be included by your game. The header will contain something like this depending on the names of your cues:

typedef enum
{
    XACT_CUE_SOUND_BANK_ZAP = 0,
} XACT_CUE_SOUND_BANK;

#define XACT_CUE_SOUND_BANK_ENTRY_COUNT 1

Now that the XACT is initialized, the wave and sound banks have been created and your engine has indices to all the cues, you are ready to use XACT.

Step 5: Registering notifications

You can optionally register for any number of notifications depending on the game's needs. The process simply involves filling out the XACT_NOTIFICATION_DESCRIPTION structure and calling IXACTEngine::RegisterNotification like so:

XACT_NOTIFICATION_DESCRIPTION desc = {0};
desc.type = XACTNOTIFICATIONTYPE_CUESTOP;
desc.pSoundBank = pSoundBank;
desc.cueIndex = iZapCueIndex;
pXACTEngine->RegisterNotification(&desc);

The structure is described in detail in the docs along with all of the notification types (XACTNOTIFICATIONTYPE) available but it should be noted that you don't have to tie the notification to a one time event or a specific cue or bank. For example, you can setup a persistent notification for all sound banks like so:

XACT_NOTIFICATION_DESCRIPTION desc = {0};
desc.flags = XACT_FLAG_NOTIFICATION_PERSIST;
desc.type = XACTNOTIFICATIONTYPE_CUESTOP;
desc.cueIndex = XACTINDEX_INVALID;
pXACTEngine->RegisterNotification(&desc);

This notification will trigger whenever any cue stops on any sound bank. If you have multiple sound or wave banks and want to swap them in and out as the game progresses, you can use a notification like this:

XACT_NOTIFICATION_DESCRIPTION desc = {0};
desc.flags = XACT_FLAG_NOTIFICATION_PERSIST;
desc.type = XACTNOTIFICATIONTYPE_SOUNDBANKDESTROYED;
pXACTEngine->RegisterNotification(&desc);

desc.flags = XACT_FLAG_NOTIFICATION_PERSIST;
desc.type = XACTNOTIFICATIONTYPE_WAVEBANKDESTROYED;
pXACTEngine->RegisterNotification(&desc);

So you will be notified whenever a wave or sound bank is destroyed so you can free its associated file memory.

Step 6: Playing sounds with XACT

To play sounds using XACT, the game plays a specific XACT cue when a game event occurs. This cue is defined in the XACT project by the sound designer to play a certain set of XACT sounds which in turn play events which trigger the playback of a certain set of wave data with possibly a variation of volumes and pitches. Because of the way XACT is designed, the audio that is heard when a cue is played can be changed without recompiling the game. This allows the audio to be designed and tweaked independently once the game events are defined and the cues are triggered by the game engine.

The simplistic method to play a cue is done by calling IXACTSoundBank::Play with the appropriate cue index when an event happens in the game. We'll look at more complex methods later. For the typical case the code is simply:

pSoundBank->Play( iCueIndex, 0, NULL );

Note that it is often not necessary to retrieve the pointer to the IXACTCue object unless your game needs to stop or pause the cue so NULL can be used as the 3rd parameter.

Step 7: Handling notifications

Notifications are received in a notification callback function that looks like this:

void WINAPI XACTNotificationCallback(const XACT_NOTIFICATION* pNotification)
{
   if( pNotification->type == XACTNOTIFICATIONTYPE_CUESTOP )
   {
       // Handle the cue stop notification
   }

   // ....
}

This callback is set when calling IXACTEngine::Initialize. This callback can be executed on a different thread than the application thread, so any shared data referenced in this callback must be made thread safe. The application also needs to minimize the amount of time spent in this callback to avoid glitching, and a limited subset of XACT APIs can be called from inside the callback (see XACT_NOTIFICATION_CALLBACK for a list of acceptable APIs) so it is sometimes necessary to handle the notification outside of this callback.

The XACT_NOTIFICATION structure will contain all the information the game needs to process the notification. If in the rare case the game wants to remove all pending notifications from the queue without handling them it can flush them like so:

XACT_NOTIFICATION_DESCRIPTION desc = {0};
desc.type = XACTNOTIFICATIONTYPE_CUESTOP;
XACTFlushNotification(&desc);

You can also use IXACTEngine::UnRegisterNotification to stop receiving a certain type of notification.

Step 8: Periodically allow XACT to do work

It is important to allow XACT to do periodic work by calling IXACTEngine::DoWork. However this function must be called often enough. If you call it too infrequently, streaming will suffer and resources will not be managed promptly. On the other hand if you call it too frequently, it will negatively affect performance. Calling it once per frame is usually a good balance as shown below:

while( WM_QUIT != msg.message  )
{
    // Use PeekMessage() so we can use idle time to render the scene and call DoWork()
    bGotMsg = ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0 );

    if( bGotMsg )
    {
        // Translate and dispatch the message
        TranslateMessage( &msg );
        DispatchMessage( &msg );
    }
    else
    {
        RenderFrame();
        pXACTEngine->DoWork();
    }
}

Step 9: XACT shut down and clean up

To shut down and clean up XACT, first release all the XACT interfaces and then call IXACTEngine::ShutDown and free the sound and wave bank data like shown below. Be aware that IXACTEngine::ShutDown is synchronous and will take some time to complete if there are still playing cues. Also IXACTEngine::ShutDown is generally only called when a game exits and not the preferred method of changing audio resources. To unload resources while game is running, use notifications.

VOID CleanupXACT()
{
    // Release XACT interfaces
    if( g_pSoundBank )
        g_pSoundBank->Release();
    if( g_pWaveBank )
        g_pWaveBank->Release();

    // Shut down XACT
    pXACTEngine->ShutDown();

    // Release memory mapped files
    if( g_pbSoundBank )
        UnmapViewOfFile( g_pbSoundBank );
    if( g_pbWaveBank )
        UnmapViewOfFile( g_pbWaveBank );
}


XACT API Streaming Tutorial

This tutorial builds on the basic knowledge gained of the first API tutorial and takes a closer look at using Microsoft Cross-Platform Audio Creation Tool (XACT) to stream audio data directly from a storage medium, such as a DVD or hard drive.

Getting Started

The full working source code for this tutorial is in:

<Installed SDK Location>\Samples\C++\XACT\Tutorials\Tut02_Stream

This source code is designed to be examined separately and after the discussion below.

Background concepts

Streaming is when data is read directly from a storage medium, such as a DVD or hard drive, instead of being cached in memory. Streaming data saves memory usage since the whole file does not need to be read at once but depending on the speed of the storage medium, there could be significant delay between the time the request to read the data and time the data is actually read. This delay is called latency.

Latency is the time between when the request to play is made and when the audio is heard. When reading audio data from a storage medium, the latency could be substantial as device takes time to position to the proper sector under the read/write head. Latency can cause delays in playback of streamed audio, or even intermittent breaks if a slow-reading disk fails to feed data to the audio output fast enough for continuous sound. While the worst-case latency of a hard drive might be around 100 milliseconds, the worst-case latency of a DVD can be a full second or more. Latency on a DVD can be minimized when audio data are strategically placed on the disc so that the data contiguously streamed. If the read head does not have to move far to retrieve the next block of data, delays will remain small.

XACT wave banks types

There are 2 types of wave banks available in XACT:

  • In-memory wave banks are loaded entirely into system memory from the storage medium (DVD or hard drive) for later playback. Waves played directly from memory have no inherent timing or latency issues. In-memory wave banks are typically used for shorter duration sounds such as sound effects that need to be zero-latency without the requirement for the cues to be prepared before playing.
  • Streaming wave banks are where the wave data remains on the storage medium and read by XACT as needed. This is often necessary for audio that is too large to load into working memory. Streaming banks are typically used for longer duration sounds such as background music, or sounds that don't require zero-latency playback, and for large collections of sounds. However, we will discuss later how it is possible to do zero-latency streaming with XACT.

Creating a Streaming Wave Bank

To do streaming, the first step is to set the wave bank's "streaming" property to true in the XACT authoring tool. Typically the sound designer sets this and informs the programmer to stream that wave bank.

Once this is done, the programmer can then use CreateFile to open the file with the flags FILE_FLAG_OVERLAPPED and FILE_FLAG_NO_BUFFERING like so:

IXACTWaveBank* pStreamingWaveBank = NULL;

hFile = CreateFile( str, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
                    FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, NULL );

if( hFile != INVALID_HANDLE_VALUE )
{
    XACT_WAVEBANK_STREAMING_PARAMETERS wsParams;
    ZeroMemory( &wsParams, sizeof(XACT_WAVEBANK_STREAMING_PARAMETERS) );
    wsParams.file = hFile;
    wsParams.offset = 0;
    wsParams.packetSize = 64;

    hr = pEngine->CreateStreamingWaveBank( &wsParams, &pStreamingWaveBank );
}

The packetSize parameter specifies the how stream packet size in multiples of 2k bytes (the size of a DVD sector). So 64 equates to a stream packet size of 128k which equates approximately to a nice 6 seconds of stereo audio and will take better advantage of the drive's internal read cache than a smaller size. An optimal number to use for reading from a DVD is a multiple of DVD block size or 16 DVD sectors.

After creating a streaming wave bank, it can not be used by a cue until the streaming wave bank itself is prepared. XACT automatically prepares the wave bank, but time must be allowed for this process to happen. The application can tell when this is done by registering and handling the notification like so:

XACT_NOTIFICATION_DESCRIPTION desc = {0};
desc.flags = XACT_FLAG_NOTIFICATION_PERSIST;
desc.type = XACTNOTIFICATIONTYPE_WAVEBANKPREPARED;
pEngine->RegisterNotification(&desc);

And in the notification callback, handling it like this:

void WINAPI XACTNotificationCallback(const XACT_NOTIFICATION* pNotification)
{
    if( pNotification->type == XACTNOTIFICATIONTYPE_WAVEBANKPREPARED &&
        pNotification->waveBank.pWaveBank == g_pStreamingWaveBank )
    {
        // Respond to this notification outside of this callback so Prepare() can be called
        EnterCriticalSection( &g_cs );
        g_bHandleStreamingWaveBankPrepared = true;
        LeaveCriticalSection( &g_cs );
    }

}

Since IXACTSoundBank::Prepare is not allowed to be called from inside the callback, you must call it outside the callback like so:

EnterCriticalSection( &g_cs );
bool bHandleStreamingWaveBankPrepared = g_bHandleStreamingWaveBankPrepared;
LeaveCriticalSection( &g_cs );

if( bHandleStreamingWaveBankPrepared )
{
    EnterCriticalSection( &g_cs );
    g_bHandleStreamingWaveBankPrepared = false;
    LeaveCriticalSection( &g_cs );

    g_pSoundBank->Prepare( iCue, 0, &gpZeroLatencyRevCue );
}

Notice that you must use critical sections properly to make shared data thread safe while avoiding deadlocks. Some advice to follow is:

  • Use a specific critical section only to protect the specific shared data structures between the callback and the app thread.
  • Don't make any API calls while holding the critical section. Use it to access the shared data, make a local copy of the data, release the critical section and then make the API call.
  • Spend minimal amount of time in the critical section (to prevent the callback thread from waiting too long causing a glitch).

Instead of using a critical section, you can also use non-blocking queues to keep track of notifications, meaning that the callback will push, never pop, and the app thread will only pop, never push.

Playing a Cue that Uses Streamed Data

If you are not concerned about latency when playing a cue that references streamed wave data, playing the cue is no different than if it used in-memory wave data:

pSoundBank->Play( iCueIndex, 0, NULL );

However, if latency is important (such as with dialog or action sound effects) then XACT has a method for setting up zero-latency streaming. This is discussed next.

Zero-Latency Streaming

Zero-latency streaming sometimes called "primed streaming" allows a game to make use of large, high-quality wave banks, without crowding out other needs for memory while supporting smooth, uninterrupted playback by preparing the cue ahead of time.

This means that for each wave streamed by the prepared cue, XACT allocates a set of memory buffers that are considerably smaller than the total size of the file. XACT gives itself a head-start by loading a small portion of the wave file's beginning into the allocated memory; the rest remains on the storage disk. Once playback begins, XACT will continue to reload subsequent portions of the wave into the memory buffers as they become free. If the packet size buffer discussed earlier when the wave bank was created is appropriately sized, the inherent latency of the storage media will not interrupt playback.

Because zero-latency streaming requires additional setup by the programmer, the programmer and the audio designer need to work together to identify which cues (if any) could reference streaming wave data where latency should to be avoided.

To accomplish this zero-latency streaming technique, a 3 step process must be followed:

Step 1: Prepare the Cue

Some reasonable amount of time before the sound needs to play, the engine calls IXACTSoundBank::Prepare like so:

pSoundBank->Prepare( iZapCueIndex, 0, &pCue );

The engine needs to store the cue instance returned by IXACTSoundBank::Prepare as this is the only cue instance that will be prepared for zero-latency streaming.

Doing this prepare a fair amount of time before playback is essential because if a cue is not prepared and it is needed immediately then there is little that can be done other than simply calling IXACTSoundBank::Play or IXACTCue::Play which will cause the cue to be played immediately after it's prepared and will result in unseemly latency. However with good design and planning the cue can be prepared before it is needed.

For cues that reference in-memory waves, there will be no benefit nor any harm caused from calling IXACTSoundBank::Prepare first.

Step 2: Wait

After calling IXACTSoundBank::Prepare, some reasonable amount time must be allowed to pass while IXACTEngine::DoWork is called periodically. In other words, the cue will not become prepared unless IXACTEngine::DoWork is called regularly so do not busy loop, waiting for the cue to be prepared.

While waiting for the storage medium to seek to the data, the game should continue doing other tasks such as rendering or updating the game state.

If for your game needs to know needs to know when if the cue has been prepared, there are a few methods available. One method is to call IXACTCue::GetState on the cue and check for the _PREPARED state. Another, more preferred method is to register and handle the XACTNOTIFICATIONTYPE_CUEPREPARED notification:

XACT_NOTIFICATION_DESCRIPTION desc = {0};
desc.flags = XACT_FLAG_NOTIFICATION_PERSIST;
desc.type = XACTNOTIFICATIONTYPE_CUEPREPARED;
desc.cueIndex = XACTINDEX_INVALID;
pEngine->RegisterNotification(&desc);

One good reason to check state of the cue before playing is when syncing animation to a streaming sound - by waiting until the cue is prepared, the game can trigger both at the same time so they will remain in sync.

One quick note is that once a cue has been prepared it will never become un-prepared. The prepared buffers will remain in memory until you release the cue.

Step 3: Play the Cue Instance

After the first 2 steps and the cue is needed for immediate playback, simply call IXACTCue::Play on the cue instance returned by IXACTSoundBank::Prepare:

pCue->Play();

Note that you can only call IXACTCue::Play on this cue instance when it is the state of preparing or is prepared. The call will fail if the cue is already playing or stopped.

Conclusion

That's all there is to it. Identify which sounds if any should go into streaming wave banks, and which of those need to be zero latency. Then have the game do the proper setup work, and play away.


XACT API Variables Tutorial

This tutorial contains a brief introduction to using variables, categories, and RPCs within the Microsoft Cross-Platform Audio Creation Tool (XACT) engine.

Getting Started

The full working source code for this tutorial is in:

<Installed SDK Location>\Samples\C++\XACT\Tutorials\Tut03_Variable

Categories

XACT categories group XACT sounds into sets that can be adjusted as a whole. For example, all sounds of a specific category can paused or have their volume changed. All sounds belong to a root category called "Global" which can be used to control all of the sounds at once, but the sounds can also belong to sub-categories as defined by the XACT project. Typically, a game would create a "Music", "Sound FX", and "Dialog" category so all of these could be adjusted independently by the user.

Retrieving a category index is similar to retrieving a cue index. Just call IXACTEngine::GetCategory with the string name of the category and store the return value:

iMusicCategory = pXACTEngine->GetCategory( "Music" );
iGlobalCategory = pXACTEngine->GetCategory( "Global" );

For more information on categories, see Making XACT Categories.

Pausing and Resuming Sounds By Category

To pause all sounds of a specific category, simply call IXACTEngine::Pause like so:

pXACTEngine->Pause(  iMusicCategory, TRUE );

Controlling Sound Volume By Category

To adjust the volume of all sounds of a specific category, simple call IXACTEngine::SetVolume with the category index like so:

pXACTEngine->SetVolume( iGlobalCategory, fVolume );

The volume is a floating point scale where 0.0 means -96db, 1.0 means 0db, and 2.0 means +6db.

Variables

Variables are defined in an XACT project and are set by the game engine based on a game state, such as the RPM level of a car engine. The XACT project defines how this value, which is linked to a set of sounds, adjusts the sounds using a runtime parameter control (RPC). The RPC could change a sound pitch or volume based on the value of the variable. This allows the audio designer to have full control of how the sound responds to this floating point value.

Getting the index of a variable is similar to getting the index of a cue or category:

iVariable = pXACTEngine->GetGlobalVariableIndex( "RPM" );

Setting Variables

To change a global variable, call IXACTEngine::SetGlobalVariable like this:

pXACTEngine->SetGlobalVariable(  iVariable, nValue );

Where nValue could be any game state the audio designer and game programmer agree they need.


XACT Game Sample

A simple game that demonstrates how to integrate Direct3D with the Microsoft Cross-Platform Audio Creation Tool (XACT).

Sample Location

The full working source code for this tutorial is in:

<Installed SDK Location>\Samples\C++\XACT\XACTGame

Sample Description

This sample shows a simple XACT-based game that uses Direct3D graphics. The game plays background music, and it plays sound effects when bullets are fired, and when the bullets bounce around the environment and hit enemies.

This sample uses controls that are similar to a typical first-person shooter game. To see a specific controls list, compile and run the sample.


XACT Code-Driven API Sample

This sample demonstrates the XACT code-driven API by showing how to create and play sounds without authoring a wave bank with the Microsoft Cross-Platform Audio Creation Tool (XACT) tool.

Sample Location

The full working source code for this tutorial is in:

<Installed SDK Location>\Samples\C++\XACT\XACTCodeDriven

Sample Description

Here is a quick overview of the basic steps used by the sample:

  1. Initialize the XACT engine by calling IXACTEngine::Initialize. Here you can set some basic runtime parameters and set the notification callback.
  2. Create and play an in-memory IXACTWave.
    1. Read the raw PCM audio data from a wave file into memory.
    2. Initialize a WAVEBANKENTRY struct to match the properties of the wave file.
    3. Create an in-memory IXACTWave interface using wave file data by calling IXACTEngine::PrepareInMemoryWave
    4. Play wave by calling IXACTWave::Play.
    5. When the wave has stopped playing, free the memory.
  3. Create and play a streaming IXACTWave.
    1. Get a handle to a file containing the raw PCM audio data.
    2. Initialize a WAVEBANKENTRY struct to match the properties of the wave file.
    3. Initialize a XACT_STREAMING_PARAMETERS struct to match the properties of the wave file.
    4. Create an streaming IXACTWave interface using wave file data by calling IXACTEngine::PrepareStreamingWave.
    5. Wait until the IXACTWave has been prepared before playing it.
    6. Play wave by calling IXACTWave::Play.
    7. When the wave has stopped playing, close the file handle.
  4. Shut down the IXACTEngine.


DirectSound

This section provides information about using DirectSound to play and capture sounds in applications written in C and C++.

Information is presented in the following sections:

  • What's New in DirectSound. A guide to new features of DirectSound.
  • The Power of DirectSound. Information on the capabilities of the DirectSound system.
  • Programming Guide. A guide to using the DirectSound API. You'll probably want to familiarize yourself with the table of contents for this section, and then refer to parts of it as you need specific information. It should be used in conjunction with the reference section.
  • DirectSound Samples. A guide to the sample applications in the SDK, to point you to the sample code you need. As well as showing how to implement basic functionality, each sample demonstrates one or more particular features of DirectSound.
  • DirectSound Reference. Detailed information about all the API elements declared in Dsound.h.


What's New in DirectSound

The DirectSound application programming interface (API) has not been significantly revised for DirectX 9.0. However, many performance enhancements were implemented for the Summer 2004 Update (DirectX 9.0c).

In addition, the following changes have been made:

  • The maximum frequency of sound buffers has been increased from 100 kHz to 200 kHz, where supported by the operating system. (These higher frequencies are not supported by DirectShow.)
  • Frequency and effects controls (DSBCAPS_CTRLFREQUENCY and DSBCAPS_CRTLFX) can now be combined on buffers. Combining these flags makes it possible to have Doppler shift on buffers with effects.
  • Audio formats described by the WAVEFORMATEXTENSIBLE structure are fully supported throughout DirectSound.
  • The standard effects support parameter curves (when hosted outside of DirectSound) without having to call IMediaObjectInPlace::Process on them repeatedly in very small increments.

With the DirectX SDK December 2004 release, the StreamData sample has been removed.

Windows XP SP 2

For Windows XP SP 2, Windows Server 2003 SP1, and Windows XP Pro x64 Edition, speaker configuration was expanded. DSSPEAKER_7POINT1 is now DSSPEAKER_7POINT1_WIDE and a new configuration DSSPEAKER_7POINT1_SURROUND was added.

Windows Vista

The following changes were made for the Windows Vista version of the DirectSound API to reflect the features of the new audio driver stack:

  • Software (DSBCAPS_LOCSOFTWARE) buffers support multichannel audio on Windows Vista.
  • Hardware (DSBCAPS_LOCHARDWARE) buffers always fail to create on Windows Vista.
  • DSSPEAKER_5POINT1 is now DSSPEAKER_5POINT1_BACK and a new configuration DSSPEAKER_5POINT1_SURROUND was added. For a complete list, see speaker configurations in IDirectSound8::SetSpeakerConfig.


The Power of DirectSound

DirectSound enables the playing of sounds with very low latency and gives applications a high level of control over hardware resources.

By using the DirectSound interfaces in your application, you can do the following:

  • Play sounds from files or resources in WAV format.
  • Play multiple sounds simultaneously.
  • Assign high-priority sounds to hardware-controlled buffers.
  • Locate sounds in a customizable 3D environment.
  • Add effects such as echo and chorus, and change effect parameters dynamically.
  • Capture WAV sounds from a microphone or other input.

DirectSound works on Microsoft Windows 98, Microsoft Windows 2000, and later operating systems. Some functionality, chiefly capture effects, is available only on Microsoft Windows XP and later.


Programming Guide

This section is a guide to using the DirectSound application programming interface (API) in application development.

Information is presented in the following topics:

  • DirectSound Playback Objects
  • DirectSound Devices
  • DirectSound Buffers
  • Using WAV Data
  • 3D Sound
  • Using Effects
  • Capturing Waveforms

See Also

  • Introduction to DirectSound
  • Advanced Topics in DirectSound
  • DirectSound C/C++ Reference


Getting Started with DirectSound

This section gives information on setting up and debugging DirectSound projects, as well as a brief overview of the programming steps required to play a sound.

More information on getting started is included in the following topics:

  • Building DirectSound Projects
  • Debugging DirectSound Projects
  • Adjusting DirectSound Acceleration for Testing
  • First Steps in DirectSound Programming


Building DirectSound Projects

Projects need to include the Dsound.h header file. If you are using DirectSound in conjunction with DirectMusic, this header is included when you include Dmusici.h.

If you are using the DirectSound API directly and want to be able to use helper functions such as DirectSoundCreate8, be sure to link to Dsound.lib and include the appropriate folder in the library search path.

You must also ensure that your application has access to the GUIDs used by DirectSound. Define INITGUID before all other preprocessor directives, or link to Dxguid.lib.


Debugging DirectSound Projects

The DirectSound dynamic-link library (DLL) installed with the debug version of the DirectX software development kit generates information in the debug output window as the application is running.

To access DirectSound debugging support, download the DirectX SDK Extras folder and copy the following debug files to your applications working directory:

  • ...\Extras\DirectSound\debug\x86\Dsound.dll

    or

    ...\Extras\DirectSound\debug\x64\Dsound.dll

  • ...\Extras\Symbols\Debug\x86\dll\Dsound.pdb

    or

    ...\Extras\Symbols\Debug\x64\dll\Dsound.pdb

Using the DirectX Properties Control Panel, select the Audio tab and set the desired debugging level using the Debug Output Level slider control.

You can set the debug level within the range of 0 to 5. A setting of 0 produces no debugging information, and 5 produces the most detail. For most purposes it is unnecessary to set the level higher than 2; output at higher levels does not pertain to errors or warnings but is purely informational.


Adjusting DirectSound Acceleration for Testing

By using the Sounds and Audio Devices page in Control Panel, you can adjust the performance of DirectSound on the system. Click the Advanced button in the Sound Playback group on the Audio tab. In the Advanced Audio Properties dialog box, choose the Performance tab. A slider lets you adjust hardware acceleration to one of the following settings:

Full
Enables complete DirectSound acceleration, including the enabling of IKsPropertySet extensions.
Standard
Enables acceleration of DirectSound secondary buffers, but disables any hardware-specific IKsPropertySet extensions. This is the default setting on Windows 2000.
Basic
Disables hardware acceleration of DirectSound secondary buffers. This option is useful if you want to emulate a nonaccelerated sound card for testing purposes.
Emulation
Forces DirectSound into emulation mode, where it acts as if there is no DirectSound-compatible driver on the system. All mixing is done by DirectSound in user mode, and the resulting data is sent to the Win32 waveform-audio functions. This typically results in a large increase in latency.


First Steps in DirectSound Programming

This topic provides a brief overview of the steps you must take to play a sound by using the DirectSound API. For details, see Using DirectSound.

Playing a short sound requires the following steps:

Call DirectSoundCreate8 to create an object that supports the IDirectSound8 interface. This object usually represents the default playback device. Optionally, you can first enumerate available devices to obtain the GUID of the device you want to use, and pass this to DirectSoundCreate8.

DirectSound is based on the Component Object Model (COM). However, you do not have to initialize COM explicitly unless you are using effect DMOs.

2. Create a secondary buffer

Use IDirectSound8::CreateSoundBuffer to create a buffer object that will contain sound data. Such buffers are called secondary buffers, to distinguish them from the primary buffer, which is the object that mixes all sounds.

3. Obtain PCM data

Read data from a WAV file or resource into a private buffer. The DirectX SDK contains sample code that you can use to do this.

4. Put data in the buffer

Prepare the secondary buffer for a write operation by calling IDirectSoundBuffer8::Lock. In most cases, this method returns a single memory address. Copy data from your private buffer to that address, and then call IDirectSoundBuffer8::Unlock.

5. Play the buffer

Play the sound by calling IDirectSoundBuffer8::Play. You can instruct the buffer either to stop when it reaches the end, or to continue playing over and over again until you call IDirectSoundBuffer8::Stop. You can start and stop the buffer repeatedly; however, only one instance of the sound can play at one time, unless you create other buffers containing the same data. Any number of buffers can be played at a given time, and mixing is done automatically.

The preceding steps apply to the simplest possible scenario, that of a short sound that fits into a buffer of a reasonable size. Typically, sounds that last more than a few seconds are streamed: that is, data that has already been played is periodically replaced by new data.

Sample code distributed with the SDK shows how to perform many common tasks using DirectSound. For more information, see DirectSound C++ Samples.


DirectSound Playback Objects

The following objects are used in playing sounds:

Object | Number | Purpose | Main interfaces
Device | One in each application | Manages the device and creates sound buffers. | IDirectSound8
Secondary buffer | One for each sound | Manages a static or streaming sound and plays it into the primary buffer. | IDirectSoundBuffer8, IDirectSound3DBuffer8, IDirectSoundNotify8
Primary buffer | One in each application | Mixes and plays sounds from secondary buffers, and controls global 3D parameters. | IDirectSoundBuffer, IDirectSound3DListener8
Effect | Zero or more for each secondary buffer | Transforms the sound in a secondary buffer. | Interface for the particular effect, such as IDirectSoundFXChorus8

The first step in implementing DirectSound in an application is to create a device object, which represents the rendering device. This object is then used to create buffers.

Note DirectSound is based on the Component Object Model (COM). However, you do not have to initialize COM explicitly, by calling CoInitialize or CoInitializeEx, unless you are using effect DMOs.

Secondary buffers are created and managed by the application. DirectSound automatically creates and manages the primary buffer, and an application can play sounds without obtaining an interface to this object. However, in order to obtain the IDirectSound3DListener8 interface, the application must explicitly create a primary buffer object.

When sounds in secondary buffers are played, DirectSound mixes them in the primary buffer and sends them to the rendering device. Only the available processing time limits the number of buffers that DirectSound can mix.

Note Under the Windows driver model (WDM), mixing is done by the kernel mixer, and the primary buffer does not actually contain any data. For more information, see DirectSound Driver Models.

A short sound can be loaded into a secondary buffer in its entirety and played at any time by a simple method call. Longer sounds have to be streamed. An application can ascertain when it is time to stream more data into the buffer either by polling the position of the play cursor or by requesting notification when the play cursor reaches certain points.

Secondary buffers can contain effects such as chorus and echo. They can also have 3D control capabilities. Global 3D parameters are controlled by the IDirectSound3DListener8 interface on the primary buffer.


DirectSound Devices

The DirectSound device object represents a rendering device and is used to manage the device and to create sound buffers.

Multiple applications can create objects for the same sound device. When the input focus changes between applications, the audio output automatically switches from one application's streams to the other's. As a result, applications do not have to repeatedly play and stop their buffers when the input focus changes.

This section describes how your application can enumerate available sound devices, create the device object, and use the IDirectSound8 methods of the object to manage the device. The following topics are covered:

  • Enumerating Sound Devices
  • Creating the Device Object
  • Normal Cooperative Levels
  • Device Capabilities
  • Speaker Configuration


Enumerating Sound Devices

If your application is simply going to play sounds through the user's preferred playback device, there is no need to enumerate the available devices. When you create the device object by calling the DirectSoundCreate8 function, you can specify a default device. For more information, see Creating the Device Object.

Enumeration is necessary in the following situations:

  • Your application needs capabilities that may not be available on all devices.
  • Your application requires two or more devices.
  • You wish to offer the user a choice of devices.

Enumeration serves three purposes:

  • It reports what hardware is available.
  • It supplies a GUID for each device.
  • It enables you to create a temporary device object for each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices, you must first set up a callback function that will be called once for each device on the system. You can do anything you want within this function, and you can give it any name, but you must declare it in the same form as the DSEnumCallback prototype. The callback function must return TRUE if enumeration is to continue, or FALSE otherwise - for instance, after finding a device with the capabilities you need.

The following callback function adds the name of each enumerated device to a combo box and stores its GUID as the item data. Values for the first three parameters are supplied by the device driver. The fourth parameter is passed on from the DirectSoundEnumerate function; this parameter can be used to pass any 32-bit value, and in this case is the window handle of the combo box. Macros defined in Windowsx.h are used to add strings and data to the combo box.

    BOOL CALLBACK DSEnumProc(LPGUID lpGUID,
             LPCTSTR lpszDesc,
             LPCTSTR lpszDrvName,
             LPVOID lpContext )
    {
      HWND hCombo = (HWND)lpContext;
      LPGUID lpTemp = NULL;

      if (lpGUID != NULL)  //  NULL only for "Primary Sound Driver".
      {
        if ((lpTemp = (LPGUID)malloc(sizeof(GUID))) == NULL)
        {
            return(TRUE);
        }
        memcpy(lpTemp, lpGUID, sizeof(GUID));
      }

      ComboBox_AddString(hCombo, lpszDesc);
      ComboBox_SetItemData(hCombo,
          ComboBox_FindString(hCombo, 0, lpszDesc),
          lpTemp );
      free(lpTemp);
      return(TRUE);
    }

The enumeration is set in motion when the dialog box containing the combo box is initialized. Assume that hCombo is the handle of the combo box and hDlg is the handle of the dialog box.

    if (FAILED(DirectSoundEnumerate((LPDSENUMCALLBACK)DSEnumProc,
        (VOID*)&hCombo)))
    {
      EndDialog(hDlg, TRUE);
      return(TRUE);
    }

In this case, the address of the combo box handle is passed into DirectSoundEnumerate, which in turn passes it to the callback function. This parameter can be any 32-bit value that you want to have access to within the callback.

The first device enumerated is always called the Primary Sound Driver, and the lpGUID parameter of the callback is NULL. This device represents the preferred playback device set by the user in Control Panel. It is enumerated separately to make it easy for the application to add "Primary Sound Driver" to a list when presenting the user with a choice of devices. The primary device is also enumerated with its proper name and GUID.


Creating the Device Object

The simplest way to create the device object is by using the DirectSoundCreate8 function. The first parameter of this function specifies the GUID of the device to be associated with the object. You can obtain this GUID by enumerating devices, or you can pass one of the following GUIDs to specify a default device:

GUID definition | Description
DSDEVID_DefaultPlayback | The default system audio device. You can also specify this device by passing a NULL pointer in the device GUID parameter. The default device is the one enumerated as "Primary DirectSound Driver".
DSDEVID_DefaultVoicePlayback | The default voice communications device. Typically this is a secondary device such as a USB headset with microphone.

If no device driver is present, the call to DirectSoundCreate8 fails.

The function returns an error if there is no sound device or, under VXD drivers, if the sound device is under the control of an application using the standard Win32 waveform-audio functions. You should prepare your applications for this call to fail so that they can either continue without sound or prompt the user to close the application that is already using the sound device.

The following code creates an object for the default device and obtains the IDirectSound8 interface:

LPDIRECTSOUND8 lpds;
HRESULT hr = DirectSoundCreate8(NULL, &lpds, NULL));

If your application will capture sounds as well as play them, you can conveniently create both rendering and capture devices, as well as playback and capture buffers, by using the DirectSoundFullDuplexCreate8 function.

You can also create the device object by using standard COM functions, as follows.

  1. Initialize COM at the start of your application by calling CoInitializeEx.
        HRESULT hr = CoInitializeEx(NULL, 0);
    if (FAILED(hr))
    {
      ErrorHandler(hr);  // Add error-handling here.
    }
  2. Create the device object by using CoCreateInstance and the IDirectSound8::Initialize method, rather than the DirectSoundCreate8 function.
        LPDIRECTSOUND8 lpds;
    hr = CoCreateInstance(&CLSID_DirectSound8,
              NULL,
              CLSCTX_INPROC_SERVER,
              IID_IDirectSound8,
              (LPVOID*) &lpds);
    if (FAILED(hr))
    {
      ErrorHandler(hr);  // Add error-handling here.
    }

    CLSID_DirectSound8 is the class identifier of the DirectSound driver object class and IID_IDirectSound8 is the interface identifier. The lpds parameter receives the interface pointer.

  3. Call the IDirectSound8::Initialize method to associate the object with a device. This method takes the same device GUID parameter that DirectSoundCreate8 uses.
        hr = lpds->Initialize(NULL);
    if (FAILED(hr))
    {
      ErrorHandler(hr);  // Add error-handling here.
    }
  4. Before you close the application, close the COM library by calling the CoUninitialize function, as follows:
        CoUninitialize();


Cooperative Levels

Because Windows is a multitasking environment, more than one application can be working with a device driver at any one time. Through the use of cooperative levels, DirectX makes sure that each application does not gain access to the device in the wrong way or at the wrong time. Each DirectSound application has a cooperative level that determines the extent to which it is allowed to access the device.

After creating a device object, you must set the cooperative level for the device by using the IDirectSound8::SetCooperativeLevel method. Unless you do this, no sounds will be heard.

The following example sets the cooperative level for the DirectSound device represented by the IDirectSound8 interface at lpDirectSound. The hwnd parameter is the handle to the application window.

HRESULT hr = lpDirectSound->SetCooperativeLevel(hwnd, DSSCL_PRIORITY);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}

DirectSound defines three cooperative levels for sound devices, specified by the values DSSCL_NORMAL, DSSCL_PRIORITY, and DSSCL_WRITEPRIMARY. These levels are explained in the following topics:

  • Normal Cooperative Level
  • Priority Cooperative Level
  • Write-primary Cooperative Level

Note The DSSCL_EXCLUSIVE cooperative level is obsolete. It is no longer possible for a DirectX application to mute other applications. Applications that request the exclusive level are granted the priority level instead.


Normal Cooperative Level

At the normal cooperative level (DSSCL_NORMAL), the application cannot set the format of the primary buffer or write to the primary buffer. All applications at this cooperative level use a primary buffer format of 22 kHz, stereo sound, and 8-bit samples, so that the device can switch between applications as smoothly as possible.


Priority Cooperative Level

When using a DirectSound device with the priority cooperative level (DSSCL_PRIORITY), the application has first rights to hardware resources, such as hardware mixing, and can set the format of the primary sound buffer.

Game applications should use the priority cooperative level in almost all circumstances. This level gives the most robust behavior while allowing the application control over sampling rate and bit depth. The priority cooperative level also allows audio from other applications, such as IP telephony, to be heard along with the audio from the game.


Write-primary Cooperative Level

The highest cooperative level is write-primary (DSSCL_WRITEPRIMARY). When using a DirectSound device with this cooperative level, your application has direct access to the primary sound buffer on non-WDM drivers. In this mode, the application must write directly to the primary buffer. Secondary buffers cannot be played while this is happening.

An application must be set to the write-primary level in order to obtain direct write access to the audio samples in the primary buffer. If the application is not set to this level, then all calls to the IDirectSoundBuffer::Lock method on the primary buffer will fail.

When your application is set to the write-primary cooperative level and gains the foreground, all secondary buffers for other applications are stopped and marked as lost. When your application in turn moves to the background, its primary buffer is marked as lost and must be restored when the application again moves to the foreground. For more information, see Buffer Management.

You cannot set the write-primary cooperative level if a DirectSound driver is not present on the user's system. To determine whether this is the case, call the IDirectSound8::GetCaps method and check for the DSCAPS_EMULDRIVER flag in the DSCAPS structure.

See Also

  • Writing to the Primary Buffer


Device Capabilities

DirectSound enables your application to examine the hardware capabilities of the sound device. Many applications do not need to do this, because DirectSound automatically takes advantage of any available hardware acceleration. However, high-performance applications can use the information to scale their sound requirements to the available hardware. For example, an application might choose to play more sounds if hardware mixing is available than if it is not.

After calling the DirectSoundCreate8 function to create a device object, your application can retrieve the capabilities of the sound device by calling the IDirectSound8::GetCaps method.

The following example retrieves the capabilities of the device represented by the IDirectSound8 interface pointer lpDirectSound:

DSCAPS dscaps;

dscaps.dwSize = sizeof(DSCAPS);
HRESULT hr = lpDirectSound->GetCaps(&dscaps);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}

The DSCAPS structure receives information about the performance and resources of the sound device, including the maximum resources of each type and the resources that are currently available. Note that the dwSize member of this structure must be initialized before the method is called.

If your application scales to hardware capabilities, you should call the IDirectSound8::GetCaps method between every buffer allocation to determine if there are enough resources to create the next buffer.


Speaker Configuration

DirectSound uses the speaker configuration - that is, the position of the speakers relative to the listener - to optimize 3D effects for the user's sound system.

In Windows 98, Windows 2000, and later operating systems, the speaker configuration can be set by the user in Control Panel. An application can retrieve this value by using IDirectSound8::GetSpeakerConfig. Applications should not override the setting by calling IDirectSound8::SetSpeakerConfig, as this is a global setting that affects other users and applications.


Buffer Basics

DirectSound buffer objects control the delivery of waveform data from a source to a destination. The source might be a synthesizer, another buffer, a WAV file, or a resource. For most buffers, the destination is a mixing engine called the primary buffer. From the primary buffer, the data goes to the hardware that converts the samples to sound waves.

Information about using DirectSound buffers is contained in the following topics:

  • Creating Secondary Buffers
  • Duplicating Buffers
  • Buffer Control Options
  • Algorithms for Buffers
  • Filling and Playing Static Buffers
  • Using Streaming Buffers
  • Playback Controls
  • Play and Write Cursors
  • Play Buffer Notification
  • Mixing Sounds
  • Looping Sounds
  • Buffer Management

For information about capture buffers, see Capturing Waveforms.

Your application must create at least one secondary sound buffer for storing and playing individual sounds.

A secondary buffer can exist throughout the life of an application, or it can be destroyed when no longer needed. It can be a static buffer that contains a single short sound, or a streaming buffer that is refreshed with new data as it plays. To limit demands on memory, long sounds should be played through streaming buffers that hold no more than a few seconds of data.

You mix sounds from different secondary buffers simply by playing them at the same time. Any number of secondary buffers can be played at one time, up to the limits of available processing power.

Secondary buffers are not all created alike. Characteristics of buffers include the following:

  • Format. The format of a buffer must match the format of the waveform data it plays.
  • Controls. Different buffers can have different controls, such as volume, frequency, and movement in two or three dimensions. When creating a buffer, you should specify only the controls you need; for example, don't create a 3D buffer for a sound that isn't in a 3D environment.
  • Location. A buffer can be in memory managed by hardware, or in memory managed by software. Hardware buffers are more efficient but limited in number. Hardware buffers are not supported in 64-bit operating systems.

See Also

  • DSBUFFERDESC


Creating Secondary Buffers

To create a buffer, call the IDirectSound8::CreateSoundBuffer method. This method returns a pointer to an IDirectSoundBuffer interface, from which the application can obtain an IDirectSoundBuffer8 interface.

The following example function creates a secondary sound buffer and returns the IDirectSoundBuffer8 interface.

HRESULT CreateBasicBuffer(LPDIRECTSOUND8 lpDirectSound, LPDIRECTSOUNDBUFFER8* ppDsb8)
{
  WAVEFORMATEX wfx;
  DSBUFFERDESC dsbdesc;
  LPDIRECTSOUNDBUFFER pDsb = NULL;
  HRESULT hr;

  // Set up WAV format structure.

  memset(&wfx, 0, sizeof(WAVEFORMATEX));
  wfx.wFormatTag = WAVE_FORMAT_PCM;
  wfx.nChannels = 2;
  wfx.nSamplesPerSec = 22050;
  wfx.nBlockAlign = 4;
  wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
  wfx.wBitsPerSample = 16;

  // Set up DSBUFFERDESC structure.

  memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
  dsbdesc.dwSize = sizeof(DSBUFFERDESC);
  dsbdesc.dwFlags =
    DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY
    | DSBCAPS_GLOBALFOCUS;
  dsbdesc.dwBufferBytes = 3 * wfx.nAvgBytesPerSec;
  dsbdesc.lpwfxFormat = &wfx;

  // Create buffer.

  hr = lpDirectSound->CreateSoundBuffer(&dsbdesc, &pDsb, NULL);
  if (SUCCEEDED(hr))
  {
     hr = pDsb->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*) ppDsb8);
     pDsb->Release();
  }
  return hr;
}

The example function creates a streaming buffer large enough to hold 3 seconds of streaming data. Nonstreaming buffers should be made just large enough to accommodate the entire sound.

The DSBCAPS_GLOBALFOCUS flag in the example ensures that the buffer will continue playing even when the application window is not in the foreground. Without this flag, the buffer will be muted when another application or even a dialog box has the input focus.

If the location of a buffer is not specified, DirectSound places it in hardware-controlled memory if possible. Because hardware buffers are mixed by the sound card processor, they have much less impact on application performance.

If you wish to specify the location of a buffer rather than letting DirectSound decide where it belongs, set either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag in the DSBUFFERDESC structure. If the DSBCAPS_LOCHARDWARE flag is set and there are insufficient hardware resources, the buffer creation request fails.

To take advantage of the voice management features of DirectSound, specify the DSBCAPS_LOCDEFER flag when creating the buffer. This flag defers the allocation of resources for the buffer until it is played. For more information, see Dynamic Voice Management.

You can ascertain the location of an existing buffer by using the IDirectSoundBuffer8::GetCaps method and checking the dwFlags member of the DSBCAPS structure for either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flags. One or the other is always specified.

Buffer objects are owned by the device object that created them. When the device object is released, all buffers created by that object are also released and should not be referenced.


Duplicating Buffers

You can create two or more secondary buffers containing the same data by using the IDirectSound8::DuplicateSoundBuffer method. You cannot duplicate the primary sound buffer. Because the duplicate buffer shares memory with the original buffer, changes to the data of one buffer will be reflected in duplicate buffers.


Buffer Control Options

When creating a sound buffer, your application must specify the control options needed for that buffer. This is done with the dwFlags member of the DSBUFFERDESC structure, which can contain one or more of the flags in the following table.

Flag | Description
DSBCAPS_CTRL3D | The sound source can be moved in 3D space.
DSBCAPS_CTRLFX | Effects can be added to the buffer.
DSBCAPS_CTRLFREQUENCY | The frequency of the sound can be changed.
DSBCAPS_CTRLPAN | The sound source can be moved from left to right.
DSBCAPS_CTRLPOSITIONNOTIFY | Notification positions can be set on the buffer.
DSBCAPS_CTRLVOLUME | The volume of the sound can be changed.

Note that certain combinations of controls are not allowed. For more information, see DSBUFFERDESC.

To obtain the best performance on all sound cards, your application should specify only control options it will use.

DirectSound uses the control options in determining whether hardware resources can be allocated to sound buffers. For example, a device might support hardware buffers but provide no pan control on those buffers. In this case, DirectSound would use hardware acceleration only if the DSBCAPS_CTRLPAN flag was not specified.

If your application attempts to use a control that a buffer lacks, the method call fails. For example, if you attempt to change the volume by using the IDirectSoundBuffer8::SetVolume method, the method can succeed only if the DSBCAPS_CTRLVOLUME flag was specified when the buffer was created. Otherwise the method fails and returns the DSERR_CONTROLUNAVAIL error code.

See Also

Playback Controls


Algorithms for Buffers

When you create a secondary buffer with the DSBCAPS_CTRL3D control flag, you can also specify an algorithm to be used in spatializing the sound if the buffer is in software. By default, no head-related transfer function (HRTF) processing is performed, and the location of the sound relative to the listener is indicated by panning and volume only. You can request two levels of HRTF for the buffer.

For more information, see DSBUFFERDESC.


Filling and Playing Static Buffers

A secondary buffer that contains an entire self-contained sound is called a static buffer. Although it is possible to reuse the same buffer for different sounds, typically data is written to a static buffer only once.

Static buffers are created and managed just like streaming buffers. The only difference is in the way they are used: static buffers are filled once and then played, but streaming buffers are constantly refreshed with data as they are playing.

Note A static buffer is not necessarily one created by setting the DSBCAPS_STATIC flag in the buffer description. This flag requests allocation of memory on the sound card, which is not available on most modern hardware. A static buffer can exist in system memory and can be created with either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag.

Loading data into a static buffer is a three-step process:

  1. Lock the entire buffer by using IDirectSoundBuffer8::Lock. You specify the offset within the buffer where you intend to begin writing (normally 0), and get back the memory address of that point.
  2. Write the audio data to the returned address by using a standard memory-copy routine.
  3. Unlock the buffer using IDirectSoundBuffer8::Unlock.

These steps are shown in the following example, where lpdsbStatic is an IDirectSoundBuffer8 interface pointer and pbData is the address of the data source:

LPVOID lpvWrite;
DWORD  dwLength;

if (DS_OK == lpdsbStatic->Lock(
      0,          // Offset at which to start lock.
      0,          // Size of lock; ignored because of flag.
      &lpvWrite,  // Gets address of first part of lock.
      &dwLength,  // Gets size of first part of lock.
      NULL,       // Address of wraparound not needed.
      NULL,       // Size of wraparound not needed.
      DSBLOCK_ENTIREBUFFER))  // Flag.
{
  memcpy(lpvWrite, pbData, dwLength);
  lpdsbStatic->Unlock(
      lpvWrite,   // Address of lock start.
      dwLength,   // Size of lock.
      NULL,       // No wraparound portion.
      0);         // No wraparound size.
}
else
(
  ErrorHandler();  // Add error-handling here.
}

To play the buffer, call IDirectSoundBuffer8::Play, as in the following example:

lpdsbStatic->SetCurrentPosition(0);
HRESULT hr = lpdsbStatic->Play(
    0,  // Unused.
    0,  // Priority for voice management.
    0); // Flags.
if (FAILED(hr))
(
  ErrorHandler();  // Add error-handling here.
}

Because the DSBPLAY_LOOPING flag is not set in the example, the buffer automatically stops when it reaches the end. You can also stop it prematurely by using IDirectSoundBuffer8::Stop. When you stop a buffer prematurely, the play cursor position remains where it is. Hence the call to IDirectSoundBuffer8::SetCurrentPosition in the example, which ensures that the buffer starts from the beginning.


Using Streaming Buffers

A streaming buffer plays a long sound that cannot all fit into the buffer at once. As the buffer plays, old data is periodically replaced with new data.

To play a streaming buffer, call the IDirectSoundBuffer8::Play method, specifying DSBPLAY_LOOPING in the dwFlags parameter.

To halt playback, call the IDirectSoundBuffer8::Stop method. This method stops the buffer immediately, so you need to be sure that all data has been played. This can be done by polling the play position or by setting a notification position.

Streaming into a buffer requires the following steps:

  1. Ascertain whether the buffer is ready to receive new data. This can be done either by polling the play cursor or by waiting for a notification.
  2. Lock a portion of the buffer by using IDirectSoundBuffer8::Lock. This method returns one or two addresses where data can now be written.
  3. Write the audio data to the returned address or addresses by using a standard memory-copy routine.
  4. Unlock the buffer using IDirectSoundBuffer8::Unlock.

The reason IDirectSoundBuffer8::Lock might return two addresses is that you can lock any number of bytes, up to the size of the buffer, regardless of the start point. If necessary, the locked portion wraps around to the beginning of the buffer. If it does, you have to perform two separate memory copies.

For example, say you lock 30,000 bytes beginning at offset 20,000 in a 40,000-byte buffer. When you call Lock in this case, it returns four values:

  • The memory address of offset 20,000.
  • The number of bytes locked from that point to the end of the buffer; that is, 20,000 bytes. You write this number of bytes to the first address.
  • The memory address of offset 0.
  • The number of bytes locked from that point; that is, 10,000 bytes. You write this number of bytes to the second address.

If no wraparound is necessary, the last two values are NULL and 0 respectively.

Although it's possible to lock the entire buffer, you must not do so while it is playing. Normally you refresh only a fraction of the buffer each time. For example, you might lock and write to the first quarter of the buffer as soon as the play cursor reaches the second quarter, and so on. You must never write to the part of the buffer that lies between the play cursor and the write cursor.

The following function writes data to a sound buffer, starting at the position passed in dwOffset:

    BOOL AppWriteDataToBuffer(
        LPDIRECTSOUNDBUFFER8 lpDsb,  // The buffer.
        DWORD dwOffset,              // Our own write cursor.
        LPBYTE lpbSoundData,         // Start of our data.
        DWORD dwSoundBytes)          // Size of block to copy.
    {
      LPVOID  lpvPtr1;
      DWORD dwBytes1;
      LPVOID  lpvPtr2;
      DWORD dwBytes2;
      HRESULT hr;

      // Obtain memory address of write block. This will be in two parts
      // if the block wraps around.

      hr = lpDsb->Lock(dwOffset, dwSoundBytes, &lpvPtr1,
          &dwBytes1, &lpvPtr2, &dwBytes2, 0);

      // If the buffer was lost, restore and retry lock.

      if (DSERR_BUFFERLOST == hr)
      {
        lpDsb->Restore();
        hr = lpDsb->Lock(dwOffset, dwSoundBytes,
            &lpvPtr1, &dwBytes1,
            &lpvPtr2, &dwBytes2, 0);
      }
      if (SUCCEEDED(hr))
      {
        // Write to pointers.

        CopyMemory(lpvPtr1, lpbSoundData, dwBytes1);
        if (NULL != lpvPtr2)
        {
          CopyMemory(lpvPtr2, lpbSoundData+dwBytes1, dwBytes2);
        }

        // Release the data back to DirectSound.

        hr = lpDsb->Unlock(lpvPtr1, dwBytes1, lpvPtr2,
        dwBytes2);
        if (SUCCEEDED(hr))
        {
          // Success.
          return TRUE;
        }
      }

      // Lock, Unlock, or Restore failed.

      return FALSE;
    }

See Also

  • Play and Write Cursors
  • Play Buffer Notification
  • Reading WAV Data
  • Using Buffers Efficiently


Playback Controls

To retrieve and set the volume at which a buffer is played, your application can use the IDirectSoundBuffer8::GetVolume and IDirectSoundBuffer8::SetVolume methods. Setting the volume on the primary buffer changes the waveform-audio volume of the sound card. Volume is measured as hundredths of decibels (dB) of attenuation; it is not possible to amplify the default volume. Note that the decibel scale is not linear; a reduction in volume of 3 dB is equivalent to a halving of the sound energy, and sounds generally become inaudible long before the maximum attenuation of 100 dB is reached.

By calling the IDirectSoundBuffer8::GetFrequency and IDirectSoundBuffer8::SetFrequency methods, you can retrieve and set the frequency at which audio samples play. You cannot change the frequency of the primary buffer.

To retrieve and set the position of the sound source on the left-right axis, you can call the IDirectSoundBuffer8::GetPan and IDirectSoundBuffer8::SetPan methods. Buffers with 3D capabilities cannot be panned.

In order to use any of these controls, you must set the appropriate flags when creating the buffer. See Buffer Control Options.


Play and Write Cursors

DirectSound maintains two pointers into the buffer: the play cursor and the write cursor. These positions are byte offsets into the buffer, not absolute memory addresses.

The IDirectSoundBuffer8::Play method always starts playing at the position of the play cursor. When a buffer is created, the play cursor is set to 0. As the buffer is played, the cursor moves and always points to the next byte of data to be played. When the buffer is stopped, the cursor remains where it is.

The write cursor is the point after which it is safe to write data into the buffer. The block between the play cursor and the write cursor is already committed to be played, and cannot be changed safely.

You might visualize the buffer as a clock face, with data written to it in a clockwise direction. The play cursor and the write cursor are like two hands sweeping around the face at the same speed, the write cursor always keeping a little ahead of the play cursor. If the play cursor points to the 1 and the write cursor points to the 2, it is only safe to write data after the 2. Data between the 1 and the 2 may already have been queued for playback by DirectSound and should not be touched.

The write cursor moves with the play cursor, not with data written to the buffer. If you're streaming data, you are responsible for maintaining your own pointer into the buffer to indicate where the next block of data should be written.

An application can retrieve the play and write cursors by calling the IDirectSoundBuffer8::GetCurrentPosition method. The IDirectSoundBuffer8::SetCurrentPosition method lets you move the play cursor. Applications do not control the position of the write cursor.

To ensure that the play cursor is reported as accurately as possible, always specify the DSBCAPS_GETCURRENTPOSITION2 flag when creating a secondary buffer. For more information, see DSBUFFERDESC.


Play Buffer Notification

DirectSound can notify your application when the play cursor reaches certain points in a buffer, or when the buffer stops. This can be useful in two common situations:

  • The application must take some action, such as playing another buffer, when a sound has finished playing.
  • The application is streaming data to the buffer, and needs to know when the play cursor reaches predefined points so that data that has been played can be replaced by new data.

If you are taking advantage of voice management, it's possible that a buffer could be terminated before a notification position is reached. See the Remarks for DSBPOSITIONNOTIFY.

Using the IDirectSoundNotify8::SetNotificationPositions method, you can set any number of points within the buffer where events are to be signaled. You cannot do this while the buffer is playing.

First you obtain a pointer to the IDirectSoundNotify8 interface. You can do this by using the buffer object's QueryInterface method. A separate interface must be obtained from each buffer on which you want to set notifications.

For each notification position, create an event object with the Win32 CreateEvent function. Put the handle to this event in the hEventNotify member of a DSBPOSITIONNOTIFY structure. In the dwOffset member of that structure, specify the offset within the buffer where you want the event to be signaled. Then pass the address of the structure-or of an array of structures, if you want to set more than one notification position-to SetNotificationPositions.

The following example function sets a single notification position. The event will be signaled when playback stops, either because the end of a nonlooping buffer has been reached, or because the application called the IDirectSoundBuffer8::Stop method. Assume that hMyEvent is a handle returned by CreateEvent and that lpDsbSecondary is a secondary buffer created with the DSBCAPS_CTRLPOSITIONNOTIFY flag.

HRESULT SetStopNotification(HANDLE hMyEvent,
        LPDIRECTSOUNDBUFFER8 lpDsbSecondary)
{
  LPDIRECTSOUNDNOTIFY8 lpDsNotify;
  DSBPOSITIONNOTIFY PositionNotify;
  HRESULT hr;

  if (SUCCEEDED(
      hr = lpDsbSecondary->QueryInterface(IID_IDirectSoundNotify8,
             (LPVOID*)&lpDsNotify)))
  {
    PositionNotify.dwOffset = DSBPN_OFFSETSTOP;
    PositionNotify.hEventNotify = hMyEvent;
    hr = lpDsNotify->SetNotificationPositions(1, &PositionNotify);
    lpDsNotify->Release();
  }
  return hr;
}

Notifications for hardware-controlled buffers are not provided reliably by all drivers; some may generate false notifications. To work around this problem, you can call IDirectSoundBuffer8::GetCurrentPosition whenever your application receives a notification, to be sure that the notification position has actually been reached. Another solution is to create the buffer in software.


Mixing Sounds

Secondary buffers played simultaneously are automatically mixed in the primary buffer. Under the Windows driver model, the mixing is done in the kernel mixer. Different secondary buffers can have different WAV formats (for example, different sampling rates), and sounds are converted to the format of the primary buffer or kernel mixer as necessary.

On VXD drivers, the DirectSound mixer produces the best sound quality if all your application's sounds use the same WAV format and the hardware output format is matched to the format of the sounds. If this is done, the mixer does not need to perform any format conversion. Your application can change the hardware output format by creating a primary sound buffer object and calling the IDirectSoundBuffer8::SetFormat method. To do this, you need the Priority Cooperative Level. You must set the format of the primary buffer before creating any secondary buffers. DirectSound will restore the hardware format to the format specified in the last call every time the application gains the input focus.

On WDM drivers, setting the primary buffer format has no effect. The format is determined by the kernel mixer. For more information, see DirectSound Driver Models.


Looping Sounds

DirectSound does not directly support looping within a buffer, or repetition of only a portion of a sound. (The DSBPLAY_LOOPING flag causes the entire buffer to play again when the play cursor reaches the end.) Although it is possible to implement looping on a static buffer by resetting the play cursor to the start of the loop each time it reaches the end of the loop, doing so might result in audio glitches, as DirectSound must discard any preprocessed data and begin preprocessing again.

To repeat a portion of a sound, play the sound in a streaming buffer and implement the loop in your source data.

See Also

Using Streaming Buffers


Buffer Management

The IDirectSoundBuffer8::GetCaps method retrieves the capabilities of the DirectSoundBuffer object.

Your application can use the IDirectSoundBuffer8::GetStatus method to determine if the buffer is playing or if it has stopped.

Use the IDirectSoundBuffer8::GetFormat method to retrieve information about the format of the sound data in a buffer. You also can use IDirectSoundBuffer8::SetFormat to set the format of the sound data in the primary buffer. For more information, see Mixing Sounds.

Note The SetFormat method cannot be called on secondary buffers. After a secondary buffer is created, its format is fixed. To play a sound that is in another format, you must create a new sound buffer with this format.

Memory for a sound buffer can be lost in certain situations: for example, when buffers are located in sound card memory and another application gains control of the hardware resources. Loss can also occur when an application with the write-primary cooperative level moves to the foreground; in this case, DirectSound makes all other sound buffers lost so that the foreground application can write directly to the primary buffer.

The DSERR_BUFFERLOST error code is returned when the IDirectSoundBuffer8::Lock or IDirectSoundBuffer8::Play method is called for a lost buffer. When the application that caused the loss either lowers its cooperative level from write-primary or moves to the background, other applications can attempt to reallocate the buffer memory by calling the IDirectSoundBuffer8::Restore method. If successful, this method restores the buffer memory and all other settings for the buffer, such as volume and pan settings. However, a restored buffer may not contain valid sound data, so the owning application should rewrite the data to the buffer.


Using WAV Data

Under the Windows driver model (WDM), DirectSound hardware buffers can play any uncompressed or compressed sound format that can be described in a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure, provided the format is supported by the hardware. Software buffers and non-WDM hardware buffers support only 8-bit and 16-bit uncompressed formats.

Waveform (or WAV) data is usually stored in files or resources in Resource Interchange File Format (RIFF). The data includes a description of the WAV format, including parameters such as the sampling rate and number of output channels.

More information on WAV sounds is included in the following topics:

  • Multichannel and High-Resolution WAV Formats
  • Reading WAV Data
  • Calculating the Duration of a WAV Sound


Multichannel and High-Resolution WAV Formats

On WDM drivers, DirectSound buffers support WAV formats that have more than two output channels, for speaker configurations such as 5.1, which has speakers at the front left, front center, front right, back left, and back right, plus a low-frequency enhancer. They also support formats with sample resolutions of greater than 16 bits.

Such formats can be described by a WAVEFORMATEXTENSIBLE structure. This structure is an extension of WAVEFORMATEX that configures the extra bytes specified by the WAVEFORMATEX.cbSize. A WAVEFORMATEXTENSIBLE structure can be cast as WAVEFORMATEX wherever the latter is expected, as for example in the DSBUFFERDESC structure. DirectSound recognizes multichannel and high-resolution formats by the WAVE_FORMAT_EXTENSIBLE tag in WAVEFORMATEX.wFormatTag.

You do not have to use the WAVEFORMATEXTENSIBLE type definition in your application in order to play multichannel or high-resolution files. You need only parse the file header correctly into a WAVEFORMATEX structure that contains the extra bytes specified by cbSize. For an example of how to allocate the WAVEFORMATEX structure, see the CWaveFile::ReadMMIO function in the DirectSound samples.

If the system is configured for fewer physical speakers than the number of channels specified in a multichannel WAV file, the audio data is mixed appropriately and output to the existing speakers.

DirectSound does not support effects or 3D processing on buffers in a multichannel format. An attempt to create a buffer with the DSBCAPS_CTRL3D or DSBCAPS_CTRLFX flag and a multichannel WAV format will fail.

For more information on multichannel WAV formats, see Multiple Channel Audio Data and WAVE Files, available at www.microsoft.com.


Reading WAV Data

WAV files are in the Resource Interchange File Format (RIFF), which consists of a variable number of named chunks containing either header information (for example, the format of sound samples) or data (the samples themselves). The Win32 API supplies functions for opening and closing RIFF files, seeking to chunks, and so on. The names of these functions all start with "mmio".

To store WAV sounds in an executable, import your WAV files as resources and give them string names. Note that the CWaveFile Sample Class expects these resources to be of type "WAVE" or "WAV", and expects to find them in the executable module rather than a DLL.

The DirectSound API does not include methods for loading sound data. However, the DXUTsound.cpp file used by many of the SDK sample applications implements several classes that can be used to create sound buffers from files, resources, or a memory location.

The basic steps involved in using the sample classes to initialize DirectSound and to create and load buffers are as follows:

  1. Create an object of the CSoundManager Sample Class.
  2. Call CSoundManager::Initialize to create the device object.
  3. Pass the name of a file or resource to CSoundManager::Create or a memory location to CSoundManager::CreateFromMemory. These methods return an object of the CSound Sample Class representing one or more static buffers just large enough to contain the data. (You can create multiple buffers to play several instances of the sound at the same time.) Alternatively, pass the name of a file or resource to CSoundManager::CreateStreaming. This method returns an object of the CStreamingSound Sample Class representing a single streaming buffer .
  4. Call the FillBufferWithSound method on the object retrieved in the preceding step. This reads the data from the file, resource, or memory location into the buffer. For a streaming buffer, it fills the buffer only with as much data as it can hold; to refresh the data as the buffer plays, use CStreamingSound::HandleWaveStreamNotification.

Note that the actual reading of data is done by a CWaveFile object that is a protected member of the CSound or CStreamingSound object. You do not normally need to use the CWaveFile class directly; however, you can refer to the implementation of this class for information on how to parse WAV data.

See Also

  • DirectSound samples


Calculating the Duration of a WAV Sound

The length of time for which a waveform will play is determined by the data size and the format. The data size and format can be retrieved by using the CWaveFile::GetSize and CWaveFile::GetFormat methods in the DirectSound samples.

The following example function returns the duration of a WAV file, in milliseconds:

DWORD GetSoundLength(LPSTR strFileName)
{
  CWaveFile* pWav;
  DWORD dwLen = 0;
  DWORD dwSize;
  WAVEFORMATEX* wfx;

  pWav = new CWaveFile();
  if (SUCCEEDED(pWav->Open(strFileName, NULL, WAVEFILE_READ)))
  {
    wfx = pWav->GetFormat();
    dwSize = pWav->GetSize();
    dwLen = (DWORD) (1000 * dwSize / wfx->nAvgBytesPerSec);
    pWav->Close();
  }
  if (pWav) delete pWav;
  return dwLen;
}

See Also

CWaveFile Sample Class, DirectSound Sample Utility Classes, Reading WAV Data


Sounds in 3D

Using DirectSound, you can create a 3D world for sounds that can be integrated with 3D graphics. You can locate sound sources and the listener in space, apply Doppler shift to moving sounds, and control physical parameters such as the rate at which sound attenuates over distance.

DirectSound can create virtual 3D effects on two speakers or a set of headphones. It will also take advantage of multichannel systems with WDM drivers if the user has selected a surround sound speaker configuration in Control Panel. For more information, see DSBUFFERDESC.

The following topics cover some general aspects of 3D sound:

  • Coordinates of 3D Space
  • Perception of Sound Positions

Information on how to use 3D sound in an application is found in the following sections:

  • DirectSound 3D Buffers
  • DirectSound 3D Listeners


Coordinates of 3D Space

The position, velocity, and orientation of sound sources and listeners in 3D space are represented by Cartesian coordinates, which are values on three axes: the x-axis, the y-axis, and the z-axis. The axes are relative to a viewpoint established by the application. Values on the x-axis increase from left to right, on the y-axis from down to up, and on the z-axis from near to far.

The D3DVECTOR structure contains values describing position, velocity, or orientation on the three axes.

Conventionally, vectors are expressed as three values enclosed in parentheses and separated by commas, in the order (x, y, z).

For position, the values are in meters by default. If your application does not use the meter as its unit of measure for 3D graphics, you can set a distance factor, which is a floating-point value representing meters per application-specified distance unit. For example, if your application uses feet, it could specify a distance factor of .3048, which is the number of meters in a foot. For more information, see Distance Factor.

For velocity, the vector describes the rate of movement along each axis in units per second. Again, the default unit is meters, but this can be changed by the application.

For orientation, the values are in arbitrary units and are relative to one another. If the base view of the 3D world is facing north toward the horizon, and the orientation of the listener is (-1, 0, 1) the listener is facing northwest. Because the values within a vector are not in absolute units, the vector could equally well be expressed as (-5, 0, 5) or (-0.25, 0, 0.25).

You can see how vectors in 2D space work by drawing them on a sheet of graph paper. Let the values increase from the bottom of the paper to the top and from left to right. A line drawn from (0, 0) to (1, 1) has the same orientation, or direction, as one drawn from (0, 0), to (5, 5). However, the second line indicates a greater distance, or velocity. 3D vectors work in just the same way, with an additional axis in the up-down direction.


Perception of Sound Positions

In the real world, the perception of a sound's position in space is influenced by several factors. Not all of these factors are acoustical; one of the most important is sight. Clues from the sounds themselves include the following:

  • Overall loudness. As a sound source moves away from the listener, its perceived volume decreases at a fixed rate. This phenomenon is known as rolloff.
  • Interaural intensity difference. A sound coming from the listener's right sounds louder in the right ear than in the left.
  • Interaural time difference. A sound emitted by a source to the listener's right will arrive at the right ear slightly before it arrives at the left ear. The duration of this offset is approximately a millisecond.
  • Muffling. The shape and orientation of the ears ensures that sounds coming from behind the listener are slightly muffled compared with sounds coming from in front. In addition, if a sound is coming from the right, the sound reaching the left ear will be muffled by the mass of the listener's head as well as by the orientation of the left ear.
  • Effect of the earlobes. The pinnae, or folds of the ear, cause subtle changes to the pitch and timing of sounds arriving from different directions. The mathematics behind this effect are known as the head-related transfer function (HRTF).


DirectSound 3D Buffers

Each sound source in a 3D environment is represented by an IDirectSound3DBuffer8 interface. This interface is supported only by sound buffers created with the DSBCAPS_CTRL3D flag. Methods of the interface are used to set and retrieve parameters of a single sound source.

Applications must supply monaural sound sources when using the 3D capabilities of DirectSound. If you attempt to create a buffer with the DSBCAPS_CTRL3D flag set and a WAV format with more than one channel, an error results.

This section describes how your applications can obtain and manage 3D buffer objects.The following topics are discussed:

  • Obtaining the 3D Buffer Object
  • Minimum and Maximum Distances
  • Processing Mode
  • Buffer Position and Velocity
  • Sound Cones
  • Batch Parameters for 3D Buffers


Obtaining the 3D Buffer Object

The IDirectSound3DBuffer8 interface is obtained from a secondary DirectSound buffer that has been created with the DSBCAPS_CTRL3D flag in the dwFlags member of the DSBUFFERDESC structure.

You can retrieve the IDirectSound3DBuffer8 interface by calling QueryInterface method on the buffer, as in the following sample code, where lpDsbSecondary is an IDirectSoundBuffer8 interface.

LPDIRECTSOUND3DBUFFER8 lpDs3dBuffer;

HRESULT hr = lpDsbSecondary->QueryInterface(IID_IDirectSound3DBuffer8,
                (LPVOID *)&lpDs3dBuffer);


Minimum and Maximum Distances

As a listener approaches a sound source, the sound gets louder; the volume doubles when the distance is halved. Past a certain point, however, it is not reasonable for the volume to continue to increase. This is the minimum distance for the sound source.

The minimum distance that you set for a sound determines how quickly that sound fades away with distance. For example, you might set this value to 100 meters for a jet engine and to 2 centimeters for a bee. With these settings, the jet engine is at half volume when 200 meters away from the listener, but the bee is at half volume when only 4 centimeters away.

The following illustration shows how minimum and maximum distance affect the volume of a jet engine and a bee at increasing distances.

Figure 1. Minimum and maximum distances

The default minimum distance for a sound buffer, DS3D_DEFAULTMINDISTANCE, is defined as 1 unit, or 1 meter at the default distance factor. Unless you change this value, the sound is at full volume when it is 1 meter away from the listener, at half volume at 2 meters, at quarter volume at 4 meters, and so on. For most sounds you will probably want to set a larger minimum distance so that the sound does not fade so rapidly as it moves away.

The maximum distance for a sound source is the distance beyond which the volume of the sound no longer decreases. The default maximum distance for a DirectSound 3D buffer (DS3D_DEFAULTMAXDISTANCE) is 1 billion, meaning that in most cases the attenuation will continue to be calculated long after the sound has moved out of hearing range. To avoid unnecessary processing on software buffers under VXD drivers, applications should set a reasonable maximum distance and include the DSBCAPS_MUTE3DATMAXDISTANCE flag when creating the buffer. (In DirectMusic, this flag is automatically set on standard 3D buffers created as part of an audiopath.)

The maximum distance can also be used to prevent a sound from becoming inaudible. For example, if you have set the minimum distance for a sound at 100 meters, that sound might become effectively inaudible at 1,000 meters or less. By setting the maximum distance at 800 meters, you ensure that the sound always has at least one-eighth of its maximum volume regardless of the distance. In this case, of course, you would not set the DSBCAPS_MUTE3DATMAXDISTANCE flag.

By default, distance values are expressed in meters.

To adjust the effect of distance on volume for all sound buffers, you can change the rolloff factor.


Processing Mode

Sound buffers have three processing modes: normal, head-relative, and disabled.

In normal mode (DS3DMODE_NORMAL), the sound source is positioned and oriented absolutely in world space. This is the default mode, and is used for sound sources that do not move and turn with the listener.

In head-relative mode (DS3DMODE_HEADRELATIVE), the 3D properties of the sound source are all relative to the current position, velocity, and orientation of the listener. As the listener moves and turns, the buffer is automatically repositioned in world space. Head-relative mode can be used for sounds such as a fly buzzing around the listener's head. However, most sounds that travel with the listener don't have to be 3D sounds at all.

In disabled mode (DS3DMODE_DISABLE), 3D sound processing is disabled and the sound seems to originate from the center of the listener's head.


Buffer Position and Velocity

As a sound source moves, it is up to the application to specify values for its position and velocity.

Position is measured in distance units along each of the three axes, relative to either world space or the listener, depending on the processing mode.

Velocity is measured in distance units per second along each of the three axes of a vector. By default, distance units are meters. Velocity is used by DirectSound only to calculate the effects of Doppler shift.


Sound Cones

A sound with no orientation has the same amplitude at a given distance in all directions. A sound with an orientation is loudest in the direction of orientation. The model that describes the loudness of the oriented sound is called a sound cone. Sound cones are made up of an inside (or inner) cone and an outside (or outer) cone. The outside cone angle must always be equal to or greater than the inside cone angle.

At any angle within the inner cone, the volume of the sound is just what it would be if there were no cone, after taking into account the basic volume of the buffer, the distance from the listener, the listener's orientation, and so on.

At any angle outside the outer cone, the normal volume is attenuated by a factor set by the application. The outside cone volume is expressed in hundredths of decibels and is a negative value, because it represents attenuation from the default volume of 0.

Between the inner and outer cones is a zone of transition from the inside volume to the outside volume. The volume decreases as the angle increases.

The following illustration shows the concept of sound cones.

Figure 1. Sound cones

Every 3D sound buffer has a sound cone, but by default a buffer behaves like an omnidirectional sound source, because the outside volume is not attenuated, and the inside and outside cone angles are 360 degrees. Unless the application changes these values, the sound does not have any apparent orientation.

Designing sound cones properly can add dramatic effects to your application. For example, you could position a sound source in the center of a room, setting its orientation toward an open door in a hallway. Then set the angle of the inside cone so that it extends to the width of the doorway, make the outside cone a bit wider, and set the outside cone volume to inaudible. A listener moving along the hallway will begin to hear the sound only when near the doorway, and the sound will be loudest as the listener passes in front of the open door.


Batch Parameters for 3D Buffers

Applications can retrieve or set a 3D sound buffer's parameters individually or in batches. If the sound source is moving, you might want to set multiple parameters such as position, orientation, and velocity all at once. You can do so by calling IDirectSound3DBuffer8::GetAllParameters to retrieve the current parameters, changing the appropriate parameters in the DS3DBUFFER structure, and passing the structure back to IDirectSound3DBuffer8::SetAllParameters.

Parameter changes can also be made more efficiently by flagging them as deferred and then executing them all at once. For more information, see Deferred Settings.


DirectSound 3D Listeners

In a virtual 3D environment as in the real world, sounds exist only in relation to a point of reception. The 3D sound effects in a DirectX application are affected not only by the position, orientation, and velocity values of the sound sources, but also by the position, orientation, and velocity of the virtual listener.

By default, the listener is stationary at the zero point of all vectors, oriented with the nose toward the positive Z-axis and the top of the head toward the positive Y-axis. The application can change all these values to reflect the movement and facing of the user within virtual space. The listener object also controls the general parameters of the acoustic environment, such as the amount of Doppler shift and the rate of volume attenuation over distance.

This section describes how your application can obtain a listener object and manage global 3D sound parameters. The following topics are discussed:

  • Obtaining the 3D Listener
  • Spatial Parameters of the Listener
  • Distance Factor
  • Doppler Effect
  • Rolloff Factor
  • Batch Parameters for 3D Listeners
  • Deferred Settings


Obtaining the 3D Listener

Global sound parameters are set and retrieved by using the IDirectSound3DListener8 interface from the primary buffer. There is only one primary buffer in an application, and only one listener.

To obtain a listener interface, you must first create a primary buffer object by using the IDirectSound8::CreateSoundBuffer method, specifying the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags in the dwFlags member of the DSBUFFERDESC structure. Call the QueryInterface method on the resulting buffer to obtain a pointer to an IDirectSound3DListener8 interface for that buffer.

The following example function retrieves an interface to the listener.

GetListener(LPDIRECTSOUND8 lpds, LPDIRECTSOUND3DLISTENER8* ppListener)
{
  DSBUFFERDESC             dsbd;
  LPDIRECTSOUNDBUFFER      lpdsbPrimary;  // Cannot be IDirectSoundBuffer8.
  LPDIRECTSOUND3DLISTENER8 lp3DListener = NULL;
  HRESULT hr;

  ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
  dsbd.dwSize = sizeof(DSBUFFERDESC);
  dsbd.dwFlags = DSBCAPS_CTRL3D | DSBCAPS_PRIMARYBUFFER;

  if (SUCCEEDED(hr = lpds->CreateSoundBuffer(&dsbd, &lpdsbPrimary, NULL)))
  {
    hr = lpdsbPrimary->QueryInterface(IID_IDirectSound3DListener8,
                                 (LPVOID *)ppListener);
    lpdsbPrimary->Release();
  }
  return hr;
}


Spatial Parameters of the Listener

Like a sound source, the listener has a position, orientation, and velocity in the 3D world.

The orientation of the listener is defined by the relationship between two vectors that share an origin at the center of the listener's head: the top and front vectors. The top vector points straight up through the top of the head, and the front vector points forward through the listener's face at right angles to the top vector, as in the following illustration.

Figure 1. Listener_vectors

By default, the front vector is (0.0, 0.0, 1.0), and the top vector is (0.0, 1.0, 0.0). The two vectors must always be at right angles to one another. If necessary, DirectSound will adjust the front vector so that it is at right angles to the top vector.

Position is measured in distance units along a vector.

Velocity is measured in distance units per second along a vector. By default, distance units are meters. Velocity is used by DirectSound only to calculate the effects of Doppler shift.


Distance Factor

The distance factor is the number of meters in a vector unit. By default, the distance factor is 1.0. If the velocity of a buffer is (2.0, 0.0, 0.0), the sound source is considered to be moving along the x-axis at 2 meters per second. Applications that are using a different unit of measurement for 3D graphics vectors might want to change the distance factor accordingly.

Suppose, for example, that the basic unit of measurement in your application is the foot, or 0.3048 meters. You set the distance factor to 0.3048. From then on, you use feet in parameters to method calls, and they are automatically converted to meters.

The distance factor mainly affects Doppler shift, by changing the actual velocity represented by n units per second. It does not directly affect rolloff, because the rate of attenuation over distance is based on the minimum distance in vector units. If you set the minimum distance for a given sound at 2 units, the volume will be halved at a distance of 4 units, regardless of whether those units are in feet, meters, or any other measure. For more information, see Minimum and Maximum Distances.


Doppler Effect

DirectSound automatically creates Doppler shift effects for any buffer or listener that has a velocity. Effects are cumulative: if the listener and the sound buffer are both moving, the system automatically calculates the relative velocity and adjusts the Doppler effect accordingly.

In order to have realistic Doppler shift effects in your application, you must calculate the speed of any object that is moving and set the appropriate velocity for that sound source or listener. You are free to exaggerate or lessen this value in a particular case in order to create special effects. You can also globally increase or decrease Doppler shift by changing the Doppler factor.

The Doppler factor can range from DS3D_MINDOPPLERFACTOR to DS3D_MAXDOPPLERFACTOR, defined as 0.0 and 10.0 respectively. A value of 0 means no Doppler shift is applied to a sound. Every other value represents a multiple of the real-world Doppler shift.

See Also

  • IDirectSound3DListener8::GetDopplerFactor
  • IDirectSound3DListener8::SetDopplerFactor


Rolloff Factor

Rolloff is the amount of attenuation that is applied to sounds, based on the listener's distance from the sound source. DirectSound can ignore rolloff, exaggerate it, or give it the same effect as in the real world, depending on a global parameter called the rolloff factor.

The rolloff factor can range from DS3D_MINROLLOFFFACTOR to DS3D_MAXROLLOFFFACTOR, defined as 0.0 and 10.0 respectively. A value of DS3D_MINROLLOFFFACTOR means that sounds remain at full volume regardless of their distance from the listener. Every other value represents a multiple of the real-world rolloff.

The rolloff factor is global. To change the effect of distance for an individual sound buffer, you can set the minimum distance for the buffer.


Batch Parameters for 3D Listeners

Applications can retrieve or set a 3D listener object's parameters individually or in batches. If the listener is moving, you might want to set multiple parameters such as position, orientation, and velocity all at once. You can do so by calling IDirectSound3DListener8::GetAllParameters to retrieve the current parameters, changing the appropriate parameters in the DS3DLISTENER structure, and passing the structure back to IDirectSound3DListener8::SetAllParameters.

Parameter changes can also be made more efficiently by flagging them as deferred and then executing them all at once. For more information, see Deferred Settings.


Deferred Settings

Every change to 3D sound buffer and listener settings causes remixing, at the expense of CPU cycles. To minimize the performance impact of changing 3D settings, set the DS3D_DEFERRED flag in the dwApply parameter of any of the IDirectSound3DListener8 or IDirectSound3DBuffer8 methods that change 3D settings. Then call the IDirectSound3DListener8::CommitDeferredSettings method to execute all of the deferred commands at once.

Deferred settings are overwritten by immediate settings. For example, if you set the listener velocity to (1.0, 0.0, 0.0) with the DS3D_DEFERRED flag and then set it to (2.0, 0.0, 0.0) with the DS3D_IMMEDIATE flag, the velocity becomes (2.0, 0.0, 0.0) and does not change when CommitDeferredSettings is called.


Using Effects

DirectX provides support for effects processing of sounds by DirectX Media Objects (DMOs). A standard set of effects is available to every DirectX application. Other DMOs can be registered on the system. All the standard DMOs can process 8-bit or 16-bit PCM data, as well as 32-bit floating-point formats.

To implement effects, a DirectSound application must first call CoInitialize to initialize COM. Doing so does not preclude creating the device object by using DirectSoundCreate8.

Using the DirectSound API, it is not possible to create chains of effects, where the output of multiple buffers is mixed into another buffer containing an effect. Buffer chains are available, however, in content authored for DirectMusic.

To take advantage of hardware-specific effects, use the IKsPropertySet interface.

The following topics contain information on setting up and using effects:

  • Setting Effects on Buffers
  • Effect Parameters
  • Standard Effects
  • Audio Effect DMO Wizard


Setting Effects on Buffers

You can set any number of effects on a secondary buffer that was created with the DSBCAPS_CTRLFX flag in the DSBUFFERDESC structure. The buffer must be stopped and not locked. Since DirectX 9.0, effects are never hardware-accelerated. It is possible to set an effect on a hardware buffer, but doing so confers no advantages.

Effects might not work smoothly on very small buffers. DirectSound does not permit the creation of effects-capable buffers that hold less than 150 milliseconds of data. This value is defined as DSBSIZE_FX_MIN.

The following sample function sets an echo effect on a buffer and displays the result in the output window of the development environment.

HRESULT SetEcho(LPDIRECTSOUNDBUFFER8 pDSBuffer)
{
  HRESULT hr;
  DWORD dwResults[1];  // One element for each effect.

  // Describe the effect.
  DSEFFECTDESC dsEffect;
  memset(&dsEffect, 0, sizeof(DSEFFECTDESC));
  dsEffect.dwSize = sizeof(DSEFFECTDESC);
  dsEffect.dwFlags = 0;
  dsEffect.guidDSFXClass = GUID_DSFX_STANDARD_ECHO;

  // Set the effect
  if (SUCCEEDED(hr = pDSBuffer->SetFX(1, &dsEffect, dwResults)))
  {
    switch (dwResults[0])
    {
      case DSFXR_LOCHARDWARE:
        OutputDebugString("Effect was placed in hardware.");
        break;
      case DSFXR_LOCSOFTWARE:
        OutputDebugString("Effect was placed in software.");
        break;
      case DSFXR_UNALLOCATED:
        OutputDebugString("Effect is not yet allocated to hardware or software.");
        break;
    }
  }
  return hr;
}


Effect Parameters

To set or retrieve parameters of sound effects, you must first obtain the appropriate interface to the buffer that contains the effect. The following interfaces give you access to parameters of the standard DMOs available on all systems.

  • IDirectSoundFXChorus8
  • IDirectSoundFXCompressor8
  • IDirectSoundFXDistortion8
  • IDirectSoundFXEcho8
  • IDirectSoundFXFlanger8
  • IDirectSoundFXGargle8
  • IDirectSoundFXI3DL2Reverb8
  • IDirectSoundFXParamEq8
  • IDirectSoundFXWavesReverb8

To obtain one of these interfaces, pass the corresponding IID to the QueryInterface method of the buffer containing the effect. For a list of IIDs, see DirectSound Interface GUIDs.


Standard Effects

This topic is an introduction to the sound effects provided with DirectX. The following effects are covered:

  • Chorus
  • Compression
  • Distortion
  • Echo
  • Environmental Reverberation
  • Flange
  • Gargle
  • Parametric Equalizer
  • Waves Reverberation


Chorus

Chorus is a voice-doubling effect created by echoing the original sound with a slight delay and slightly modulating the delay of the echo.

This effect is represented by the IDirectSoundFXChorus8 interface. Its parameters are contained in the DSFXChorus structure.


Compression

Compression is a reduction in the fluctuation of a signal above a certain amplitude.

This effect is represented by the IDirectSoundFXCompressor8 interface. Its parameters are contained in the DSFXCompressor structure.


Distortion

Distortion is achieved by adding harmonics to the signal in such a way that, as the level increases, the top of the waveform becomes squared off or clipped.

This effect is represented by the IDirectSoundFXDistortion8 interface. Its parameters are contained in the DSFXDistortion structure.


Echo

An echo effect causes an entire sound to be repeated after a fixed delay.

This effect is represented by the IDirectSoundFXEcho8 interface. Its parameters are contained in the DSFXEcho structure.


Environmental Reverberation

DirectX provides partial support for environmental reverberation in accordance with the Interactive 3D Audio Level 2 (I3DL2) specification, published by the Interactive Audio Special Interest Group. The DirectX environmental reverb effect is an implementation of the listener properties in the I3DL2 specification. Source properties are not supported.

Sounds reaching the listener have three temporal components:

  • The direct path is the audio signal that goes straight from the sound source to the listener, without bouncing off any surface.
  • Early reflections are the audio signals that reach the listener after one or two reflections off surfaces such as the walls, floor, and ceiling. If a signal is the result of the sound hitting only one wall on its way to the listener, it is called a first-order reflection. If it bounces off two walls before reaching the listener, it is called a second-order reflection. Humans can typically perceive individual reflections only of the first or second order.
  • Late reverberation, or simply reverb, consists of the combined lower-order reflections, usually a dense succession of echoes of diminishing intensity.

The combination of early reflections and late reverberation is sometimes called the room effect.

In the DirectSound implementation, only the signal sent to the room effect is heard. To hear the direct path, play the sound simultaneously in another buffer that does not have the environmental reverb effect.

Reverberation properties include the following:

  • Attenuation of the early reflections and late reverberation.
  • Rolloff factor, or the rate at which reflected signals become attenuated with distance. The rolloff factor for the direct path is managed by the DirectSound listener.
  • Reflections delay. This is the interval between the arrival of the direct-path signals and the arrival of the first early reflections.
  • Reverb delay. This is the interval between the first of the early reflections and the onset of late reverberation.
  • Decay time. This is the interval between the onset of late reverberation and the time when its intensity has been reduced by 60 dB.
  • Diffusion, which is proportional to the number of echos per second in the late reverberation. Depending on the implementation, the density of echos can change as the reverberation decays. In DirectX, the application can control this property by setting a percentage of the range allowed by the implementation.
  • Density, which is is proportional to the number of resonances per hertz in the late reverberation. Lower densities produce hollower sounds like those found in small rooms. In DirectX, the application can control this property by setting a percentage of the range allowed by the implementation.

Reverb properties are represented by an IDirectSoundFXI3DL2Reverb8 interface, and the parameters of the environment are contained in a DSFXI3DL2Reverb structure.

DirectX supports many sets of default parameters, or presets, that describe the reverb properties of audio environments ranging from mountains to sewer pipes. Most applications can simply choose one of these environments by using IDirectSoundFXI3DL2Reverb8::SetPreset.

To set custom properties, use IDirectSoundFXI3DL2Reverb8::SetAllParameters. You can retrieve the current properties by using IDirectSoundFXI3DL2Reverb8::GetAllParameters.


Flange

Flange is an echo effect in which the delay between the original signal and its echo is very short and varies over time. The result is sometimes referred to as a sweeping sound. The term flange originated with the practice of grabbing the flanges of a tape reel to change the speed.

This effect is represented by the IDirectSoundFXFlanger8 interface. Its parameters are contained in the DSFXFlanger structure.


Parametric Equalizer

A parametric equalizer amplifies or attenuates signals of a given frequency.

Parametric equalizer effects for different pitches can be applied in parallel by setting multiple instances of the GUID_DSFX_STANDARD_PARAMEQ effect on the same buffer. In this way, the application can have tone control similar to that provided by a hardware equalizer.

This effect is represented by the IDirectSoundFXParamEq8 interface. Its parameters are contained in the DSFXParamEq structure.


Gargle

The gargle effect modulates the amplitude of the signal.

This effect is represented by the IDirectSoundFXGargle8 interface. Its parameters are contained in the DSFXGargle structure.


Waves Reverberation

The Waves reverberation effect is intended for use with music. The Waves reverberation Direct Media Object (DMO) is based on the Waves MaxxVerb technology, which is licenced to Microsoft.

This effect is represented by the IDirectSoundFXWavesReverb8 interface. Its parameters are contained in the DSFXWavesReverb structure.


Audio Effect DMO Wizard

The Audio Effect DMO Wizard simplifies the task of creating a DirectX Media Object (DMO) that implements an audio effect that can be used in DirectSound buffers and in other applications.

Microsoft Visual C++ 6.0 is required to run the wizard. Select New from the File menu, and then select Audio Effect DMO Wizard from the Projects tab of the New dialog box.

The wizard creates a Visual Studio project and several C++ code and header files, which implement the framework for the DMO. After the project is created, you must add code that implements the audio effect.

For more information, see the Help for the wizard.


Capturing Waveforms

DirectSound can be used to capture sounds, as an alternative to the Windows Multimedia functions such as waveInOpen. Other than support for acoustic echo cancellation (AEC), DirectSound offers no performance advantages over the Windows Multimedia functions.

The DirectSound capture device object, represented by the IDirectSoundCapture8 interface, is used to query the capabilities of sound capture devices and to create buffers for capturing audio from an input source. Data can be captured in PCM or compressed formats.

The DirectSound capture buffer object, represented by the IDirectSoundCaptureBuffer8 interface, represents a buffer used for receiving data from the input device. Like playback buffers, this buffer is conceptually circular: when input reaches the end of the buffer, it automatically starts again at the beginning.

The methods of IDirectSoundCaptureBuffer8 enable you to retrieve the properties of the buffer, start and stop audio capture, and lock portions of the memory, so that you can safely retrieve data for saving to a file or for playback in a full-duplex implementation. On operating systems that support capture effects, this interface also provides methods for retrieving DMOs and ascertaining the status of effects.

More information about waveform capture is found in the following topics:

  • Enumerating Capture Devices
  • Creating the Capture Device Object
  • Capture Device Capabilities
  • Creating a Capture Buffer
  • Capture Buffer Information
  • Capture Buffer Notification
  • Capture Buffer Effects
  • Using the Capture Buffer
  • Writing to a WAV File


Enumerating Capture Devices

If your application is simply going to capture sounds through the user's preferred capture device, there is no need to enumerate the available devices. When you create the device object by calling the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 function, you can specify a default device. For more information, see Creating the Capture Device Object.

Enumeration is necessary in the following situations:

  • Your application needs capabilities that may not be available on all devices.
  • Your application requires two or more devices.
  • You wish to offer the user a choice of devices.

Enumeration serves three purposes:

  • It reports what hardware is available.
  • It supplies a GUID for each device.
  • It enables you to create a temporary device object for each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices, you must first set up a callback function that will be called once for each device on the system. You can do anything you want within this function, and you can give it any name, but you must declare it in the same form as the DSEnumCallback prototype. The callback function must return TRUE if enumeration is to continue, or FALSE otherwise - for instance, after finding a device with the capabilities you need.

For a sample callback function, see Enumerating Sound Devices.

The enumeration is set in motion by using the DirectSoundCaptureEnumerate function, as follows:

    DWORD pv;  // Can be any 32-bit type.

    HRESULT hr = DirectSoundCaptureEnumerate(
        (LPDSENUMCALLBACK)DSEnumProc, (VOID*)&pv);

The second parameter can be any 32-bit value that you want to have access to within the callback.

The first device enumerated is always called the Primary Sound Capture Driver, and the lpGUID parameter of the callback is NULL. This device represents the preferred capture device set by the user in Control Panel. It is enumerated separately to make it easy for the application to add "Primary Sound Capture Driver" to a list when presenting the user with a choice of devices. The primary capture device is also enumerated with its proper name and GUID.


Creating the Capture Device Object

You can create the capture device object by calling either the DirectSoundCaptureCreate8 or the DirectSoundFullDuplexCreate8 function. Both these functions retrieve a pointer to the IDirectSoundCapture8 interface.

The lpcGUID parameter to DirectSoundCaptureCreate, or the pcGuidRenderDevice parameter to DirectSoundFullDuplexCreate8, can be a GUID obtained by enumeration, or it can be one of the following predefined GUIDs:

GUID | Description
DSDEVID_DefaultCapture | The default system capture device. You can also specify this device by passing a NULL pointer instead of a device GUID.
DSDEVID_DefaultVoiceCapture | The default voice communications capture device. Typically, this is a secondary device such as a USB headset with microphone.

If no device driver is present, the call fails.

You can also use the CoCreateInstance function to create the object. The procedure is similar to that for the device object; see Creating the Device Object. If you use CoCreateInstance, the object is created for the default capture device selected by the user in Control Panel.

If you want playback and capture device objects to coexist, then you should create and initialize the playback device object before creating and initializing the capture device object, or use DirectSoundFullDuplexCreate8.

Some audio devices aren't configured for full duplex audio by default. If your application has problems with creating and initializing both a playback device object and a capture device object, you should advise the user to check the audio device properties to ensure that full duplex is enabled.


Capture Device Capabilities

To retrieve the capabilities of a capture device, call the IDirectSoundCapture8::GetCaps method. The parameter to this method is a pointer to a DSCCAPS structure. As with other such structures, you have to initialize the dwSize member before passing it. On return, the structure contains the number of channels the device supports, as well as a combination of values for supported formats, equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions.

On non-WDM drivers, a capture device can be used by only one application at a time. If the driver supports simultaneous use of the device by more than one application, DSCCAPS_MULTIPLECAPTURE is returned in the dwFlags member of DSCCAPS. Each application can set its own format for the capture buffer.


Creating a Capture Buffer

To create a capture buffer, call the IDirectSoundCapture8::CreateCaptureBuffer method.

One of the parameters to the method is a DSCBUFFERDESC structure that describes the characteristics of the desired buffer. The last member of this structure is a WAVEFORMATEX structure, which must be initialized with the details of the desired WAV format.

Note that if your application is playing sounds as well as capturing them, capture buffer creation can fail when the format of the capture buffer is not the same as that of the primary buffer. The reason is that some cards have only a single clock and cannot support capture and playback at two different frequencies.

The following example function creates a capture buffer that will hold 1 second of data. Note that the interface to the capture device object passed in as a parameter must be obtained by using the DirectSoundCaptureCreate8 function rather than the earlier DirectSoundCaptureCreate function; otherwise the buffer will not support the IDirectSoundCaptureBuffer8 interface.

HRESULT CreateCaptureBuffer(LPDIRECTSOUNDCAPTURE8 pDSC,
                            LPDIRECTSOUNDCAPTUREBUFFER8* ppDSCB8)
{
  HRESULT hr;
  DSCBUFFERDESC               dscbd;
  LPDIRECTSOUNDCAPTUREBUFFER  pDSCB;
  WAVEFORMATEX                wfx =
    {WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0};
    // wFormatTag, nChannels, nSamplesPerSec, mAvgBytesPerSec,
    // nBlockAlign, wBitsPerSample, cbSize

  if ((NULL == pDSC) || (NULL == ppDSCB8)) return E_INVALIDARG;
  dscbd.dwSize = sizeof(DSCBUFFERDESC);
  dscbd.dwFlags = 0;
  dscbd.dwBufferBytes = wfx.nAvgBytesPerSec;
  dscbd.dwReserved = 0;
  dscbd.lpwfxFormat = &wfx;
  dscbd.dwFXCount = 0;
  dscbd.lpDSCFXDesc = NULL;

  if (SUCCEEDED(hr = pDSC->CreateCaptureBuffer(&dscbd, &pDSCB, NULL)))
  {
    hr = pDSCB->QueryInterface(IID_IDirectSoundCaptureBuffer8, (LPVOID*)ppDSCB8);
    pDSCB->Release();
  }
  return hr;
}


Capture Buffer Information

You can use the IDirectSoundCaptureBuffer8::GetCaps method to retrieve the size of a capture buffer. Be sure to initialize the dwSize member of the DSCBCAPS structure before passing it as a parameter.

To retrieve information about the format of the data in the buffer, as set when the buffer was created, call IDirectSoundCaptureBuffer8::GetFormat. This method returns the format information in a WAVEFORMATEX structure.

Note that your application can allow for extra format information in the WAVEFORMATEX structure by first calling the GetFormat method with NULL as the lpwfxFormat parameter. In this case the DWORD pointed to by the lpdwSizeWritten parameter receives the size of the structure needed to receive complete format information.

To find out what a capture buffer is currently doing, call the IDirectSoundCaptureBuffer8::GetStatus method. This method fills a DWORD variable with a combination of flags that indicate whether the buffer is busy capturing, and if so, whether it is looping; that is, whether the DSCBSTART_LOOPING flag was set in the last call to IDirectSoundCaptureBuffer8::Start.

The IDirectSoundCaptureBuffer8::GetCurrentPosition method returns the offsets of the read and capture cursors within the buffer. The read cursor is at the end of the data that has been fully captured into the buffer at this point. The capture cursor is at the end of the block of data that is currently being copied from the hardware. You can safely copy data from the buffer only up to the read cursor.


Capture Buffer Notification

To copy data out of the capture buffer at regular intervals, your application has to know when the read cursor, which is the point up to which it is safe to read data, reaches certain points in the buffer. One way to get this information is to poll the position of the read cursor using IDirectSoundCaptureBuffer8::GetCurrentPosition. A more efficient way is to use notifications. Using the IDirectSoundNotify8::SetNotificationPositions method, you can set any number of points within the buffer where events are to be signaled. You cannot do this while the buffer is running.

First you must obtain the IDirectSoundNotify8 interface. You can do this by using the buffer object's QueryInterface method.

For each notification position, create an event object with the Win32 CreateEvent function. Put the handle to this event in the hEventNotify member of a DSBPOSITIONNOTIFY structure. In the dwOffset member of that structure, specify the offset within the buffer where you want the event to be signaled. Then pass the address of the structure-or of an array of structures, if you want to set more than one notification position-to SetNotificationPositions.

The following example sets up three notification positions in a one-second buffer. One event will be signaled when the read position nears the halfway point in the buffer, another will be signaled when it nears the end of the buffer, and the third will be signaled when capture stops.

HRESULT SetCaptureNotifications(LPDIRECTSOUNDCAPTUREBUFFER8 pDSCB)
{
  #define cEvents  3

  LPDIRECTSOUNDNOTIFY8 pDSNotify;
  WAVEFORMATEX         wfx;
  HANDLE     rghEvent[cEvents] = {0};
  DSBPOSITIONNOTIFY  rgdsbpn[cEvents];
  HRESULT    hr;

  if (NULL == pDSCB) return E_INVALIDARG;
  if (FAILED(hr = pDSCB->QueryInterface(IID_IDirectSoundNotify, (LPVOID*)&pDSNotify)))
  {
    return hr;
  }
  if (FAILED(hr = pDSCB->GetFormat(&wfx, sizeof(WAVEFORMATEX), NULL)))
  {
    return hr;
  }

  // Create events.
  for (int i = 0; i < cEvents; ++i)
  {
    rghEvent[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (NULL == rghEvent[i])
    {
      hr = GetLastError();
      return hr;
    }
  }

  // Describe notifications.

  rgdsbpn[0].dwOffset = (wfx.nAvgBytesPerSec/2) -1;
  rgdsbpn[0].hEventNotify = rghEvent[0];

  rgdsbpn[1].dwOffset = wfx.nAvgBytesPerSec - 1;
  rgdsbpn[1].hEventNotify = rghEvent[1];

  rgdsbpn[2].dwOffset = DSBPN_OFFSETSTOP;
  rgdsbpn[2].hEventNotify = rghEvent[2];

  // Create notifications.

  hr = pDSNotify->SetNotificationPositions(cEvents, rgdsbpn);
  pDSNotify->Release();
  return hr;
}


Capture Buffer Effects

Two capture buffer effects are available as kernel-mode implementations on Microsoft Windows XP:

  • Acoustic echo cancellation (AEC)
  • Noise suppression

Other effects in DMOs, such as those used on rendering buffers, are not supported.

Both the DirectSoundFullDuplexCreate8 function and the IDirectSoundCapture8::CreateCaptureBuffer method take as a parameter a DSCBUFFERDESC structure that points to an array of DSCEFFECTDESC structures describing desired effects. However, to use the Microsoft implementations you must create the capture buffer by using DirectSoundFullDuplexCreate8. You must also play the secondary sound buffer created by that function; until you do so, the effects are not applied.

In the dwFlags member for each DSCEFFECTDESC structure, you must specify either DSCFX_LOCHARDWARE or DSCFX_LOCSOFTWARE. In most cases, specify DSCFX_LOCSOFTWARE. Buffer creation fails if the effect is not available in the specified location.

The effect is identified in the guidDSCFXClass member of the DSCEFFECTDESC structure. To obtain the Microsoft software implementation, specify DSCFX_MS_AEC or DSCFX_MS_NS in the guidDSCFXInstance member. To use another implementation available in hardware or software, obtain the class and instance GUID from the manufacturer.

After the buffer has been created, you can retrieve information about the effects by using the IDirectSoundCaptureBuffer8::GetFXStatus method.

Acoustic echo cancellation (AEC) is primarily of interest for applications that use voice communication from one site to another. The signal from a microphone at site A is output from the speakers at site B and picked up by the microphone at site B. Without AEC, the signal is then sent back to site A, resulting in an echo and possibly a feedback squeal. AEC overcomes this problem by monitoring the incoming signal at each site, adjusting it to take the room environment into account, and then removing it from the outgoing signal. It also removes any local sounds being played by the computer, such as music, so that these do not interfere with the voice signal being sent over the network.

AEC is implemented at the kernel level of the operating system and is global in its effect. It has the following limitations:

  • Only one capture buffer at a time can use AEC.
  • AEC cannot be started if another application is capturing or playing audio. If AEC has been started, no other application can capture audio without using AEC.
  • Regardless of the input or output format, the kernel mixer processes the sound in 16-bit mono format. As a result, the quality of the sound may be reduced. To minimize processor usage, capture sounds in a 16-bit mono format.
  • While AEC is in use, all DirectSound hardware acceleration on the device is disabled, affecting the user experience for other applications sharing the device.
  • Changes to AEC parameters affect all applications that are running.
  • AEC does not work with some combinations of sound cards and drivers. Applications should always provide the user with the option of turning off AEC.
  • On versions of the operating system prior to Windows XP SP1, AEC does not work with USB speakers, or on any machine in which audio capture and rendering are provided by different devices with different clocks.
  • If the acoustic environment changes, the adaptive filter can take two seconds or more to adjust.
  • Any late reverberations occurring more than 128 milliseconds after the original signal are not removed from the outgoing signal.

Use the IDirectSoundCaptureFXAec8interface to set and retrieve AEC parameters on a capture buffer that contains this effect. You can also enable noise fill, which is a means of preventing complete silence when there is no new data in the outgoing signal.

Noise suppression can be applied only if AEC is also enabled. The noise suppression capture effect removes constant background noise, such as fan noise. Use the IDirectSoundCaptureFXNoiseSuppress8 interface to set and retrieve parameters.

The effect interfaces are obtained from the capture buffer object by using IDirectSoundCaptureBuffer8::GetObjectInPath.


Using the Capture Buffer

Capturing a sound consists of the following steps:

  1. Start the buffer by calling the IDirectSoundCaptureBuffer8::Start method. Normally you should pass DSCBSTART_LOOPING in the dwFlags parameter so that the buffer will keep running continuously rather than stopping when it reaches the end. Audio data from the input device begins filling the buffer from the beginning.

  2. Wait until the desired amount of data is available. For one method of determining when the capture cursor reaches a certain point, see Capture Buffer Notification.

  3. When sufficient data is available, lock a portion of the capture buffer by calling the IDirectSoundCaptureBuffer8::Lock method.

    To make sure you are not attempting to lock a portion of memory that is about to be used for capture, you can first obtain the position of the read cursor by calling IDirectSoundCaptureBuffer8::GetCurrentPosition.

    As parameters to the Lock method, you pass the size and offset of the block of memory you want to read. The method returns a pointer to the address where the memory block begins, and the size of the block. If the block wraps around from the end of the buffer to the beginning, two pointers are returned, one for each section of the block. The second pointer is NULL if the locked portion of the buffer does not wrap around.

  4. Copy the data from the buffer, using the addresses and block sizes returned by the Lock method.
  5. Unlock the buffer with the IDirectSoundCaptureBuffer8::Unlock method.
  6. Repeat steps 2 to 5 until you are ready to stop capturing data. Then call the IDirectSoundCaptureBuffer8::Stop method.


Writing to a WAV File

WAV files are in the Resource Interchange File Format (RIFF), which consists of a variable number of named chunks containing either header information (for example, the format of sound samples) or data (the samples themselves). The Win32 API supplies functions for opening and closing RIFF files, seeking to chunks, and so on. The names of these functions all start with "mmio".

The DirectSound API does not include methods for writing to WAV files. However, the DXUTsound.cpp file used by many of the SDK sample applications implements a CWaveFile class that has the following methods for managing capture files:

  • Open. Opens a file and writes the header chunks.
  • Write. Writes from a buffer to the data chunk and advances the write cursor.
  • Close. Writes the size of the data chunk in the header and closes the file.

The first step in writing a WAV file is to call the CWaveFile::Open method. This creates the file and writes the WAV format chunk. The parameters are the filename, a pointer to an initialized WAVEFORMATEX structure, and the WAVEFILE_WRITE flag. The method returns an HRESULT.

The following code opens a WAV file for writing:

    CWaveFile   g_pWaveFile;
    WAVEFORMATEX  wfxInput;

    ZeroMemory( &wfxInput, sizeof(wfxInput));
    wfxInput.wFormatTag = WAVE_FORMAT_PCM;
    wfxInput.nSamplesPerSec = 22050
    wfxInput.wBitsPerSample =  8;
    wfxInput.nChannels = 1;
    wfxInput.nBlockAlign =
        wfxInput.nChannels * (wfxInput.wBitsPerSample / 8);
    wfxInput.nAvgBytesPerSec =
        wfxInput.nBlockAlign * wfxInput.nSamplesPerSec;

    g_pWaveFile = new CWaveFile;
    if (FAILED(g_pWaveFile->Open("mywave.wav", &wfxInput,
        WAVEFILE_WRITE)))
    {
      g_pWaveFile->Close();
    }

The application can now begin copying data from the capture buffer to the file.

The following example function is called each time the read cursor reaches a notification position. In this function, the following global variables are used:

  • g_pDSBCapture is a pointer to the IDirectSoundCaptureBuffer8 interface of the capture buffer.
  • g_dwNextCaptureOffset tracks the buffer offset of the next block of data that will be copied to the file.
  • g_dwCaptureBufferSize is the size of the capture buffer, used in calculating wraparound.
    HRESULT RecordCapturedData()
    {
      HRESULT hr;
      VOID* pbCaptureData  = NULL;
      DWORD dwCaptureLength;
      VOID* pbCaptureData2 = NULL;
      DWORD dwCaptureLength2;
      VOID* pbPlayData   = NULL;
      UINT  dwDataWrote;
      DWORD dwReadPos;
      LONG lLockSize;

      if (NULL == g_pDSBCapture)
          return S_FALSE;
      if (NULL == g_pWaveFile)
          return S_FALSE;

      if (FAILED (hr = g_pDSBCapture->GetCurrentPosition(
        NULL, &dwReadPos)))
          return hr;

      // Lock everything between the private cursor
      // and the read cursor, allowing for wraparound.

      lLockSize = dwReadPos - g_dwNextCaptureOffset;
      if( lLockSize < 0 ) lLockSize += g_dwCaptureBufferSize;

      if( lLockSize == 0 ) return S_FALSE;

      if (FAILED(hr = g_pDSBCapture->Lock(
            g_dwNextCaptureOffset, lLockSize,
            &pbCaptureData, &dwCaptureLength,
            &pbCaptureData2, &dwCaptureLength2, 0L)))
        return hr;

      // Write the data. This is done in two steps
      // to account for wraparound.

      if (FAILED( hr = g_pWaveFile->Write( dwCaptureLength,
          (BYTE*)pbCaptureData, &dwDataWrote)))
        return hr;

      if (pbCaptureData2 != NULL)
      {
        if (FAILED(hr = g_pWaveFile->Write(
            dwCaptureLength2, (BYTE*)pbCaptureData2,
            &dwDataWrote)))
          return hr;
      }

      // Unlock the capture buffer.

     g_pDSBCapture->Unlock( pbCaptureData, dwCaptureLength,
        pbCaptureData2, dwCaptureLength2  );

      // Move the capture offset forward.

      g_dwNextCaptureOffset += dwCaptureLength;
      g_dwNextCaptureOffset %= g_dwCaptureBufferSize;
      g_dwNextCaptureOffset += dwCaptureLength2;
      g_dwNextCaptureOffset %= g_dwCaptureBufferSize;

      return S_OK;
    }

When capturing is finished, the application closes the WAV file.

    g_pWaveFile->Close();

See Also

  • CaptureSound Sample


Advanced Topics in DirectSound

This section contains information about optimizations and advanced features not needed by all DirectSound applications.

Information is presented in the following topics:

  • DirectSound Driver Models
  • Property Sets for DirectSound Buffers
  • Optimizing DirectSound Performance
  • Writing to the Primary Buffer


DirectSound Driver Models

Under the VXD driver model, all DirectSound mixing is done in Dsound.vxd, a virtual device driver. Dsound.vxd also provides close access to the actual DMA buffer that the sound card uses to receive data from the host CPU. This is the same as the DirectSound primary buffer. A DirectSound application can set specific properties of the primary buffer, such as sampling rate and bit depth, thus changing the properties of the hardware itself.

Under the Windows Driver Model (WDM), DirectSound does not have direct access to the sound hardware, except in the case of hardware-accelerated buffers. Instead, DirectSound sends data to the kernel mixer. The kernel mixer's job is to convert the format of multiple audio streams to a common format, mix them together and send the result to the hardware. In a sense, it does what Dsound.vxd does. One major difference is that Dsound.vxd mixes only DirectSound buffer data, but the kernel mixer mixes all Windows audio data, including data from applications that use the Win32 waveOut functions. The rule that DirectSound and the waveform-audio output device cannot both be open at the same time is not true on systems with WDM drivers.

Of particular importance is the kernel mixer's relationship with the audio hardware. the kernel mixer is the only software on the system that can specify the format of the hardware's DMA buffer. It selects the format on the basis of sounds it is asked to mix. It sets the output format to the highest-quality format of sounds that it is asked to mix, or to the closest format to this that the hardware supports.

This has one very important implication: DirectSound cannot set the format of the hardware's DMA buffer. For your application, this means that the hardware format is based on the data you actually play. If you play a 44 kHz file, Kmixer will mix all data up to 44 kHz and ensure that the hardware is running at 44 kHz.

As an application developer, you don't choose the driver model used. That is completely determined by the type of sound card, the version of Windows, and the installed driver. For this reason, it is very important that you cover all possibilities when you test your application. DirectSound might be using Dsound.vxd or it might be using the kernel mixer, and you should ensure that your application's behavior and performance are acceptable on both.


System Property Sets

Information about system-wide DirectSound device properties can be obtained from an object of class CLSID_DirectSoundPrivate (11AB3EC0-25EC-11d1-A4D8-00C04FC28ACA). This class supports the IKsPropertySet interface. The CLSID and properties are defined in Dsconf.h.

  1. To create an object of this classCall the LoadLibrary function to load Dsound.dll.
  2. Call the GetProcAddress function to obtain the DllGetClassObject function.
  3. Call DllGetClassObject to obtain the IClassFactory interface of the class factory for the CLSID_DirectSoundPrivate class.
  4. Call IClassFactory::CreateInstance to create the CLSID_DirectSoundPrivate object and retrieve the IKsPropertySet interface (IID_IKsPropertySet).

The CLSID_DirectSoundPrivate object supports one property set, DSPROPSETID_DirectSoundDevice (84624F82-25EC-11d1-A4D8-00C04FC28ACA). This property set exposes the following three read-only properties.

  • DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING
  • DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION
  • DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE

DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING

This property retrieves the DirectSound device GUID corresponding to a specified Windows Multimedia device name.

Property data is contained in a DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_DATA structure, available in ANSI and Unicode versions. This structure has the following members.

Member | Type | Description
DeviceName | String | [in] Name of device
DataFlow | DIRECTSOUNDDEVICE_DATAFLOW | [in] Direction of data flow, either DIRECTSOUNDDEVICE_DATAFLOW_RENDER or DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE
DeviceID | GUID | [out] DirectSound device ID

DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION

This property retrieves a full description of a DirectSound device specified by GUID.

Property data is contained in a DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_DATA structure, available in ANSI and Unicode versions. This structure has the following members.

Member | Type | Description
Type | DIRECTSOUNDDEVICE_TYPE | [out] Device type: DIRECTSOUNDDEVICE_TYPE_EMULATED, DIRECTSOUNDDEVICE_TYPE_VXD or DIRECTSOUNDDEVICE_TYPE_WDM
DataFlow | DIRECTSOUNDDEVICE_DATAFLOW | [in, out] Direction of data flow, either DIRECTSOUNDDEVICE_DATAFLOW_RENDER or DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE
DeviceID | GUID | [in] DirectSound device GUID, or NULL for the default device of the type specified by DataFlow
Description | String | [out] Description of DirectSound device
Module | String | [out] Module name of the DirectSound driver
Interface | String | [out] PnP device interface name
WaveDeviceID | ULONG | [out] Identifier of the corresponding Windows Multimedia device

DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE

This property enumerates all DirectSound render or capture devices.

Property data is contained in a DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_DATA structure, available in Ansi and Unicode versions. This structure has the following members.

Member | Type | Description
Callback | LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK | [in] Application-defined callback function. When IKsPropertySet::Get is called, this function is called once for each device enumerated. It takes as parameters a DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_DATA structure describing the enumerated device, and the value in Context.
Context | LPVOID | [in] User-defined value to be passed to the callback function for each device enumerated.


Property Sets for DirectSound Buffers

To make use of extended properties on sound cards, you must first determine whether the driver supports the IKsPropertySet interface, and obtain a pointer to the interface if it is supported. You can do this by calling the QueryInterface method of an existing interface on a DirectSound 3D buffer object, as follows:

HRESULT hr = lpDirectSound3DBuffer->QueryInterface(
    IID_IKsPropertySet,
    (void**)&lpKsPropertySet));

In the example, lpDirectSound3DBuffer is a pointer to the buffer's interface and lpKsPropertySet receives the address of the IKsPropertySet interface if one is found. IID_IKsPropertySet is a GUID defined in Dsound.h. The interface is available only if the buffer is hardware-accelerated and the underlying driver supports property sets.

Note The declaration of this interface in Dsound.h is different from that in Ksproxy.h and Strmif.h. If your project includes Ksproxy.h or Strmif.h but you wish to use the DirectSound implementation, be sure to include Dsound.h first. Failing to do so may cause your application to stop responding when a method of IKsPropertySet is called.

You can look for a particular property by using the IKsPropertySet::QuerySupport method. The value of the PropertySetId parameter is a GUID defined by the hardware vendor.

After you've determined that support for a particular property exists, you can change the state of the property by using the IKsPropertySet::Set method and determine its present state by using the IKsPropertySet::Get method. The state of the property is set or returned in the pPropertyData parameter.

Additional property parameters may also be passed to the object in the pPropertyParams parameter to the IKsPropertySet::Set method. The exact way in which this parameter is to be used is defined in the hardware vendor's specifications for the property set, but typically it would be used to define the instance of the property set. In practice, the pPropertyParams parameter is rarely used.


Optimizing DirectSound Performance

This section offers miscellaneous tips for improving the performance of applications that play their audio data directly into DirectSound buffers. The following topics are covered:

  • Using Hardware Mixing
  • Dynamic Voice Management
  • Using Buffers Efficiently


Using Hardware Mixing

Modern sound cards are designed to connect to the peripheral component interconnect (PCI) local bus. This bus provides the card with rapid access to system memory. As a result, it is practical for the audio processor to mix data directly from buffers in system memory, and it is unnecessary to have memory buffers on the card itself.

On PCI cards, static buffers and streaming buffers are effectively the same, and the same buffers may be reported in DSCAPS as both static and streaming buffers. The DSBCAPS_STATIC flag in DSBUFFERDESC does not affect the location of a DirectSound buffer.

The following tips will help you make the most of hardware mixing.

  • At run time, use the IDirectSound8::GetCaps method to determine what formats are supported by the sound-accelerator hardware, and use only those formats if possible.
  • Create sound buffers first for the sounds you use the most. There is a limit to the number of buffers that can be mixed by hardware.
  • To force a buffer to be created in hardware, specify the DSBCAPS_LOCHARDWARE flag in the dwFlags member of the DSBUFFERDESC structure. If you do this and resources for hardware mixing are not available, the IDirectSound8::CreateSoundBuffer method will fail.
  • Use voice management to enable DirectSound to assign buffers to hardware resources when they are available, and to force termination of less important buffers in order to free hardware resources. See Dynamic Voice Management.


Dynamic Voice Management

Many sound cards maintain their own secondary buffers and handle 3D effects and mixing for them. These hardware buffers, as they are called, usually reside in system memory rather than on the card itself, but because they are mixed by the device, they make far smaller demands on the system processor than do software buffers. It is therefore most efficient to have as many buffers as possible allocated to hardware, especially 3D buffers.

By default, DirectSound allocates buffers to hardware whenever it can. However, it can create only as many hardware buffers as the device can play at one time. In other words, the number of hardware buffers is limited by the availability of hardware voices. DirectSound allocates a hardware voice when a buffer is created and releases it only when the buffer is destroyed. If an application creates many buffers, some of them will likely end up in software, which means that they will be managed and mixed by the CPU rather than the sound card.

Note The DirectSound voice manager allocates hardware mixing resources, not memory. On a PCI card, the buffer occupies the same memory before and after it is allocated, regardless of whether it is allocated to the hardware mixer or the software mixer.

Dynamic voice management helps you overcome the limited availability of hardware resources by deferring voice allocation until buffers are played, and by enabling DirectSound to stop lower-priority sounds prematurely and release their resources so that these resources can be allocated to new sounds.

To defer the allocation of resources for hardware mixing and 3D effects to the moment when the buffer is played, specify the DSBCAPS_LOCDEFER flag in the DSBUFFERDESC structure passed to IDirectSound8::CreateSoundBuffer. When you call IDirectSoundBuffer8::Play or IDirectSoundBuffer8::AcquireResources on such a buffer, DirectSound places the buffer in hardware if possible, and in software otherwise.

When calling Play, you can attempt to free a hardware voice for the buffer by passing one of the flags in the following table, or one of the first two flags in combination with the third. DirectSound then searches for a playing buffer that is suitable for termination as specified by the flags.

Flag | Criterion
DSBPLAY_TERMINATEBY_TIME | Select the buffer that has been playing longer than any other candidate buffers.
DSBPLAY_TERMINATEBY_DISTANCE | Select the 3D candidate buffer farthest from the listener.
DSBPLAY_TERMINATEBY_PRIORITY | Select the buffer that has the lowest priority of candidate buffers, as set in the call to Play. If this is combined with one of the other two flags, the other flag is used only to resolve ties.

If it finds a suitable buffer, DirectSound stops it and allocates the voice it was using to the newly played buffer. If no buffer is suitable for termination, the newly played buffer is played in software, unless the DSBPLAY_LOCHARDWARE flag was specified, in which case the call to Play fails.

For more information on how deferred buffers are dealt with when played, see IDirectSoundBuffer8::Play.

Note Do not use the DSBCAPS_STATIC flag in combination with DSBCAPS_LOCDEFER when creating buffers. DSBCAPS_STATIC buffers are placed in on-card memory when this is available, as is the case on some older cards. If you create such a buffer with the DSBCAPS_LOCDEFER flag, the buffer memory is not copied to the sound card until the buffer is played for the first time, which can result in unacceptable delays.


Using Buffers Efficiently

When using streaming buffers, limit the frequency of notifications and data writes. Do not create buffers with many notification positions, or small buffers with notifications at very short intervals. A streaming buffer can work efficiently and reliably with as few as three notification positions.

Performance is affected when you make control changes on a secondary buffer. To improve performance, reduce the frequency of calls to IDirectSoundBuffer8::SetVolume, IDirectSoundBuffer8::SetPan, and IDirectSoundBuffer8::SetFrequency. For example, if you have a routine that moves a sound from the left to the right speaker in synchronization with animation frames, try calling the SetPan method only every second or third frame.

Keep in mind that 3D buffers in software make high demands on the central processing unit. To limit these demands you can do the following:

  • Put frequently-used sounds in hardware buffers if possible.
  • Don't create 3D buffers for sounds that won't benefit from the effect.
  • Use IDirectSound3DBuffer8::SetMode with the DS3DMODE_DISABLE flag to disable 3D processing on any 3D sound buffer that is no longer moving in relation to the listener.
  • Make parameter changes in batches, or use deferred settings to make changes to all buffers and the listener at once.

See Also

  • Batch Parameters for 3D Buffers
  • Batch Parameters for 3D Listeners
  • Deferred Settings
  • Minimum and Maximum Distances


Writing to the Primary Buffer

For applications that require specialized mixing or other effects not supported by secondary buffers, DirectSound allows direct access to the primary buffer.

When you obtain write access to the primary buffer, other DirectSound features become unavailable. Secondary buffers are not mixed, so hardware-accelerated mixing is unavailable.

Most applications should use secondary buffers instead of directly accessing the primary buffer. Applications can write to a secondary buffer easily because the larger buffer size provides more time to write the next block of data, thereby minimizing the risk of gaps in the audio. Even if an application has simple audio requirements, such as using one stream of audio data that does not require mixing, it will achieve better performance by using a secondary buffer to play its audio data.

Note Writing directly to the primary buffer offers no advantages under the Windows driver model (WDM). Under WDM, the primary buffer is in effect a secondary buffer that is mixed by the kernel mixer. For more information on WDM, see DirectSound Driver Models.

You cannot specify the size of the primary buffer, and you must accept the returned size after the buffer is created. A primary buffer is typically very small, so if your application writes directly to this kind of buffer, it must write blocks of data at short intervals to prevent the previously written data from being replayed.

You cannot obtain write access to a primary buffer unless it exists in hardware. To determine whether this is the case, call the IDirectSoundBuffer8::GetCaps method and check for the DSBCAPS_LOCHARDWARE flag in the dwFlags member of the DSBCAPS structure that is returned. If you attempt to lock a primary buffer that is emulated in software, the call will fail.

You create an accessible primary buffer by specifying the DSBCAPS_PRIMARYBUFFER flag in the DSBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method. If you want to write to the buffer, the cooperative level must be DSSCL_WRITEPRIMARY.

Primary sound buffers must be played with looping. Ensure that the DSBPLAY_LOOPING flag is set.

The following example shows how to obtain write access to the primary buffer. Note that the primary buffer supports only the IDirectSoundBuffer interface, not IDirectSoundBuffer8.

    BOOL AppCreateWritePrimaryBuffer(
      LPDIRECTSOUND8 lpDirectSound,
      LPDIRECTSOUNDBUFFER *lplpDsb,
      LPDWORD lpdwBufferSize,
      HWND hwnd)
    {
      DSBUFFERDESC dsbdesc;
      DSBCAPS dsbcaps;
      HRESULT hr;
      WAVEFORMATEX wf;

      // Set up wave format structure.
      memset(&wf, 0, sizeof(WAVEFORMATEX));
      wf.wFormatTag = WAVE_FORMAT_PCM;
      wf.nChannels = 2;
      wf.nSamplesPerSec = 22050;
      wf.nBlockAlign = 4;
      wf.nAvgBytesPerSec =
          wf.nSamplesPerSec * wf.nBlockAlign;
      wf.wBitsPerSample = 16;

      // Set up DSBUFFERDESC structure.
      memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
      dsbdesc.dwSize = sizeof(DSBUFFERDESC);
      dsbdesc.dwFlags = DSBCAPS_PRIMARYBUFFER;
      // Buffer size is determined by sound hardware.
      dsbdesc.dwBufferBytes = 0;
      dsbdesc.lpwfxFormat = NULL; // Must be NULL for primary buffers.

      // Obtain write-primary cooperative level.
      hr = lpDirectSound->SetCooperativeLevel(hwnd, DSSCL_WRITEPRIMARY);
      if SUCCEEDED(hr)
      {
        // Try to create buffer.
        hr = lpDirectSound->CreateSoundBuffer(&dsbdesc,
          lplpDsb, NULL);
        if SUCCEEDED(hr)
        {
          // Set primary buffer to desired format.
          hr = (*lplpDsb)->SetFormat(&wf);
          if SUCCEEDED(hr)
          {
            // If you want to know the buffer size, call GetCaps.
            dsbcaps.dwSize = sizeof(DSBCAPS);
            (*lplpDsb)->GetCaps(&dsbcaps);
            *lpdwBufferSize = dsbcaps.dwBufferBytes;
            return TRUE;
          }
        }
      }
      // Failure.
      *lplpDsb = NULL;
      *lpdwBufferSize = 0;
      return FALSE;
    }

The following example illustrates how an application might implement a custom mixer. The AppMixIntoPrimaryBuffer sample function would have to be called at regular intervals, frequently enough to prevent the sound device from repeating blocks of data. The CustomMixer function is an application-defined function that mixes several streams together, as specified in an application-defined APPSTREAMINFO structure, and writes the result to the specified pointer.

    BOOL AppMixIntoPrimaryBuffer(
        APPSTREAMINFO* lpAppStreamInfo,
        LPDIRECTSOUNDBUFFER lpDsbPrimary,
        DWORD dwDataBytes,
        DWORD dwOldPos,
        LPDWORD lpdwNewPos)
    {
      LPVOID lpvPtr1;
      DWORD dwBytes1;
      LPVOID lpvPtr2;
      DWORD dwBytes2;
      HRESULT hr;
      // Obtain write pointer.
      hr = lpDsbPrimary->Lock(dwOldPos, dwDataBytes,
              &lpvPtr1, &dwBytes1,
              &lpvPtr2, &dwBytes2, 0);

      // If DSERR_BUFFERLOST is returned, restore and retry lock.

      if (DSERR_BUFFERLOST == hr)
      {
        lpDsbPrimary->Restore();
        hr = lpDsbPrimary->Lock(dwOldPos, dwDataBytes,
                &lpvPtr1, &dwBytes1,
                &lpvPtr2, &dwBytes2, 0);
      }
      if SUCCEEDED(hr)
      {
        // Mix data into the returned pointers.
        CustomMixer(lpAppStreamInfo, lpvPtr1, dwBytes1);
        *lpdwNewPos = dwOldPos + dwBytes1;
        if (NULL != lpvPtr2)
        {
          CustomMixer(lpAppStreamInfo, lpvPtr2, dwBytes2);
          *lpdwNewPos = dwBytes2; // Because it wrapped around.
        }
        // Release the data back to DirectSound.
        hr = lpDsbPrimary->Unlock(lpvPtr1, dwBytes1,
                lpvPtr2, dwBytes2);
        if SUCCEEDED(hr)
        {
          return TRUE;
        }
      }
      // Lock or Unlock failed.
      return FALSE;
    }


DirectSound Samples

The sample applications described in this section demonstrate the use and capabilities of the DirectSound application programming interface (API).

The following samples are found on the Start menu under All Programs, Microsoft DirectX SDK, DirectX Sample Browser.

  • AdjustSound Sample
  • AmplitudeModulation Sample
  • CaptureSound Sample
  • Enumerate DirectSound Devices Sample
  • Full Duplex Filter Sample
  • Play 3D Sound Sample
  • Play Sound Sample
  • SoundFX Sample
  • Voice Management Sample

The source code is in the following folder, where SDK root is the installation folder for the DirectX SDK:

    (SDK root)\Samples\C++\DirectSound

The samples use common source files that implement functions and classes for basic DirectSound functionality and for general tasks such as finding media files. For more information, see DirectSound sample utility classes.


DirectSound Sample Utility Classes

The core functionality for the DirectSound samples is in a common set of classes, declared in DXUTsound.h and implemented in DXUTsound.cpp.

These files are found in the following folder:

(SDK root)\samples\C++\Common

The utility classes provide basic functionality for the samples, and you can use them as a starting-point for your own applications. However, they are not intended to be a full-featured wrapper for the DirectSound API.

The following classes are used in the samples:

Class | Description
CSound Sample Class | Represents a static buffer.
CSoundManager Sample Class | Contains functionality for creating and initializing DirectSound, accessing the primary buffer, and creating secondary buffers.
CStreamingSound Sample Class | Represents a sound in one or more streaming buffers.
CWaveFile Sample Class | Used for reading from and writing to WAV files and reading from WAV resources or waveforms stored in memory.

See Also

DirectSound Samples


CSound Sample Class

The CSound sample class represents a sound in one or more static buffers. An object of this class can be used to play multiple instances of a sound effect. The object is usually created through a call to the Create method of the CSoundManager Sample Class.

class CSound
{
protected:
    LPDIRECTSOUNDBUFFER* m_apDSBuffer;
    DWORD                m_dwDSBufferSize;
    CWaveFile*           m_pWaveFile;
    DWORD                m_dwNumBuffers;
    DWORD                m_dwCreationFlags;

    HRESULT RestoreBuffer(LPDIRECTSOUNDBUFFER pDSB, BOOL* pbWasRestored);

public:
    CSound(LPDIRECTSOUNDBUFFER* apDSBuffer, DWORD dwDSBufferSize,
        DWORD dwNumBuffers, CWaveFile* pWaveFile, DWORD dwCreationFlags);
    virtual ~CSound();

    HRESULT Get3DBufferInterface(DWORD dwIndex,
        LPDIRECTSOUND3DBUFFER* ppDS3DBuffer);
    HRESULT FillBufferWithSound(LPDIRECTSOUNDBUFFER pDSB,
        BOOL bRepeatWavIfBufferLarger);
    LPDIRECTSOUNDBUFFER GetFreeBuffer();
    LPDIRECTSOUNDBUFFER GetBuffer(DWORD dwIndex);
    HRESULT Play(DWORD dwPriority = 0, DWORD dwFlags = 0,
        LONG lVolume = 0, LONG lFrequency = 0);
    HRESULT Play3D(LPDS3DBUFFER p3DBuffer, DWORD dwPriority = 0,
        DWORD dwFlags = 0, LONG lFrequency = 0);
    HRESULT Stop();
    HRESULT Reset();
    BOOL    IsSoundPlaying();
};

Constructor

The constructor fills one or more buffers with the data from a specified WAV file and initializes private data members.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
FillBufferWithSound | Fills the specified buffer with the data from the WAV file that was passed to the object constructor. If the buffer is larger than the data, data can optionally be repeated; otherwise the rest of the buffer is filled with silence.
Get3DBufferInterface | Retrieves the IDirectSound3DBuffer8 interface pointer for the specified buffer, if the buffer has 3D capabilities.
GetBuffer | Retrieves the IDirectSoundBuffer interface of the specified buffer. Use QueryInterface to retrieve IDirectSoundBuffer8.
GetFreeBuffer | Retrieves the IDirectSoundBuffer interface of the first buffer that is not playing. If all buffers are playing, the method returns a randomly selected buffer. Use QueryInterface to retrieve IDirectSoundBuffer8.
IsSoundPlaying | Returns a Boolean variable that indicates whether the specified buffer is playing.
Play | Plays a buffer. The method selects the buffer to play by calling GetFreeBuffer, and restores it if necessary The application can pass in a voice management flag; the DSBPLAY_LOOPING flag to repeat the sound; a volume in hundredths of decibels (where 0 is full volume and -10,000 is silence); and a frequency in hertz that is added to the basic frequency of the sound.
Play3D | Plays a 3D buffer. This method is similar to Play, but the application also passes in a DS3DBUFFER structure describing the 3D parameters to be set. (Note that if the CSound object has more than one buffer, there is no way to determine which one is played by this call. If you want to set 3D parameters dynamically while the buffer is playing, add functionality to return a buffer pointer.)
Reset | Sets the play cursor on all buffers to the beginning.
Stop | Stops all buffers.

The class is implemented in (SDK root)\samples\C++\Common\DXUTsound.cpp.

See Also

DirectSound sample utility classes, DirectSound Buffers


CSoundManager Sample Class

The CSoundManager sample class contains functionality for creating and initializing DirectSound, accessing the primary buffer, and creating secondary buffers.

class CSoundManager
{
protected:
    LPDIRECTSOUND8 m_pDS;

public:
    CSoundManager();
    ~CSoundManager();

    HRESULT Initialize( HWND hWnd, DWORD dwCoopLevel );
    inline  LPDIRECTSOUND8 GetDirectSound() { return m_pDS; }
    HRESULT SetPrimaryBufferFormat( DWORD dwPrimaryChannels,
        DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate );
    HRESULT Get3DListenerInterface(LPDIRECTSOUND3DLISTENER* ppDSListener );
    HRESULT Create( CSound** ppSound, LPTSTR strWaveFileName,
        DWORD dwCreationFlags = 0, GUID guid3DAlgorithm = GUID_NULL,
        DWORD dwNumBuffers = 1 );
    HRESULT CreateFromMemory( CSound** ppSound, BYTE* pbData,
        ULONG ulDataSize, LPWAVEFORMATEX pwfx, DWORD dwCreationFlags = 0,
        GUID guid3DAlgorithm = GUID_NULL, DWORD dwNumBuffers = 1 );
    HRESULT CreateStreaming( CStreamingSound** ppStreamingSound,
        LPTSTR strWaveFileName, DWORD dwCreationFlags,
        GUID guid3DAlgorithm, DWORD dwNotifyCount, DWORD dwNotifySize,
        HANDLE hNotifyEvent );
};

Constructor

The constructor initializes a data member.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
Create | Creates a CSound object associated with a WAV file and containing the specified number of buffers. For information on possible values in the dwCreationFlags and guid3DAlgorithm parameters, see DSBUFFERDESC.
CreateFromMemory | Creates a CSound object associated with a waveform in memory and containing the specified number of buffers. For information on possible values in the dwCreationFlags and guid3DAlgorithm parameters, see DSBUFFERDESC.
CreateStreaming | Creates a CStreamingSound object associated with a WAV file and containing a single streaming buffer. The application specifies notification positions and an event. In response to notifications, the application calls CStreamingSound::HandleWaveStreamNotification to refresh the data in the buffer. For information on possible values in the dwCreationFlags and guid3DAlgorithm parameters, see DSBUFFERDESC.
Get3DListenerInterface | Retrieves the IDirectSound3DListener8 interface.
GetDirectSound | Retrieves the IDirectSound8 interface of the DirectSound object created by Initialize.
Initialize | Creates the DirectSound object and sets the cooperative level.
SetPrimaryBufferFormat | Sets the format of the primary buffer. This method should not be used by most applications. For more information, see Mixing Sounds.

The class is implemented in (SDK root)\samples\C++\Common\DXUTsound.cpp.

See Also

  • DirectSound sample utility classes
  • CSound Sample Class
  • CStreamingSound Sample Class
  • DirectSound Buffers


CStreamingSound Sample Class

The CStreamingSound sample class represents a streaming buffer. The class inherits from CSound. An object of this class is usually created through a call to the CreateStreaming method of the CSoundManager Sample Class.

A CStreaming object has only one buffer. When calling methods inherited from CSound that take a buffer index, pass 0.

class CStreamingSound : public CSound
{
protected:
    DWORD m_dwLastPlayPos;
    DWORD m_dwPlayProgress;
    DWORD m_dwNotifySize;
    DWORD m_dwNextWriteOffset;
    BOOL  m_bFillNextNotificationWithSilence;

public:
    CStreamingSound(LPDIRECTSOUNDBUFFER pDSBuffer, DWORD dwDSBufferSize,
        CWaveFile* pWaveFile, DWORD dwNotifySize);
    ~CStreamingSound();

    HRESULT HandleWaveStreamNotification(BOOL bLoopedPlay);
    HRESULT Reset();
};

Constructor

The constructor calls the CSound constructor to fill the buffer with data from the beginning of the WAV file, and initializes private data members.

Public Methods

In addition to the methods inherited from CSound, the class contains the following public methods, in alphabetical order.

Method | Description
HandleWaveStreamNotification | Restores the buffer if necessary, then reads data from the file and writes it to the part of the buffer that has just been played. If the end of data is reached, the rest of the buffer is filled with silence, and the buffer is stopped after all data has been played. Call this method in response to notifications received in the message loop. Pass in TRUE as the parameter to repeat the sound when it reaches the end.
Reset | Restores the buffer if necessary, then resets the play position and the file so that the sound can begin playing again from the beginning.

The class is implemented in (SDK root)\samples\C++\Common\DXUTsound.cpp.

See Also

  • DirectSound sample utility classes
  • CSound Sample Class
  • DirectSound Buffers


CWaveFile Sample Class

The CWaveFile sample class is used for reading from and writing to WAV files and reading from WAV resources or waveforms stored in memory. An object of this class is created by CSoundManager when creating a CSound or CStreamingSound object. Applications do not usually need to call methods of CWaveFile directly.

class CWaveFile
{
public:
    WAVEFORMATEX* m_pwfx;
    HMMIO         m_hmmio;
    MMCKINFO      m_ck;
    MMCKINFO      m_ckRiff;
    DWORD         m_dwSize;
    MMIOINFO      m_mmioinfoOut;
    DWORD         m_dwFlags;
    BOOL          m_bIsReadingFromMemory;
    BYTE*         m_pbData;
    BYTE*         m_pbDataCur;
    ULONG         m_ulDataSize;
    CHAR*         m_pResourceBuffer;

protected:
    HRESULT ReadMMIO();
    HRESULT WriteMMIO(WAVEFORMATEX *pwfxDest);

public:
    CWaveFile();
    ~CWaveFile();

    HRESULT Open(LPTSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags);
    HRESULT OpenFromMemory(BYTE* pbData, ULONG ulDataSize,
        WAVEFORMATEX* pwfx, DWORD dwFlags);
    HRESULT Close();
    HRESULT Read(BYTE* pBuffer, DWORD dwSizeToRead, DWORD* pdwSizeRead);
    HRESULT Write(UINT nSizeToWrite, BYTE* pbData, UINT* pnSizeWrote);
    DWORD   GetSize();
    HRESULT ResetFile();
    WAVEFORMATEX* GetFormat() { return m_pwfx; };
};

Constructor

The constructor initializes data members.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
Close | Closes the file. If the file is being written to, first writes RIFF chunk sizes.
GetFormat | Returns a WAVEFORMATEX structure describing the format of the waveform.
GetSize | Retrieves the size of the data chunk, after Open has been called.
Open | Opens the file or loads the resource and retrieves the WAV format and data chunk size, or opens the file for writing and writes the header chunks. The strFileName parameter can be a file path or the name of a resource of type "WAVE" or "WAV". Pass WAVEFILE_READ in dwFlags to read from the file, or WAVEFILE_WRITE if capturing to the file. Use the pwfx parameter to specify the format of captured data; this parameter is ignored if the file is being read.
OpenFromMemory | Initializes data members so that subsequent calls to Read will get data from the supplied memory location rather than from a file or resource. It is assumed that the data does not contain any RIFF headers, and that pbData points to the start of the waveform samples.
Read | Reads data from the file, resource, or memory and copies it to the supplied address, which the application is responsible for obtaining by using IDirectSoundBuffer8::Lock. Read advances the pointer into the data by the number of bytes specified in dwSizeToRead.
ResetFile | Resets the pointer into the file or data to the beginning of the data chunk.
Write | Writes data to the file from the specified address, which the application is responsible for obtaining by using IDirectSoundCaptureBuffer8::Lock.

The class is implemented in (SDK root)\samples\C++\Common\DXUTsound.cpp.

See Also

  • DirectSound sample utility classes
  • Reading WAV Data
  • Writing to a WAV File


AdjustSound Sample

The AdjustSound sample shows how to create a DirectSound secondary buffer to play a WAV file, and how to change the parameters of the buffer.

Path

Source: (SDK root)\Samples\C++\DirectSound\AdjustSound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select Focus and Buffer Mixing options; note that the various settings are explained under Expected Behavior as you select them. Click Play. If you don't hear any sound, check the Status pane. The application might fail to create the buffer in hardware if this option has been selected.

By using the sliders you can adjust the frequency, pan, and volume dynamically as the buffer is playing.

Programming Notes

To set the focus behavior of the buffer, the application calls IDirectSound8::CreateSoundBuffer with DSBCAPS_GLOBALFOCUS or DSBCAPS_STICKYFOCUS, or neither of these flags. To set the memory location of the buffer, it sets either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE, or neither of these flags to allow DirectSound to create the buffer in a either hardware or software.

Parameters are set by using IDirectSoundBuffer8::SetFrequency, IDirectSoundBuffer8::SetPan, and IDirectSoundBuffer8::SetVolume.

For a simpler example of how to set up a DirectSound buffer without as many controls, see the Play Sound Sample.

See Also

  • DirectSound C++ Samples
  • DirectSound Buffers


AmplitudeModulation Sample

The AmplitudeModulation sample shows how to apply an effect to a DirectSound secondary buffer and modify the parameters of the effect.

Path

Source: (SDK root)\Samples\C++\DirectSound\AmplitudeModulation

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Play the default sound or load another WAV file by clicking Sound File. Change the parameters of the effect by selecting one of the Wave Form options and moving the slider to change the modulation rate.

Programming Notes

The application takes the following steps to set an effect on a buffer and change its parameters:

  1. Creates the buffer with the DSBCAPS_CTRLFX flag.
  2. Describe the effect in a DSEFFECTDESC structure, setting the guidDSFXClass member to the GUID of the effect desired.
  3. Passes the buffer description to IDirectSoundBuffer8::SetFX.
  4. Calls IDirectSoundBuffer8::GetObjectInPath to get an interface pointer to the effect, in this case IDirectSoundFXGargle8.
  5. In the OnEffectChanged function, uses IDirectSoundFXGargle8::SetAllParameters to change the parameters of the gargle effect.

See Also

  • DirectSound C++ Samples
  • Using Effects


CaptureSound Sample

The CaptureSound application shows how to capture waveforms to a file.

Path

Source: (SDK root)\Samples\C++\DirectSound\CaptureSound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Select a device and a format. Create a file, or replace an existing one, by clicking Sound File. Click Record to start and stop recording.

Programming Notes

The sample relies on notifications to ascertain when data should be read from the buffer. The notification positions are set up in the InitNotifications function, and the events are received in the WinMain function.

See Also

  • DirectSound C++ Samples
  • Capturing Waveforms


Enumerate DirectSound Devices Sample

The Enumerate DirectSound Devices sample shows how to enumerate and create playback and capture devices.

Path

Source: (SDK root)\Samples\C++\DirectSound\EnumDevices

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Select a playback and capture device from the dropdown lists. Click Create.

Programming Notes

The sample demonstrates the use of the DSEnumCallback function. The handle of the listbox is passed to this function as the pContext parameter so that the name of the device can be displayed and the GUID can be stored as list item data.

See Also

  • DirectSound C++ Samples
  • Enumerating Capture Devices
  • Enumerating Sound Devices


Full Duplex Filter Sample

The Full Duplex Filter sample application shows how to capture and play back sounds at the same time.

Path

Source: (SDK root)\Samples\C++\DirectSound\FullDuplexFilter

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Be sure your sound card is configured for full-duplex operation and that you have a microphone attached. Choose a format from the Output Format list. A list of formats appears in the Input Format list. Select one. Click OK. If full duplex is successfully created, another dialog box is displayed with a Record button. Click this button. Speak into the microphone and your voice is heard over the speakers.

Programming Notes

The sample does not use the DirectSoundFullDuplexCreate8 function, which is not supported on earlier operating systems. Note that the DirectSound device is created before the DirectSoundCapture device.

See Also

  • DirectSound C++ Samples
  • Creating the Capture Device Object
  • Creating the Device Object


Play 3D Sound Sample

The Play 3D Sound sample shows how to create a 3D sound buffer and manipulate its properties.

Path

Source: (SDK root)\Samples\C++\DirectSound\Play3DSound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Click Sound File and load a WAV file. Play the sound. The position of the sound source is shown as a red dot on the graph, where the x-axis is from left to right and the z-axis is from bottom to top. Change the range of movement on the two axes by using the sliders.

The listener is located at the center of the graph, and has its default orientation, looking along the positive z-axis; that is, toward the top of the screen. The sound source moves to the listener's left and right and to the listener's front and rear, but does not move above and below the listener.

The sliders in the center of the window control the properties of the listener; that is, the global sound properties. If you click Defer Settings, changes are not applied until you click Apply Settings.

Programming Notes

For a simpler example of how to set up a DirectSound buffer without 3D positioning, see the Play Sound Sample.

The sample obtains an IDirectSound3DListener8 interface as follows:

  1. Describes a buffer in a DSBUFFERDESC structure containing the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags.
  2. Passes the buffer description to IDirectSound8::CreateSoundBuffer. This creates a primary buffer object with 3D capabilities.
  3. Calls QueryInterface to obtain the IDirectSound3DListener8 interface. This interface controls global 3D properties.

The sample obtains an IDirectSound3DBuffer8 interface as follows:

  1. Describes a buffer in a DSBUFFERDESC structure, setting the DSBCAPS_CTRL3D capabilties flag and and a 3D virtualization algorithm.
  2. Passes the buffer description to IDirectSound8::CreateSoundBuffer, creating a secondary buffer object with 3D capabilities.
  3. Calls QueryInterface to obtain the IDirectSound3DBuffer8 interface. This interface controls the 3D properties of sounds played through the buffer.

The application sets the parameters of the listener by calling IDirectSound3DListener8::SetAllParameters. The listener properties are described in a DS3DLISTENER structure. To set the position of the sound source, the application calls IDirectSound3DBuffer8::SetAllParameters, passing in a DS3DBUFFER structure.

If the DS3D_DEFERRED flag is set when parameters are set, nothing is actually changed until IDirectSound3DListener8::CommitDeferredSettings is called. This method commits all deferred settings for buffers as well as the listener, and makes it possible for DirectSound to perform calculations once instead of many times.

See Also

  • DirectSound C++ Samples
  • 3D Sound


Play Sound Sample

The Play Sound sample shows how to play a WAV file in a DirectSound secondary buffer.

Path

Source: (SDK root)\Samples\C++\DirectSound\PlaySound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select Loop Sound if you want it to play repeatedly. Click Play.

Programming Notes

The sample shows the basic tasks required to play a sound in a DirectSound Buffer, as follows:

Set up DirectSound:

  1. Call the DirectSoundCreate function to create the DirectSound object.
  2. Call IDirectSound8::SetCooperativeLevel.
  3. Set the primary buffer format. This sample calls the SetPrimaryBufferFormat function in DXUTsound.cpp to do this.

Load a WAV file into a DirectSound buffer:

  1. Read the WAV file header to get the data size and format.
  2. If the WAV file is a reasonable size, create a secondary buffer in the same format as the data, large enough to hold the entire file. If the WAV file is too large, data will have to be streamed to the buffer.
  3. Fill the buffer with data. Obtain a pointer into the buffer by calling IDirectSoundBuffer8::Lock. Because data is not being streamed as the buffer is playing, the entire buffer can be locked. After the memory has been copied, call IDirectSoundBuffer8::Unlock.

Play the DirectSound buffer:

  1. Check to see if the buffer has been lost. If so, restore it.
  2. To play the buffer call IDirectSoundBuffer8::Play.

Free DirectSound:

Call Release on all the DirectSound interfaces that were obtained. Release buffers before releasing the DirectSound object.

See Also

  • DirectSound C++ Samples
  • Filling and Playing Static Buffers


SoundFX Sample

The SoundFX sample shows how to use DMOs with DirectSound and how to manipulate effect parameters.

Path

Source: (SDK root)\Samples\C++\DirectSound\SoundFX

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

A default sound file is loaded when the application is run. If you wish, load a different one by clicking Open File.

At first, no effects are enabled. Click Play to hear the sound without effects.

Click Stop to stop the buffer. Apply one or more effects by selecting checkboxes in the Enable column. Play the sound again.

To adjust parameters for an effect, select an option button in the Adjust column and change the values in the frame on the right side of the window. This can be done regardless of whether the sound is playing and regardless of whether the effect has been applied yet.

Programming Notes

The application implements a CSoundFXManager class to manage effects. An IDirectSoundBuffer8 interface is used to set effects on the buffer in the CSoundFXManager::ActivateFX method. Effect parameters are set in the OnEffectChanged function in response to messages from the interface.

See Also

  • DirectSound C++ Samples
  • Using Effects


Voice Management Sample

The Voice Management sample shows how to implement dynamic voice management when creating DirectSound secondary buffers.

Path

Source: (SDK root)\Samples\C++\DirectSound\VoiceManagement

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select the Voice Allocation Flags, Buffer Priority, and Voice Management Flags options. Note that the effect of the selected options is described under Expected Behavior. Create the buffer and play the sound by clicking Play.

Programming Notes

To use voice management flags, the buffer must be created using DSBCAPS_LOCDEFER. Otherwise DirectSound will not be able to dynamically place the buffer in either hardware or software at run time.

When playing the buffer, call IDirectSoundBuffer8::Play with a valid combination of voice management flags. Run the sample to observe the result of any combination of flags.

See Also

  • DirectSound C++ Samples
  • Dynamic Voice Management


DirectSound C/C++ Reference

This section contains reference information for the DirectSound application programming interface (API). Reference material is divided into the following categories.

  • DirectSound Interfaces
  • DirectSound Callback Function
  • DirectSound Functions
  • DirectSound Structures
  • DirectSound Return Values


DirectSound Interfaces

This section contains references for methods of the DirectSound interfaces shown in the following table.

Function | Description
IDirectSound8 | Used to create buffer objects and set up the environment.
IDirectSound3DBuffer8 | Used to retrieve and set parameters that describe the position, orientation, and environment of a sound buffer in 3-D space.
IDirectSound3DListener8 | Used to retrieve and set parameters that describe a listener's position, orientation, and listening environment in 3-D space.
IDirectSoundBuffer8 | Used to manage sound buffers.
IDirectSoundCapture8 | Used to create sound capture buffers.
IDirectSoundCaptureBuffer8 | Used to manipulate sound capture buffers.
IDirectSoundCaptureFXAec8 | Used to set and retrieve parameters on a capture buffer that supports acoustic echo cancellation.
IDirectSoundCaptureFXNoiseSuppress8 | Used to set and retrieve parameters on a capture buffer that supports noise suppression.
IDirectSoundFullDuplex8 | Represents a full-duplex stream.
IDirectSoundFXChorus8 | Used to set and retrieve effect parameters on a buffer that supports chorus.
IDirectSoundFXCompressor8 | Used to set and retrieve effect parameters on a buffer that supports compression.
IDirectSoundFXDistortion8 | Used to set and retrieve effect parameters on a buffer that supports distortion.
IDirectSoundFXEcho8 | Used to set and retrieve effect parameters on a buffer that supports echo.
IDirectSoundFXFlanger8 | Used to set and retrieve effect parameters on a buffer that supports flange.
IDirectSoundFXGargle8 | Used to set and retrieve effect parameters on a buffer that supports amplitude modulation.
IDirectSoundFXI3DL2Reverb8::IDirectSoundFXI3DL2Reverb8 | Used to set and retrieve effect parameters on a buffer that supports I3DL2 (Interactive 3D Audio Level 2) reverberation effects.
IDirectSoundFXParamEq8 | Used to set and retrieve effect parameters on a buffer that supports parametric equalizer effects.
IDirectSoundFXWavesReverb8 | Used to set and retrieve effect parameters on a buffer that supports Waves reverberation effects.
IDirectSoundNotify8 | Sets up notification events for a playback or capture buffer.
IKsPropertySet | Enables drivers to provide extended capabilities that can be used without API extensions.

For DirectX 8.0 and later, only IDirectSound8, IDirectSoundBuffer8, and IDirectSoundCaptureBuffer8 are new interfaces that supersede interfaces with similar, unnumbered names. Other interface names ending in 8 are simple defines for unchanged or new unnumbered interfaces. For example, IDirectSoundCapture8 is exactly equivalent to IDirectSoundCapture.

All interfaces that have a defined name ending in 8 are documented under that defined name, and it is recommended that you always use this name in your code.

For information on which methods are supported by an earlier version of an interface, see the declaration of the interface in Dsound.h.

When a method takes an interface pointer as an in parameter, you can pass in the newer version even where the parameter type is declared as the earlier version. For example, a pointer to either IDirectSoundBuffer or IDirectSoundBuffer8 can be passed to IDirectSound8::DuplicateSoundBuffer as the pDSBufferOriginal parameter.

When a method returns an interface, however, it is usually the earlier interface, and to obtain the newer interface you must use QueryInterface. This is the case, for example, with the ppDSBuffer parameter of IDirectSound8::CreateSoundBuffer.


IDirectSound8

The IDirectSound8 interface is used to create buffer objects, manage devices, and set up the environment. This interface supersedes IDirectSound and adds new methods.

Obtain this interface by using the DirectSoundCreate8 or DirectSoundFullDuplexCreate8 function, or by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSound8.

In addition to the methods inherited from IUnknown, the IDirectSound8 interface exposes the following methods.

IDirectSound8 Members

Method | Description
IDirectSound8::Compact | The Compact method has no effect.
IDirectSound8::CreateSoundBuffer | The CreateSoundBuffer method creates a sound buffer object to manage audio samples.
IDirectSound8::DuplicateSoundBuffer | The DuplicateSoundBuffer method creates a new secondary buffer that shares the original buffer's memory.
IDirectSound8::GetCaps | The GetCaps method retrieves the capabilities of the hardware device that is represented by the device object.
IDirectSound8::GetSpeakerConfig | The GetSpeakerConfig method retrieves the speaker configuration.
IDirectSound8::Initialize | The Initialize method initializes a device object that was created by using the CoCreateInstance function.
IDirectSound8::SetCooperativeLevel | The SetCooperativeLevel method sets the cooperative level of the application for this sound device.
IDirectSound8::SetSpeakerConfig | The SetSpeakerConfig method specifies the speaker configuration of the device.
IDirectSound8::VerifyCertification | The VerifyCertification method ascertains whether the device driver is certified for DirectX.

The LPDIRECTSOUND8 type is defined as a pointer to the IDirectSound8 interface:

typedef struct IDirectSound8  *LPDIRECTSOUND8;

Remarks

Only objects of class CLSID_DirectSound8 support this interface. All device objects created by DirectSoundCreate8 and DirectSoundFullDuplexCreate8 fall into this category. Objects of class CLSID_DirectSound, which include all those created by using the earlier DirectSoundCreate function, support only the earlier IDirectSound interface.

The behavior of CLSID_DirectSound8 objects is somewhat different from that of CLSID_DirectSound objects. These differences are found in the IDirectSound interface as well as the IDirectSound8 interface. Specific differences in the behavior of the newer object include the following:

  • In calls to IDirectSound::CreateSoundBuffer and CreateSoundBuffer, DSBCAPS_CTRL3D cannot be set on a buffer with a non-mono format, and DSBCAPS_CTRL3D cannot be combined with DSBCAPS_CTRLPAN.
  • New buffer creation flags are supported.
  • Buffers are not filled with silence on creation.
  • The IDirectSoundBuffer interface returned by CreateSoundBuffer can be queried for the IDirectSoundBuffer8 interface.
  • WAV formats in the DSBUFFERDESC structure that have the WAVE_FORMAT_EXTENSIBLE format tag are checked more strictly for validity.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSound8::Compact

The Compact method has no effect.

HRESULT Compact();

Parameters

None.

Return Values

The return value is DS_OK.

Remarks

This method was formerly used for compacting the on-board memory of ISA sound cards.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound8


IDirectSound8::CreateSoundBuffer

The CreateSoundBuffer method creates a sound buffer object to manage audio samples.

HRESULT CreateSoundBuffer(
  LPCDSBUFFERDESC pcDSBufferDesc,
  LPDIRECTSOUNDBUFFER * ppDSBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pcDSBufferDesc
Address of a DSBUFFERDESC structure that describes the sound buffer to create.
ppDSBuffer
Address of a variable that receives the IDirectSoundBuffer interface of the new buffer object. Use QueryInterface to obtain IDirectSoundBuffer8. IDirectSoundBuffer8 is not available for the primary buffer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Return Values

If the method succeeds, the return value is DS_OK, or DS_NO_VIRTUALIZATION if a requested 3D algorithm was not available and stereo panning was substituted. See the description of the guid3DAlgorithm member of DSBUFFERDESC. If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_ALLOCATED
DSERR_BADFORMAT
DSERR_BUFFERTOOSMALL
DSERR_CONTROLUNAVAIL
DSERR_DS8_REQUIRED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

DirectSound does not initialize the contents of the buffer, and the application cannot assume that it contains silence.

If an attempt is made to create a buffer with the DSBCAPS_LOCHARDWARE flag on a system where hardware acceleration is not available, the method fails with either DSERR_CONTROLUNAVAIL or DSERR_INVALIDCALL, depending on the operating system.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound8


IDirectSound8::DuplicateSoundBuffer

The DuplicateSoundBuffer method creates a new secondary buffer that shares the original buffer's memory.

HRESULT DuplicateSoundBuffer(
  LPDIRECTSOUNDBUFFER pDSBufferOriginal,
  LPDIRECTSOUNDBUFFER * ppDSBufferDuplicate
);

Parameters

pDSBufferOriginal
Address of the IDirectSoundBuffer or IDirectSoundBuffer8 interface of the buffer to duplicate.
ppDSBufferDuplicate
Address of a variable that receives the IDirectSoundBuffer interface pointer for the new buffer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_ALLOCATED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

This method is not valid for buffers created with the DSBCAPS_CTRLFX flag.

Initially, the duplicate buffer will have the same parameters as the original buffer. However, the application can change the parameters of each buffer independently, and each can be played or stopped without affecting the other.

The buffer memory is released when the last object referencing it is released.

There is a known issue with volume levels of duplicated buffers. The duplicated buffer will play at full volume unless you change the volume to a different value than the original buffer's volume setting. If the volume stays the same (even if you explicitly set the same volume in the duplicated buffer with a IDirectSoundBuffer8::SetVolume call), the buffer will play at full volume regardless. To work around this problem, immediately set the volume of the duplicated buffer to something slightly different than what it was, even if you change it one millibel. The volume may then be immediately set back again to the original desired value.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound8


IDirectSound8::GetCaps

The GetCaps method retrieves the capabilities of the hardware device that is represented by the device object.

HRESULT GetCaps(
  LPDSCAPS pDSCaps
);

Parameters

pDSCaps
Address of a DSCAPS structure that receives the capabilities of this sound device.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

Information retrieved in the DSCAPS structure describes the maximum capabilities of the sound device and those currently available, such as the number of hardware mixing channels and the amount of on-board sound memory. You can use this information to fine-tune performance and optimize resource allocation.

Because of resource-sharing requirements, the maximum capabilities in one area might be available only at the cost of another area.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound8


IDirectSound8::GetSpeakerConfig

The GetSpeakerConfig method retrieves the speaker configuration.

HRESULT GetSpeakerConfig(
  LPDWORD pdwSpeakerConfig
);

Parameters

pdwSpeakerConfig
Address of the speaker configuration (see remarks in IDirectSound8::SetSpeakerConfig).

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

The value returned at pdwSpeakerConfig can be a packed DWORD containing both configuration and geometry information. Use the DSSPEAKER_CONFIG and DSSPEAKER_GEOMETRY macros to unpack the DWORD, as in the following example:

    if (DSSPEAKER_CONFIG(dwSpeakerConfig) == DSSPEAKER_STEREO)
      {
      if (DSSPEAKER_GEOMETRY(dwSpeakerConfig) ==
            DSSPEAKER_GEOMETRY_WIDE)
        {
          // Configuration is wide stereo.
     ...}
      }

To use #defines implemented in Windows Vista, set the DIRECTSOUND_VERSION to 0x1000 before including dsound.h.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound8


IDirectSound8::Initialize

The Initialize method initializes a device object that was created by using the CoCreateInstance function.

HRESULT Initialize(
  LPCGUID pcGuidDevice
);

Parameters

pcGuidDevice
Address of the globally unique identifier (GUID) specifying the sound driver to which this device object binds. Pass NULL to select the primary sound driver.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_ALREADYINITIALIZED
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_NODRIVER

Remarks

This method is provided for compliance with the Component Object Model (COM) protocol. If the DirectSoundCreate8 function was used to create the device object, this method returns DSERR_ALREADYINITIALIZED. If IDirectSound8::Initialize is not called when using CoCreateInstance to create the device object, any method called afterward returns DSERR_UNINITIALIZED.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound8


IDirectSound8::SetCooperativeLevel

The SetCooperativeLevel method sets the cooperative level of the application for this sound device.

HRESULT SetCooperativeLevel(
  HWND hwnd,
  DWORD dwLevel
);

Parameters

hwnd
Handle to the application window.
dwLevel
Requested level. Specify one of the values shown in the following table.
Value | Description
DSSCL_EXCLUSIVE | For DirectX 8.0 and later, has the same effect as DSSCL_PRIORITY. For previous versions, sets the application to the exclusive level. This means that when it has the input focus, the application will be the only one audible; sounds from applications with the DSBCAPS_GLOBALFOCUS flag set will be muted. With this level, it also has all the privileges of the DSSCL_PRIORITY level. DirectSound will restore the hardware format, as specified by the most recent call to the SetFormat method, after the application gains the input focus.
DSSCL_NORMAL | Sets the normal level. This level has the smoothest multitasking and resource-sharing behavior, but because it does not allow the primary buffer format to change, output is restricted to the default 8-bit format.
DSSCL_PRIORITY | Sets the priority level. Applications with this cooperative level can call the SetFormat and Compact methods.
DSSCL_WRITEPRIMARY | Sets the write-primary level. The application has write access to the primary buffer. No secondary buffers can be played. This level cannot be set if the DirectSound driver is being emulated for the device; that is, if the GetCaps method returns the DSCAPS_EMULDRIVER flag in the DSCAPS structure.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

The application must set the cooperative level by calling this method before its buffers can be played. The recommended cooperative level is DSSCL_PRIORITY.

Do not call this method if any buffers are locked.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound8


IDirectSound8::SetSpeakerConfig

The SetSpeakerConfig method specifies the speaker configuration of the device.

HRESULT SetSpeakerConfig(
  DWORD dwSpeakerConfig
);

Parameters

dwSpeakerConfig
The speaker configuration. See remarks.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

Speaker Configurations

These tables contain the possible speaker configurations.

Value | Description
DSSPEAKER_5POINT1_BACK | The audio is played through a speaker arrangement of five surround speakers with a subwoofer. (DSSPEAKER_5POINT1 is still defined, but is obsolete as of Windows Vista. Use DSSPEAKER_5POINT1_BACK instead.)
DSSPEAKER_5POINT1_SURROUND | The audio is played through a home theater speaker arrangement of five surround speakers with a subwoofer. This value applies to Windows Vista or later.
DSSPEAKER_DIRECTOUT | The audio is passed through directly, without being configured for speakers.
DSSPEAKER_HEADPHONE | The audio is played through headphones.
DSSPEAKER_MONO | The audio is played through a single speaker.
DSSPEAKER_QUAD | The audio is played through quadraphonic speakers.
DSSPEAKER_STEREO | The audio is played through stereo speakers (default value).
DSSPEAKER_SURROUND | The audio is played through surround speakers.
DSSPEAKER_7POINT1_WIDE | The audio is played through a wide speaker arrangement of seven surround speakers with a subwoofer. (DSSPEAKER_7POINT1 is still defined, but is obsolete as of Windows XP SP 2. Use DSSPEAKER_7POINT1_WIDE instead.)
DSSPEAKER_7POINT1_SURROUND | The audio is played through a home theater speaker arrangement of seven surround speakers with a subwoofer. This value applies to Windows XP SP2 or later.

DSSPEAKER_STEREO can be combined with one of the values shown in the following table.

Value | Description
DSSPEAKER_GEOMETRY_WIDE | The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW | The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN | The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX | The speakers are directed over an arc of 180 degrees.

If a geometry value is to be used, it must be packed in a DWORD along with the DSSPEAKER_STEREO flag. This can be done by using the DSSPEAKER_COMBINED macro, as in the following C++ example:

    lpds->SetSpeakerConfig(DSSPEAKER_COMBINED(
        DSSPEAKER_STEREO, DSSPEAKER_GEOMETRY_WIDE));

To use #defines implemented in Windows Vista, set the DIRECTSOUND_VERSION to 0x1000 before including dsound.h.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound8


IDirectSound8::VerifyCertification

The VerifyCertification method ascertains whether the device driver is certified for DirectX.

HRESULT VerifyCertification(
  LPDWORD pdwCertified
);

Parameters

pdwCertified
Address of a DWORD variable that receives one of the values shown in the following table.
Value | Description
DS_CERTIFIED | Driver is certified for DirectSound.
DS_UNCERTIFIED | Driver is not certified for DirectSound.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_INVALIDPARAM
DSERR_UNSUPPORTED

Remarks

This method may attempt to retrieve certification information from the Internet.

On emulated devices, the method returns DSERR_UNSUPPORTED. Emulated devices are identified by the DSCAPS_EMULDRIVER flag in the dwFlags member of DSCAPS.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound8


IDirectSound3DBuffer8

The IDirectSound3DBuffer8 interface is used to retrieve and set parameters that describe the position, orientation, and environment of a sound buffer in 3D space.

IDirectSound3DBuffer8 is a define for IDirectSound3DBuffer. The two interface names are interchangeable.

The IDirectSound3DBuffer8 interface is obtained from a buffer that was created with the DSBCAPS_CTRL3D flag. You can get it from the IDirectSoundBuffer8 interface by using the QueryInterface method, or retrieve it from a DirectMusic audiopath by using IDirectMusicSegmentState8::GetObjectInPath or IDirectMusicAudioPath8::GetObjectInPath.

In addition to the methods inherited from IUnknown, the IDirectSound3DBuffer8 interface exposes the following methods, arranged by category.

3D mode

Method | Description
IDirectSound3DBuffer8::GetMode | The GetMode method retrieves the operation mode for 3D sound processing.
IDirectSound3DBuffer8::SetMode | The SetMode method sets the operation mode for 3D sound processing.

Batch Parameters

Method | Description
IDirectSound3DBuffer8::GetAllParameters | The GetAllParameters method retrieves the 3D properties of the sound buffer.
IDirectSound3DBuffer8::SetAllParameters | The SetAllParameters method sets all 3D sound buffer properties.

Minimum and Maximum Distance

Method | Description
IDirectSound3DBuffer8::GetMaxDistance | The GetMaxDistance method retrieves the maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.
IDirectSound3DBuffer8::GetMinDistance | The GetMinDistance method retrieves the minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.
IDirectSound3DBuffer8::SetMaxDistance | The SetMaxDistance method sets the maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.
IDirectSound3DBuffer8::SetMinDistance | The SetMinDistance method sets the minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.

Position

Method | Description
IDirectSound3DBuffer8::GetPosition | The GetPosition method retrieves the position of the sound source.
IDirectSound3DBuffer8::SetPosition | The SetPosition method sets the position of the sound source.

Sound Projection Cone

Method | Description
IDirectSound3DBuffer8::GetConeAngles | The GetConeAngles method retrieves the inside and outside angles of the sound projection cone.
IDirectSound3DBuffer8::GetConeOrientation | The GetConeOrientation method retrieves the orientation of the sound projection cone.
IDirectSound3DBuffer8::GetConeOutsideVolume | The GetConeOutsideVolume method retrieves the volume of the sound outside the outside angle of the sound projection cone.
IDirectSound3DBuffer8::SetConeAngles | The SetConeAngles method sets the inside and outside angles of the sound projection cone.
IDirectSound3DBuffer8::SetConeOrientation | The SetConeOrientation method sets the orientation of the sound projection cone.
IDirectSound3DBuffer8::SetConeOutsideVolume | The SetConeOutsideVolume method sets the volume of the sound outside the outside angle of the sound projection cone.

Velocity

Method | Description
IDirectSound3DBuffer8::GetVelocity | The GetVelocity method retrieves the velocity of the sound source.
IDirectSound3DBuffer8::SetVelocity | The SetVelocity method sets the velocity of the sound source.

The LPDIRECTSOUND3DBUFFER type is defined as a pointer to the IDirectSound3DBuffer8 interface:

typedef struct IDirectSound3DBuffer  *LPDIRECTSOUND3DBUFFER;

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSound3DBuffer8::GetAllParameters

The GetAllParameters method retrieves the 3D properties of the sound buffer.

HRESULT GetAllParameters(
  LPDS3DBUFFER pDs3dBuffer
);

Parameters

pDs3dBuffer
Address of a DS3DBUFFER structure that receives the information describing the 3D characteristics of the sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::GetConeAngles

The GetConeAngles method retrieves the inside and outside angles of the sound projection cone.

HRESULT GetConeAngles(
  LPDWORD pdwInsideConeAngle,
  LPDWORD pdwOutsideConeAngle
);

Parameters

pdwInsideConeAngle
Addresses of a variable that receives the inside angle of the sound projection cone, in degrees. This is the angle within which the sound is at its normal volume.
pdwOutsideConeAngle
Addresses of a variable that receives the outside angle of the sound projection cone, in degrees. This is the angle outside of which the sound is at its outside volume.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in Dsound.h as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::GetConeOrientation

The GetConeOrientation method retrieves the orientation of the sound projection cone.

HRESULT GetConeOrientation(
  D3DVECTOR * pvOrientation
);

Parameters

pvOrientation
Address of a D3DVECTOR structure that receives the orientation of the sound projection cone. The vector information represents the center of the sound cone.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The values returned are not necessarily the same as those set by using the SetConeOrientation method. DirectSound normalizes orientation vectors so that all axes have a magnitude of less than or equal to 1.0.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::GetConeOutsideVolume

The GetConeOutsideVolume method retrieves the volume of the sound outside the outside angle of the sound projection cone.

HRESULT GetConeOutsideVolume(
  LPLONG plConeOutsideVolume
);

Parameters

plConeOutsideVolume
Address of a variable that receives the cone outside volume for this buffer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Volume levels are expressed as attenuation, in hundredths of a decibel. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). These values are defined in Dsound.h. DirectSound does not support amplification.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::GetMaxDistance

The GetMaxDistance method retrieves the maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.

HRESULT GetMaxDistance(
  D3DVALUE * pflMaxDistance
);

Parameters

pflMaxDistance
Address of a variable that receives the maximum distance, in meters by default. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::GetMinDistance

The GetMinDistance method retrieves the minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.

HRESULT GetMinDistance(
  D3DVALUE * pflMinDistance
);

Parameters

pflMinDistance
Address of a variable that receives the minimum distance, in meters by default. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::GetMode

The GetMode method retrieves the operation mode for 3D sound processing.

HRESULT GetMode(
  LPDWORD pdwMode
);

Parameters

pdwMode
Address of a variable that receives the mode setting. This value will be one of those in the following table.
Value | Description
DS3DMODE_DISABLE | Processing of 3D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE | Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL | Normal processing. This is the default mode.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::GetPosition

The GetPosition method retrieves the position of the sound source.

HRESULT GetPosition(
  D3DVECTOR * pvPosition
);

Parameters

pvPosition
Address of a D3DVECTOR structure that receives the position of the sound buffer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, distance units are meters, but the units can be changed by using the SetDistanceFactor method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::GetVelocity

The GetVelocity method retrieves the velocity of the sound source.

HRESULT GetVelocity(
  D3DVECTOR * pvVelocity
);

Parameters

pvVelocity
Address of a D3DVECTOR structure that receives the sound buffer's velocity, in meters per second by default.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used for Doppler effects only. It does not actually move the buffer. For more information, see Doppler Effect.

The default unit of measurement is meters per second, but this can be changed by using the SetDistanceFactor method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::SetAllParameters

The SetAllParameters method sets all 3D sound buffer properties.

HRESULT SetAllParameters(
  LPCDS3DBUFFER pcDs3dBuffer,
  DWORD dwApply
);

Parameters

pcDs3dBuffer
Address of a DS3DBUFFER structure that describes the 3D characteristics of the sound buffer.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::SetConeAngles

The SetConeAngles method sets the inside and outside angles of the sound projection cone.

HRESULT SetConeAngles(
  DWORD dwInsideConeAngle,
  DWORD dwOutsideConeAngle,
  DWORD dwApply
);

Parameters

dwInsideConeAngle
Inside cone angle, in degrees. This is the angle within which the sound is at its normal volume.
dwOutsideConeAngle
Outside cone angle, in degrees. This is the angle outside of which the sound is at its outside volume.
dwApply
Value that indicates when the setting should be applied. Must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in Dsound.h as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE. Each angle must be in the range of 0 degrees (no cone) to 360 degrees (the full sphere). The default value is 360.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::SetConeOrientation

The SetConeOrientation method sets the orientation of the sound projection cone.

HRESULT SetConeOrientation(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x
Value that specifies the x coordinate of the sound cone orientation vector. D3DVALUE is defined as float.
y
Value that specifies the y coordinate of the sound cone orientation vector. D3DVALUE is defined as float.
z
Value that specifies the z coordinate of the sound cone orientation vector. D3DVALUE is defined as float.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

This method has no effect unless the cone angle and cone outside volume have also been set to values other than the default.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::SetConeOutsideVolume

The SetConeOutsideVolume method sets the volume of the sound outside the outside angle of the sound projection cone.

HRESULT SetConeOutsideVolume(
  LONG lConeOutsideVolume,
  DWORD dwApply
);

Parameters

lConeOutsideVolume
Cone outside volume, in hundredths of a decibel.
dwApply
Value that specifies when the setting should be applied. This value must be one of the those shown in the following table.
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Volume levels are represented by attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). These values are defined in Dsound.h. DirectSound does not support amplification.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::SetMaxDistance

The SetMaxDistance method sets the maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.

HRESULT SetMaxDistance(
  D3DVALUE flMaxDistance,
  DWORD dwApply
);

Parameters

flMaxDistance
Maximum distance, in meters by default. D3DVALUE is defined as float.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

The default unit of measurement is meters, but this can be changed by using the SetDistanceFactor method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::SetMinDistance

The SetMinDistance method sets the minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.

HRESULT SetMinDistance(
  D3DVALUE flMinDistance,
  DWORD dwApply
);

Parameters

flMinDistance
Minimum distance, in meters by default. D3DVALUE is defined as float.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

The default unit of measurement is meters, but this can be changed by using the SetDistanceFactor method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::SetMode

The SetMode method sets the operation mode for 3D sound processing.

HRESULT SetMode(
  DWORD dwMode,
  DWORD dwApply
);

Parameters

dwMode
Flag specifying the 3D sound processing mode to be set. The flags in the following table are defined.
Value | Description
DS3DMODE_DISABLE | Processing of 3D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE | Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL | Normal processing. This is the default mode.
dwApply
Value that specifies when the setting should be applied. This value must be one of those in the following table.
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::SetPosition

The SetPosition method sets the position of the sound source.

HRESULT SetPosition(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x
Value that specifies the x coordinate of the position vector. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.
y
Value that specifies the y coordinate of the position vector. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.
z
Value that specifies the z coordinate of the position vector. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default unit of measurement is meters, but this can be changed by using the SetDistanceFactor method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DBuffer8::SetVelocity

The SetVelocity method sets the velocity of the sound source.

HRESULT SetVelocity(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x
Value that specifies the x coordinate of the velocity vector, in meters per second by default. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.
y
Value that specifies the y coordinate of the velocity vector, in meters per second by default. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.
z
Value that specifies the z coordinate of the velocity vector, in meters per second by default. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for calculating Doppler effect. It does not change the position of the buffer. For more information, see Doppler Effect.

The default unit of measurement is meters per second, but this can be changed by using the SetDistanceFactor method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DBuffer8


IDirectSound3DListener8

The IDirectSound3DListener8 interface is used to retrieve and set parameters that describe a listener's position, orientation, and listening environment in 3D space.

The interface can be obtained by calling the IDirectSoundBuffer8::QueryInterface method on a primary buffer created with the DSBCAPS_CTRL3D flag.

In addition to the methods inherited from IUnknown, the IDirectSound3DListener8 interface exposes the following methods, arranged by category.

Batch Parameters

Method | Description
IDirectSound3DListener8::CommitDeferredSettings | The CommitDeferredSettings method commits any deferred settings made since the last call to this method.
IDirectSound3DListener8::GetAllParameters | The GetAllParameters method retrieves all 3D parameters of the sound environment and the listener.
IDirectSound3DListener8::SetAllParameters | The SetAllParameters method sets all 3D parameters of the sound environment and the listener.

Global Sound Properties

Method | Description
IDirectSound3DListener8::GetDistanceFactor | The GetDistanceFactor method retrieves the distance factor, which is the number of meters in a vector unit.
IDirectSound3DListener8::GetDopplerFactor | The GetDopplerFactor method retrieves the multiplier for the Doppler effect.
IDirectSound3DListener8::GetRolloffFactor | The GetRolloffFactor method retrieves the rolloff factor, which determines the rate of attenuation over distance.
IDirectSound3DListener8::SetDistanceFactor | The SetDistanceFactor method sets the distance factor, which is the number of meters in a vector unit.
IDirectSound3DListener8::SetDopplerFactor | The SetDopplerFactor method sets the multiplier for the Doppler effect.
IDirectSound3DListener8::SetRolloffFactor | The SetRolloffFactor method sets the rolloff factor, which determines the rate of attenuation over distance.

Listener Properties

Method | Description
IDirectSound3DListener8::GetOrientation | The GetOrientation method retrieves the orientation of the listener's head.
IDirectSound3DListener8::GetPosition | The GetPosition method retrieves the listener's position.
IDirectSound3DListener8::GetVelocity | The GetVelocity method retrieves the listener's velocity.
IDirectSound3DListener8::SetOrientation | The SetOrientation method sets the orientation of the listener's head.
IDirectSound3DListener8::SetPosition | The SetPosition method sets the listener's position.
IDirectSound3DListener8::SetVelocity | The SetVelocity method sets the listener's velocity.

The LPDIRECTSOUND3DLISTENER type is defined as a pointer to the IDirectSound3DListener interface:

typedef struct IDirectSound3DListener  *LPDIRECTSOUND3DLISTENER;

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSound3DListener8::CommitDeferredSettings

The CommitDeferredSettings method commits any deferred settings made since the last call to this method.

HRESULT CommitDeferredSettings();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::GetAllParameters

The GetAllParameters method retrieves all 3D parameters of the sound environment and the listener.

HRESULT GetAllParameters(
  LPDS3DLISTENER pListener
);

Parameters

pListener
Address of a DS3DLISTENER structure that receives the state of the 3D world and listener.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::GetDistanceFactor

The GetDistanceFactor method retrieves the distance factor, which is the number of meters in a vector unit.

HRESULT GetDistanceFactor(
  D3DVALUE * pflDistanceFactor
);

Parameters

pflDistanceFactor
Address of a variable that receives the distance factor value. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::GetDopplerFactor

The GetDopplerFactor method retrieves the multiplier for the Doppler effect.

HRESULT GetDopplerFactor(
  D3DVALUE * pflDopplerFactor
);

Parameters

pflDopplerFactor
Address of a variable that receives the Doppler factor value. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (defined as 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::GetOrientation

The GetOrientation method retrieves the orientation of the listener's head.

HRESULT GetOrientation(
  D3DVECTOR * pvOrientFront,
   D3DVECTOR * pvOrientTop
);

Parameters

pvOrientFront
Address of a D3DVECTOR structure that receives the listener's front orientation vector.
pvOrientTop
Address of a D3DVECTOR structure that receives the listener's top orientation vector.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points up from the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The values returned are not necessarily the same as those set by using SetOrientation. DirectSound normalizes orientation vectors so that they are at right angles and have a magnitude of less than or equal to 1.0.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::GetPosition

The GetPosition method retrieves the listener's position.

HRESULT GetPosition(
  D3DVECTOR * pvPosition
);

Parameters

pvPosition
Address of a D3DVECTOR structure that receives the listener's position vector.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, measurement units are meters, but this can be changed by calling the SetDistanceFactor method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::GetRolloffFactor

The GetRolloffFactor method retrieves the rolloff factor, which determines the rate of attenuation over distance.

HRESULT GetRolloffFactor(
  D3DVALUE * pflRolloffFactor
);

Parameters

pflRolloffFactor
Address of a variable that receives the rolloff factor. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (defined as 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For more information, see Rolloff Factor.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::GetVelocity

The GetVelocity method retrieves the listener's velocity.

HRESULT GetVelocity(
  D3DVECTOR * pvVelocity
);

Parameters

pvVelocity
Address of a D3DVECTOR structure that receives the listener's velocity.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for calculating Doppler effect. It does not change the listener's position. To move the listener, use the SetPosition method.

The default velocity is (0,0,0).

By default, measurement units are meters per second, but this can be changed by calling the SetDistanceFactor method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::SetAllParameters

The SetAllParameters method sets all 3D parameters of the sound environment and the listener.

HRESULT SetAllParameters(
  LPCDS3DLISTENER pcListener,
  DWORD dwApply
);

Parameters

pcListener
Address of a DS3DLISTENER structure that contains information describing all 3D listener parameters.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::SetDistanceFactor

The SetDistanceFactor method sets the distance factor, which is the number of meters in a vector unit.

HRESULT SetDistanceFactor(
  D3DVALUE flDistanceFactor,
  DWORD dwApply
);

Parameters

flDistanceFactor
Distance factor. D3DVALUE is defined as float.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The distance factor has a range of DS3D_MINDISTANCEFACTOR to DS3D_MAXDISTANCEFACTOR, defined in Dsound.h as FLT_MIN and FLT_MAX respectively. The default value is DS3D_DEFAULTDISTANCEFACTOR, or 1.0.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::SetDopplerFactor

The SetDopplerFactor method sets the multiplier for the Doppler effect.

HRESULT SetDopplerFactor(
  D3DVALUE flDopplerFactor,
  DWORD dwApply
);

Parameters

flDopplerFactor
Doppler factor. D3DVALUE is defined as float.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (defined as 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::SetOrientation

The SetOrientation method sets the orientation of the listener's head.

HRESULT SetOrientation(
  D3DVALUE xFront,
  D3DVALUE yFront,
  D3DVALUE zFront,
  D3DVALUE xTop,
  D3DVALUE yTop,
  D3DVALUE zTop,
  DWORD dwApply
);

Parameters

xFront
Value that specifies the x coordinate of the front orientation vector. D3DVALUE is defined as float.
yFront
Value that specifies the y coordinate of the front orientation vector. D3DVALUE is defined as float.
zFront
Value that specifies the z coordinate of the front orientation vector. D3DVALUE is defined as float.
xTop
Value that specifies the x coordinates of the top orientation vector.
yTop
Value that specifies the y coordinates of the top orientation vector.
zTop
Value that specifies the z coordinates of the top orientation vector.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points up from the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The top vector must be at right angles to the front vector. If necessary, DirectSound adjusts the top vector after setting the front vector.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::SetPosition

The SetPosition method sets the listener's position.

HRESULT SetPosition(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x
Value that specifies the x coordinate of the listener's position vector. Note that DirectSound may adjust this value to prevent floating-point overflow. D3DVALUE is defined as float.
y
Value that specifies the y coordinate of the listener's position vector. Note that DirectSound may adjust this value to prevent floating-point overflow. D3DVALUE is defined as float.
z
Value that specifies the z coordinate of the listener's position vector. Note that DirectSound may adjust this value to prevent floating-point overflow. D3DVALUE is defined as float.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, measurement units are meters, but this can be changed by calling the SetDistanceFactor method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::SetRolloffFactor

The SetRolloffFactor method sets the rolloff factor, which determines the rate of attenuation over distance.

HRESULT SetRolloffFactor(
  D3DVALUE flRolloffFactor,
  DWORD dwApply
);

Parameters

flRolloffFactor
Rolloff factor. D3DVALUE is defined as float.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (defined as 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For more information, see Rolloff Factor.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSound3DListener8::SetVelocity

The SetVelocity method sets the listener's velocity.

HRESULT SetVelocity(
  D3DVALUE x, y, and z,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Value that specifies the x coordinate of the listener's velocity vector. DirectSound may adjust this value to prevent floating-point overflow. D3DVALUE is defined as float.
y
Value that specifies the y coordinate of the listener's velocity vector. DirectSound may adjust this value to prevent floating-point overflow. D3DVALUE is defined as float.
z
Value that specifies the z coordinate of the listener's velocity vector. DirectSound may adjust this value to prevent floating-point overflow. D3DVALUE is defined as float.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3D coordinates for all 3D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for Doppler effects. It does not actually move the listener. To change the listener's position, use the SetPosition method. The default velocity is (0,0,0).

By default, measurement units are meters per second, but this can be changed by calling the SetDistanceFactor method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSound3DListener8


IDirectSoundBuffer8

The IDirectSoundBuffer8 interface is used to manage sound buffers.

The IDirectSoundBuffer8 interface supersedes IDirectSoundBuffer and adds new methods.

To obtain the interface, use the CreateSoundBuffer method to retrieve IDirectSoundBuffer, and then pass IID_IDirectSoundBuffer8 to IDirectSoundBuffer::QueryInterface.

For the primary buffer, you must use the IDirectSoundBuffer interface; IDirectSoundBuffer8 is not available. IDirectSoundBuffer is not documented separately. For documentation, see the corresponding IDirectSoundBuffer8 methods.

Not all methods of IDirectSoundBuffer are valid for primary buffers. For example, SetCurrentPosition will fail. See the reference topics for individual methods.

In addition to the methods inherited from IUnknown, the IDirectSoundBuffer8 interface exposes the following methods, arranged by category.

Effects

Method | Description
IDirectSoundBuffer8::GetObjectInPath | The GetObjectInPath method retrieves an interface for an effect object associated with the buffer.
IDirectSoundBuffer8::SetFX | Number of elements in the pDSFXDesc and pdwResultCodes arrays. If this value is 0, pDSFXDesc and pdwResultCodes must both be NULL. Set to 0 to remove all effects from the buffer.

Resource Management

Method | Description
IDirectSoundBuffer8::AcquireResources | The AcquireResources method allocates resources for a buffer that was created with the DSBCAPS_LOCDEFER flag in the DSBUFFERDESCDSBUFFERDESC
IDirectSoundBuffer8::Restore | The Restore method restores the memory allocation for a lost sound buffer.

Play Management

Method | Description
IDirectSoundBuffer8::GetCurrentPosition | The GetCurrentPosition method retrieves the position of the play and write cursors in the sound buffer.
IDirectSoundBuffer8::Lock | The Lock method readies all or part of the buffer for a data write and returns pointers to which data can be written.
IDirectSoundBuffer8::Play | The Play method causes the sound buffer to play, starting at the play cursor.
IDirectSoundBuffer8::SetCurrentPosition | The SetCurrentPosition method sets the position of the play cursor, which is the point at which the next byte of data is read from the buffer.
IDirectSoundBuffer8::Stop | The Stop method causes the sound buffer to stop playing.
IDirectSoundBuffer8::Unlock | The Unlock method releases a locked sound buffer.

Sound Parameters

Method | Description
IDirectSoundBuffer8::GetFrequency | The GetFrequency method retrieves the frequency, in samples per second, at which the buffer is playing.
IDirectSoundBuffer8::GetPan | The GetPan method retrieves the relative volume of the left and right audio channels.
IDirectSoundBuffer8::GetVolume | The GetVolume method retrieves the attenuation of the sound.
IDirectSoundBuffer8::SetFrequency | The SetFrequency method sets the frequency at which the audio samples are played.
IDirectSoundBuffer8::SetPan | The SetPan method sets the relative volume of the left and right channels.
IDirectSoundBuffer8::SetVolume | The SetVolume method sets the attenuation of the sound.

Miscellaneous

Method | Description
IDirectSoundBuffer8::GetCaps | The GetCaps method retrieves the capabilities of the buffer object.
IDirectSoundBuffer8::GetFormat | The GetFormat method retrieves a description of the format of the sound data in the buffer, or the buffer size needed to retrieve the format description.
IDirectSoundBuffer8::GetStatus | The GetStatus method retrieves the status of the sound buffer.
IDirectSoundBuffer8::Initialize | The Initialize method initializes a sound buffer object if it has not yet been initialized.
IDirectSoundBuffer8::SetFormat | The SetFormat method sets the format of the primary buffer. Whenever this application has the input focus, DirectSound will set the primary buffer to the specified format.

The following table shows which methods are supported for buffer objects obtained from a DirectMusic audiopath. Mix-in buffers accept sends from other buffers, and exist only in audiopath configurations created in DirectMusic Producer. All other buffers in the audiopath are sink-in buffers, which means that they accept data only from the synthesizer sink.

IDirectSoundBuffer8 method | Mix-in | Sink-in
AcquireResources | No | No
GetCaps | Yes | Yes
GetCurrentPosition | No | No
GetFormat | Yes | Yes
GetFrequency | No | No
GetObjectInPath | Yes | Yes
GetPan | Yes | Yes
GetStatus | Yes | Yes
GetVolume | Yes | Yes
Initialize | No | No
Lock | No | No
Play | Yes | No
Restore | No | No
SetCurrentPosition | No | No
SetFormat | No | No
SetFrequency | No | No
SetFX | Yes | Yes
SetPan | Yes | Yes
SetVolume | Yes | Yes
Stop | Yes | No
Unlock | No | No

The LPDIRECTSOUNDBUFFER8 type is defined as a pointer to the IDirectSoundBuffer interface:

typedef struct IDirectSoundBuffer8  *LPDIRECTSOUNDBUFFER8;

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundBuffer8::AcquireResources

The AcquireResources method allocates resources for a buffer that was created with the DSBCAPS_LOCDEFER flag in the DSBUFFERDESC structure.

HRESULT AcquireResources(
  DWORD dwFlags,
  DWORD dwEffectsCount,
  LPDWORD pdwResultCodes
);

Parameters

dwFlags
Flags specifying how resources are to be allocated for a buffer created with the DSBCAPS_LOCDEFER flag. For a list of values, see the voice management and voice allocation flags for Play.
dwEffectsCount
Number of elements in the pdwResultFlags array, or 0 if pdwResultCodes is NULL.
pdwResultCodes
Address of an array of DWORD variables that receives information about the effects associated with the buffer. This array must contain one element for each effect that was assigned to the buffer by SetFX. For each effect, one of the values shown in the following table is returned.

Note This parameter can be NULL if result codes are not wanted.

Value | Description
DSFXR_LOCHARDWARE | Effect is instantiated in hardware.
DSFXR_LOCSOFTWARE | Effect is instantiated in software.
DSFXR_FAILED | No effect was created because resources weren't available.
DSFXR_PRESENT | The effect is available but was not created because the method failed for some other reason.
DSFXR_UNKNOWN | No effect was created because the effect isn't registered on the system.

Return Values

If the method succeeds, the return value is DS_OK or DS_INCOMPLETE. If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDCALL
DSERR_INVALIDPARAM

Remarks

Normally, buffers created with DSBCAPS_LOCDEFER are not allocated resources until Play is called. IDirectSoundBuffer8::AcquireResources can be used to allocate resources for a deferred buffer before it is played. By doing so, the application can retrieve information about effects processing and set effect parameters. If the method fails, check the values in pdwResultCodes to determine which effects caused the failure.

A buffer with acquired resources that is not yet playing is not a candidate for premature termination by the voice management flags passed to the Play method.

Resources that have been acquired by AcquireResources are released when playback is stopped.

If the method is called on a buffer on which it has already been called, the status of the effects is returned but no additional resources are allocated.

The dwEffectsCount parameter to this function must be the same as the one passed in the call to SetFX.

If an attempt is made to acquire resources for a buffer with the DSBCAPS_LOCHARDWARE flag on a system where hardware acceleration is not available, the method fails with either DSERR_CONTROLUNAVAIL or DSERR_INVALIDCALL, depending on the operating system.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::GetCaps

The GetCaps method retrieves the capabilities of the buffer object.

HRESULT GetCaps(
  LPDSBCAPS pDSBufferCaps
);

Parameters

pDSBufferCaps
Address of a DSBCAPS structure to contain the capabilities of this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The DSBCAPS structure contains similar information to the DSBUFFERDESC structure passed to the CreateSoundBuffer method, with some additional information. This additional information can include the buffer's location, either in hardware or software, and performance measures.

The flags specified in the dwFlags member of the DSBCAPS structure are the same flags used by the DSBUFFERDESC structure. The only difference is that in the DSBCAPS structure, either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE will be specified according to the location of the buffer memory. In the DSBUFFERDESC structure, these flags are optional and, depending on which flag is specified, force the buffer to be located in either hardware or software.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::GetCurrentPosition

The GetCurrentPosition method retrieves the position of the play and write cursors in the sound buffer.

HRESULT GetCurrentPosition(
  LPDWORD pdwCurrentPlayCursor,
  LPDWORD pdwCurrentWriteCursor
);

Parameters

pdwCurrentPlayCursor
Address of a variable that receives the offset, in bytes, of the play cursor. This parameter can be NULL if the value is not wanted.
pdwCurrentWriteCursor
Address of a variable that receives the offset, in bytes, of the write cursor. This parameter can be NULL if the value is not wanted.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The write cursor is the point in the buffer ahead of which it is safe to write data to the buffer. Data should not be written to the part of the buffer after the play cursor and before the write cursor.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::GetFormat

The GetFormat method retrieves a description of the format of the sound data in the buffer, or the buffer size needed to retrieve the format description.

HRESULT GetFormat(
  LPWAVEFORMATEX pwfxFormat,
  DWORD dwSizeAllocated,
  LPDWORD pdwSizeWritten
);

Parameters

pwfxFormat
Address of a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure that receives a description of the sound data in the buffer. To retrieve the buffer size needed to contain the format description, specify NULL. In this case the variable at pdwSizeWritten receives the size of the structure needed to receive the data.
dwSizeAllocated
Size, in bytes, of the structure at pwfxFormat. If pwfxFormat is not NULL, this value must be equal to or greater than the size of the expected data.
pdwSizeWritten
Address of a variable that receives the number of bytes written to the structure at pwfxFormat. This parameter can be NULL.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The format structure can have a variable length that depends on the format. Before retrieving the format description, the application should query the buffer object for the size of the format by calling this method and specifying NULL for the pwfxFormat parameter. The necessary size of the structure is returned in the pdwSizeWritten parameter. The application can then allocate sufficient memory and call GetFormat again to retrieve the format description.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::GetFrequency

The GetFrequency method retrieves the frequency, in samples per second, at which the buffer is playing.

HRESULT GetFrequency(
  LPDWORD pdwFrequency
);

Parameters

pdwFrequency
Address of a variable that receives the frequency at which the audio buffer is being played, in hertz.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The frequency value for software buffers is in the range of DSBFREQUENCY_MIN to DSBFREQUENCY_MAX, defined in Dsound.h. Hardware buffers can return other values.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::GetObjectInPath

The GetObjectInPath method retrieves an interface for an effect object associated with the buffer.

HRESULT GetObjectInPath(
  REFGUID rguidObject ,
  DWORD dwIndex ,
  REFGUID rguidInterface ,
  LPVOID * ppObject
);

Parameters

rguidObject
Unique class identifier of the object being searched for, such as GUID_DSFX_STANDARD_ECHO. Set this parameter to GUID_All_Objects to search for objects of any class.
dwIndex
Index of the object within objects of that class in the path. See Remarks.
rguidInterface
Unique identifier of the desired interface. See Remarks.
ppObject
Address of a variable that receives the desired interface pointer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_OBJECTNOTFOUND

Remarks

Any DMO that has been set on a buffer by using SetFX can be retrieved, even it has not been allocated resources.

The following interfaces can be retrieved for the various DMOs supplied with DirectX.

rguidInterface | *ppObject
IID_IDirectSoundFXGargle8 | IDirectSoundFXGargle8
IID_IDirectSoundFXChorus8 | IDirectSoundFXChorus8
IID_IDirectSoundFXFlanger8 | IDirectSoundFXFlanger8
IID_IDirectSoundFXEcho8 | IDirectSoundFXEcho8
IID_IDirectSoundFXDistortion8 | IDirectSoundFXDistortion8
IID_IDirectSoundFXCompressor8 | IDirectSoundFXCompressor8
IID_IDirectSoundFXParamEq8 | IDirectSoundFXParamEq8
IID_IDirectSoundFXWavesReverb8 | IDirectSoundFXWavesReverb8
IID_IDirectSoundFXI3DL2Reverb8 | IDirectSoundFXI3DL2Reverb8

In addition, the following interfaces are available for any of the standard DMOs. For information on these interfaces, see the Help for DirectX Media Objects.

rguidInterface | *ppObject
IID_IMediaObject | IMediaObject
IID_IMediaObjectInPlace | IMediaObjectInPlace
IID_IMediaParams | IMediaParams

NoteWhen the DirectSound API is used to play buffers, parameter curves (envelopes) set by using the IMediaParams interface do not work, because DirectSound does not timestamp the DMO buffers.

The value in dwIndex is the index of the object within the array of effects passed to SetFX. This is not necessarily the actual position of the object in the effects chain, because some effects might not have been created.

An object is returned solely on the basis of whether it matches rguidObject and dwIndex. It is up to the application to ensure that rguidInterface specifies an interface that can be expected to be found on the object.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::GetPan

The GetPan method retrieves the relative volume of the left and right audio channels.

HRESULT GetPan(
  LPLONG plPan
);

Parameters

plPan
Address of a variable that receives the relative volume, in hundredths of a decibel.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The returned value is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are defined in Dsound.h as -10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is effectively silent. The value DSBPAN_RIGHT means the left channel is effectively silent. The neutral value is DSBPAN_CENTER, defined as 0, which means that both channels are at full volume. When one channel is attenuated, the other remains at full volume.

The pan control acts cumulatively with the volume control.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::GetStatus

The GetStatus method retrieves the status of the sound buffer.

HRESULT GetStatus(
  LPDWORD pdwStatus
);

Parameters

pdwStatus
Address of a variable that receives the status of the sound buffer. The status can be a combination of the following flags:
Value | Description
DSBSTATUS_BUFFERLOST | The buffer is lost and must be restored before it can be played or locked.
DSBSTATUS_LOOPING | The buffer is being looped. If this value is not set, the buffer will stop when it reaches the end of the sound data. This value is returned only in combination with DSBSTATUS_PLAYING.
DSBSTATUS_PLAYING | The buffer is playing. If this value is not set, the buffer is stopped.
DSBSTATUS_LOCSOFTWARE | The buffer is playing in software. Set only for buffers created with the DSBCAPS_LOCDEFER flag.
DSBSTATUS_LOCHARDWARE | The buffer is playing in hardware. Set only for buffers created with the DSBCAPS_LOCDEFER flag.
DSBSTATUS_TERMINATED | The buffer was prematurely terminated by the voice manager and is not playing. Set only for buffers created with the DSBCAPS_LOCDEFER flag.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

DSBSTATUS_PLAYING is set if the buffer is being heard. Because of latency, a call to Play or Stop might not immediately change the status.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::GetVolume

The GetVolume method retrieves the attenuation of the sound.

HRESULT GetVolume(
  LPLONG plVolume
);

Parameters

plVolume
Address of a variable that receives the attenuation, in hundredths of a decibel.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The return value is between DSBVOLUME_MAX and DSBVOLUME_MIN. These values are defined as 0 and ?10,000, respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the sound. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for practical purposes, is silence.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::Initialize

The Initialize method initializes a sound buffer object if it has not yet been initialized.

HRESULT Initialize(
  LPDIRECTSOUND pDirectSound,
  LPCDSBUFFERDESC pcDSBufferDesc
);

Parameters

pDirectSound
Address of the device object associated with this buffer.
pcDSBufferDesc
Address of a DSBUFFERDESC structure that contains the values used to initialize this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values.

Return code
DSERR_INVALIDPARAM
DSERR_ALREADYINITIALIZED

Remarks

Because the CreateSoundBuffer method calls Initialize internally, applications do not need to call this method.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::Lock

The Lock method readies all or part of the buffer for a data write and returns pointers to which data can be written.

HRESULT Lock(
  DWORD dwOffset,
  DWORD dwBytes,
  LPVOID * ppvAudioPtr1,
  LPDWORD  pdwAudioBytes1,
  LPVOID * ppvAudioPtr2,
  LPDWORD pdwAudioBytes2,
  DWORD dwFlags
);

Parameters

dwOffset
Offset, in bytes, from the start of the buffer to the point where the lock begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR is specified in the dwFlags parameter.
dwBytes
Size, in bytes, of the portion of the buffer to lock. The buffer is conceptually circular, so this number can exceed the number of bytes between dwOffset and the end of the buffer.
ppvAudioPtr1
Address of a variable that receives a pointer to the first locked part of the buffer.
pdwAudioBytes1
Address of a variable that receives the number of bytes in the block at ppvAudioPtr1. If this value is less than dwBytes, the lock has wrapped and ppvAudioPtr2 points to a second block of data at the beginning of the buffer .
ppvAudioPtr2
Address of a variable that receives a pointer to the second locked part of the capture buffer. If NULL is returned, the ppvAudioPtr1 parameter points to the entire locked portion of the capture buffer.
pdwAudioBytes2
Address of a variable that receives the number of bytes in the block at ppvAudioPtr2. If ppvAudioPtr2 is NULL, this value is zero.
dwFlags
Flags modifying the lock event. The following flags are defined:
Value | Description
DSBLOCK_FROMWRITECURSOR | Start the lock at the write cursor. The dwOffset parameter is ignored.
DSBLOCK_ENTIREBUFFER | Lock the entire buffer. The dwBytes parameter is ignored.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method accepts an offset and a byte count, and returns two write pointers and their associated sizes. If the locked portion does not extend to the end of the buffer and wrap to the beginning, the second pointer, ppvAudioBytes2, receives NULL. If the lock does wrap, ppvAudioBytes2 points to the beginning of the buffer.

If the application passes NULL for the ppvAudioPtr2 and pdwAudioBytes2 parameters, the lock extends no further than the end of the buffer and does not wrap.

After writing data to the pointers returned by this method, the application must immediately call Unlock to notify DirectSound that the data is ready for playback. Failure to do so can cause audio breakup or silence on some sound device configurations.

This method returns write pointers only. The application should not try to read sound data from this pointer, because the data might not be valid. For example, if the buffer is located in on-card memory, the pointer might be an address to a temporary buffer in system memory. When IDirectSoundBuffer8::Unlock is called, the contents of this temporary buffer are transferred to the on-card memory.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::Play

The Play method causes the sound buffer to play, starting at the play cursor.

HRESULT Play(
  DWORD dwReserved1,
  DWORD dwPriority,
  DWORD dwFlags
);

Parameters

dwReserved1
Reserved. Must be 0.
dwPriority
Priority for the sound, used by the voice manager when assigning hardware mixing resources. The lowest priority is 0, and the highest priority is 0xFFFFFFFF. If the buffer was not created with the DSBCAPS_LOCDEFER flag, this value must be 0.
dwFlags
Flags specifying how to play the buffer. The following flags are defined:

Looping flag

Value | Description
DSBPLAY_LOOPING | After the end of the audio buffer is reached, play restarts at the beginning of the buffer. Play continues until explicitly stopped. This flag must be set when playing a primary buffer.

Voice allocation flags

The voice allocation flags are valid only for buffers created with the DSBCAPS_LOCDEFER flag. One of the following flags can be used to force the processing of the sound into hardware or software. If neither DBSPLAY_LOCHARDWARE nor DBSPLAY_LOCSOFTWARE is set, the sound is played in either software or hardware, depending on the availability of resources at the time the method is called. See Remarks.
Value | Description
DSBPLAY_LOCHARDWARE | Play this voice in a hardware buffer only. If the hardware has no available voices and no voice management flags are set, the call to IDirectSoundBuffer8::Play fails. This flag cannot be combined with DSBPLAY_LOCSOFTWARE.
DSBPLAY_LOCSOFTWARE | Play this voice in a software buffer only. This flag cannot be combined with DSBPLAY_LOCHARDWARE or any voice management flag.

Voice management flags

The voice management flags are valid only for buffers created with the DSBCAPS_LOCDEFER flag, and are used for sounds that are to play in hardware. These flags enable hardware resources that are already in use to be yielded to the current sound. Only buffers created with the DSBCAPS_LOCDEFER flag are candidates for premature termination. See Remarks.
Value | Description
DSBPLAY_TERMINATEBY_TIME | If the hardware has no available voices, a currently playing nonlooping buffer will be stopped to make room for the new buffer. The buffer prematurely terminated is the one with the least time left to play.
DSBPLAY_TERMINATEBY_DISTANCE | If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer prematurely terminated will be selected from buffers that have the buffer's DSBCAPS_ MUTE3DATMAXDISTANCE flag set and are beyond their maximum distance. If there are no such buffers, the method fails.
DSBPLAY_TERMINATEBY_PRIORITY | If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer prematurely terminated will be the one with the lowest priority as set by the dwPriority parameter passed to IDirectSoundBuffer8::Play for the buffer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

If SetCooperativeLevel has not been called, the method returns DS_OK, but no sound will be produced until a cooperative level has been set.

If the application is multithreaded, the thread that plays the buffer must continue to exist as long as the buffer is playing. Buffers created on WDM drivers stop playing when the thread is terminated.

If the buffer specified in the method is already playing, the call to the method succeeds and the buffer continues to play. However, the flags defined in the most recent call supersede flags defined in previous calls.

When called on the primary buffer, this method causes the buffer to start playing to the sound device. If the application has set the DSSCL_WRITEPRIMARY cooperative level, any audio data put in the primary buffer by the application is sent to the sound device. Under any other cooperative level, the primary buffer plays silence if no secondary buffers are playing. Primary buffers must be played with the DSBPLAY_LOOPING flag set.

If the method is called with a voice allocation or voice management flag set on a buffer that was not created with the DSBCAPS_LOCDEFER flag, the call fails with DSERR_INVALIDPARAM.

DSBPLAY_TERMINATEBY_TIME and DSBPLAY_TERMINATEBY_DISTANCE cannot be combined, but either may be combined with DSBPLAY_TERMINATEBY_PRIORITY, in which case the DSBPLAY_TERMINATEBY_TIME or DSBPLAY_TERMINATEBY_DISTANCE flag is used to determine which buffer should be terminated in the event of a priority tie.

The following table shows the behavior of the method under various combinations of the voice allocation and voice management flags when no free hardware voices are available.

 | DSBPLAY_LOCHARDWARE | Neither DSBPLAY_LOCHARDWARE nor DSBPLAY_LOCSOFTWARE | DSBPLAY_LOCSOFTWARE
DSBPLAY_TERMINATEBY_TIME | Sound with least time left to play is terminated and the new sound plays on the released voice. | Sound with least time left to play is terminated and the new sound plays on the released voice. | New sound plays in software.
DSBPLAY_TERMINATEBY_DISTANCE | If any sounds currently playing in hardware are beyond their maximum distance and have the DSBCAPS_MUTE3DATMAXDISTANCE flag set, one of them is terminated and the new sound plays in hardware. Otherwise, the call fails. | If any sounds currently playing in hardware are beyond their maximum distance and have the DSBCAPS_MUTE3DATMAXDISTANCE flag set, one of them is terminated and the new sound plays in hardware. Otherwise, the new sound plays in software. | New sound plays in software.
DSBPLAY_TERMINATEBY_PRIORITY | If the new sound's priority is higher than or equal to that of any sound currently playing in hardware, one of the lowest-priority sounds is terminated and the new sound plays in hardware. Otherwise, the call fails. | If the new sound's priority is higher than or equal to that of any sound currently playing in hardware, one of the lowest-priority sounds is terminated and the new sound plays in hardware. Otherwise, the new sound plays in software. | New sound plays in software.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::Restore

The Restore method restores the memory allocation for a lost sound buffer.

HRESULT Restore();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code

  • DSERR_BUFFERLOST
  • DSERR_INVALIDCALL
  • DSERR_PRIOLEVELNEEDED

Remarks

If the application does not have the input focus, IDirectSoundBuffer8::Restore might not succeed. For example, if the application with the input focus has the DSSCL_WRITEPRIMARY cooperative level, no other application will be able to restore its buffers. Similarly, an application with the DSSCL_WRITEPRIMARY cooperative level must have the input focus to restore its primary buffer.

After DirectSound restores the buffer memory, the application must rewrite the buffer with valid sound data. DirectSound cannot restore the contents of the memory, only the memory itself.

The application can receive notification that a buffer is lost when it specifies that buffer in a call to the Lock or Play method. These methods return DSERR_BUFFERLOST to indicate a lost buffer. The GetStatus method can also be used to retrieve the status of the sound buffer and test for the DSBSTATUS_BUFFERLOST flag.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::SetCurrentPosition

The SetCurrentPosition method sets the position of the play cursor, which is the point at which the next byte of data is read from the buffer.

HRESULT SetCurrentPosition(
  DWORD dwNewPosition
);

Parameters

dwNewPosition
Offset of the play cursor, in bytes, from the beginning of the buffer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method cannot be called on the primary buffer.

If the buffer is playing, the cursor immediately moves to the new position and play continues from that point. If it is not playing, playback will begin from the new position the next time the Play method is called.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::SetFormat

The SetFormat method sets the format of the primary buffer. Whenever this application has the input focus, DirectSound will set the primary buffer to the specified format.

HRESULT SetFormat(
  LPCWAVEFORMATEX pcfxFormat
);

Parameters

pcfxFormat
Address of a WAVEFORMATEX structure that describes the new format for the primary sound buffer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_BADFORMAT
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_PRIOLEVELNEEDED
DSERR_UNSUPPORTED

Remarks

The format of the primary buffer should be set before secondary buffers are created.

The method fails if the application has the DSSCL_NORMAL cooperative level.

If the application is using DirectSound at the DSSCL_WRITEPRIMARY cooperative level, and the format is not supported, the method fails.

If the cooperative level is DSSCL_PRIORITY, DirectSound stops the primary buffer, changes the format, and restarts the buffer. The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest supported format. To determine whether this has happened, an application can call the GetFormat method for the primary buffer and compare the result with the format that was requested with the SetFormat method.

This method is not available for secondary sound buffers. If a new format is required, the application must create a new DirectSoundBuffer object.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::SetFrequency

The SetFrequency method sets the frequency at which the audio samples are played.

HRESULT SetFrequency(
  DWORD dwFrequency
);

Parameters

dwFrequency
Frequency, in hertz (Hz), at which to play the audio samples. A value of DSBFREQUENCY_ORIGINAL resets the frequency to the default value of the buffer format.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

Increasing or decreasing the frequency changes the perceived pitch of the audio data. This method does not affect the format of the buffer.

Before setting the frequency, you should ascertain whether the frequency is supported by checking the dwMinSecondarySampleRate and dwMaxSecondarySampleRate members of the DSCAPS structure for the device. Some operating systems do not support frequencies greater than 100,000 Hz.

This method is not valid for the primary buffer.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::SetFX

The SetFX method enables effects on a buffer.

For this method to succeed, CoInitialize must have been called. This is done automatically in applications that create DirectSound by using IDirectMusicPerformance8::InitAudio. However, applications that create DirectSound by using DirectSoundCreate8 must also call CoInitialize.

The buffer must not be playing or locked.

HRESULT SetFX(
  DWORD dwEffectsCount,
  LPDSEFFECTDESC pDSFXDesc,
  LPDWORD pdwResultCodes
);

Parameters

dwEffectsCount
Number of elements in the pDSFXDesc and pdwResultCodes arrays. If this value is 0, pDSFXDesc and pdwResultCodes must both be NULL. Set to 0 to remove all effects from the buffer.
pDSFXDesc
Address of an array of DSEFFECTDESC structures, of size dwEffectsCount, that specifies the effects wanted on the buffer. Must be NULL if dwEffectsCount is 0.
pdwResultCodes
Address of an array of DWORD elements, of size dwEffectsCount. Each element receives one of the values shown in the following table, indicating the result of the attempt to create the corresponding effect in the pDSFXDesc array.

Note This parameter must be NULL if dwEffectsCount is 0, or can be NULL if results are not wanted.

Value | Description
DSFXR_LOCHARDWARE | Effect is instantiated in hardware.
DSFXR_LOCSOFTWARE | Effect is instantiated in software.
DSFXR_UNALLOCATED | Effect has not yet been assigned to hardware or software. This value is returned if the buffer was created with the DSBCAPS_LOCDEFER flag in DSBUFFERDESC.
DSFXR_FAILED | No effect was created because resources weren't available.
DSFXR_PRESENT | Effect is available but was not created because one of the other effects requested could not be created. If any of the effects requested cannot be created, none of them are, and the call fails.
DSFXR_UNKNOWN | Effect is not registered on the system, and the method failed as a result.

Return Values

If the method succeeds, the return value is DS_OK or DS_INCOMPLETE. If the method fails, the return value may be one of the error values shown in the following table.

Return code
CO_E_NOTINITIALIZED
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_INVALIDCALL
DSERR_NOINTERFACE
DSERR_PRIOLEVELNEEDED

In addition, the method can return an error value from DMO methods, including IMediaObject::SetInputType and IMediaObject::SetOutputType. See the DirectShow documentation for possible error values.

Remarks

If the method fails, the value for each effect in pdwResultCodes is either DSFXF_PRESENT or DSFXR_UNKNOWN. Check these values to determine which effects caused the failure.

For the method to succeed, the buffer must have been created with the DSBCAPS_CTRLFX flag and must not be playing or locked.

If the method returns DSERR_NOINTERFACE or another COM error, check the result code array for DSFXR_PRESENT or DSFXR_UNKNOWN to ascertain which effect caused the error. If the method returns DSERR_INVALIDPARAM, check the result codes for DSFXR_FAILED to see which effects failed to acquire resources.

If the buffer is part of a DirectMusic audiopath, the audiopath must be inactive.

An effect must be set on a buffer before the effect interface can be obtained. To obtain the effect interface, use GetObjectInPath.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::SetPan

The SetPan method sets the relative volume of the left and right channels.

HRESULT SetPan(
  LONG lPan
);

Parameters

lPan
Relative volume between the left and right channels.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The returned value is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are defined in Dsound.h as -10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is attenuated by 100 dB and is effectively silent. The value DSBPAN_RIGHT means the left channel is silent. The neutral value is DSBPAN_CENTER, defined as 0, which means that both channels are at full volume. When one channel is attenuated, the other remains at full volume.

The pan control acts cumulatively with the volume control.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::SetVolume

The SetVolume method sets the attenuation of the sound.

HRESULT SetVolume(
  LONG lVolume
);

Parameters

lVolume
Attenuation, in hundredths of a decibel (dB).

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). These values are defined in Dsound.h as 0 and ?10,000 respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the stream. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for all practical purposes, is silence. DirectSound does not support amplification.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::Stop

The Stop method causes the sound buffer to stop playing.

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Remarks

For secondary sound buffers, IDirectSoundBuffer8::Stop sets the play cursor to the sample that follows the last sample played. This means that when the Play method is next called on the buffer, it will continue playing where it left off.

For the primary buffer, if an application has the DSSCL_WRITEPRIMARY level, this method will stop the buffer and reset the play cursor to 0 (the beginning of the buffer). This is necessary because the primary buffers on most sound cards can play only from the beginning of the buffer.

However, if IDirectSoundBuffer8::Stop is called on a primary buffer and the application has a cooperative level other than DSSCL_WRITEPRIMARY, this method simply reverses the effects of IDirectSoundBuffer8::Play. It configures the primary buffer to stop if no secondary buffers are playing. If other buffers are playing in this or other applications, the primary buffer will not actually stop until they are stopped. This method is useful because playing the primary buffer consumes processing overhead even if the buffer is playing sound data with the amplitude of 0 decibels.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundBuffer8::Unlock

The Unlock method releases a locked sound buffer.

HRESULT Unlock(
  LPVOID pvAudioPtr1,
  DWORD dwAudioBytes1,
  LPVOID pvAudioPtr2,
  DWORD dwAudioBytes2
);

Parameters

pvAudioPtr1
Address of the value retrieved in the ppvAudioPtr1 parameter of the Lock method.
dwAudioBytes1
Number of bytes written to the portion of the buffer at pvAudioPtr1. See Remarks.
pvAudioPtr2
Address of the value retrieved in the ppvAudioPtr2 parameter of the IDirectSoundBuffer8::Lock method.
dwAudioBytes2
Number of bytes written to the portion of the buffer at pvAudioPtr2. See Remarks.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

An application must pass both pointers, pvAudioPtr1 and pvAudioPtr2, returned by the IDirectSoundBuffer8::Lock method to ensure the correct pairing of IDirectSoundBuffer8::Lock and IDirectSoundBuffer8::Unlock. The second pointer is needed even if nothing was written to the second pointer.

The values in dwAudioBytes1 and dwAudioBytes2 must specify the number of bytes actually written to each part of the buffer, which might be less than the size of the lock. DirectSound uses these values to determine how much data to commit to the device.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundBuffer8


IDirectSoundCapture8

The IDirectSoundCapture8 interface is used to create sound capture buffers.

The interface is obtained by using the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 functions, or by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSoundCapture8.

IDirectSoundCapture8 is a define for IDirectSoundCapture. The two interface names are interchangeable. However, objects supporting this interface can have different functionality, depending on their class. For more information, see DirectSoundCaptureCreate8 and IDirectSoundCapture8::CreateCaptureBuffer.

In addition to the methods inherited from IUnknown, the IDirectSoundCapture8 interface exposes the following methods.

IDirectSoundCapture8 Members

Method | Description
IDirectSoundCapture8::CreateCaptureBuffer | The CreateCaptureBuffer method creates a buffer for capturing waveform audio.
IDirectSoundCapture8::GetCaps | The GetCaps method retrieves the capabilities of the capture device.
IDirectSoundCapture8::Initialize | The Initialize method initializes a capture device object created by using CoCreateInstance. Calling this method is not required when the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 function is used to create the object.

The LPDIRECTSOUNDCAPTURE type is defined as a pointer to the IDirectSoundCapture interface:

typedef struct IDirectSoundCapture *LPDIRECTSOUNDCAPTURE;

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundCapture8::CreateCaptureBuffer

The CreateCaptureBuffer method creates a buffer for capturing waveform audio.

HRESULT CreateCaptureBuffer(
  LPCDSCBUFFERDESC pcDSCBufferDesc,
  LPDIRECTSOUNDCAPTUREBUFFER * ppDSCBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pcDSCBufferDesc
Pointer to a DSCBUFFERDESC structure containing values for the capture buffer being created.
ppDSCBuffer
Address of a variable that receives an IDirectSoundCaptureBuffer interface pointer. Use QueryInterface to obtain IDirectSoundCaptureBuffer8. See Remarks.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values.

Return code
DSERR_INVALIDPARAM
DSERR_BADFORMAT
DSERR_GENERIC
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

On Microsoft Windows98 and Windows2000, each capture device supports a single buffer.

The IDirectSoundCaptureBuffer8 interface is supported only on buffers created by an object of class CLSID_DirectSoundCapture8. If the IDirectSoundCapture8 interface was obtained from DirectSoundCaptureCreate8, IDirectSoundCaptureBuffer8 is supported. If IDirectSoundCapture8 was obtained from the earlier DirectSoundCaptureCreate function, only IDirectSoundCaptureBuffer is supported.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCapture8


IDirectSoundCapture8::GetCaps

The GetCaps method retrieves the capabilities of the capture device.

HRESULT GetCaps(
  LPDSCCAPS pDSCCaps
);

Parameters

pDSCCaps
Pointer to a DSCCAPS structure to be receive information about the capture device. When the method is called, the dwSize member must specify the size of the structure in bytes.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCapture8


IDirectSoundCapture8::Initialize

The Initialize method initializes a capture device object created by using CoCreateInstance. Calling this method is not required when the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 function is used to create the object.

HRESULT Initialize(
  LPCGUID pcGuidDevice
);

Parameters

pcGuidDevice
Address of the GUID specifying the sound driver to which the DirectSoundCapture object binds. Use NULL to select the primary sound driver.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_ALREADYINITIALIZED

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCapture8


IDirectSoundCaptureBuffer8

The IDirectSoundCaptureBuffer8 interface is used to manipulate sound capture buffers.

To obtain the IDirectSoundCaptureBuffer8 interface, call the IDirectSoundCapture8::CreateCaptureBuffer method to obtain IDirectSoundCaptureBuffer, then pass IID_IDirectSoundCaptureBuffer8 to IDirectSoundCaptureBuffer::QueryInterface.

In addition to the methods inherited from IUnknown, the IDirectSoundCaptureBuffer8 interface exposes the following methods, arranged by category.

Capture Management

Method | Description
IDirectSoundCaptureBuffer8::Lock | The Lock method locks a portion of the buffer. Locking the buffer returns pointers into the buffer, allowing the application to read or write audio data into memory.
IDirectSoundCaptureBuffer8::Start | The Start method begins capturing data into the buffer. If the buffer is already capturing, the method has no effect.
IDirectSoundCaptureBuffer8::Stop | The Stop method stops the buffer so that it is no longer capturing data. If the buffer is not capturing, the method has no effect.
IDirectSoundCaptureBuffer8::Unlock | The Unlock method unlocks the buffer.

Effects

Method | Description
IDirectSoundCaptureBuffer8::GetFXStatus | The GetFXStatus method retrieves the status of capture effects.
IDirectSoundCaptureBuffer8::GetObjectInPath | The GetObjectInPath method retrieves an interface to an effect object associated with the buffer.

Initialization

Method | Description
IDirectSoundCaptureBuffer8::Initialize | The Initialize method initializes a capture buffer object. Because the IDirectSoundCapture8::CreateCaptureBufferIDirectSoundCapture8::CreateCaptureBuffer

Information

Method | Description
IDirectSoundCaptureBuffer8::GetCaps | The GetCaps method retrieves the capabilities of the buffer.
IDirectSoundCaptureBuffer8::GetCurrentPosition | Address of a variable that receives the offset from the start of the buffer, in bytes, of the capture cursor. The parameter can be NULL if this value is not wanted.
IDirectSoundCaptureBuffer8::GetFormat | The GetFormat method retrieves the waveform format of the capture buffer.
IDirectSoundCaptureBuffer8::GetStatus | The GetStatus method retrieves the status of the capture buffer.

The LPDIRECTSOUNDCaptureBuffer8 type is defined as a pointer to the IDirectSoundCaptureBuffer8 interface:

typedef struct IDirectSoundCaptureBuffer8 *LPDIRECTSOUNDCaptureBuffer8;

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundCaptureBuffer8::GetCaps

The GetCaps method retrieves the capabilities of the buffer.

HRESULT GetCaps(
  LPDSCBCAPS pDSCBCaps
);

Parameters

pDSCBCaps
Pointer to a DSCBCAPS structure that receives information about the capture buffer. On input, the dwSize member must specify the size of the structure in bytes.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_OUTOFMEMORY

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureBuffer8::GetCurrentPosition

The GetCurrentPosition method retrieves the positions of the capture and read cursors in the buffer.

The capture cursor is ahead of the read cursor. The data after the read position up to and including the capture position is not necessarily valid data.

HRESULT GetCurrentPosition(
  LPDWORD pdwCapturePosition,
  LPDWORD pdwReadPosition
);

Parameters

pdwCapturePosition
Address of a variable that receives the offset from the start of the buffer, in bytes, of the capture cursor. The parameter can be NULL if this value is not wanted.
pdwReadPosition
Address of a variable that receives the offset from the start of the buffer, in bytes, of the read cursor.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureBuffer8::GetFormat

The GetFormat method retrieves the waveform format of the capture buffer.

HRESULT GetFormat(
  LPWAVEFORMATEX pwfxFormat,
  DWORD dwSizeAllocated,
  LPDWORD pdwSizeWritten
);

Parameters

pwfxFormat
Address of a WAVEFORMATEX structure that receives a description of the sound data in the capture buffer. To retrieve the buffer size needed to contain the format description, specify NULL.; in this case, the DWORD pointed to by the pdwSizeWritten parameter receives the size of the structure needed to receive complete format information.
dwSizeAllocated
Size, in bytes, of the WAVEFORMATEX structure. DirectSoundCapture writes, at most, dwSizeAllocated bytes to the structure.
pdwSizeWritten
Address of a variable that receives the number of bytes written to the WAVEFORMATEX structure; or, if pwfxFormat is NULL, the size of the WAVEFORMATEX structure that would be necessary to receive the information. This parameter can be NULL if the value is not wanted.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureBuffer8::GetFXStatus

The GetFXStatus method retrieves the status of capture effects.

HRESULT GetFXStatus(
  DWORD dwFXCount,
  LPDWORD pdwFXStatus
);

Parameters

dwFXCount
Number of elements in the pdwFXStatus array.
pdwFXStatus
Address of an array of DWORD variables that receive the status of each effect. This should contain the same number of elements as the array passed in the dwFXCount member of the DSCBUFFERDESC structure passed to DirectSoundFullDuplexCreate8 or IDirectSoundCapture8::CreateCaptureBuffer. The possible values returned in the array are as follows:
Value | Description
DSCFXR_LOCHARDWARE | Effect is instantiated in hardware.
DSCFXR_LOCSOFTWARE | Effect is instantiated in software.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureBuffer8::GetObjectInPath

The GetObjectInPath method retrieves an interface to an effect object associated with the buffer.

HRESULT GetObjectInPath(
  REFGUID rguidObject ,
  DWORD dwIndex ,
  REFGUID rguidInterface ,
  LPVOID * ppObject
);

Parameters

rguidObject
Value of type REFGUID that specifies the unique class identifier of the object being searched for, such as GUID_DSCFX_CLASS_AEC.
dwIndex
Index of the object within objects of that class in the path. See Remarks.
rguidInterface
Unique identifier of the desired interface, such as IID_IDirectSoundCaptureFXAec8.
ppObject
Address of a variable that receives the desired interface pointer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_OBJECTNOTFOUND

Remarks

The value in dwIndex is the index of the object within the array of effects in the DSCBUFFERDESC structure passed to DirectSoundFullDuplexCreate8 or IDirectSoundCapture8::CreateCaptureBuffer.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureBuffer8::GetStatus

The GetStatus method retrieves the status of the capture buffer.

HRESULT GetStatus(
  LPDWORD pdwStatus
);

Parameters

pdwStatus
Address of a variable that receives the status of the capture buffer. The status can be set to one or more of the following:
Value | Description
DSCBSTATUS_CAPTURING | The buffer is capturing audio data.
DSCBSTATUS_LOOPING | The buffer is looping.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureBuffer8::Initialize

The Initialize method initializes a capture buffer object. Because the IDirectSoundCapture8::CreateCaptureBuffer method and the DirectSoundFullDuplexCreate8 function call the IDirectSoundCaptureBuffer8::Initialize method internally, this method is not used by applications.

HRESULT Initialize(
  LPDIRECTSOUNDCAPTURE pDirectSoundCapture,
  LPCDSCBUFFERDESC pcDSCBufferDesc
);

Parameters

pDirectSoundCapture
Address of the DirectSoundCapture object associated with this DirectSoundCaptureBuffer object.
pcDSCBufferDesc
Address of a DSCBUFFERDESC structure that contains the values used to initialize this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_ALREADYINITIALIZED

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureBuffer8::Lock

The Lock method locks a portion of the buffer. Locking the buffer returns pointers into the buffer, allowing the application to read or write audio data into memory.

HRESULT Lock(
  DWORD dwOffset,
  DWORD dwBytes,
  LPVOID * ppvAudioPtr1,
  LPDWORD  pdwAudioBytes1,
  LPVOID * ppvAudioPtr2,
  LPDWORD pdwAudioBytes2,
  DWORD dwFlags
);

Parameters

dwOffset
Offset, in bytes, from the start of the buffer to the point where the lock begins.
dwBytes
Size, in bytes, of the portion of the buffer to lock. Because the buffer is conceptually circular, this number can exceed the number of bytes between dwOffset and the end of the buffer.
ppvAudioPtr1
Address of a variable that receives a pointer to the first locked part of the buffer.
pdwAudioBytes1
Address of a variable that receives the number of bytes in the block at ppvAudioPtr1. If this value is less than dwBytes, the lock has wrapped and ppvAudioPtr2 points to a second block of data at the beginning of the buffer.
ppvAudioPtr2
Address of a variable that receives a pointer to the second locked part of the capture buffer. If NULL is returned, the ppvAudioPtr1 parameter points to the entire locked portion of the capture buffer.
pdwAudioBytes2
Address of a variable that receives the number of bytes in the block at ppvAudioPtr2. If ppvAudioPtr2 is NULL, this value is zero.
dwFlags
Flags modifying the lock event. This value can be zero or the following flag:
Value | Description
DSCBLOCK_ENTIREBUFFER | Ignore dwBytes and lock the entire capture buffer.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Remarks

This method accepts an offset and a byte count, and returns two read pointers and their associated sizes. If the locked portion does not extend to the end of the buffer and wrap to the beginning, the second pointer, ppvAudioBytes2, receives NULL. If the lock does wrap, ppvAudioBytes2 points to the beginning of the buffer.

If the application passes NULL for the ppvAudioPtr2 and pdwAudioBytes2 parameters, the lock extends no further than the end of the buffer and does not wrap.

The application should read data from the pointers returned by this method and then immediately call Unlock. The sound buffer should not remain locked while it is running; if it does, the capture cursor will reach the locked bytes and audio problems may result.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureBuffer8::Start

The Start method begins capturing data into the buffer. If the buffer is already capturing, the method has no effect.

HRESULT Start(
  DWORD dwFlags
);

Parameters

dwFlags
Flags that specify the behavior of the buffer when capturing sound data. The following flag is defined:
Value | Description
DSCBSTART_LOOPING | After the end of the buffer is reached, capture restarts at the beginning and continues until explicitly stopped.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Remarks

If the buffer is already capturing, a call to this method using a different value in dwFlags might not change the value returned by GetStatus.

If the application is multithreaded, the thread that starts the buffer must continue to exist as long as the buffer is capturing. Buffers created on WDM drivers stop capturing when the thread is terminated.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureBuffer8::Stop

The Stop method stops the buffer so that it is no longer capturing data. If the buffer is not capturing, the method has no effect.

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureBuffer8::Unlock

The Unlock method unlocks the buffer.

HRESULT Unlock(
  LPVOID pvAudioPtr1,
  DWORD dwAudioBytes1,
  LPVOID pvAudioPtr2,
  DWORD dwAudioBytes2
);

Parameters

pvAudioPtr1
Address of the value retrieved in the ppvAudioPtr1 parameter of the Lock method.
dwAudioBytes1
Number of bytes read from the pvAudioPtr1 parameter. See Remarks.
pvAudioPtr2
Address of the value retrieved in the ppvAudioPtr2 parameter of the IDirectSoundCaptureBuffer8::Lock method.
dwAudioBytes2
Number of bytes read from the pvAudioPtr2 parameter. See Remarks.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Remarks

An application must pass both pointers, pvAudioPtr1 and pvAudioPtr2, returned by the IDirectSoundCaptureBuffer8::Lock method to ensure the correct pairing of IDirectSoundCaptureBuffer8::Lock and IDirectSoundCaptureBuffer8::Unlock. The second pointer is needed even if zero bytes were written to the second pointer.

The values in dwAudioBytes1 and dwAudioBytes2 must specify the number of bytes actually read from each part of the buffer, which might be less than the size of the lock. DirectSound uses these values to determine how much data to transfer from the device.

Make sure that the capture buffer does not remain locked for long periods of time.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureBuffer8


IDirectSoundCaptureFXAec8

The IDirectSoundCaptureFXAec8 interface is used to set and retrieve parameters on a capture buffer that supports acoustic echo cancellation. This interface requires Microsoft Windows XP or later operating systems.

IDirectSoundCaptureFXAec8 is a define for IDirectSoundCaptureFXAec. The interface names are interchangeable.

This interface is obtained by calling GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundCaptureFXAec8 interface exposes the following methods.

IDirectSoundCaptureFXAec8 Members

Method | Description
IDirectSoundCaptureFXAec8::GetAllParameters | The IDirectSoundCaptureFXAec8::GetAllParameters method retrieves the acoustic echo cancellation parameters of a buffer.
IDirectSoundCaptureFXAec8::GetStatus | The IDirectSoundCaptureFXAec8::GetStatus method retrieves the status of the effect.
IDirectSoundCaptureFXAec8::Reset | The IDirectSoundCaptureFXAec8::Reset method resets the effect to its initial state.
IDirectSoundCaptureFXAec8::SetAllParameters | The IDirectSoundCaptureFXAec8::SetAllParameters method sets the acoustic echo cancellation parameters of a buffer.

The LPDIRECTSOUNDCAPTUREFXAEC8 type is defined as a pointer to the IDirectSoundCaptureFXAec8 interface:

typedef struct IDirectSoundCaptureFXAec8 *LPDIRECTSOUNDCAPTUREFXAEC8;

Info

Operating System: Requires Microsoft WindowsXP or later.

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

See Also

DirectSound Interfaces


IDirectSoundCaptureFXAec8::GetAllParameters

The GetAllParameters method retrieves the acoustic echo cancellation parameters of a buffer.

HRESULT GetAllParameters(
  LPDSCFXAec pDscFxAec
);

Parameters

pDscFxAec
Address of a DSCFXAec structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following values.

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundCaptureFXAec8


IDirectSoundCaptureFXAec8::GetStatus

The IDirectSoundCaptureFXAec8::GetStatus method retrieves the status of the effect.

HRESULT GetStatus(
  PDWORD pdwStatus
);

Parameters

pdwStatus
Address of a DWORD variable to receive the status. The following flags are defined. See Remarks.
Constant | Value
DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED | 0x0
DSCFX_AEC_STATUS_HISTORY_CONTINUOUSLY_CONVERGED | 0x1
DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED | 0x2
DSCFX_AEC_STATUS_CURRENTLY_CONVERGED | 0x8

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following values.

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Remarks

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

The three least significant bits in *pdwStatus describe the convergence history; that is, the success of the effect in canceling the echo. The convergence history can be used by the application to determine if the algorithm has converged and remained in the converged state since it started processing data.

Initially, the AEC algorithm sets the three lower bits to 0 for the uninitialized state (DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED). When the AEC algorithm has converged, the convergence history is switched to the DSCFX_AEC_STATUS_HISTORY_CONTINUOUSLY_CONVERGED state. If the AEC algorithm ever loses convergence, the convergence history is then transitioned to the DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED state. A transition from DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED to DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED is also possible. The convergence history remains in the DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED state until the algorithm is reset or timely data is no longer arriving on the capture or render stream.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundCaptureFXAec8


IDirectSoundCaptureFXAec8::Reset

The IDirectSoundCaptureFXAec8::Reset method resets the effect to its initial state.

HRESULT Reset();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_OUTOFMEMORY.

Remarks

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

Applications should not reset an effect except when necessary because it has entered an incorrect state. This might be done in response to user input. An effect must not be reset arbitrarily at startup, because another application might be using the same effect.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureFXAec8


IDirectSoundCaptureFXAec8::SetAllParameters

The SetAllParameters method sets the acoustic echo cancellation parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSCFXAec pcDscFxAec
);

Parameters

pcDscFxAec
Address of a DSCFXAec structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following values.

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Remarks

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundCaptureFXAec8


IDirectSoundCaptureFXNoiseSuppress8

The IDirectSoundCaptureFXNoiseSuppress8 interface is used to set and retrieve parameters on a capture buffer that supports noise suppression. This interface requires Microsoft WindowsXP or later.

IDirectSoundCaptureFXNoiseSuppress8 is a define for IDirectSoundCaptureFXNoiseSuppress. The interface names are interchangeable.

This interface is obtained by calling GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundCaptureFXNoiseSuppress8 interface exposes the following methods.

IDirectSoundCaptureFXNoiseSuppress8 Members

Method | Description
IDirectSoundCaptureFXNoiseSuppress8::GetAllParameters | The IDirectSoundCaptureFXNoiseSuppress8::GetAllParameters method retrieves the noise suppression parameters of a buffer.
IDirectSoundCaptureFXNoiseSuppress8::Reset | The IDirectSoundCaptureFXNoiseSuppress8::Reset method resets the effect to its initial state.
IDirectSoundCaptureFXNoiseSuppress8::SetAllParameters | The IDirectSoundCaptureFXNoiseSuppress8::SetAllParameters method sets the noise suppression parameters of a buffer.

The LPDIRECTSOUNDNOISESUPPRESS8 type is defined as a pointer to the IDirectSoundNoiseSuppress8 interface:

typedef struct IDirectSoundCaptureFXNoiseSuppress8  *LPDIRECTSOUNDCAPTUREFXNOISESUPPRESS8;

Info

Operating System: Requires Microsoft WindowsXP or later.

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

See Also

DirectSound Interfaces


IDirectSoundCaptureFXNoiseSuppress8::GetAllParameters

The GetAllParameters method retrieves the noise suppression parameters of a buffer.

HRESULT GetAllParameters(
  LPDSCFXNoiseSuppress pDscFxNoiseSuppress
);

Parameters

pDscFxNoiseSuppress
Address of a DSCFXNoiseSuppress structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Remarks

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundCaptureFXNoiseSuppress8


IDirectSoundCaptureFXNoiseSuppress8::Reset

The IDirectSoundCaptureFXNoiseSuppress8::Reset method resets the effect to its initial state.

HRESULT Reset();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_OUTOFMEMORY.

Remarks

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

Applications should not reset an effect except when necessary because it has entered an incorrect state. This might be done in response to user input. An effect must not be reset arbitrarily at startup, because another application might be using the same effect.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundCaptureFXNoiseSuppress8


IDirectSoundCaptureFXNoiseSuppress8::SetAllParameters

The SetAllParameters method sets the noise suppression parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSCFXNoiseSuppression pcDscFxNoiseSuppress
);

Parameters

pcDscFxNoiseSuppress
Address of a DSCFXNoiseSuppress structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Remarks

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundCaptureFXNoiseSuppress8


IDirectSoundFullDuplex8

The IDirectSoundFullDuplex8 interface represents a full-duplex stream.

The interface is obtained by using the DirectSoundFullDuplexCreate8 function. This function initializes DirectSound capture and playback.

The interface can also be obtained by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSoundFullDuplex8.

IDirectSoundFullDuplex8 is a define for IDirectSoundFullDuplex. The interface names are interchangeable.

In addition to the methods inherited from IUnknown, the IDirectSoundFullDuplex8 interface exposes the following method.

IDirectSoundFullDuplex8 Members

Method | Description
IDirectSoundFullDuplex8::Initialize | The Initialize method initializes a full duplex object that was created by using CoCreateInstance.

The LPDIRECTSOUNDFULLDUPLEX type is defined as a pointer to IDirectSoundFullDuplex.

typedef struct IDirectSoundFullDuplex *LPDIRECTSOUNDFULLDUPLEX;

Info

Operating System: Requires Microsoft Windows XP or later.

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

See Also

DirectSound Interfaces


IDirectSoundFullDuplex8::Initialize

The Initialize method initializes a full-duplex object that was created by using CoCreateInstance.

HRESULT Initialize(
  LPCGUID pCaptureGuid,
  LPCGUID pRenderGuid ,
  LPCDSCBUFFERDESC lpDscBufferDesc ,
  LPCDSBUFFERDESC lpDsBufferDesc,
  HWND hWnd ,
  DWORD dwLevel ,
  LPLPDIRECTSOUNDCAPTUREBUFFER8 lplpDirectSoundCaptureBuffer8 ,
  LPLPDIRECTSOUNDBUFFER8 lplpDirectSoundBuffer8
);

Parameters

pCaptureGuid
Address of the GUID that identifies the sound capture device for full duplex input. Must be one of the GUIDs returned by DirectSoundCaptureEnumerate, NULL for the default capture device, or one of the values shown in the following table.
Value | Description
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.
pRenderGuid
Address of the GUID that identifies the sound rendering device for full-duplex output. Must be one of the GUIDs returned by DirectSoundEnumerate, NULL for the default rendering device, or one of the values shown in the following table.
Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.
lpDscBufferDesc
Address of a DSCBUFFERDESC structure that specifies the characteristics of the capture buffer.
lpDsBufferDesc
Address of a DSBUFFERDESC structure that specifies the characteristics of the render buffer.
hWnd
Handle to the application window.
dwLevel
Cooperative level for the device. For more information, see SetCooperativeLevel.
lplpDirectSoundCaptureBuffer8
Address of a variable that receives the IDirectSoundCaptureBuffer8 interface of the capture buffer.
lplpDirectSoundBuffer8
Address of a variable that receives the IDirectSoundBuffer8 interface of the render buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If it fails, the return value may be one of the values shown in the following table.

Return code
DSERR_ALREADYINITIALIZED
DSERR_BADFORMAT
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundFullDuplex8


IDirectSoundFXChorus8

The IDirectSoundFXChorus8 interface is used to set and retrieve effect parameters on a buffer that supports chorus.

This interface is obtained by calling GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXChorus8 interface exposes the following methods.

IDirectSoundFXChorus8 Members

Method | Description
IDirectSoundFXChorus8::GetAllParameters | The GetAllParameters method retrieves the chorus parameters of a buffer.
IDirectSoundFXChorus8::SetAllParameters | The SetAllParameters method sets the chorus parameters of a buffer.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundFXChorus8::GetAllParameters

The GetAllParameters method retrieves the chorus parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXChorus pDsFxChorus
);

Parameters

pDsFxChorus
Address of a DSFXChorus structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXChorus8


IDirectSoundFXChorus8::SetAllParameters

The SetAllParameters method sets the chorus parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXChorus pcDsFxChorus
);

Parameters

pcDsFxChorus
Address of a DSFXChorus structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXChorus8


IDirectSoundFXCompressor8

The IDirectSoundFXCompressor8 interface is used to set and retrieve effect parameters on a buffer that supports compression.

This interface is obtained by calling GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXCompressor8 interface exposes the following methods.

IDirectSoundFXCompressor8 Members

Method | Description
IDirectSoundFXCompressor8::GetAllParameters | The GetAllParameters method retrieves the compression parameters of a buffer.
IDirectSoundFXCompressor8::SetAllParameters | The SetAllParameters method sets the compression parameters of a buffer.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundFXCompressor8::GetAllParameters

The GetAllParameters method retrieves the compression parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXCompressor pDsFxCompressor
);

Parameters

pDsFxCompressor
Address of a DSFXCompressor structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXCompressor8


IDirectSoundFXCompressor8::SetAllParameters

The SetAllParameters method sets the compression parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXCompressor pcDsFxCompressor
);

Parameters

pcDsFxCompressor
Address of a DSFXCompressor structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXCompressor8


IDirectSoundFXDistortion8

The IDirectSoundFXDistortion8 interface is used to set and retrieve effect parameters on a buffer that supports distortion.

This interface is obtained by calling GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXDistortion8 interface exposes the following methods.

IDirectSoundFXDistortion8 Members

Method | Description
IDirectSoundFXDistortion8::GetAllParameters | The GetAllParameters method retrieves the distortion parameters of a buffer.
IDirectSoundFXDistortion8::SetAllParameters | The SetAllParameters method sets the distortion parameters of a buffer.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundFXDistortion8::GetAllParameters

The GetAllParameters method retrieves the distortion parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXDistortion pDsFxDistortion
);

Parameters

pDsFxDistortion
Address of a DSFXDistortion structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXDistortion8


IDirectSoundFXDistortion8::SetAllParameters

The SetAllParameters method sets the distortion parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXDistortion pcDsFxDistortion
);

Parameters

pcDsFxDistortion
Address of a DSFXDistortion structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK or S_FALSE. See the Remarks for DSFXDistortion. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXDistortion8


IDirectSoundFXEcho8

The IDirectSoundFXEcho8 interface is used to set and retrieve effect parameters on a buffer that supports echo.

This interface is obtained by calling GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXEcho8 interface exposes the following methods.

IDirectSoundFXEcho8 Members

Method | Description
IDirectSoundFXEcho8::GetAllParameters | The GetAllParameters method retrieves the echo parameters of a buffer.
IDirectSoundFXEcho8::SetAllParameters | The SetAllParameters method sets the echo parameters of a buffer.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundFXEcho8::GetAllParameters

The GetAllParameters method retrieves the echo parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXEcho pDsFxEcho
);

Parameters

pDsFxEcho
Address of a DSFXEcho structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXEcho8


IDirectSoundFXEcho8::SetAllParameters

The SetAllParameters method sets the echo parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXEcho pcDsFxEcho
);

Parameters

pcDsFxEcho
Address of a DSFXEcho structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXEcho8


IDirectSoundFXFlanger8

The IDirectSoundFXFlanger8 interface is used to set and retrieve effect parameters on a buffer that supports flange.

This interface is obtained by calling GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXFlanger8 interface exposes the following methods.

IDirectSoundFXFlanger8 Members

Method | Description
IDirectSoundFXFlanger8::GetAllParameters | The GetAllParameters method retrieves the flange parameters of a buffer.
IDirectSoundFXFlanger8::SetAllParameters | The SetAllParameters method sets the flange parameters of a buffer.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundFXFlanger8::GetAllParameters

The GetAllParameters method retrieves the flange parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXFlanger pDsFxFlanger
);

Parameters

pDsFxFlanger
Address of a DSFXFlanger structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXFlanger8


IDirectSoundFXFlanger8::SetAllParameters

The SetAllParameters method sets the flange parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXFlanger pcDsFxFlanger
);

Parameters

pcDsFxFlanger
Address of a DSFXFlanger structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXFlanger8


IDirectSoundFXGargle8

The IDirectSoundFXGargle8 interface is used to set and retrieve effect parameters on a buffer that supports amplitude modulation.

This interface is obtained by calling GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXGargle8 interface exposes the following methods.

IDirectSoundFXGargle8 Members

Method | Description
IDirectSoundFXGargle8::GetAllParameters | The GetAllParameters method retrieves the amplitude modulation parameters of a buffer.
IDirectSoundFXGargle8::SetAllParameters | The SetAllParameters method sets the amplitude modulation parameters of a buffer.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundFXGargle8::GetAllParameters

The GetAllParameters method retrieves the amplitude modulation parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXGargle pDsFxGargle
);

Parameters

pDsFxGargle
Address of a DSFXGargle structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value can be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXGargle8


IDirectSoundFXGargle8::SetAllParameters

The SetAllParameters method sets the amplitude modulation parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXGargle pcDsFxGargle
);

Parameters

pcDsFxGargle
Address of a DSFXGargle structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value can be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXGargle8


IDirectSoundFXI3DL2Reverb8::IDirectSoundFXI3DL2Reverb8

IDirectSoundFXI3DL2Reverb8

The IDirectSoundFXI3DL2Reverb8 interface is used to set and retrieve effect parameters on a buffer that supports I3DL2 (Interactive 3D Audio Level 2) reverberation effects.

This interface is obtained by calling GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXI3DL2Reverb8 interface exposes the following methods.

Parameters

Method | Description
IDirectSoundFXI3DL2Reverb8::GetAllParameters | The GetAllParameters method retrieves the I3DL2 environmental reverberation parameters of a buffer.
IDirectSoundFXI3DL2Reverb8::GetQuality | The GetQuality method retrieves the quality of the environmental reverberation effect.
IDirectSoundFXI3DL2Reverb8::SetAllParameters | The SetAllParameters method sets the I3DL2 environmental reverberation parameters of a buffer.
IDirectSoundFXI3DL2Reverb8::SetQuality | The SetQuality method sets the quality of the environmental reverberation effect. Higher values produce better quality at the expense of processing time.

Presets

Method | Description
IDirectSoundFXI3DL2Reverb8::GetPreset | The GetPreset method retrieves an identifier for standard reverberation parameters of a buffer.
IDirectSoundFXI3DL2Reverb8::SetPreset | The SetPreset method sets standard reverberation parameters of a buffer.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundFXI3DL2Reverb8::GetAllParameters

The GetAllParameters method retrieves the I3DL2 environmental reverberation parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXI3DL2Reverb pDsFxI3DL2Reverb
);

Parameters

pDsFxI3DL2Reverb
Address of a DSFXI3DL2Reverb structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXI3DL2Reverb8::IDirectSoundFXI3DL2Reverb8


IDirectSoundFXI3DL2Reverb8::GetPreset

The GetPreset method retrieves an identifier for standard reverberation parameters of a buffer.

HRESULT GetPreset(
  LPDWORD pdwPreset
);

Parameters

pdwPreset
Address of a DWORD that receives one of the preset identifiers. For a list of defined values, see SetPreset.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXI3DL2Reverb8::IDirectSoundFXI3DL2Reverb8


IDirectSoundFXI3DL2Reverb8::GetQuality

The GetQuality method retrieves the quality of the environmental reverberation effect.

HRESULT GetQuality(
  LONG * plQuality
);

Parameters

plQuality
Address of a LONG variable to receive the quality of the effect.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXI3DL2Reverb8::IDirectSoundFXI3DL2Reverb8


IDirectSoundFXI3DL2Reverb8::SetAllParameters

The SetAllParameters method sets the I3DL2 environmental reverberation parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXI3DL2Reverb pcDsFxI3DL2Reverb
);

Parameters

pcDsFxI3DL2Reverb
Address of a DSFXI3DL2Reverb structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXI3DL2Reverb8::IDirectSoundFXI3DL2Reverb8


IDirectSoundFXI3DL2Reverb8::SetPreset

The SetPreset method sets standard reverberation parameters of a buffer.

HRESULT SetPreset(
  DWORD dwPreset
);

Parameters

dwPreset
Value that specifies a preset. The following constants are defined. See Dsound.h for the default parameters associated with each preset.
Value
DSFX_I3DL2_ENVIRONMENT_PRESET_DEFAULT
DSFX_I3DL2_ENVIRONMENT_PRESET_GENERIC
DSFX_I3DL2_ENVIRONMENT_PRESET_PADDEDCELL
DSFX_I3DL2_ENVIRONMENT_PRESET_ROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_BATHROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_LIVINGROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_STONEROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_AUDITORIUM
DSFX_I3DL2_ENVIRONMENT_PRESET_CONCERTHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_CAVE
DSFX_I3DL2_ENVIRONMENT_PRESET_ARENA
DSFX_I3DL2_ENVIRONMENT_PRESET_HANGAR
DSFX_I3DL2_ENVIRONMENT_PRESET_CARPETEDHALLWAY
DSFX_I3DL2_ENVIRONMENT_PRESET_HALLWAY
DSFX_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR
DSFX_I3DL2_ENVIRONMENT_PRESET_ALLEY
DSFX_I3DL2_ENVIRONMENT_PRESET_FOREST
DSFX_I3DL2_ENVIRONMENT_PRESET_CITY
DSFX_I3DL2_ENVIRONMENT_PRESET_MOUNTAINS
DSFX_I3DL2_ENVIRONMENT_PRESET_QUARRY
DSFX_I3DL2_ENVIRONMENT_PRESET_PLAIN
DSFX_I3DL2_ENVIRONMENT_PRESET_PARKINGLOT
DSFX_I3DL2_ENVIRONMENT_PRESET_SEWERPIPE
DSFX_I3DL2_ENVIRONMENT_PRESET_UNDERWATER
DSFX_I3DL2_ENVIRONMENT_PRESET_SMALLROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_PLATE

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXI3DL2Reverb8::IDirectSoundFXI3DL2Reverb8


IDirectSoundFXI3DL2Reverb8::SetQuality

The SetQuality method sets the quality of the environmental reverberation effect. Higher values produce better quality at the expense of processing time.

HRESULT SetQuality(
  LONG lQuality
);

Parameters

lQuality
Quality of the effect, in the range from DSFX_I3DL2REVERB_QUALITY_MIN to DSFX_I3DL2REVERB_QUALITY_MAX. The default value is 2.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXI3DL2Reverb8::IDirectSoundFXI3DL2Reverb8


IDirectSoundFXParamEq8

The IDirectSoundFXParamEq8 interface is used to set and retrieve effect parameters on a buffer that supports parametric equalizer effects.

In addition to the methods inherited from IUnknown, the IDirectSoundFXParamEq8 interface exposes the following methods.

IDirectSoundFXParamEq8 Members

Method | Description
IDirectSoundFXParamEq8::GetAllParameters | The GetAllParameters method retrieves the parametric equalizer parameters of a buffer.
IDirectSoundFXParamEq8::SetAllParameters | The SetAllParameters method sets the parametric equalizer parameters of a buffer.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundFXParamEq8::GetAllParameters

The GetAllParameters method retrieves the parametric equalizer parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXParamEq pDsFxParamEq
);

Parameters

pDsFxParamEq
Address of a DSFXParamEq structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXParamEq8


IDirectSoundFXParamEq8::SetAllParameters

The SetAllParameters method sets the parametric equalizer parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXParamEq pcDsFxParamEq
);

Parameters

pcDsFxParamEq
Address of a DSFXParamEq structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK or S_FALSE. See the Remarks for DSFXParamEq. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXParamEq8


IDirectSoundFXWavesReverb8

The IDirectSoundFXWavesReverb8 interface is used to set and retrieve effect parameters on a buffer that supports Waves reverberation.

This interface is obtained by calling GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXWavesReverb8 interface exposes the following methods.

IDirectSoundFXWavesReverb8 Members

Method | Description
IDirectSoundFXWavesReverb8::GetAllParameters | The GetAllParameters method retrieves the music reverberation parameters of a buffer.
IDirectSoundFXWavesReverb8::SetAllParameters | The SetAllParameters method sets the music reverberation parameters of a buffer.

The Waves reverberation DMO is based on the Waves MaxxVerb technology, which is licenced to Microsoft.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundFXWavesReverb8::GetAllParameters

The GetAllParameters method retrieves the music reverberation parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXWavesReverb pDsFXWavesReverb
);

Parameters

pDsFXWavesReverb
Address of a DSFXWavesReverb structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXWavesReverb8


IDirectSoundFXWavesReverb8::SetAllParameters

The SetAllParameters method sets the music reverberation parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXWavesReverb pcDsFXWavesReverb
);

Parameters

pcDsFXWavesReverb
Address of a DSFXWavesReverb structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsdmo.dll.

See Also

IDirectSoundFXWavesReverb8


IDirectSoundNotify8

The IDirectSoundNotify8 interface sets up notification events for a playback or capture buffer.

IDirectSoundNotify8 is a define for IDirectSoundNotify. The two interface names are interchangeable.

The interface is obtained by calling the QueryInterface method of an existing interface on a DirectSound buffer object. Secondary buffers support notifications only if they are created with the DSBCAPS_CTRLPOSITIONNOTIFY flag.

In addition to the methods inherited from IUnknown, the IDirectSoundNotify8 interface exposes the following method.

IDirectSoundNotify8 Member

Method | Description
IDirectSoundNotify8::SetNotificationPositions | The SetNotificationPositions method sets the notification positions. During capture or playback, whenever the read or play cursor reaches one of the specified offsets, the associated event is signaled.

The LPDIRECTSOUNDNOTIFY type is defined as a pointer to the IDirectSoundNotify interface:

typedef struct IDirectSoundNotify  *LPDIRECTSOUNDNOTIFY;

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IDirectSoundNotify8::SetNotificationPositions

The SetNotificationPositions method sets the notification positions. During capture or playback, whenever the read or play cursor reaches one of the specified offsets, the associated event is signaled.

HRESULT SetNotificationPositions(
  DWORD dwPositionNotifies,
  LPCDSBPOSITIONNOTIFY pcPositionNotifies
);

Parameters

dwPositionNotifies
Number of DSBPOSITIONNOTIFY structures.
pcPositionNotifies
Pointer to an array of DSBPOSITIONNOTIFY structures (the maximum array size is DSBNOTIFICATIONS_MAX).

Return Values

If the method succeeds, the return value is DS_OK. If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Remarks

The value DSBPN_OFFSETSTOP can be specified in the dwOffset member to tell DirectSound to signal the associated event when the Stop or Stop method is called or when the end of the buffer has been reached and the playback is not looping. If it is used, this should be the last item in the position-notify array.

If a position-notify array has already been set, the method replaces the previous array.

The buffer must be stopped when this method is called.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IDirectSoundNotify8


IKsPropertySet

The IKsPropertySet interface allows drivers to provide extended capabilities that can be used without API extensions. DirectSound supports this interface for accessing properties of sound drivers.

The IKsPropertySet interface is part of the WDM KS (Win32 driver model kernel streaming) architecture.

To retrieve this interface, call the QueryInterface method of any interface on a DirectSound buffer.

In addition to the methods inherited from IUnknown, the IKsPropertySet interface exposes the following methods.

IKsPropertySet Members

Method | Description
IKsPropertySet::Get | The Get method retrieves data for an item in a property set.
IKsPropertySet::QuerySupport | The QuerySupport method ascertains whether a property in a property set is supported on the port or device.
IKsPropertySet::Set | The Set method sets the value of a property in a property set.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

DirectSound Interfaces


IKsPropertySet::Get

The Get method retrieves data for an item in a property set.

HRESULT Get(
  REFGUID rguidPropSet,
  ULONG ulId,
  LPVOID pInstanceData,
  ULONG ulInstanceLength,
  LPVOID pPropertyData,
  ULONG ulDataLength,
  PULONG pulBytesReturned
);

Parameters

rguidPropSet
Reference to (C++) or address of (C) a GUID representing the property set to be accessed.
ulId
Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set GUID.
pInstanceData
Instance data for the get call.
ulInstanceLength
Number of bytes pointed to by pInstanceData.
pPropertyData
Data to set for this item.
ulDataLength
Number of bytes pointed to by pPropertyData
pulBytesReturned
Address of a variable that receives the number of bytes written into pPropertyData.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK.

If it fails, the method may return one E_POINTER.

Remarks

The format of the data in both pInstanceData and pPropertyData is item-specific.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IKsPropertySet


IKsPropertySet::QuerySupport

The QuerySupport method ascertains whether a property in a property set is supported on the port or device.

HRESULT QuerySupport(
  REFGUID rguidPropSet,
  ULONG ulId,
  PULONG pulTypeSupport
);

Parameters

rguidPropSet
Reference to (C++) or address of (C) a GUID representing the property set to be queried.
ulId
Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set.
pulTypeSupport
Address of a variable that receives information about support for the property. This variable can receive one or both of the following flags. See Remarks.
Value | Description
KSPROPERTY_SUPPORT_GET | The property item may be retrieved.
KSPROPERTY_SUPPORT_SET | The property item may be set.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK. (See Remarks.)

If it fails, the method may return one of the following error values:

Return code
E_NOTIMPL (See Remarks.)
E_POINTER

Remarks

Whether it is valid to support some properties within the set but not others depends on the definition of the property set. Consult the hardware manufacturer's specification for the property set of interest.

Some implementations may return S_OK when the property is not supported, and others may return E_NOTIMPL. To be sure that a property is supported, check both the return value of the method and the value returned in pulTypeSupport. If S_OK is returned but pulTypeSupport does not contain a valid flag, the property is not supported.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IKsPropertySet


IKsPropertySet::Set

The Set method sets the value of a property in a property set.

HRESULT Set(
  REFGUID rguidPropSet,
  ULONG ulId,
  LPVOID pInstanceData,
  ULONG ulInstanceLength,
  LPVOID pPropertyData,
  ULONG ulDataLength
);

Parameters

rguidPropSet
Reference to (C++) or address of (C) a GUID representing the property set to be accessed.
ulId
Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set.
pInstanceData
Instance data for the set call. If there are multiple objects within the port that this operation could act on, the instance data specifies which object should be used. No standard property set items at the DirectMusic API level use instance data; however, vendor-defined extensions are free to use it.
ulInstanceLength
Number of bytes pointed to by pInstanceData.
pPropertyData
Property data to set for this item.
ulDataLength
Number of bytes pointed to by pPropertyData.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK.

If it fails, the method may return E_POINTER.

Remarks

The format of the data in both pInstanceData and pPropertyData is item-specific.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound3d.dll.

See Also

IKsPropertySet


DirectSound Functions

This section contains reference information for the following DirectSound and DirectSoundCapture global functions.

Function | Description
DirectSoundCaptureCreate8 | Creates and initializes an object that supports the IDirectSoundCapture8 interface.
DirectSoundCaptureEnumerate | Enumerates the DirectSoundCapture objects installed in the system.
DirectSoundCreate8 | Creates and initializes an object that supports the IDirectSound8 interface.
DirectSoundEnumerate | Enumerates the DirectSound drivers installed in the system.
DirectSoundFullDuplexCreate8 | Creates the DirectSound and DirectSoundCapture objects and returns the IDirectSoundFullDuplex8 interface.
GetDeviceID | Retrieves the unique device identifier of the default playback and capture devices selected by the user.


DirectSoundCaptureCreate8

The DirectSoundCaptureCreate8 function creates and initializes an object that supports the IDirectSoundCapture8 interface. Although the older DirectSoundCaptureCreate function can also be used to obtain the IDirectSoundCapture8 interface, the object created by that function cannot be used to create capture buffers that support the IDirectSoundCaptureBuffer8 interface.

HRESULT DirectSoundCaptureCreate8(
  LPCGUID lpcGUID,
  LPDIRECTSOUNDCAPTURE8 * lplpDSC,
  LPUNKNOWN pUnkOuter
);

Parameters

lpcGUID
Address of the GUID that identifies the sound capture device. The value of this parameter must be one of the GUIDs returned by DirectSoundCaptureEnumerate, or NULL for the default device, or one of the following values.
Value | Description
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.
lplpDSC
Address of a variable to receive an IDirectSoundCapture8 interface pointer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following values.

Return Code
DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY

Remarks

On sound cards that do not support full duplex, this method will fail and return DSERR_ALLOCATED.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound.lib.

See Also

Creating the Capture Device Object


DirectSoundCaptureEnumerate

The DirectSoundCaptureEnumerate function enumerates the DirectSoundCapture objects installed in the system.

HRESULT DirectSoundCaptureEnumerate(
  LPDSENUMCALLBACK lpDSEnumCallback,
  LPVOID lpContext
);

Parameters

lpDSEnumCallback
Address of the DSEnumCallback function that will be called for each DirectSoundCapture object installed in the system.
lpContext
Address of the user-defined context passed to the enumeration callback function every time that function is called.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound.lib.

See Also

Enumerating Capture Devices


DirectSoundCreate8

The DirectSoundCreate8 function creates and initializes an object that supports the IDirectSound8 interface.

HRESULT DirectSoundCreate8(
  LPCGUID lpcGuidDevice,
  LPDIRECTSOUND8 * ppDS8,
  LPUNKNOWN pUnkOuter
);

Parameters

lpcGuidDevice
Address of the GUID that identifies the sound device. The value of this parameter must be one of the GUIDs returned by DirectSoundEnumerate, or NULL for the default device, or one of the following values.
Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device. Equivalent to NULL.
DSDEVID_DefaultVoicePlayback | Default voice playback device.
ppDS8
Address of a variable to receive an IDirectSound8 interface pointer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following.

Return Code
DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Remarks

The application must call the IDirectSound8::SetCooperativeLevel method immediately after creating a device object.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound.lib.

See Also

IDirectSound8::GetCaps | IDirectSound8::SetCooperativeLevel | Creating the Device Object

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DirectSoundEnumerate

The DirectSoundEnumerate function enumerates the DirectSound drivers installed in the system.

HRESULT DirectSoundEnumerate(
  LPDSENUMCALLBACK lpDSEnumCallback,
  LPVOID lpContext
);

Parameters

lpDSEnumCallback
Address of the DSEnumCallback function that will be called for each device installed in the system.
lpContext
Address of the user-defined context passed to the enumeration callback function every time that function is called.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound.lib.

See Also

Enumerating Sound Devices


DirectSoundFullDuplexCreate8

The DirectSoundFullDuplexCreate8 function creates the DirectSound and DirectSoundCapture objects and returns the IDirectSoundFullDuplex8 interface. This function requires Microsoft Windows XP. Full duplex can be implemented on other operating systems, but the capture and rendering devices must be created separately.

HRESULT DirectSoundFullDuplexCreate8(
  LPCGUID pcGuidCaptureDevice,
  LPCGUID pcGuidRenderDevice,
  LPCDSCBUFFERDESC pcDSCBufferDesc,
  LPCDSBUFFERDESC pcDSBufferDesc,
  HWND hWnd,
  DWORD dwLevel,
  LPDIRECTSOUNDFULLDUPLEX * ppDSFD,
  LPDIRECTSOUNDCAPTUREBUFFER8 * ppDSCBuffer8,
  LPDIRECTSOUNDBUFFER8 * ppDSBuffer8,
  LPUNKNOWN pUnkOuter
);

Parameters

pcGuidCaptureDevice
Address of the GUID that identifies the sound capture device. The value of this parameter must be one of the GUIDs returned by DirectSoundCaptureEnumerate, or NULL for the default device, or one of the following values.
Value | Description
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.
pcGuidRenderDevice
Address of the GUID that identifies the sound render device for full-duplex output. Must be one of the GUIDs returned by DirectSoundEnumerate, or NULL for the default render device, or one of the following values.
Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.
pcDSCBufferDesc
Address of a DSCBUFFERDESC structure that specifies the characteristics of the capture buffer.
pcDSBufferDesc
Address of a DSCBUFFERDESC structure that specifies the characteristics of the render buffer.
hWnd
Handle to the application window.
dwLevel
Cooperative level for the device. For more information, see IDirectSound8::SetCooperativeLevel.
ppDSFD
Address of a variable that receives the IDirectSoundFullDuplex8 interface pointer.
ppDSCBuffer8
Address of a variable that receives the IDirectSoundCaptureBuffer8 interface of the capture buffer.
ppDSBuffer8
Address of a variable that receives the IDirectSoundBuffer8 interface of the render buffer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following.

Return Code
DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Remarks

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound.lib.

See Also

Creating the Capture Device Object | Creating the Device Object

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


GetDeviceID

The GetDeviceID function retrieves the unique device identifier of the default playback and capture devices selected by the user in Control Panel.

HRESULT GetDeviceID(
  LPCGUID pGuidSrc,
  LPGUID pGuidDest
);

Parameters

pGuidSrc
Address of a variable that specifies a valid device identifier, or the address of one of the following predefined variables.
Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.
pGuidDest
Address of a variable that receives the unique identifier of the device.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.

Remarks

If pGuidSrc points to a valid device identifier, the same value is returned in pGuidDest. If pGuidSrc is one of the listed constants, pGuidDest returns the address of the corresponding device GUID.

Requirements

Header: Declared in DSound.h.

Library: Use Dsound.lib.


Callback Function

This section contains reference information for the following DirectSound callback function.

Function | Description
DSEnumCallback | Application-defined callback function that enumerates the DirectSound drivers.


DSEnumCallback

The DSEnumCallback function is an application-defined callback function that enumerates the DirectSound drivers. The system calls this function in response to the application's call to the DirectSoundEnumerate or DirectSoundCaptureEnumerate function.

BOOL CALLBACK DSEnumCallback(
  LPGUID lpGuid,
  LPCSTR lpcstrDescription,
  LPCSTR lpcstrModule,
  LPVOID lpContext
);

Parameters

lpGuid
Address of the GUID that identifies the device being enumerated, or NULL for the primary device. This value can be passed to the DirectSoundCreate8 or DirectSoundCaptureCreate8 function to create a device object for that driver.
lpcstrDescription
Address of a null-terminated string that provides a textual description of the DirectSound device.
lpcstrModule
Address of a null-terminated string that specifies the module name of the DirectSound driver corresponding to this device.
lpContext
Address of application-defined data. This is the pointer passed to DirectSoundEnumerate or DirectSoundCaptureEnumerate as the lpContext parameter.

Return Values

Returns TRUE to continue enumerating drivers, or FALSE to stop.

Remarks

The memory pointed to by lpGuid, lpcstrDescription, and lpcstrModule is local in scope. If you want to save these values, you must allocate them in global memory. The primary device is enumerated twice, first with NULL in lpGuid and then with its GUID in that parameter.

Requirements

Header: Declared in DSound.h.


DirectSound Structures

This section contains reference information for the following structures used with DirectSound.

Structure | Description
D3DVECTOR | Describes a vector.
DS3DBUFFER | Contains all information necessary to uniquely describe the location, orientation, and motion of a 3D sound buffer.
DS3DLISTENER | Describes the 3D world parameters and position of the listener.
DSBCAPS | Describes the capabilities of a DirectSound buffer object.
DSBPOSITIONNOTIFY | Describes a notification position.
DSBUFFERDESC | Describes the characteristics of a buffer.
DSCAPS | Describes the capabilities of a device.
DSCBCAPS | Describes the capabilities of a capture buffer.
DSCBUFFERDESC | Describes a capture buffer.
DSCCAPS | Describes the capabilities of a capture device.
DSCEFFECTDESC | Contains parameters for an effect associated with a capture buffer.
DSCFXAec | Contains parameters for acoustic echo cancellation in a capture buffer.
DSCFXNoiseSuppress | Contains parameters for noise suppression in a capture buffer.
DSEFFECTDESC | Describes an effect associated with a buffer.
DSFXI3DL2Reverb | Contains parameters for an I3DL2 (Interactive 3D Audio Level 2) reverberation effect.
DSFXChorus | Contains parameters for a chorus effect.
DSFXCompressor | Contains parameters for a compression effect.
DSFXDistortion | Contains parameters for a distortion effect.
DSFXEcho | Contains parameters for an echo effect.
DSFXFlanger | Contains parameters for a flange effect.
DSFXGargle | Contains parameters for an amplitude modulation effect.
DSFXParamEq | Contains parameters for a parametric equalizer effect.
DSFXWavesReverb | Contains parameters for a Waves reverberation effect.
WAVEFORMATEX | Defines the format of waveform-audio data.
WAVEFORMATEXTENSIBLE | Defines the format of waveform-audio data for formats having more than two channels or higher resolutions than allowed by WAVEFORMATEX.

Note The memory for all DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DSCAPS:

DSCAPS dscaps;

ZeroMemory(&dscaps, sizeof(dscaps));
dscaps.dwSize = sizeof(dscaps);


D3DVECTOR

The D3DVECTOR structure defines a vector.

typedef struct D3DVECTOR {
    float x, y, z ;
} D3DVECTOR;

Members

x, y, z
Values for the axes of the vector.

Requirements

Header: Declared in DSound.h.

See Also

Coordinates of 3D Space


DS3DBUFFER

The DS3DBUFFER structure contains all information necessary to uniquely describe the location, orientation, and motion of a 3D sound buffer. This structure is used with the IDirectSound3DBuffer8::GetAllParameters and IDirectSound3DBuffer8::SetAllParameters methods.

typedef struct DS3DBUFFER {
    DWORD dwSize;
    D3DVECTOR vPosition;
    D3DVECTOR vVelocity;
    DWORD dwInsideConeAngle;
    DWORD dwOutsideConeAngle;
    D3DVECTOR vConeOrientation;
    LONG lConeOutsideVolume;
    D3DVALUE flMinDistance;
    D3DVALUE flMaxDistance;
    DWORD dwMode;
} DS3DBUFFER;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
vPosition
A D3DVECTOR structure that describes the current position of the 3D sound buffer.
vVelocity
A D3DVECTOR structure that describes the current velocity of the 3D sound buffer.
dwInsideConeAngle
The angle of the inside sound projection cone.
dwOutsideConeAngle
The angle of the outside sound projection cone.
vConeOrientation
A D3DVECTOR structure that describes the current orientation of this 3D buffer's sound projection cone.
lConeOutsideVolume
The cone outside volume.
flMinDistance
The minimum distance.
flMaxDistance
The maximum distance.
dwMode
The 3D sound processing mode to be set. This value must be one of the values shown in the following table.
Value | Description
DS3DMODE_DISABLE | 3D sound processing is disabled. The sound will appear to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE | Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant. In other words, the sound moves with the listener.
DS3DMODE_NORMAL | Default. The parameters of the sound are relative to world space.

Requirements

Header: Declared in DSound.h.

See Also

DirectSound 3D Buffers


DS3DLISTENER

The DS3DLISTENER structure describes the 3D world parameters and the position of the listener. This structure is used with the IDirectSound3DListener8::GetAllParameters and IDirectSound3DListener8::SetAllParameters methods.

typedef struct DS3DLISTENER {
    DWORD dwSize;
    D3DVECTOR vPosition;
    D3DVECTOR vVelocity;
    D3DVECTOR vOrientFront;
    D3DVECTOR vOrientTop;
    D3DVALUE flDistanceFactor;
    D3DVALUE flRolloffFactor;
    D3DVALUE flDopplerFactor;
} DS3DLISTENER;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
vPosition
D3DVECTOR structure that describes the listener's position.
vVelocity
D3DVECTOR structure that describes the listener's velocity.
vOrientFront
D3DVECTOR structure that describes the listener's front orientation.
vOrientTop
D3DVECTOR structure that describes the listener's top orientation.
flDistanceFactor
Number of meters in a vector unit.
flRolloffFactor
Ratio of attenuation over distance to that in the real world.
flDopplerFactor
Ratio of Doppler effect to that in the real world.

Requirements

Header: Declared in DSound.h.

See Also

DirectSound 3D Listeners


DSBCAPS

The DSBCAPS structure describes the capabilities of a DirectSound buffer object. It is used by the IDirectSoundBuffer8::GetCaps method.

typedef struct DSBCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwBufferBytes;
    DWORD dwUnlockTransferRate;
    DWORD dwPlayCpuOverhead;
} DSBCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Flags that specify buffer-object capabilities. Use one or more of the values shown in the following table.
Value | Description
DSBCAPS_CTRL3D | The buffer has 3D control capability.
DSBCAPS_CTRLFREQUENCY | The buffer has frequency control capability.
DSBCAPS_CTRLFX | The buffer supports effects processing.
DSBCAPS_CTRLPAN | The buffer has pan control capability.
DSBCAPS_CTRLVOLUME | The buffer has volume control capability.
DSBCAPS_CTRLPOSITIONNOTIFY | The buffer has position notification capability. See the Remarks for DSCBUFFERDESC.
DSBCAPS_GETCURRENTPOSITION2 | The buffer uses the new behavior of the play cursor when IDirectSoundBuffer8::GetCurrentPosition is called. In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play cursor. If this flag is not specified, the old behavior is preserved for compatibility. This flag affects only emulated devices; if a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS | The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCDEFER | The buffer can be assigned to a hardware or software resource at play time, or when IDirectSoundBuffer8::AcquireResources is called.
DSBCAPS_LOCHARDWARE | The buffer uses hardware mixing.
DSBCAPS_LOCSOFTWARE | The buffer is in software memory and uses software mixing.
DSBCAPS_MUTE3DATMAXDISTANCE | The sound is reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted. Applies only to software buffers.
DSBCAPS_PRIMARYBUFFER | The buffer is a primary buffer.
DSBCAPS_STATIC | The buffer is in on-board hardware memory.
DSBCAPS_STICKYFOCUS | The buffer has sticky focus. If the user switches to another application not using DirectSound, the buffer is still audible. However, if the user switches to another DirectSound application, the buffer is muted.
DSBCAPS_TRUEPLAYPOSITION | Force IDirectSoundBuffer8::GetCurrentPosition to return the buffer's true play position. This flag is only valid in Windows Vista.
dwBufferBytes
Size of this buffer, in bytes.
dwUnlockTransferRate
The rate, in kilobytes per second, at which data is transferred to the buffer memory when IDirectSoundBuffer8::Unlock is called. High-performance applications can use this value to determine the time required for IDirectSoundBuffer8::Unlock to execute. For software buffers located in system memory, the rate will be very high because no processing is required. For hardware buffers, the rate might be slower because the buffer might have to be downloaded to the sound card, which might have a limited transfer rate.
dwPlayCpuOverhead
The processing overhead as a percentage of main processor cycles needed to mix this sound buffer. For hardware buffers, this member will be zero because the mixing is performed by the sound device. For software buffers, this member depends on the buffer format and the speed of the system processor.

Remarks

The DSBCAPS structure contains information similar to that found in the DSCBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method, with some additional information. Additional information includes the location of the buffer (hardware or software) and some cost measures (such as the time to download the buffer if located in hardware, and the processing overhead to play the buffer if it is mixed in software).

The dwFlags member contains the same flags used by the DSBUFFERDESC structure. The only difference is that in the DSBCAPS structure, either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag is specified, according to the location of the buffer. In the DSBUFFERDESC structure, these flags are optional and are used to force the buffer to be located in either hardware or software.

To use #defines implemented in Windows Vista, set the DIRECTSOUND_VERSION to 0x1000 before including DSound.h.

Requirements

Header: Declared in DSound.h.

See Also

IDirectSound8::CreateSoundBuffer | IDirectSoundBuffer8::GetCaps

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSBPOSITIONNOTIFY

The DSBPOSITIONNOTIFY structure describes a notification position. It is used by IDirectSoundNotify8::SetNotificationPositions.

typedef struct DSBPOSITIONNOTIFY {
    DWORD dwOffset;
    HANDLE hEventNotify;
} DSBPOSITIONNOTIFY;

Members

dwOffset
Offset from the beginning of the buffer where the notify event is to be triggered, or DSBPN_OFFSETSTOP.
hEventNotify
Handle to the event to be signaled when the offset has been reached.

Remarks

The DSBPN_OFFSETSTOP value in the dwOffset member causes the event to be signaled when playback or capture stops, either because the end of the buffer has been reached (and playback or capture is not looping) or because the application called the IDirectSoundBuffer8::Stop or IDirectSoundCaptureBuffer8::Stop method.

>When a playback buffer was created with DSBCAPS_LOCDEFER and DSBCAPS_CTRLPOSITIONNOTIFY along with any voice management flag, it is possible that a sound that has notifications set, but not yet reached, will be terminated by the voice manager. In this case, no event is signaled.

Requirements

Header: Declared in DSound.h.

See Also

Play Buffer Notification | Capture Buffer Notification

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSBUFFERDESC

The DSBUFFERDESC structure describes the characteristics of a new buffer object. It is used by the IDirectSound8::CreateSoundBuffer method and by the DirectSoundFullDuplexCreate8 function.

An earlier version of this structure, DSBUFFERDESC1, is maintained in Dsound.h for compatibility with DirectX 7 and earlier.

typedef struct DSBUFFERDESC {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwBufferBytes;
    DWORD dwReserved;
    LPWAVEFORMATEX lpwfxFormat;
    GUID guid3DAlgorithm;
} DSBUFFERDESC;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Flags specifying the capabilities of the buffer. See the dwFlags member of the DSBCAPS structure for a detailed listing of valid flags.
dwBufferBytes
Size of the new buffer, in bytes. This value must be 0 when creating a buffer with the DSBCAPS_PRIMARYBUFFER flag. For secondary buffers, the minimum and maximum sizes allowed are specified by DSBSIZE_MIN and DSBSIZE_MAX, defined in Dsound.h.
dwReserved
Reserved. Must be 0.
lpwfxFormat
Address of a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure specifying the waveform format for the buffer. This value must be NULL for primary buffers.
guid3DAlgorithm
Unique identifier of the two-speaker virtualization algorithm to be used by DirectSound3D hardware emulation. If DSBCAPS_CTRL3D is not set in dwFlags, this member must be GUID_NULL (DS3DALG_DEFAULT). The following algorithm identifiers are defined.
Value | Description | Availability
DS3DALG_DEFAULT | DirectSound uses the default algorithm. In most cases this is DS3DALG_NO_VIRTUALIZATION. On WDM drivers, if the user has selected a surround sound speaker configuration in Control Panel, the sound is panned among the available directional speakers. | Applies to software mixing only. Available on WDM or Vxd Drivers.
DS3DALG_NO_VIRTUALIZATION | 3D output is mapped onto normal left and right stereo panning. At 90 degrees to the left, the sound is coming out of only the left speaker; at 90 degrees to the right, sound is coming out of only the right speaker. The vertical axis is ignored except for scaling of volume due to distance. Doppler shift and volume scaling are still applied, but the 3D filtering is not performed on this buffer. This is the most efficient software implementation, but provides no virtual 3D audio effect. When the DS3DALG_NO_VIRTUALIZATION algorithm is specified, HRTF processing will not be done. Because DS3DALG_NO_VIRTUALIZATION uses only normal stereo panning, a buffer created with this algorithm may be accelerated by a 2D hardware voice if no free 3D hardware voices are available. | Applies to software mixing only. Available on WDM or Vxd Drivers.
DS3DALG_HRTF_FULL | The 3D API is processed with the high quality 3D audio algorithm. This algorithm gives the highest quality 3D audio effect, but uses more CPU cycles. See Remarks. | Applies to software mixing only. Available on Microsoft Windows 98 Second Edition and later operating systems when using WDM drivers.
DS3DALG_HRTF_LIGHT | The 3D API is processed with the efficient 3D audio algorithm. This algorithm gives a good 3D audio effect, but uses fewer CPU cycles than DS3DALG_HRTF_FULL. | Applies to software mixing only. Available on Windows 98 Second Edition and later operating systems when using WDM drivers.

Remarks

When creating a primary buffer, applications must set the dwBufferBytes member to zero. DirectSound will determine the best buffer size for the particular sound device in use. To determine the size of a created primary buffer, call IDirectSoundBuffer8::GetCaps.

The DSBCAPS_CTRLDEFAULT flag is no longer supported. This flag was defined as DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY. By specifying only the flags you need, you cut down on unnecessary resource usage.

On VXD drivers, a sound buffer created with DSBCAPS_CTRLPOSITIONNOTIFY is always a software buffer, because the VXD driver model does not support notifications. With WDM drivers, a notification-enabled buffer can be in hardware, if hardware resources are available.

The DSBCAPS_LOCHARDWARE and DSBCAPS_LOCSOFTWARE flags are optional and mutually exclusive. DSBCAPS_LOCHARDWARE forces the buffer to reside in hardware, meaning that it will be mixed by the sound card. DSBCAPS_LOCSOFTWARE forces the buffer to reside in software, where it is mixed by the CPU. These flags are also defined for the dwFlags member DSBCAPS.

The 3D algorithms represent selection of the software emulation layer only: that is, the software algorithm that is used when no hardware is present for acceleration. In order to maximize hardware utilization, DS3DALG_NO_VIRTUALIZATION is treated as a special case. If no free 3D hardware voices are available, the buffer is then treated as a 2D buffer, but with 3D control. Specifically, when a sound buffer is created with DS3DALG_NO_VIRTUALIZATION, or when the buffer is played if the buffer was created with DSBPLAY_LOCDEFER, the following procedure is followed:

  1. If a free hardware 3D voice is available, that 3D hardware voice is used.
  2. If no free hardware 3D voices are available and a 2D hardware voice is available, that 2D hardware voice will be used. This is possible because the DS3DALG_NO_VIRTUALIZATION algorithm is a simple stereo pan algorithm
  3. If no free 2D or 3D hardware voices are available, the voice will be played in software using the DS3DALG_NO_VIRTUALIZATION algorithm.

If a speaker configuration other than DSSPEAKER_HEADPHONE or DSSPEAKER_STEREO is in effect, the processing will be done as if for a two-speaker configuration.

If a buffer is created using one of the HRTF algorithms, and the HRTF algorithm is not available on the system (for example, a non-WDM system), a success code, DS_NO_VIRTUALIZATION, is returned. The sound buffer created will use DS3DALG_NO_VIRTUALIZATION instead. For this reason, applications should use the SUCCEEDED or FAILED macros rather than checking explicitly for DS_OK when calling CreateSoundBuffer.

Requirements

Header: Declared in DSound.h.

See Also

DirectSound Buffers | Dynamic Voice Management | IDirectSound8::CreateSoundBuffer

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSCAPS

The DSCAPS structure describes the capabilities of a device. It is used by the IDirectSound8::GetCaps method.

typedef struct DSCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwMinSecondarySampleRate, dwMaxSecondarySampleRate;
    DWORD dwPrimaryBuffers;
    DWORD dwMaxHwMixingAllBuffers;
    DWORD dwMaxHwMixingStaticBuffers;
    DWORD dwMaxHwMixingStreamingBuffers;
    DWORD dwFreeHwMixingAllBuffers;
    DWORD dwFreeHwMixingStaticBuffers;
    DWORD dwFreeHwMixingStreamingBuffers;
    DWORD dwMaxHw3DAllBuffers;
    DWORD dwMaxHw3DStaticBuffers;
    DWORD dwMaxHw3DStreamingBuffers;
    DWORD dwFreeHw3DAllBuffers;
    DWORD dwFreeHw3DStaticBuffers;
    DWORD dwFreeHw3DStreamingBuffers;
    DWORD dwTotalHwMemBytes;
    DWORD dwFreeHwMemBytes;
    DWORD dwMaxContigFreeHwMemBytes;
    DWORD dwUnlockTransferRateHwBuffers;
    DWORD dwPlayCpuOverheadSwBuffers;
    DWORD dwReserved1;
    DWORD dwReserved2;
} DSCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Flags describing device capabilities. Can include the values shown in the following table.
Value | Description
DSCAPS_CERTIFIED | The driver has been tested and certified by Microsoft. This flag is always set for WDM drivers. To test for certification, use IDirectSound8::VerifyCertification.
DSCAPS_CONTINUOUSRATE | The device supports all sample rates between the dwMinSecondarySampleRate and dwMaxSecondarySampleRate member values. Typically, this means that the actual output rate will be within +/- 10 hertz (Hz) of the requested frequency.
DSCAPS_EMULDRIVER | The device does not have a DirectSound driver installed, so it is being emulated through the waveform-audio functions. Performance degradation should be expected.
DSCAPS_PRIMARY16BIT | The device supports a primary buffer with 16-bit samples.
DSCAPS_PRIMARY8BIT | The device supports primary buffers with 8-bit samples.
DSCAPS_PRIMARYMONO | The device supports monophonic primary buffers.
DSCAPS_PRIMARYSTEREO | The device supports stereo primary buffers.
DSCAPS_SECONDARY16BIT | The device supports hardware-mixed secondary sound buffers with 16-bit samples.
DSCAPS_SECONDARY8BIT | The device supports hardware-mixed secondary buffers with 8-bit samples.
DSCAPS_SECONDARYMONO | The device supports hardware-mixed monophonic secondary buffers.
DSCAPS_SECONDARYSTEREO | The device supports hardware-mixed stereo secondary buffers.
dwMinSecondarySampleRate, dwMaxSecondarySampleRate
Minimum and maximum sample rate specifications that are supported by this device's hardware secondary sound buffers.
dwPrimaryBuffers
Number of primary buffers supported. This value will always be 1.
dwMaxHwMixingAllBuffers
Number of buffers that can be mixed in hardware. This member can be less than the sum of dwMaxHwMixingStaticBuffers and dwMaxHwMixingStreamingBuffers. Resource tradeoffs frequently occur.
dwMaxHwMixingStaticBuffers
Maximum number of static buffers.
dwMaxHwMixingStreamingBuffers
Maximum number of streaming sound buffers.
dwFreeHwMixingAllBuffers
Number of unallocated buffers. On WDM drivers, this includes dwFreeHw3DAllBuffers.
dwFreeHwMixingStaticBuffers
Number of unallocated static buffers.
dwFreeHwMixingStreamingBuffers
Number of unallocated streaming buffers.
dwMaxHw3DAllBuffers
Maximum number of 3D buffers.
dwMaxHw3DStaticBuffers
Maximum number of static 3D buffers.
dwMaxHw3DStreamingBuffers
Maximum number of streaming 3D buffers.
dwFreeHw3DAllBuffers
Number of unallocated 3D buffers.
dwFreeHw3DStaticBuffers
Number of unallocated static 3D buffers.
dwFreeHw3DStreamingBuffers
Number of unallocated streaming 3D buffers.
dwTotalHwMemBytes
Size, in bytes, of the amount of memory on the sound card that stores static sound buffers.
dwFreeHwMemBytes
Size, in bytes, of the free memory on the sound card.
dwMaxContigFreeHwMemBytes
Size, in bytes, of the largest contiguous block of free memory on the sound card.
dwUnlockTransferRateHwBuffers
The rate, in kilobytes per second, at which data can be transferred to hardware static sound buffers. This and the number of bytes transferred determines the duration of a call to the IDirectSoundBuffer8::Unlock method.
dwPlayCpuOverheadSwBuffers
The processing overhead, as a percentage of main processor cycles, needed to mix software buffers. This varies according to the bus type, the processor type, and the clock speed.
dwReserved1
Not used.
dwReserved2
Not used.

Remarks

Some audio cards may be unable to report accurately the number of available or free hardware buffers. This can happen, for example, when the card can play more sounds at lower sampling rates than at higher rates. In general, a nonzero value in any of the members relating to number of free hardware buffers signifies that at least one hardware resource of the appropriate type is available.

The unlock transfer rate for software buffers is 0, because the data need not be transferred anywhere. Similarly, the play processing overhead for hardware buffers is 0 because the mixing is done by the sound device.

Requirements

Header: Declared in DSound.h.

See Also

IDirectSound8::GetCaps


DSCBCAPS

The DSCBCAPS structure describes the capabilities of a capture buffer. It is used by the IDirectSoundCaptureBuffer8::GetCaps method.

typedef struct DSCBCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwBufferBytes;
    DWORD dwReserved;
} DSCBCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Specifies device capabilities. Can be zero or DSCBCAPS_WAVEMAPPED. The Win32 wave mapper will be used for formats not supported by the device.
dwBufferBytes
The size, in bytes, of the capture buffer.
dwReserved
Reserved for future use.

Requirements

Header: Declared in DSound.h.


DSCBUFFERDESC

The DSCBUFFERDESC structure describes a capture buffer. It is used by the IDirectSoundCapture8::CreateCaptureBuffer method and by the DirectSoundFullDuplexCreate8 function.

An earlier version of this structure, DSCBUFFERDESC1, is maintained in Dsound.h for compatibility with DirectX 7 and earlier.

typedef struct DSCBUFFERDESC {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwBufferBytes;
    DWORD dwReserved;
    LPWAVEFORMATEX lpwfxFormat;
    DWORD dwFXCount;
    LPDSCEFFECTDESC lpDSCFXDesc;
} DSCBUFFERDESC;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Specifies device capabilities. Can be zero, or one or more of the flags shown in the following table.
Value | Description
DSCBCAPS_CTRLFX | The buffer supports effects. See Remarks.
DSCBCAPS_WAVEMAPPED | The Win32 wave mapper will be used for formats not supported by the device.
dwBufferBytes
Size of capture buffer to create, in bytes.
dwReserved
Reserved for future use.
lpwfxFormat
Pointer to a WAVEFORMATEX structure containing the format in which to capture the data.
dwFXCount
Number of elements in the array pointed to by lpDSCFXDesc. Must be zero unless DSCBCAPS_CTRLFX is present in dwFlags.
lpDSCFXDesc
Address of an array of DSCEFFECTDESC structures that describe effects supported by hardware for the buffer. User-mode DMOs are not supported.

Remarks

The DSCBCAPS_CTRLFX flag is supported only on buffers created by an object of class CLSID_DirectSoundCapture8. If the IDirectSoundCapture8 interface was obtained from the DirectSoundCaptureCreate8 function, this flag is supported; if it was obtained from the earlier DirectSoundCaptureCreate function, it is not supported.

Capture effects require Microsoft Windows XP.

Requirements

Header: Declared in DSound.h.


DSCCAPS

The DSCCAPS structure describes the capabilities of the capture device. It is used by the IDirectSoundCapture8::GetCaps method.

typedef struct DSCCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwFormats;
    DWORD dwChannels;
} DSCCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Specifies device capabilities. Can be zero or one or more of the following flags.
Value | Description
DSCCAPS_CERTIFIED | The driver for the device is a certified WDM driver.
DSCCAPS_EMULDRIVER | There is no DirectSoundCapture driver for the device, so the standard waveform audio functions are being used.
DSCCAPS_MULTIPLECAPTURE | Multiple capture objects can be used simultaneously on the capture device.
dwFormats
Standard formats that are supported. These are equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions, and are defined in MMSystem.h in the Platform SDK.
dwChannels
Number of channels supported by the device, where 1 is mono, 2 is stereo, and so on.

Requirements

Header: Declared in DSound.h.


DSCEFFECTDESC

The DSCEFFECTDESC structure contains parameters for an effect associated with a capture buffer.

typedef struct DSCEFFECTDESC {
    DWORD dwSize;
    DWORD dwFlags;
    GUID guidDSCFXClass;
    GUID guidDSCFXInstance;
    DWORD dwReserved1;
    DWORD dwReserved2;
} DSCEFFECTDESC;

Members

dwSize
Size of the structure, in bytes.
dwFlags
Flags that specify desired parameters of the effect. When this structure is passed to DirectSoundFullDuplexCreate8, or IDirectSoundCapture8::CreateCaptureBuffer, this member must be one of the values shown in the following table.
Value | Description
DSCFX_LOCHARDWARE | Effect specified by guidDSCFXInstance must be in hardware.
DSCFX_LOCSOFTWARE | Effect specified by guidDSCFXInstance must be in software.

On return, this member can contain one of the values shown in the following table.

Value | Description
DSCFX_LOCHARDWARE | Effect was created in hardware.
DSCFX_LOCSOFTWARE | Effect was created in software.
guidDSCFXClass
Value of type GUID that specifies the class identifier of the effect. The following standard identifiers are defined.
Value | Description
GUID_DSCFX_CLASS_AEC | Acoustic echo cancellation.
GUID_DSCFX_CLASS_NS | Noise suppression.
guidDSCFXInstance
Value of type GUID that specifies the unique identifier of the preferred effect. The following standard identifiers are defined.
Value | Description
GUID_DSCFX_MS_AEC | Microsoft acoustic echo cancellation. Available in software only.
GUID_DSCFX_MS_NS | Microsoft noise suppression. Available in software only.
GUID_DSCFX_SYSTEM_AEC | System default acoustic echo cancellation.
GUID_DSCFX_SYSTEM_NS | System default noise suppression.
dwReserved1
Reserved. Must be zero.
dwReserved2
Reserved. Must be zero.

Requirements

Header: Declared in DSound.h.


DSCFXAec

The DSCFXAec structure contains parameters for acoustic echo cancellation in a capture buffer.

typedef struct DSCFXAec {
    BOOL fEnable;
    BOOL fNoiseFill;
    DWORD dwMode;
} DSCFXAec;

Members

fEnable
Boolean value that specifies whether the effect is enabled.
fNoiseFill
Boolean value that specifies whether to enable background comfort noise, which makes the capture signal sound more natural by preventing periods of dead silence. By default, background comfort noise is not enabled.
dwMode
Operation mode. This member contains one of the following values.
Value | Description
DSCFX_AEC_MODE_PASS_THROUGH | The effect is passing capture and render data through without modifying it.
DSCFX_AEC_MODE_HALF_DUPLEX | The effect is running in half duplex mode. Not presently supported.
DSCFX_AEC_MODE_FULL_DUPLEX | The effect is running in full duplex mode.

Remarks

The dwMode member is ignored when this structure is passed to IDirectSoundCaptureFXAec8::SetAllParameters.

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

Requirements

Header: Declared in DSound.h.

See Also

IDirectSoundCaptureFXAec8::GetAllParameters | IDirectSoundCaptureFXAec8::SetAllParameters

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSCFXNoiseSuppress

The DSCFXNoiseSuppress structure contains parameters for noise suppression in a capture buffer.

typedef struct DSCFXNoiseSuppress {
    BOOL fEnable;
} DSCFXNoiseSuppress;

Members

fEnable
Boolean value that specifies whether the effect is enabled.

Remarks

Windows: Important Note for Windows Vista

Existing applications that access Windows XP Acoustic Echo Cancellation (AEC) features via the DirectSound API will no longer obtain AEC when running on Windows Vista. These applications will still run, but their calls to AEC-specific DirectSound API calls will have no effect on the captured audio.

To learn how to obtain AEC in Windows Vista, See the Windows Vista AEC topics in the Windows SDK.

Requirements

Header: Declared in DSound.h.

See Also

IDirectSoundCaptureFXNoiseSuppress8::GetAllParameters | IDirectSoundCaptureFXNoiseSuppress8::SetAllParameters

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSEFFECTDESC

The DSEFFECTDESC structure describes an effect associated with a buffer.

typedef struct DSEFFECTDESC {
    DWORD dwSize;
    DWORD dwFlags;
    GUID guidDSFXClass;
    DWORD_PTR dwReserved1;
    DWORD_PTR dwReserved2;
} DSEFFECTDESC;

Members

dwSize
Size of the structure, in bytes.
dwFlags
Flags. Can be zero or one of the following values.
Value | Description
DSFX_LOCHARDWARE | Effect must be in hardware. If the effect is not available in hardware, IDirectSoundBuffer8::SetFX raises an error. Since DirectX 9.0, DirectX does not support hardware acceleration of effects, so this flag should not be used.
DSFX_LOCSOFTWARE | Effect must be in software, even if the hardware supports acceleration of guidDSFXClass. If the effect is not available in software, SetFX raises an error. Since DirectX 9.0, all effects are in software regardless of whether this flag is set.
guidDSFXClass
Class identifier of the effect. The following standard effect classes are defined.
Value | Description
GUID_DSFX_STANDARD_CHORUS | Chorus
GUID_DSFX_STANDARD_COMPRESSOR | Compressor
GUID_DSFX_STANDARD_DISTORTION | Distortion
GUID_DSFX_STANDARD_ECHO | Echo
GUID_DSFX_STANDARD_FLANGER | Flanger
GUID_DSFX_STANDARD_GARGLE | Gargle
GUID_DSFX_STANDARD_I3DL2REVERB | Interactive 3D Level 2 reverb
GUID_DSFX_STANDARD_PARAMEQ | Parametric equalizer
GUID_DSFX_WAVES_REVERB | Waves reverb
dwReserved1
Reserved for future use.
dwReserved2
Reserved for future use.

Remarks

Custom effects can be implemented as DMOs. Effect DMOs must implement the IMediaObject and IMediaObjectInPlace interfaces.

If dwFlags is zero, the effect is placed in hardware if possible. If the hardware does not support the effect (always the case since DirectX 9.0), software is used. If the effect is not available at all, the call to SetFX fails.

Requirements

Header: Declared in DSound.h.

See Also

DSBCAPS | IDirectSoundBuffer8::SetFX | Using Effects

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSFXChorus

The DSFXChorus structure contains parameters for a chorus effect.

typedef struct DSFXChorus {
    FLOAT fWetDryMix;
    FLOAT fDepth;
    FLOAT fFeedback;
    FLOAT fFrequency;
    LONG lWaveform;
    FLOAT fDelay;
    LONG lPhase;
} DSFXChorus;

Members

fWetDryMix
Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXCHORUS_WETDRYMIX_MIN through DSFXCHORUS_WETDRYMIX_MAX (all wet). The default value is 50.
fDepth
Percentage by which the delay time is modulated by the low-frequency oscillator, in hundredths of a percentage point. Must be in the range from DSFXCHORUS_DEPTH_MIN through DSFXCHORUS_DEPTH_MAX. The default value is 10.
fFeedback
Percentage of output signal to feed back into the effect's input, in the range from DSFXCHORUS_FEEDBACK_MIN to DSFXCHORUS_FEEDBACK_MAX. The default value is 25.
fFrequency
Frequency of the LFO, in the range from DSFXCHORUS_FREQUENCY_MIN to DSFXCHORUS_FREQUENCY_MAX. The default value is 1.1.
lWaveform
Waveform shape of the LFO. Defined values are DSFXCHORUS_WAVE_TRIANGLE and DSFXCHORUS_WAVE_SIN. By default, the waveform is a sine.
fDelay
Number of milliseconds the input is delayed before it is played back, in the range from DSFXCHORUS_DELAY_MIN to DSFXCHORUS_DELAY_MAX. The default value is 16 ms.
lPhase
Phase differential between left and right LFOs, in the range from DSFXCHORUS_PHASE_MIN through DSFXCHORUS_PHASE_MAX. Possible values are defined as follows.
Value
DSFXCHORUS_PHASE_NEG_180
DSFXCHORUS_PHASE_NEG_90
DSFXCHORUS_PHASE_ZERO
DSFXCHORUS_PHASE_90
DSFXCHORUS_PHASE_180

The default value is DSFXCHORUS_PHASE_90.

Requirements

Header: Declared in DSound.h.

See Also

Chorus | IDirectSoundFXChorus8

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSFXCompressor

The DSFXCompressor structure contains parameters for a compression effect.

typedef struct DSFXCompressor {
    FLOAT fGain;
    FLOAT fAttack;
    FLOAT fRelease;
    FLOAT fThreshold;
    FLOAT fRatio;
    FLOAT fPredelay;
} DSFXCompressor;

Members

fGain
Output gain of signal after compression, in the range from DSFXCOMPRESSOR_GAIN_MIN to DSFXCOMPRESSOR_GAIN_MAX. The default value is 0 dB.
fAttack
Time before compression reaches its full value, in the range from DSFXCOMPRESSOR_ATTACK_MIN to DSFXCOMPRESSOR_ATTACK_MAX. The default value is 10 ms.
fRelease
Speed at which compression is stopped after input drops below fThreshold, in the range from DSFXCOMPRESSOR_RELEASE_MIN to DSFXCOMPRESSOR_RELEASE_MAX. The default value is 200 ms.
fThreshold
Point at which compression begins, in decibels, in the range from DSFXCOMPRESSOR_THRESHOLD_MIN to DSFXCOMPRESSOR_THRESHOLD_MAX. The default value is -20 dB.
fRatio
Compression ratio, in the range from DSFXCOMPRESSOR_RATIO_MIN to DSFXCOMPRESSOR_RATIO_MAX. The default value is 3, which means 3:1 compression.
fPredelay
Time after lThreshold is reached before attack phase is started, in milliseconds, in the range from DSFXCOMPRESSOR_PREDELAY_MIN to DSFXCOMPRESSOR_PREDELAY_MAX. The default value is 4 ms.

Requirements

Header: Declared in DSound.h.

See Also

Compression | IDirectSoundFXCompressor8

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSFXDistortion

The DSFXDistortion structure contains parameters for a distortion effect.

typedef struct DSFXDistortion {
    DWORD fGain;
    DWORD fEdge;
    DWORD fPostEQCenterFrequency;
    DWORD fPostEQBandwidth;
    DWORD fPreLowpassCutoff;
} DSFXDistortion;

Members

fGain
Amount of signal change after distortion, in the range from DSFXDISTORTION_GAIN_MIN through DSFXDISTORTION_GAIN_MAX. The default value is -18 dB.
fEdge
Percentage of distortion intensity, in the range in the range from DSFXDISTORTION_EDGE_MIN through DSFXDISTORTION_EDGE_MAX. The default value is 15 percent.
fPostEQCenterFrequency
Center frequency of harmonic content addition, in the range from DSFXDISTORTION_POSTEQCENTERFREQUENCY_MIN through DSFXDISTORTION_POSTEQCENTERFREQUENCY_MAX. The default value is 2400 Hz.
fPostEQBandwidth
Width of frequency band that determines range of harmonic content addition, in the range from DSFXDISTORTION_POSTEQBANDWIDTH_MIN through DSFXDISTORTION_POSTEQBANDWIDTH_MAX. The default value is 2400 Hz.
fPreLowpassCutoff
Filter cutoff for high-frequency harmonics attenuation, in the range from DSFXDISTORTION_PRELOWPASSCUTOFF_MIN through DSFXDISTORTION_PRELOWPASSCUTOFF_MAX. The default value is 8000 Hz.

Remarks

The values in fPostEQBandwidth, fPostEQCenterFrequency, and fPreLowpassCutoff cannot exceed one-third of the frequency of the buffer. If an attempt is made to set a value greater than this, but within the range of accepted values, the parameter is set to the nearest supported value and S_FALSE is returned by IDirectSoundFXDistortion8::SetAllParameters.

Requirements

Header: Declared in DSound.h.

See Also

Distortion | IDirectSoundFXDistortion8

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSFXEcho

The DSFXEcho structure contains parameters for an echo effect.

typedef struct DSFXEcho {
    FLOAT fWetDryMix;
    FLOAT fFeedback;
    FLOAT fLeftDelay;
    FLOAT fRightDelay;
    LONG lPanDelay;
} DSFXEcho;

Members

fWetDryMix
Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXECHO_WETDRYMIX_MIN through DSFXECHO_WETDRYMIX_MAX (all wet). The default value is 50.
fFeedback
Percentage of output fed back into input, in the range from DSFXECHO_FEEDBACK_MIN through DSFXECHO_FEEDBACK_MAX. The default value is 50.
fLeftDelay
Delay for left channel, in milliseconds, in the range from DSFXECHO_LEFTDELAY_MIN through DSFXECHO_LEFTDELAY_MAX. The default value is 500 ms.
fRightDelay
Delay for right channel, in milliseconds, in the range from DSFXECHO_RIGHTDELAY_MIN through DSFXECHO_RIGHTDELAY_MAX. The default value is 500 ms.
lPanDelay
Value that specifies whether to swap left and right delays with each successive echo. The default value is zero, meaning no swap. Possible values are defined as DSFXECHO_PANDELAY_MIN (equivalent to FALSE) and DSFXECHO_PANDELAY_MAX (equivalent to TRUE).

Requirements

Header: Declared in DSound.h.

See Also

Echo | IDirectSoundFXEcho8

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSFXFlanger

The DSFXFlanger structure contains parameters for a flange effect.

typedef struct DSFXFlanger {
    FLOAT fWetDryMix;
    FLOAT fDepth;
    FLOAT fFeedback;
    FLOAT fFrequency;
    LONG lWaveform;
    FLOAT fDelay;
    LONG lPhase;
} DSFXFlanger;

Members

fWetDryMix
Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXFLANGER_WETDRYMIX_MIN through DSFXFLANGER_WETDRYMIX_MAX (all wet). The default value is 50.
fDepth
Percentage by which the delay time is modulated by the low-frequency oscillator (LFO), in hundredths of a percentage point. Must be in the range from DSFXFLANGER_DEPTH_MIN through DSFXFLANGER_DEPTH_MAX. The default value is 100.
fFeedback
Percentage of output signal to feed back into the effect's input, in the range from DSFXFLANGER_FEEDBACK_MIN to DSFXFLANGER_FEEDBACK_MAX. The default value is -50.
fFrequency
Frequency of the LFO, in the range from DSFXFLANGER_FREQUENCY_MIN to DSFXFLANGER_FREQUENCY_MAX. The default value is 0.25.
lWaveform
Waveform shape of the LFO. By default, the waveform is a sine. Possible values are defined in the following table.
Value | Description
DSFXFLANGER_WAVE_TRIANGLE | Triangle.
DSFXFLANGER_WAVE_SIN | Sine.
fDelay
Number of milliseconds the input is delayed before it is played back, in the range from DSFXFLANGER_DELAY_MIN to DSFXFLANGER_DELAY_MAX. The default value is 2 ms.
lPhase
Phase differential between left and right LFOs, in the range from DSFXFLANGER_PHASE_MIN through DSFXFLANGER_PHASE_MAX. Possible values are defined in the following table.
Value
DSFXFLANGER_PHASE_NEG_180
DSFXFLANGER_PHASE_NEG_90
DSFXFLANGER_PHASE_ZERO
DSFXFLANGER_PHASE_90
DSFXFLANGER_PHASE_180

The default value is DSFXFLANGER_PHASE_ZERO.

Requirements

Header: Declared in DSound.h.

See Also

Flange | IDirectSoundFXFlanger8

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSFXGargle

The DSFXGargle structure contains parameters for an amplitude modulation effect.

typedef struct DSFXGargle {
    DWORD dwRateHz;
    DWORD dwWaveShape;
} DSFXGargle;

Members

dwRateHz
Rate of modulation, in Hertz. Must be in the range from DSFXGARGLE_RATEHZ_MIN through DSFXGARGLE_RATEHZ_MAX. The default value is 20.
dwWaveShape
Shape of the modulation waveform. The following values are defined.
Value | Description
DSFXGARGLE_WAVE_TRIANGLE | Triangular waveform.
DSFXGARGLE_WAVE_SQUARE | Square waveform.

The default value is DSFXGARGLE_WAVE_TRIANGLE.

Requirements

Header: Declared in DSound.h.

See Also

Gargle | IDirectSoundFXGargle8

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSFXI3DL2Reverb

The DSFXI3DL2Reverb structure contains parameters for an I3DL2 (Interactive 3D Audio Level 2) reverberation effect.

typedef struct DSFXI3DL2Reverb {
    LONG lRoom;
    LONG lRoomHF;
    FLOAT flRoomRolloffFactor;
    FLOAT flDecayTime;
    FLOAT flDecayHFRatio;
    LONG lReflections;
    FLOAT flReflectionsDelay;
    LONG lReverb;
    FLOAT flReverbDelay;
    FLOAT flDiffusion;
    FLOAT flDensity;
    FLOAT flHFReference;
} DSFXI3DL2Reverb;

Members

lRoom
Attenuation of the room effect, in millibels (mB), in the range from DSFX_I3DL2REVERB_ROOM_MIN to DSFX_I3DL2REVERB_ROOM_MAX. The default value is DSFX_I3DL2REVERB_ROOM_DEFAULT, or -1000 mB.
lRoomHF
Attenuation of the room high-frequency effect, in mB, in the range from DSFX_I3DL2REVERB_ROOMHF_MIN to DSFX_I3DL2REVERB_ROOMHF_MAX. The default value is DSFX_I3DL2REVERB_ROOMHF_DEFAULT, or -100 mB.
flRoomRolloffFactor
Rolloff factor for the reflected signals, in the range from DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MIN to DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MAX. The default value is DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_DEFAULT, or 0.0. The rolloff factor for the direct path is controlled by the DirectSound listener.
flDecayTime
Decay time, in seconds, in the range from DSFX_I3DL2REVERB_DECAYTIME_MIN to DSFX_I3DL2REVERB_DECAYTIME_MAX. The default value is DSFX_I3DL2REVERB_DECAYTIME_DEFAULT, or 1.49 second.
flDecayHFRatio
Ratio of the decay time at high frequencies to the decay time at low frequencies, in the range from DSFX_I3DL2REVERB_DECAYHFRATIO_MIN to DSFX_I3DL2REVERB_DECAYHFRATIO_MAX. The default value is DSFX_I3DL2REVERB_DECAYHFRATIO_DEFAULT, or 0.83.
lReflections
Attenuation of early reflections relative to lRoom, in mB, in the range from DSFX_I3DL2REVERB_REFLECTIONS_MIN to DSFX_I3DL2REVERB_REFLECTIONS_MAX. The default value is DSFX_I3DL2REVERB_REFLECTIONS_DEFAULT, or -2602 mB.
flReflectionsDelay
Delay time of the first reflection relative to the direct path, in seconds, in the range from DSFX_I3DL2REVERB_REFLECTIONSDELAY_MIN to DSFX_I3DL2REVERB_REFLECTIONSDELAY_DEFAULT. The default value is 0.007 seconds.
lReverb
Attenuation of late reverberation relative to lRoom, in mB, in the range -from DSFX_I3DL2REVERB_REVERB_MIN to DSFX_I3DL2REVERB_REVERB_MAX. The default value is DSFX_I3DL2REVERB_REVERB_DEFAULT, or 200 mB.
flReverbDelay
Time limit between the early reflections and the late reverberation relative to the time of the first reflection, in seconds, in the range from DSFX_I3DL2REVERB_REVERBDELAY_MIN to DSFX_I3DL2REVERB_REVERBDELAY_MAX. The default value is DSFX_I3DL2REVERB_REVERBDELAY_DEFAULT, or 0.011 seconds.
flDiffusion
Echo density in the late reverberation decay, in percent, in the range from DSFX_I3DL2REVERB_DIFFUSION_MIN to DSFX_I3DL2REVERB_DIFFUSION_MAX. The default value is DSFX_I3DL2REVERB_DIFFUSION_DEFAULT, or 100.0 percent.
flDensity
Modal density in the late reverberation decay, in percent, in the range from DSFX_I3DL2REVERB_DENSITY_MIN to DSFX_I3DL2REVERB_DENSITY_MAX. The default value is DSFX_I3DL2REVERB_DENSITY_DEFAULT, or 100.0 percent.
flHFReference
Reference high frequency, in hertz, in the range from DSFX_I3DL2REVERB_HFREFERENCE_MIN to DSFX_I3DL2REVERB_HFREFERENCE_MAX. The default value is DSFX_I3DL2REVERB_HFREFERENCE_DEFAULT, or 5000.0 Hz.

Requirements

Header: Declared in DSound.h.

See Also

IDirectSoundFXI3DL2Reverb8


DSFXParamEq

The DSFXParamEq structure contains parameters for a parametric equalizer effect.

typedef struct DSFXParamEq {
    FLOAT fCenter;
    FLOAT fBandwidth;
    FLOAT fGain;
} DSFXParamEq;

Members

fCenter
Center frequency, in hertz, in the range from DSFXPARAMEQ_CENTER_MIN to DSFXPARAMEQ_CENTER_MAX. The default value is 8000.
fBandwidth
Bandwidth, in semitones, in the range from DSFXPARAMEQ_BANDWIDTH_MIN to DSFXPARAMEQ_BANDWIDTH_MAX. The default value is 12.
fGain
Gain, in the range from DSFXPARAMEQ_GAIN_MIN to DSFXPARAMEQ_GAIN_MAX. The default value is 0.

Remarks

The value in fCenter cannot exceed one-third of the sampling frequency of the buffer. If an attempt is made to set a value greater than this, but within the range of accepted values, the parameter is set to the nearest supported value and S_FALSE is returned by IDirectSoundFXParamEq8::SetAllParameters.

Requirements

Header: Declared in DSound.h.

See Also

Parametric Equalizer | IDirectSoundFXParamEq8

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DSFXWavesReverb

The DSFXWavesReverb structure contains parameters for a Waves reverberation effect.

typedef struct DSFXWavesReverb {
    FLOAT fInGain;
    FLOAT fReverbMix;
    FLOAT fReverbTime;
    FLOAT fHighFreqRTRatio;
} DSFXWavesReverb;

Members

fInGain
Input gain of signal, in decibels (dB), in the range from DSFX_WAVESREVERB_INGAIN_MIN through DSFX_WAVESREVERB_INGAIN_MAX. The default value is DSFX_WAVESREVERB_INGAIN_DEFAULT, or 0 dB.
fReverbMix
Reverb mix, in dB, in the range from DSFX_WAVESREVERB_REVERBMIX_MIN through DSFX_WAVESREVERB_REVERBMIX_MAX. The default value is DSFX_WAVESREVERB_REVERBMIX_DEFAULT, or 0 dB.
fReverbTime
Reverb time, in milliseconds, in the range from DSFX_WAVESREVERB_REVERBTIME_MIN through DSFX_WAVESREVERB_REVERBTIME_MAX. The default value is DSFX_WAVESREVERB_REVERBTIME_DEFAULT, or 1000.
fHighFreqRTRatio
High-frequency reverb time ratio, in the range from DSFX_WAVESREVERB_HIGHFREQRTRATIO_MIN through DSFX_WAVESREVERB_HIGHFREQRTRATIO_MAX. The default value is DSFX_WAVESREVERB_HIGHFREQRTRATIO_DEFAULT, or 0.001.

Requirements

Header: Declared in DSound.h.

See Also

IDirectSoundFXWavesReverb8


WAVEFORMATEX

The WAVEFORMATEX structure defines the format of waveform-audio data. Only format information common to all waveform-audio data formats is included in this structure. For formats that require additional information, this structure is included as the first member in another structure, along with the additional information.

This structure is part of the Platform SDK and is not declared in Dsound.h. It is documented here for convenience.

typedef struct WAVEFORMATEX {
    WORD wFormatTag;
    WORD nChannels;
    DWORD nSamplesPerSec;
    DWORD nAvgBytesPerSec;
    WORD nBlockAlign;
    WORD wBitsPerSample;
    WORD cbSize;
} WAVEFORMATEX;

Members

wFormatTag
Waveform-audio format type. Format tags are registered with Microsoft Corporation for many compression algorithms. A complete list of format tags can be found in the Mmreg.h header file. For one- or two-channel PCM data, this value should be WAVE_FORMAT_PCM.
nChannels
Number of channels in the waveform-audio data. Monaural data uses one channel and stereo data uses two channels.
nSamplesPerSec
Sample rate, in samples per second (hertz). If wFormatTag is WAVE_FORMAT_PCM, then common values for nSamplesPerSec are 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.
nAvgBytesPerSec
Required average data-transfer rate, in bytes per second, for the format tag. If wFormatTag is WAVE_FORMAT_PCM, nAvgBytesPerSec should be equal to the product of nSamplesPerSec and nBlockAlign. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.
nBlockAlign
Block alignment, in bytes. The block alignment is the minimum atomic unit of data for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE, nBlockAlign must be equal to the product of nChannels and wBitsPerSample divided by 8 (bits per byte). For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Software must process a multiple of nBlockAlign bytes of data at a time. Data written to and read from a device must always start at the beginning of a block. For example, it is illegal to start playback of PCM data in the middle of a sample (that is, on a non-block-aligned boundary).

wBitsPerSample
Bits per sample for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM, then wBitsPerSample should be equal to 8 or 16. For non-PCM formats, this member must be set according to the manufacturer's specification of the format tag. If wFormatTag is WAVE_FORMAT_EXTENSIBLE, this value can be any integer multiple of 8. Some compression schemes cannot define a value for wBitsPerSample, so this member can be zero.
cbSize
Size, in bytes, of extra format information appended to the end of the WAVEFORMATEX structure. This information can be used by non-PCM formats to store extra attributes for the wFormatTag. If no extra information is required by the wFormatTag, this member must be set to zero. For WAVE_FORMAT_PCM formats (and only WAVE_FORMAT_PCM formats), this member is ignored.

Requirements

Header: Declared in Mmreg.h.

See Also

WAVEFORMATEXTENSIBLE


WAVEFORMATEXTENSIBLE

The WAVEFORMATEXTENSIBLE structure defines the format of waveform-audio data for formats having more than two channels or higher sample resolutions than allowed by WAVEFORMATEX.

This structure is not part of the DirectSound API but is documented here for convenience.

typedef struct WAVEFORMATEXTENSIBLE {
    WAVEFORMATEX Format;
    WORD wValidBitsPerSample;
    WORD wSamplesPerBlock;
    WORD wReserved;
    DWORD dwChannelMask;
    DWORD SubFormat;
} WAVEFORMATEXTENSIBLE;

Members

Format
WAVEFORMATEX structure that specifies the basic format. The wFormatTag member must be WAVE_FORMAT_EXTENSIBLE, defined in Mmreg.h. The cbSize member must be at least 22.
wValidBitsPerSample
Number of bits of precision in the signal. Usually equal to WAVEFORMATEX.wBitsPerSample. However, wBitsPerSample is the container size and must be a multiple of 8, whereas wValidBitsPerSample can be any value not exceeding the container size. For example, if the format uses 20-bit samples, wBitsPerSample must be at least 24, but wValidBitsPerSample is 20.
wSamplesPerBlock
Number of samples contained in one compressed block of audio data. This value is used in buffer estimation. This value is used with compressed formats that have a fixed number of samples within each block. This value can be set to zero if a variable number of samples is contained in each block of compressed audio data. In this case, buffer estimation and position information needs to be obtained in other ways.
wReserved
Reserved for internal use by operating system. Set to zero.
dwChannelMask
Bitmask specifying the assignment of channels in the stream to speaker positions. See Remarks.
SubFormat
Subformat of the data, such as KSDATAFORMAT_SUBTYPE_PCM. The subformat information is similar to that provided by the tag in the WAVEFORMATEX structure's wFormatTag member.

Remarks

WAVEFORMATEXTENSIBLE can describe any format that can be described by WAVEFORMATEX, but provides additional support for more than two channels, for greater precision in the number of bits per sample, and for new compression schemes.

WAVEFORMATEXTENSIBLE can safely be cast to WAVEFORMATEX, because it simply configures the extra bytes specified by WAVEFORMATEX.cbSize. DirectSound recognizes the WAVE_FORMAT_EXTENSIBLE format tag and correctly plays multiple-channel and compressed formats in hardware buffers, as long as these formats are supported by the driver.

The dwChannelMask member specifies which channels are present in the multichannel stream. The least significant bit corresponds with the front left speaker, the next least significant bit corresponds to the front right speaker, and so on. The bits, in order of significance, are defined in Ksmedia.h and Mmreg.h as follows.

Speaker position | Flag bit
SPEAKER_FRONT_LEFT | 0x1
SPEAKER_FRONT_RIGHT | 0x2
SPEAKER_FRONT_CENTER | 0x4
SPEAKER_LOW_FREQUENCY | 0x8
SPEAKER_BACK_LEFT | 0x10
SPEAKER_BACK_RIGHT | 0x20
SPEAKER_FRONT_LEFT_OF_CENTER | 0x40
SPEAKER_FRONT_RIGHT_OF_CENTER | 0x80
SPEAKER_BACK_CENTER | 0x100
SPEAKER_SIDE_LEFT | 0x200
SPEAKER_SIDE_RIGHT | 0x400
SPEAKER_TOP_CENTER | 0x800
SPEAKER_TOP_FRONT_LEFT | 0x1000
SPEAKER_TOP_FRONT_CENTER | 0x2000
SPEAKER_TOP_FRONT_RIGHT | 0x4000
SPEAKER_TOP_BACK_LEFT | 0x8000
SPEAKER_TOP_BACK_CENTER | 0x10000
SPEAKER_TOP_BACK_RIGHT | 0x20000

For more information on this structure, see the document Multiple Channel Audio Data and WAVE Files, available at www.microsoft.com.

Requirements

Header: Declared in Mmreg.h, Ksproxy.h.

See Also

Multichannel and High-Resolution WAV Formats


DirectSound GUIDs

This section lists globally unique identifiers used in DirectSound. The following topics are covered:

  • DirectSound Interface GUIDs
  • DirectSound Component GUIDs
  • DirectSound Device GUIDs
  • DirectSound Effect GUIDs


DirectSound Interface GUIDs

The following GUIDs are used as interface identifiers (IIDs) to obtain DirectSound interfaces.

IID | Interface
IID_IDirectSound3DBuffer8 | IDirectSound3DBuffer8
IID_IDirectSound3DListener8 | IDirectSound3DListener8
IID_IDirectSound8 | IDirectSound8
IID_IDirectSoundBuffer8 | IDirectSoundBuffer8
IID_IDirectSoundCapture8 | IDirectSoundCapture8
IID_IDirectSoundCaptureBuffer8 | IDirectSoundCaptureBuffer8
IID_IDirectSoundCaptureFXAec8 | IDirectSoundCaptureFXAec8
IID_IDirectSoundCaptureFXNoiseSuppress8 | IDirectSoundCaptureFXNoiseSuppress8
IID_IDirectSoundFullDuplex8 | IDirectSoundFullDuplex8
IID_IDirectSoundFXChorus8 | IDirectSoundFXChorus8
IID_IDirectSoundFXCompressor8 | IDirectSoundFXCompressor8
IID_IDirectSoundFXDistortion8 | IDirectSoundFXDistortion8
IID_IDirectSoundFXEcho8 | IDirectSoundFXEcho8
IID_IDirectSoundFXFlanger8 | IDirectSoundFXFlanger8
IID_IDirectSoundFXGargle8 | IDirectSoundFXGargle8
IID_IDirectSoundFXI3DL2Reverb8 | IDirectSoundFXI3DL2Reverb8::IDirectSoundFXI3DL2Reverb8
IID_IDirectSoundFXParamEq8 | IDirectSoundFXParamEq8
IID_IDirectSoundFXWavesReverb8 | IDirectSoundFXWavesReverb8
IID_IDirectSoundNotify8 | IDirectSoundNotify8
IID_IKsPropertySet | IKsPropertySet

Note Where an interface has not changed from previous versions of DirectX, the IID in the table is defined in Dsound.h as the original IID. For example, IID_IDirectSound3DBuffer8 is defined as IID_IDirectSound3DBuffer, because IDirectSoundBuffer8 is the same as IDirectSoundBuffer.


DirectSound Component GUIDs

The following GUIDS are used as class identifiers (CLSIDs) in the creation of DirectSound components.

CLSID | Component
CLSID_DirectSound | DirectSound playback device
CLSID_DirectSound8 | DirectSound8 playback device
CLSID_DirectSoundCapture | DirectSoundCapture device
CLSID_DirectSoundCapture8 | DirectSoundCapture8 device
CLSID_DirectSoundFullDuplex | Full duplex device

Note For information about the differences between the older and newer versions of playback and capture device components, see IDirectSound8 Interface and IDirectSoundCapture8::CreateCaptureBuffer.


DirectSound Device GUIDs

The following GUIDs are used to identify default playback and capture devices.

Device ID | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

See Also

Creating the Device Object Creating the Capture Device Object DirectSoundCaptureCreate8 DirectSoundCreate8 DirectSoundFullDuplexCreate8 GetDeviceID IDirectSoundFullDuplex8::Initialize


DirectSound Effect GUIDs

The following GUIDs are used to identify capture and playback effects.

GUID | Description
GUID_DSCFX_CLASS_AEC | Acoustic echo cancellation capture effect
GUID_DSCFX_CLASS_NS | Noise suppression capture effect
GUID_DSCFX_MS_AEC | Microsoft acoustic echo cancellation capture effect
GUID_DSCFX_MS_NS | Microsoft noise suppression capture effect
GUID_DSCFX_SYSTEM_AEC | System default acoustic echo cancellation capture effect
GUID_DSCFX_SYSTEM_NS | System default noise suppression capture effect
GUID_DSFX_STANDARD_CHORUS | Chorus effect
GUID_DSFX_STANDARD_COMPRESSOR | Compressor effect
GUID_DSFX_STANDARD_DISTORTION | Distortion effect
GUID_DSFX_STANDARD_ECHO | Echo effect
GUID_DSFX_STANDARD_FLANGER | Flanger effect
GUID_DSFX_STANDARD_GARGLE | Gargle effect
GUID_DSFX_STANDARD_I3DL2REVERB | Environmental reverberation effect
GUID_DSFX_STANDARD_PARAMEQ | Parametric equalizer effect
GUID_DSFX_WAVES_REVERB | Waves reverberation effect

See Also

IDirectSoundBuffer8::GetObjectInPath DSCEFFECTDESC DSEFFECTDESC

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DirectSound Return Values

This section provides a brief explanation of the various error codes that can be returned by DirectSound methods. For a partial list of the specific codes that each method can return, see the individual method descriptions.

Note The lists of error codes in method descriptions are not necessarily comprehensive. Applications should always check for method failure and not just for specific codes. For example, most methods can return DSERR_NODRIVER if the driver is removed while the application is running, or DSERR_OUTOFMEMORY if no more memory is available for operations.

Error codes are presented in the following sections:

  • DirectSound Return Values by Number
  • DirectSound Return Values by Name


DirectSound Return Values by Number

The following table lists DirectSound return values sorted by hexadecimal value. For a description, click on the constant.

Hexadecimal | Constant
0x00000000 | DS_OK
0x00000007 | DSERR_OUTOFMEMORY
0x000001AE | DSERR_NOINTERFACE
0x0878000A | DS_NO_VIRTUALIZATION
0x08780014 | DS_INCOMPLETE
0x80004001 | DSERR_UNSUPPORTED
0x80004005 | DSERR_GENERIC
0x80070005 | DSERR_ACCESSDENIED
0x80070057 | DSERR_INVALIDPARAM
0x8878000A | DSERR_ALLOCATED
0x8878001E | DSERR_CONTROLUNAVAIL
0x88780032 | DSERR_INVALIDCALL
0x88780046 | DSERR_PRIOLEVELNEEDED
0x88780064 | DSERR_BADFORMAT
0x88780078 | DSERR_NODRIVER
0x88780082 | DSERR_ALREADYINITIALIZED
0x88780096 | DSERR_BUFFERLOST
0x887800A0 | DSERR_OTHERAPPHASPRIO
0x887800AA | DSERR_UNINITIALIZED
0x887810B4 | DSERR_BUFFERTOOSMALL
0x887810BE | DSERR_DS8_REQUIRED
0x887810C8 | DSERR_SENDLOOP
0x887810D2 | DSERR_BADSENDBUFFERGUID
0x887810DC | DSERR_FXUNAVAILABLE
0x88781161 | DSERR_OBJECTNOTFOUND


DirectSound Return Values by Name

The following list describes all DirectSound return values. To find a constant from its value, see DirectSound Return Values by Number.

Return Values

DS_OK
The method succeeded.
DS_NO_VIRTUALIZATION
The buffer was created, but another 3D algorithm was substituted.
DS_INCOMPLETE
The method succeeded, but not all the optional effects were obtained.
DSERR_ACCESSDENIED
The request failed because access was denied.
DSERR_ALLOCATED
The request failed because resources, such as a priority level, were already in use by another caller.
DSERR_ALREADYINITIALIZED
The object is already initialized.
DSERR_BADFORMAT
The specified wave format is not supported.
DSERR_BADSENDBUFFERGUID
The GUID specified in an audiopath file does not match a valid mix-in buffer.
DSERR_BUFFERLOST
The buffer memory has been lost and must be restored.
DSERR_BUFFERTOOSMALL
The buffer size is not great enough to enable effects processing.
DSERR_CONTROLUNAVAIL
The buffer control (volume, pan, and so on) requested by the caller is not available. Controls must be specified when the buffer is created, using the dwFlags member of DSBUFFERDESC.
DSERR_DS8_REQUIRED
A DirectSound object of class CLSID_DirectSound8 or later is required for the requested functionality. For more information, see IDirectSound8 Interface.
DSERR_FXUNAVAILABLE
The effects requested could not be found on the system, or they are in the wrong order or in the wrong location; for example, an effect expected in hardware was found in software.
DSERR_GENERIC
An undetermined error occurred inside the DirectSound subsystem.
DSERR_INVALIDCALL
This function is not valid for the current state of this object.
DSERR_INVALIDPARAM
An invalid parameter was passed to the returning function.
DSERR_NOAGGREGATION
The object does not support aggregation.
DSERR_NODRIVER
No sound driver is available for use, or the given GUID is not a valid DirectSound device ID.
DSERR_NOINTERFACE
The requested COM interface is not available.
DSERR_OBJECTNOTFOUND
The requested object was not found.
DSERR_OTHERAPPHASPRIO
Another application has a higher priority level, preventing this call from succeeding.
DSERR_OUTOFMEMORY
The DirectSound subsystem could not allocate sufficient memory to complete the caller's request.
DSERR_PRIOLEVELNEEDED
A cooperative level of DSSCL_PRIORITY or higher is required.
DSERR_SENDLOOP
A circular loop of send effects was detected.
DSERR_UNINITIALIZED
The IDirectSound8::Initialize method has not been called or has not been called successfully before other methods were called.
DSERR_UNSUPPORTED
The function called is not supported at this time.


DirectX Graphics

  • Direct3D 10 Graphics
  • Direct3D 9 Graphics
  • DirectX 9 for Windows Vista
  • Graphics Tools


Direct3D 10 Graphics

Discover the Direct3D 10 graphics features in one of these sections:

  • Programming Guide (Direct3D 10) - This section contains architecture descriptions, functional block diagrams, descriptions of the building blocks in the pipeline, code snippets, and sample applications.
  • Tutorials and Samples - This section contains tutorials and sample applications.
  • Direct3D 10 Reference - This section contains the reference pages for the graphics components including the syntax for the API methods, functions, and data structures.


Programming Guide (Direct3D 10)

The programming guide contains information about how to use the Direct3D 10 programmable pipeline to create realtime 3D graphics for games as well as scientific and desktop applications.

  • API Features
  • Pipeline Stages
  • Resources
  • Shaders
  • Effects
  • Direct3D 9 to Direct3D 10 Considerations
  • DXGI
  • Linking Static and Dynamic Libraries


API Features (Direct3D 10)

The Direct3D 10 graphics pipeline represents a fundamental architecture change, rebuilt from the ground-up in hardware and software to power the next-generation of games and 3D multimedia applications. It is built upon the Windows Vista Display Driver Model (WDDM) infrastructure, enabling new performance and behavioral enhancements and guaranteeing of full virtualization of GPU memory.

Developers familiar with Direct3D 9 will discover a series of functional enhancements and performance improvements in Direct3D 10, including:

  • The ability to process entire primitives (with adjacency), amplify and de-amplify data in the new geometry shader stage.
  • The ability to output pipeline-generated vertex data to memory using the stream output stage.
  • New objects and paradigms provided to minimize CPU overhead spent on validation and processing in the runtime and driver.
    • Organization of pipeline state into 5 immutable state objects, enabling fast configuration of the pipeline.
    • Organization of shader constant variables into constant buffers, minimizing bandwidth overhead for supplying shader constant data.
    • The ability to perform per-primitive material swapping and setup using a geometry shader.
  • New resource types (including shader-indexable arrays of textures) and resource formats.
  • Increased generalization of resources in memory and ubiquity of resource access - resource views enable interpretation of resources in memory as different types or representations.
  • A full set of required functionality: legacy hardware capability bits (caps) have been removed in favor of a rich set of guaranteed functionality. To enable this and other design improvements, the Direct3D 10 API only targets Direct3D 10-class hardware and later.
  • Layered Runtime - The Direct3D 10 API is constructed with layers, starting with the basic functionality at the core and building optional and developer-assist functionality (debug, etc.) in outer layers.
  • Full HLSL integration - All Direct3D 10 shaders are written in HLSL and implemented with the common shader core.
  • An increase in the number of render targets, textures, and samplers. There is also no shader length limit.
  • Full support for:
    • Integer and bitwise shader operations
    • Readback of depth/stencil and multisampled resources in the shader
    • Multisample Alpha-to-Coverage

There are additional behavioral differences that Direct3D 9 developers should also be aware of. For a more complete list, refer to Direct3D 9 to Direct3D 10 Considerations (Direct3D 10).


State Objects (Direct3D 10)

In Direct3D 10, device state is grouped into state objects which greatly reduce the cost of state changes. There are several state objects, and each one is designed to initialize a set of state for a particular pipeline stage. You can create up to 4096 of each type of state object.

  • Input-Layout State
  • Rasterizer State
  • Depth-Stencil State
  • Blend State
  • Sampler State
  • Performance Considerations

Input-Layout State

This group of state (see D3D10_INPUT_ELEMENT_DESC) dictates how the input assembler stage reads data out of the input buffers and assembles it for use by the vertex shader. This includes state such as the number of elements in the input buffer and the signature of the input data. The input-assembler stage is a new stage in the pipeline whose job is to stream primitives from memory into the pipeline.

To create a input-layout-state object, see ID3D10Device::CreateInputLayout.

Rasterizer State

This group of state (see D3D10_RASTERIZER_DESC) initializes the rasterizer stage. This object includes state such as fill or cull modes, enabling a scissor rectangle for clipping, and setting multisample parameters. This stage rasterizes primitives into pixels, performing operations like clipping and mapping primitives to the viewport.

To create a rasterizer-state object, see ID3D10Device::CreateRasterizerState.

Depth-Stencil State

This group of state (see D3D10_DEPTH_STENCIL_DESC) initializes the depth-stencil portion of the output-merger stage. More specifically, this object initializes depth and stencil testing.

To create a depth-stencil-state object, see ID3D10Device::CreateDepthStencilState.

Blend State

This group of state (see D3D10_BLEND_DESC) initializes the blending portion of the output-merger stage.

To create a blend-state object, see ID3D10Device::CreateBlendState.

Sampler State

This group of state (see D3D10_SAMPLER_DESC) initializes a sampler object. A sampler object is used by the shader stages to filter textures in memory.

Differences between Direct3D 9 and Direct3D 10:

In Direct3D 10, the sampler object is no longer bound to a specific texture - it just describes how to do filtering given any attached resource.

To create a sampler-state object, see ID3D10Device::CreateSamplerState.

Performance Considerations

Designing the API to use state objects creates several performance advantages. These include validating state at object creation time, enabling caching of state objects in hardware, and greatly reducing the amount of state that is passed during a state-setting API call (by passing a handle to the state object instead of the state).

To achieve these performance improvements, you should create your state objects when your application starts up, well before your render loop. State objects are immutable, that is, once they are created, you cannot change them. Instead you must destroy and recreate them. To cope with this restriction, you can create up to 4096 of each type of state objects. For example, you could create several sampler objects with various sampler-state combinations. Changing the sampler state is then accomplished by calling the appropriate Set API which passes a handle to the object (as opposed to the sampler state). This significantly reduces the amount of overhead during each render frame for changing state since the number of calls and the amount of data are greatly reduced.

Alternatively, you can choose to use the effect system which will automatically manage efficient creation and destruction of state objects for your application.


API Layers (Direct3D 10)

The Direct3D 10 runtime is constructed with layers, starting with the basic functionality at the core and building optional and developer-assist functionality in outer layers.

Core Layer

The core layer exists by default; providing a very thin mapping between the API and the device driver, minimizing overhead for high-frequency calls. As the core layer is essential for performance, it only performs critical validation.

The remaining layers are optional. As a general rule, layers add functionality, but do not modify existing behavior. For example, core functions will have the same return values independent of the debug layer being instantiated, although additional debug output may be provided if the debug layer is instantiated.

Create layers when a device is created by calling D3D10CreateDevice and supplying one or more D3D10_CREATE_DEVICE_FLAG values.

Debug Layer

The debug layer provides extensive additional parameter and consistency validation (such as validating shader linkage and resource binding, validating parameter consistency, and reporting error descriptions). The output generated by the debug layer consists of a queue of strings which are accessible using the ID3D10InfoQueue Interface (see Customize Debug Output with ID3D10InfoQueue (Direct3D 10)). Errors generated by the core layer are highlighted with warnings by the debug layer.

To create a device that supports the debug layer, you must install the DirectX SDK (to get D3D10SDKLayers.DLL), and then specify the D3D10_CREATE_DEVICE_DEBUG flag when calling D3D10CreateDevice. Of course, running an application with the debug layer will be substantially slower.

Switch-to-Reference Layer

This layer enables an application to transition between a hardware device (HAL) and a reference or software device (REF). To switch a device, you must first create a device that supports the switch-to-reference layer (see D3D10CreateDevice) and then call ID3D10SwitchToRef::SetUseRef.

All device states, resources and objects are maintained through this device transition. However, it is sometimes not possible to exactly match resource data. This is due to the fact that some information is available to a hardware device that is not available to a reference device.

Virtually all real-time applications use the HAL implementation of the pipeline. When the pipeline is switched from a hardware device to a reference device, rendering operations are done simultaneously in both hardware and software. As the software device is rendering, it will require that resources are downloaded to system memory. This may require other resources cached in system memory to be evicted to make room.

Thread-Safe Layer

This layer is designed to allow multi-threaded applications to access the device from multiple threads.

Direct3D 10 enables an application to exercise explicit control over the device synchronization primitive with device functions that can be invoked at any time over the lifetime of the device, including enabling and disabling the use of the critical section (temporarily enabling/disabling multithread protection), and a means to take and release the critical section lock and thereby hold the lock over multiple Direct3D 10 API entrypoints.

This layer is enabled by default, but if not present has no performance impact on single-thread accessed devices.

Differences between Direct3D 9 and Direct3D 10:

Unlike Direct3D 9, the Direct3D 10 API defaults to fully thread-safe.


Customize Debug Output with ID3D10InfoQueue (Direct3D 10)

The information queue is managed by an interface (see ID3D10InfoQueue Interface) that stores, retrieves, and filters debug messages. The queue consists of: a message queue, an optional storage filter stack, and a optional retrieval filter stack. The storage-filter stack can be used to filter the messages you want stored; the retrieval-filter stack can be used to filter the messages you want stored. Once you have filtered a message, the message will be printed out to the debug window and stored in the appropriate stack.

In general:

  • Call ID3D10InfoQueue::AddApplicationMessage to generate user-defined messages
  • Call ID3D10InfoQueue::GetMessage is used to get messages (that pass an optional retrieval filter).

Registry Controls

Use registry keys to adjust filter settings, adjust break points, and to mute the debug output. The debug layer will check these paths for registry keys; the first path found will be used.

  1. HKCU\Software\Microsoft\Direct3D\<user-defined subkey>
  2. HKLM\Software\Microsoft\Direct3D\<user-defined subkey>
  3. HKCU\Software\Microsoft\Direct3D

Where:

  • HKCU stand for HKEY_CURRENT_USER, and HKLM stand for HKEY_LOCAL_MACHINE.
  • user-defined subkey is an arbitrary name to store debug settings for an application

Filtering Debug Messages using Registry Keys

If the registry contains an InfoQueueStorageFilterOverride key (and is non-zero), then messages (and debug output) can be filtered by adding the following registry controls.

  • DWORD Mute_CATEGORY_* - Debug output if this key is non-zero.
  • DWORD Mute_SEVERITY_* - Debug output is disabled if this key is non-zero.
  • DWORD Mute_ID_* - Message name or number can be used for * (just like for BreakOn_ID_* described earlier). Debug output is disabled if this key is non-zero.
  • DWORD Unmute_SEVERITY_INFO - Debug output is ENABLED if this key is non-zero. By default when InfoQueueStorageFilterOverride is enabled, debug messages with severity INFO are muted - therefore for this key allows INFO to be turned back on.

These controls change whether a message is recorded or displayed; they do not affect whether an API passes or fails.

Setting Break Conditions using Registry Keys

Applications can be forced to break on a message using the following registry keys.

EnableBreakOnMessage - This key enables breaking on messages (and causes InfoQueue's SetBreakOnCategory()/SetBreakOnSeverity()/SetBreakOnID() settings to be ignored). The actual messages to break on are defined using one or more BreakOn_* values defined below.

  • BreakOn_CATEGORY_* - Break on any message passing through the storage filters. * is one of the D3D10_MESSAGE_CATEGORY messages.
  • BreakOn_SEVERITY_* - Break on any message passing through the storage filters. * is one of the D3D10_MESSAGE_SEVERITY_ messages.
  • BreakOn_ID_* - Break on any message passing through the storage filters. * is one of the D3D10_MESSAGE_ID_ messages or can be the numerical value of the error enum. For example, Suppose the message with ID "D3D10_MESSAGE_ID_HYPOTHETICAL" had the value 123 in the D3D10_MESSAGE_ID enum. In this case, creating the value BreakOn_ID_HYPOTHETICAL=1 or BreakOn_ID_123=1 would both accomplish the same thing - break when a message having ID D3D10_MESSAGE_ID_HYPOTHETICAL is encountered.

Muting Debug Output using Registry Keys

Debug output can be muted using a MuteDebugOutput key. The presence of this value in the registry forces override of the InfoQueue's ID3D10InfoQueue::SetMuteDebugOutput method. MuteDebugOutput stops messages that pass the storage filter from being sent to debug output.

See Also

Core Interfaces


Reference Counting (Direct3D 10)

Direct3D10 pipeline Set functions do not hold a reference to the DeviceChild objects. This means that each application must hold a reference to the DeviceChild object for as long as the object needs to be bound to the pipeline. When the reference count of an object drops to zero, the object will be unbound from the pipeline and destroyed. This style of reference holding is also known as weak-reference holding because each pipeline binding location holds a weak reference to the interface/object that is bound to it.

For example:

pDevice->CreateRasterizerState( ..., &pRasterizerState );
pDevice->RSSetState( pRasterizerState );

pDevice->RSGetState( &pCurRasterizerState );
// pCurRasterizerState will be equal to pRasterizerState.
pCurRasterizerState->Release();

pRasterizerState->Release();
// Since app released the final ref on this object, it is unbound.
pDevice->GetRasterizerState( &pCurRasterizerState );
// pCurRasterizerState will be equal to NULL.

Differences between Direct3D 9 and Direct3D 10:

In Direct3D 9, pipeline Set functions hold a reference to the device's objects; in Direct3D10 pipeline Set functions do not hold a reference to the DeviceChild objects.


Pipeline Stages (Direct3D 10)

The Direct3D 10 programmable pipeline is designed for generating graphics for realtime gaming applications. The conceptual diagram below illustrates the data flow from input to output through each of the programmable stages.

Figure 1. Direct3D 10 Pipeline Stages

All of the stages are configurable via the Direct3D 10 API. Stages featuring common shader cores (the rounded rectangular blocks) are programmable using the HLSL programming language. As you will see, this makes the pipeline extremely flexible and adaptable. The purpose of each of the stages is listed below.

  • Input Assembler Stage - The input assembler stage is responsible for supplying data (triangles, lines and points) to the pipeline.
  • Vertex Shader Stage - The vertex shader stage processes vertices, typically performing operations such as transformations, skinning, and lighting. A vertex shader always takes a single input vertex and produces a single output vertex.
  • Geometry Shader Stage - The geometry shader processes entire primitives. Its input is a full primitive (which is three vertices for a triangle, two vertices for a line, or a single vertex for a point). In addition, each primitive can also include the vertex data for any edge-adjacent primitives. This could include at most an additional three vertices for a triangle or an additional two vertices for a line. The Geometry Shader also supports limited geometry amplification and de-amplification. Given an input primitive, the Geometry Shader can discard the primitive, or emit one or more new primitives.
  • Stream Output Stage - The stream output stage is designed for streaming primitive data from the pipeline to memory on its way to the rasterizer. Data can be streamed out and/or passed into the rasterizer. Data streamed out to memory can be recirculated back into the pipeline as input data or read-back from the CPU.
  • Rasterizer Stage - The rasterizer is responsible for clipping primitives, preparing primitives for the pixel shader and determining how to invoke pixel shaders.
  • Pixel Shader Stage - The pixel shader stage receives interpolated data for a primitive and generates per-pixel data such as color.
  • Output Merger Stage - The output merger stage is responsible for combining various types of output data (pixel shader values, depth and stencil information) with the contents of the render target and depth/stencil buffers to generate the final pipeline result.


Input-Assembler Stage (Direct3D 10)

The Direct3D 10 API separates functional areas of the pipeline into stages; the first stage in the pipeline is the input-assembler (IA) stage.

The purpose of the input-assembler stage is to read primitive data (points, lines and/or triangles) from user-filled buffers and assemble the data into primitives that will be used by the other pipeline stages. The IA stage can assemble vertices into several different primitive types (such as line lists, triangle strips, or primitives with adjacency). New primitive types (such as a line list with adjacency or a triangle list with adjacency) have been added to support the geometry shader.

While assembling primitives, a secondary purpose of the IA is to attach system-generated values to help make shaders more efficient. System-generated values are text strings that are also called semantics. All three shader stages are constructed from a common shader core, and the shader core uses system-generated values (such as a primitive id, an instance id, or a vertex id) so that a shader stage can reduce processing to only those primitives, instances, or vertices that have not already been processed.

As shown in the pipeline block diagram, once the IA stage reads data from memory (assembles the data into primitives and attaches system-generated values), the data is output to the vertex shader stage. Here are some other helpful links for programming the IA stage:

  • Getting Started with the Input-Assembler Stage (Direct3D 10) - covers the objects that you will need to generate to provide the input data, and tell the IA stage how to read the data.
  • Using System-Generated Values (Direct3D 10) - covers the Direct3D APIs for initializing the IA stage.

See Also

Pipeline Stages (Direct3D 10)


Getting Started with the Input-Assembler Stage (Direct3D 10)

There are a few steps necessary to initialize the input-assembler stage. For example, you need to create buffer resources with the vertex data that the pipeline needs, tell the IA stage where the buffers are and what type of data they contain, and specify the type of primitives to assemble from the data. Without getting into generation of system-level values yet, the basic steps involved in setting up the IA stage are covered in this topic:

  • Create Input Buffers - Create and initialize input buffers with input vertex data.
  • Create the Input-Layout Object - Define how the vertex buffer data will be streamed into the IA stage using an input-layout object.
  • Binding Objects to the Input-Assembler Stage - Bind the created objects (input buffers and the input-layout object) to the IA stage.
  • Specify the Primitive Type - Identify how the vertices will be assembled into primitives.
  • Draw APIs - Send the data bound to the IA stage through the pipeline.

After mastering these topics, move on to Using System-Generated Values (Direct3D 10).

Create Input Buffers

There are two types of input buffers: vertex buffers and index buffers. Vertex buffers supply vertex data to the IA stage. Index buffers are optional; they provide indices to vertices from the vertex buffer. You may create one or more vertex buffers, and optionally an index buffer. For help getting started creating these input resources, see the following guides:

  • Create a Vertex Buffer
  • Create an Index Buffer

Once the buffer resources are created, you need to create an input-layout object to describe the data layout to the IA stage, and then you need to bind the buffer resources to the IA stage.

Creating and binding buffers is not necessary if your shaders doesn't buffers. Here is an example of a simple vertex and pixel shader that draw a single triangle (Using the Input-Assembler Stage without Buffers (Direct3D 10)).

Create the Input-Layout Object

The input-layout object encapsulates the input state of the IA stage. This includes a description of the input data that is bound to the IA stage. The data is streamed into the IA stage from memory, from one or more vertex buffers. The description identifies the input data that is bound from one or more vertex buffers and gives the runtime the ability to type check the input data types against the shader input parameter types. This type checking not only verifies that the types are compatible, but also that each of the elements that the shader requires is available in the buffer resource(s).

An input-layout object is created from an array of input-element descriptions as well as a pointer to the compiled shader (see ID3D10Device::CreateInputLayout). The array contains one or more input elements; each input element describes a single vertex-data element from a single vertex buffer. The entire description describes all the vertex-data elements from all the vertex buffers that will be bound to the IA stage. For example, the following layout description describes a single vertex buffer that contains three vertex-data elements:

D3D10_INPUT_ELEMENT_DESC layout[] =
{
    { L"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
          D3D10_INPUT_PER_VERTEX_DATA, 0 },
    { L"TEXTURE0", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12,
          D3D10_INPUT_PER_VERTEX_DATA, 0 },
    { L"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 20,
          D3D10_INPUT_PER_VERTEX_DATA, 0 },
};

Each input-element description describes a single element of vertex-buffer data, including its size, type, location, and purpose. This declaration contains two elements, corresponding to two rows. Each row is enclosed in curly braces to make it easier to read. The first row or element declares per-vertex position data, the second row or element declares per-vertex color data.

Each row identifies the next element to be read from a vertex buffer. In each row, you can identify the type of data by using the semantic, the semantic index, and the data format. A semantic is a text string that identifies how the data will be used. In this example, the first row identifies 3-component position data (XYZ, for example); the second row identifies 2-component texture data (UV, for example); and the third row identifies 3-component color data (RGB, for example).

In this example description, the semantic index (which is the second parameter) is set to zero for all three rows. The semantic index helps distinguish between two rows that use the same semantics. Since there are no similar semantics in this example declaration, the semantic index can be set to its default value, zero.

The third parameter is the format. The format (see DXGI_FORMAT) specifies the number of components per element, and the data type, which defines the size of the data for each element. The format can be fully typed at resource creation time, or you may create a resource using a typeless format, which identifies the number of components in an element, but leaves the data type undefined.

Input Slots

Data enters the IA stage through inputs called input slots. The IA stage has n input slots, which are designed to accommodate up to n vertex buffers that provide input data. Each vertex buffer must be assigned to a different slot; this information is stored in the input-layout declaration when the input-layout object is created. Since the slots are zero-based, the first slot is slot 0. You may also specify an offset, from the start of each buffer to the first element in the buffer to be read.

Figure 1. Input-Asssembler Stage Input Slots

The next two parameters are the input slot and the input offset. The input slot is the number IA stage input. When you use multiple buffers, you can bind them to one or more input slots. The input offset is the number of bytes between the start of the buffer and the beginning of the data.

Reusing Input-Layout Objects

Each input-layout object is created based on a shader signature; this allows the API to validate the input-layout-object elements against the shader-input signature to make sure there is an exact match of types and semantics. You can create a single input-layout object for many shaders, as long as all the shader-input signatures exactly match.

Binding Objects to the Input-Assembler Stage

After creating vertex buffer resources and an input layout object, they can be bound to the IA stage by calling ID3D10Device::IASetVertexBuffers and ID3D10Device::IASetInputLayout. The following example shows the binding of a single vertex buffer and an input-layout object to the IA stage:

UINT stride = sizeof( SimpleVertex );
UINT offset = 0;
g_pd3dDevice->IASetVertexBuffers(
        0,                // the first input slot for binding
        1,                // the number of buffers in the array
        &g_pVertexBuffer, // the array of vertex buffers
        &stride,          // array of stride values, one for each buffer
        &offset );        // array of offset values, one for each buffer

// Set the input layout
g_pd3dDevice->IASetInputLayout( g_pVertexLayout );

Binding the input-layout object only requires a pointer to the object.

In the preceding example, a single vertex buffer was bound; however, multiple vertex buffers can be bound with a single call to ID3D10Device::IASetVertexBuffers, and the following code shows such a call to bind three vertex buffers:

UINT strides[3];
strides[0] = sizeof(SimpleVertex1);
strides[1] = sizeof(SimpleVertex2);
strides[2] = sizeof(SimpleVertex3);
UINT offsets[3] = { 0, 0, 0 };
g_pd3dDevice->IASetVertexBuffers(
        0,                 //first input slot for binding
        3,                 //number of buffers in the array
        &g_pVertexBuffers, //array of three vertex buffers
        &strides,          //array of stride values, one for each buffer
        &offsets );        //array of offset values, one for each buffer

An index buffer can be bound to the IA stage by calling ID3D10Device::IASetIndexBuffer.

Specify the Primitive Type

After the input buffers have been bound, the IA stage must also know how to assemble the vertices into primitives. This is done by specifying the primitive type with ID3D10Device::IASetPrimitiveTopology. The following code calls this function to define the data as a triangle list without adjacency:

g_pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

The rest of the primitive types are listed in D3D10_PRIMITIVE_TOPOLOGY.

Draw APIs

After input resources have been bound to the pipeline, an application calls a draw API to render primitives. There are several draw APIs, which are shown in the following table; some use index buffers, some use instance data, and some reuse data from the streaming-output stage as input to the input-assembler stage.

Draw API | Description
ID3D10Device::Draw | Draws non-indexed, non-instanced primitives.
ID3D10Device::DrawInstanced | Draws non-indexed, instanced primitives.
ID3D10Device::DrawIndexed | Draws indexed, non-instanced primitives.
ID3D10Device::DrawIndexedInstanced | Draws indexed, instanced primitives.
ID3D10Device::DrawAuto | Draws non-indexed, non-instanced primitives from input data that comes from the streaming-output stage.

See Also

Input-Assembler Stage (Direct3D 10)


Primitive Types (Direct3D 10)

The input-assembler stage reads data from vertex and index buffers, assembles the data into primitives, and then sends the data to the remaining pipeline stages. The IA uses three pieces of information to fully specify primitives: a vertex, a winding direction, and a leading vertex.

Symbol | Name | Description
 | Vertex | A point in 3D space.
 | Winding Direction | Indicates the vertex order when assembling a primitive. The winding direction can be either clockwise or counterclockwise; specify this to Direct3D by calling ID3D10Device::CreateRasterizerState.
 | Leading Vertex | The first vertex in a sequence of vertices.
n | Number of Vertices | The number of vertices in the assembled primitive.

The following diagram shows how these three pieces of information can be combined to assemble the primitive types supported by Direct3D.

Use ID3D10Device::IASetPrimitiveTopology to specify the primitive type of the data that will be streamed into the input-assembler stage.


Using the Input-Assembler Stage without Buffers (Direct3D 10)

Creating and binding buffers is not necessary if your shaders doesn't buffers. Here is an example of a simple vertex and pixel shader that draw a single triangle.

  • Vertex Shader
  • Pixel Shader Code
  • Technique
  • Application Code

Vertex Shader

For example, you could declare a vertex shader that creates its own vertices.

struct VSIn
{
    uint vertexId : SV_VertexID;
};

struct VSOut
{
    float4 pos : SV_Position;
    float4 color : color;
};

VSOut VSmain(VSIn input)
{
    VSOut output;

    if (input.vertexId == 0)
        output.pos = float4(0.0, 0.5, 0.5, 1.0);
    else if (input.vertexId == 2)
        output.pos = float4(0.5, -0.5, 0.5, 1.0);
    else if (input.vertexId == 1)
        output.pos = float4(-0.5, -0.5, 0.5, 1.0);

    output.color = clamp(output.pos, 0, 1);

    return output;
}

Pixel Shader Code

// NoBuffer.fx
// Copyright (c) 2004 Microsoft Corporation. All rights reserved.
//

struct PSIn
{
    float4 pos : SV_Position;
    linear float4 color : color;
};

struct PSOut
{
    float4 color : SV_Target;
};

PSOut PSmain(PSIn input)
{
    PSOut output;

    output.color = input.color;

    return output;
}

Technique

VertexShader vsCompiled = CompileShader( vs_4_0, VSmain() );

technique10 t0
{
    pass p0
    {
        SetVertexShader( vsCompiled );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_4_0, PSmain() ));
    }
}

Application Code

m_pD3D10Device->IASetInputLayout( NULL );

m_pD3D10Device->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

ID3D10EffectTechnique * pTech = NULL;
pTech = m_pEffect->GetTechniqueByIndex(0);
pTech->GetPassByIndex(iPass)->Apply(0);

m_pD3D10Device->Draw( 3, 0 );

See Also

Input-Assembler Stage (Direct3D 10)


Using System-Generated Values (Direct3D 10)

System-generated values are generated by the IA stage (based on user-supplied input semantics) to allow certain efficiencies in shader operations. By attaching data, such as an instance id (visible to VS), a vertex id (visible to VS), or a primitive id (visible to GS/PS), a subsequent shader stage may look for these system values to optimize processing in that stage. For instance, the VS stage may look for the instance id to grab additional per-vertex data for the shader or to perform other operations; the GS and PS stages may use the primitive id to grab per-primitive data in the same way.

  • VertexID
  • PrimitiveID
  • InstanceID
  • Example

VertexID

A VertexID is used by each shader stage to identify each vertex. It is a 32-bit unsigned integer whose default value is 0. It is assigned to a vertex when the primitive is processed by the IA stage. Attach the vertex-id semantic to the shader input declaration to inform the IA stage to generate a per-vertex id.

The IA will add a vertex id to each vertex for use by shader stages. For each draw call, the vertex id is incremented by 1. Across indexed draw calls, the count resets back to the start value. For DrawIndexed and DrawIndexedInstanced, the vertex id represents the index value. If the vertex id overflows (exceeds 232), it wraps to 0.

For all primitive types, vertices have a vertex id associated with them (regardless of adjacency).

PrimitiveID

A PrimitiveID is used by each shader stage to identify each primitive. It is a 32-bit unsigned integer whose default value is 0. It is assigned to a primitive when the primitive is processed by the IA stage. To inform the IA stage to generate a primitive id, attach the primitive-id semantic to the shader input declaration.

The IA stage will add a primitive id to each primitive for use by the geometry shader or the pixel shader stage (whichever is the first stage active after the IA stage). For each indexed draw call, the primitive id is incremented by 1, however, the primitive id resets to 0 whenever a new instance begins. All other draw calls do not change the value of the instance id. If the instance id overflows (exceeds 232), it wraps to 0.

The pixel shader stage does not have a separate input for a primitive id; however, any pixel shader input that specifies a primitive id uses a constant interpolation mode.

There is no support for automatically generating a primitive id for adjacent primitives. For primitive types with adjacency, such as a triangle strip with adjacency, a primitive id is only maintained for the interior primitives (the non-adjacent primitives), just like the set of primitives in a triangle strip without adjacency.

InstanceID

An InstanceID is used by each shader stage to identify the instance of the geometry that is currently being processed. It is a 32-bit unsigned integer whose default value is 0.

The IA stage will add an instance id to each vertex if the vertex shader input declaration includes the instance id semantic. For each indexed draw call, instance id is incremented by 1. All other draw calls do not change the value of instance id. If instance id overflows (exceeds 232), it wraps to 0.

Example

The following example shows how system values are attached to an instanced triangle strip in the IA stage.

Figure 1. Generating System Values for Two Instances of a Triangle Strip

These tables show the system values generated for both instances of the same triangle strip. The first instance (instance U) is shown in blue, the second instance (instance V) is shown in green. The solid lines connect the vertices in the primitives, the dashed lines connect the adjacent vertices.

The following tables show the system-generated values for the instance U.

Vertex Data | C,U | D,U | E,U | F,U | G,U | H,U | I,U | J,U | K,U | L,U
VertexID | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
InstanceID | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
PrimitiveID | 0 | 1 | 2
InstanceID | 0 | 0 | 0

The following tables show the system-generated values for the instance V.

Vertex Data | C,V | D,V | E,V | F,V | G,V | H,V | I,V | J,V | K,V | L,V
VertexID | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
InstanceID | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1
PrimitiveID | 0 | 1 | 2
InstanceID | 1 | 1 | 1

The input assembler generates the each of the ids (vertex, primitive, and instance). Notice also that each instance is given a unique instance id. The data ends with the strip cut, which separates each instance of the triangle strip.

See Also

Input-Assembler Stage (Direct3D 10)


Shader Stages (Direct3D 10)

The Direct3D 10 pipeline contains 3 programmable-shader stages (shown as the rounded blocks in the pipeline functional diagram):

  • Vertex-Shader Stage
  • Geometry-Shader Stage
  • Pixel-Shader Stage

Each shader stage exposes its own unique functionality, built on the shader model 4.0 common shader core.

Vertex-Shader Stage

The vertex-shader (VS) stage processes vertices from the input assembler, performing per-vertex operations such as transformations, skinning, morphing, and per-vertex lighting. Vertex shaders always operate on a single input vertex and produce a single output vertex. The vertex shader stage must always be active for the pipeline to execute. If no vertex modification or transformation is required, a pass-through vertex shader must be created and set to the pipeline.

Each vertex shader input vertex can be comprised of up to 16 32-bit vectors (up to 4 components each) and each output vertex can be comprised of as many as 16 32-bit 4-component vectors. All vertex shaders must have a minimum of one input and one output, which can be as little as one scalar value.

The vertex-shader stage can consume two system generated values from the input assembler: VertexID and InstanceID (see System Values and Semantics). Since VertexID and InstanceID are both meaningful at a vertex level, and IDs generated by hardware can only be fed into the first stage that understands them, these ID values can only be fed into the vertex-shader stage.

Vertex shaders are always run on all vertices, including adjacent vertices in input primitive topologies with adjacency. The number of times that the vertex shader has been executed can be queried from the CPU using the VSInvocations pipeline statistic.

A vertex shader can perform load and texture sampling operations where screen-space derivatives are not required (using HLSL intrinsic functions samplelevel, samplecmplevelzero, samplegrad).

Geometry-Shader Stage

The geometry-shader (GS) stage runs application-specified shader code with vertices as input and the ability to generate vertices on output. Unlike vertex shaders, which operate on a single vertex, the geometry shader's inputs are the vertices for a full primitive (two vertices for lines, three vertices for triangles, or single vertex for point). Geometry shaders can also bring in the vertex data for the edge-adjacent primitives as input (an additional two vertices for a line, an additional three for a triangle). The image below shows a triangle and a line with adjacent vertices.

TV | Triangle vertex
AV | Adjacent vertex
LV | Line vertex

The geometry-shader stage can consume the SV_PrimitiveID system-generated value that is auto-generated by the IA. This allows per-primitive data to be fetched or computed if desired.

The geometry-shader stage is capable of outputting multiple vertices forming a single selected topology (GS stage output topologies available are: tristrip, linestrip, and pointlist). The number of primitives emitted can vary freely within any invocation of the geometry shader, though the maximum number of vertices that could be emitted must be declared statically. Strip lengths emitted from a geometry shader invocation can be arbitrary, and new strips can be created via the RestartStrip HLSL intrinsic function.

Geometry shader output may be fed to the rasterizer stage and/or to a vertex buffer in memory via the stream output stage. Output fed to memory is expanded to individual point/line/triangle lists (exactly as they would be passed to the rasterizer).

When a geometry shader is active, it is invoked once for every primitive passed down or generated earlier in the pipeline. Each invocation of the geometry shader sees as input the data for the invoking primitive, whether that is a single point, a single line, or a single triangle. A triangle strip from earlier in the pipeline would result in an invocation of the geometry shader for each individual triangle in the strip (as if the strip were expanded out into a triangle list). All the input data for each vertex in the individual primitive is available (i.e. 3 vertices for triangle), plus adjacent vertex data if applicable/available.

A geometry shader outputs data one vertex at a time by appending vertices to an output stream object. The topology of the streams is determined by a fixed declaration, choosing one of: PointStream, LineStream, or TriangleStream as the output for the GS stage. There are three types of stream objects available, PointStream, LineStream and TriangleStream which are all templated objects. The topology of the output is determined by their respective object type, while the format of the vertices appended to the stream is determined by the template type. Execution of a geometry shader instance is atomic from other invocations, except that data added to the streams is serial. The outputs of a given invocation of a geometry shader are independent of other invocations (though ordering is respected). A geometry shader generating triangle strips will start a new strip on every invocation.

When a geometry shader output is identified as a System Interpreted Value (e.g. SV_RenderTargetArrayIndex or SV_Position), hardware looks at this data and performs some behavior dependent on the value, in addition to being able to pass the data itself to the next shader stage for input. When such data output from the geometry shader has meaning to the hardware on a per-primitive basis (such as SV_RenderTargetArrayIndex or SV_ViewportArrayIndex), rather than on a per-vertex basis (such as SV_ClipDistance[n] or SV_Position), the per-primitive data is taken from the leading vertex emitted for the primitive.

Partially completed primitives could be generated by the geometry shader if the geometry shader ends and the primitive is incomplete. Incomplete primitives are silently discarded. This is similar to the way the IA treats partially completed primitives.

The geometry shader can perform load and texture sampling operations where screen-space derivatives are not required (samplelevel, samplecmplevelzero, samplegrad).

Algorithms that can be implemented in the geometry shader include:

  • Point Sprite Expansion
  • Dynamic Particle Systems
  • Fur/Fin Generation
  • Shadow Volume Generation
  • Single Pass Render-to-Cubemap
  • Per-Primitive Material Swapping
  • Per-Primitive Material Setup - Including generation of barycentric coordinates as primitive data so that a pixel shader can perform custom attribute interpolation (for an example of higher-order normal interpolation, see CubeMapGS Sample).

Pixel-Shader Stage

The pixel-shader (PS) stage is invoked by the rasterizer stage, to calculate a per-pixel value for each pixel in a primitive that gets rendered. A pixel shader enables rich shading techniques such as per-pixel lighting and post-processing. A pixel shader is a program that combines constant variables, texture values, interpolated per-vertex values, and other data to produce per-pixel outputs. The stage preceding the rasterizer stage (GS stage or the VS stage if the geometry shader is NULL) must output vertex positions in homogenous clip space.

A pixel shader can input up to 32 32-bit 4-component data for the current pixel location. It is only when the geometry shader is active that all 32 inputs can be fed with data from above in the pipeline. In the absence of the geometry shader, only up to 16 4-component elements of data can be input from upstream in the pipeline.

Input data available to the pixel shader includes vertex attributes that can be chosen, on a per-element basis, to be interpolated with or without perspective correction, or be treated as per-primitive constants. In addition, declarations in a pixel shader can indicate which attributes to apply centroid evaluation rules to. Centroid evaluation is relevant only when multisampling is enabled, since cases arise where the pixel center may not be covered by the primitive (though subpixel center(s) are covered, hence causing the pixel shader to run once for the pixel). Attributes declared with centroid mode must be evaluated at a location covered by the primitive, preferably at a location as close as possible to the (non-covered) pixel center.

A pixel shader can output up to 8 32-bit 4-component data for the current pixel location to be combined with the render target(s), or no color (if the pixel is discarded). A pixel shader can also output an optional 32-bit float scalar depth value for the depth test (SV_Depth).

For each primitive entering the rasterizer, the pixel shader is invoked once for each pixel covered by the primitive. When multisampling, the pixel shader is invoked once per covered pixel, though depth/stencil tests occur for each covered multisample, and multisamples that pass the tests are updated with the pixel shader output color(s).

If there is no geometry shader, the IA stage is capable of producing one scalar per-primitive system-generated value to the pixel shader, the SV_PrimitiveID, which can be read as input to the pixel shader. The pixel shader can also retrieve the the SV_IsFrontFace value, generated by the rasterizer stage.

One of the inputs to the pixel shader can be declared with the name SV_Position, which means it will be initialized with the pixel's float32 xyzw position. Note that w is the reciprocal of the linearly interpolated 1/w value. When the rendertarget is a multisample buffer or a standard rendertarget, the xy components of position contain pixel center coordinates (which have a fraction of 0.5f).

The pixel shader intrinsic functions produce or use derivatives of quantities with respect to screen space x and y. The most common use for derivatives is to compute level-of-detail calculations for texture sampling and in the case of anisotropic filtering, selecting samples along the axis of anisotropy. Typically, hardware implementations run a pixel shader on multiple pixels (for example a 2x2 grid) simultaneously, so that derivatives of quantities computed in the pixel shader can be reasonably approximated as deltas of the values at the same point of execution in adjacent pixels.


Stream-Output Stage (Direct3D 10)

The stream-output stage (SO) is located in the pipeline right after the geometry-shader stage and just before the rasterization stage.

Figure 1. Stream-Output Stage

The purpose of the SO stage is to write vertex data streamed out of the GS stage (or the VS stage if the GS stage is inactive) to one or more buffer resources in memory. Data streamed out to memory can be read back into the pipeline in a subsequent rendering pass, or can be copied to a staging resource for readback to the CPU. Since variable amounts of data can be generated by a geometry shader, the amount of data streamed out can vary. The ID3D10Device::DrawAuto API allows this variable amount of data to be processed in a subsequent pass without the need to query (the GPU) about the amount of data written to stream output.

When primitive types with adjacency are used as inputs to the geometry shader, the adjacent vertices are discarded and not streamed out.

When a triangle or line strip is bound to the input assembler, the strips are always converted into lists before they are streamed out. Vertices are always written out as complete primitives (e.g. 3 vertices at a time for triangles); incomplete primitives are never streamed out.

There are two primary ways streaming-output data can be fed back into the pipeline. One is to generate data that can be fed back into the input assembler, and the other is to generate data that can be read into shaders using load functions. If only one buffer is bound, the buffer can capture up to 64 scalar components of per-vertex data, as long as the total amount of data being output per-vertex is 256 bytes or less. Vertex stride can be up to 2048 bytes. If more than one buffer is bound, each can only capture a single element of per-vertex data. Stream output can write to up to 4 buffers simultaneously. If multiple buffers are bound and have different sizes, as soon as one of the buffers can no longer hold any more complete primitives, writing to all buffers is stopped.


Getting Started with the Stream-Output Stage (Direct3D 10)

These are the steps required to initialize and execute the stream output stage:

  • Compile a Geometry Shader
  • Create a Geometry-Shader Object with Stream Output
  • Set the Output Targets

Compile a Geometry Shader

Given the following geometry shader (from Tutorial13):

struct GSPS_INPUT
{
    float4 Pos : SV_POSITION;
    float3 Norm : TEXCOORD0;
    float2 Tex : TEXCOORD1;
};

[maxvertexcount(3)]
void GS( triangle GSPS_INPUT input[3], inout TriangleStream<GSPS_INPUT> TriStream )
{
    GSPS_INPUT output;

    //
    // Calculate the face normal
    //
    float3 faceEdgeA = input[1].Pos - input[0].Pos;
    float3 faceEdgeB = input[2].Pos - input[0].Pos;
    float3 faceNormal = normalize( cross(faceEdgeA, faceEdgeB) );

    for( int v=0; v<3; v++ )
    {
        output.Pos = input[v].Pos + float4(faceNormal*Explode,0);
        output.Pos = mul( output.Pos, View );
        output.Pos = mul( output.Pos, Projection );

        output.Norm = input[v].Norm;

        output.Tex = input[v].Tex;

        TriStream.Append( output );
    }

    TriStream.RestartStrip();
}

This shader calculates a face normal for each triangle, and outputs position, normal and texture coordinate data. A geometry shader looks just like a vertex or pixel shader, with the following exceptions:

  • GS function return type - The function return type does one thing, declares the maximum number of vertices that can be output by the shader. In this case,
    maxvertexcount[3]
    defines the output to be a maximum of 3 vertices.
  • GS input parameter declarations - This function takes two input parameters:
    triangle GSPS_INPUT input[3] , inout TriangleStream<GSPS_INPUT> TriStream

    The first parameter is an array of vertices (3 in this case) defined by a GSPS_INPUT structure (which defines per-vertex data as a position, a normal and a texture coordinate). The first parameter also uses the triangle keyword, which means the input assembler stage must output data to the geometry shader as one of the triangle primitive types (triangle list or triangle strip).

    The second parameter is a triangle stream defined by the type TriangleStream<GSPS_INPUT>. This means the parameter is an array of triangles, each of which is made up of three vertices (that contain the data from the members of GSPS_INPUT).

    Use the triangle and trianglestream keywords to identify individual triangles or a stream of triangles in a GS.

  • GS intrinsic function - The lines of code in the shader function use common-shader-core HLSL intrinsic functions except the last two lines, which call Append and RestartStrip. These functions are only available to a geometry shader. Append informs the geometry shader to append the output to the current strip; RestartStrip creates a new primitive strip. A new strip is implicitly created in every invocation of the GS stage.

The rest of the shader looks very similar to a vertex or pixel shader. The geometry shader uses a structure to declare input parameters and marks the position member with the SV_POSITION semantic to tell the hardware that this is position data. The input structure identifies the other two input parameters as texture coordinates (even though one of them will contain a face normal). You could use your own custom semantic for the face normal if you prefer.

Having designed the geometry shader, call D3D10CompileShader to compile it like this:

DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
ID3D10Blob** ppShader;

D3D10CompileShader( pSrcData, sizeof( pSrcData ),
  "Tutorial13.fx", NULL, NULL, "GS", "gs_4_0",
  dwShaderFlags, &ppShader, NULL );

Just like vertex and pixel shaders, you will need a shader flag to tell the compiler how you want the shader compiled (for debugging, optimized for speed etc...), the entry point function, and the shader model to validate against. This example creates a geometry shader built from the Tutorial13.fx file, by using the GS function. The shader is compiled for shader model 4.0.

Create a Geometry-Shader Object with Stream Output

Once you know that you will be streaming the data from the geometry, and you have successfully compiled the shader, the next step is to call ID3D10Device::CreateGeometryShaderWithStreamOutput to create the geometry shader object.

But first, you need to declare the SO stage input signature. This signature matches or validates the GS outputs and the SO inputs at object creation time. Here's an example of the SO declaration:

D3D10_STREAM_OUTPUT_DECLARATION_ENTRY pDecl[] =
{
    // semantic name, semantic index, start component, component count, output slot
    { L"SV_POSITION", 0, 0, 4, 0 },   // output all components of position
    { L"TEXCOORD0", 0, 0, 3, 0 },     // output the first 3 of the normal
    { L"TEXCOORD1", 0, 0, 2, 0 },     // output the first 2 texture coordinates
};

    D3D10Device->CreateGeometryShaderWithStreamOut( pShaderBytecode, pDecl, 3,
        sizeof(pDecl), &pGS );

This function takes several parameters including:

  • A pointer to the compiled geometry shader (or vertex shader if no geometry shader will be present and data will be streamed out directly from the VS). To get this pointer see Getting a Pointer to a Compiled Shader.
  • A pointer to an array of declarations that describe the input data for the stream output stage. See D3D10_SO_DECLARATION_ENTRY. You can supply up to 64 declarations, one for each different type of element to be output from the SO stage. The array of declaration entries describes the data layout regardless of whether only a single Buffer or multiple buffers are to be bound for stream output.
  • The number of elements that are written out by the SO stage.
  • A pointer to the geometry shader object created (see ID3D10GeometryShader Interface).

The stream output declaration defines the way data is written to a buffer resource. You can add as many components as you want to the output declaration. Use the SO stage to write to a single buffer resource or many buffer resources. For a single buffer, the SO stage can write many different elements per-vertex. For multiple buffers, the SO stage can only write a single element of per-vertex data to each buffer.

To use the SO stage without using a geometry shader, call ID3D10Device::CreateGeometryShaderWithStreamOutput and pass NULL in the pShaderBytecode parameter.

Set the Output Targets

The last step is to set the SO stage buffers. Data can be streamed out into one or more buffers in memory for use later. This example shows how to create a single buffer that can be used for vertex data as well as for the SO stage to stream data into:

    ID3D10Buffer *m_pBuffer;
    int m_nBufferSize = 1000000;

    D3D10_BUFFER_DESC bufferDesc =
    {
        m_nBufferSize,
        D3D10_USAGE_DEFAULT,
        D3D10_BIND_STREAM_OUTPUT,
        0,
        0
    };
    D3D10Device->CreateBuffer( &bufferDesc, NULL, &m_pBuffer );

Create a buffer by calling ID3D10Device::CreateBuffer. This example illustrates default usage which is typical for a buffer resource that is expected to be updated fairly frequently by the CPU. The binding flag identifies the pipeline stage that the resource can be bound to. Any resource used by the SO stage must also be created with the D3D10_BIND_STREAM_OUTPUT bind flag.

Once the buffer is successfully created, set it to the current device by calling ID3D10Device::SOSetTargets:

    UINT offset[1] = 0;

    D3D10Device->SOSetTargets( 1, &m_pBuffer, offset );

This call takes the number of buffers, a pointer to the buffers, and an array of offsets (one offset into each of the buffers that indicates where to begin writing data). Data will be written to these streaming-output buffers when a Draw command is issued. An internal variable keeps track of the position for where to begin writing data to the streaming-output buffers, and that variables will continue to increment until SOSetTargets is called again and a new offset value is specified.

All data written out to the target buffers will be 32-bit values.


Rasterizer Stage (Direct3D 10)

This stage rasterizes primitives into pixels, interpolating specified vertex values across the primitive. To do so, the stage clips vertices to the view frustum, sets up the primitives for mapping to the 2D viewport, and determines how to invoke the pixel shader, if one is currently set to the pipeline. Some of these features are optional (like pixel shaders), however, the rasterizer always performs clipping, a perspective divide to transform the points into homogenous space, and maps the vertices to the viewport.

Vertices (x,y,z,w), coming into the rasterizer stage are assumed to be in homogenous clip-space. In this coordinate space the X axis points right, Y points up and Z points away from camera.

You may disable rasterization by telling the pipeline there is no pixel shader (set the pixel shader stage to NULL with ID3D10Device::PSSetShader), and disabling depth and stencil testing (set DepthEnable and StencilEnable to FALSE in D3D10_DEPTH_STENCIL_DESC). While disabled, rasterization-related pipeline counters will not update.

On hardware that implements hierarchical Z-buffer optimizations, you may enable preloading the z-buffer by setting the pixel shader stage to NULL while enabling depth and stencil testing.


Getting Started with the Rasterizer Stage (Direct3D 10)

The rasterizer stage is controlled with the following features:

  • Set the Viewport
  • Set the Scissor Rectangle
  • Set Rasterizer State

Set the Viewport

A viewport maps vertex positions (in clip space) into render target positions. This step scales the 3D positions into 2D space. A render target is oriented with the Y axes pointing down; this requires that the Y coordinates get flipped during the viewport scale. In addition, the x and y extents (range of the x and y values) are scaled to fit the viewport size according to the following formulas:

X = (X + 1) × Viewport.Width × 0.5 + Viewport.TopLeftX
Y = (1 - Y) × Viewport.Height × 0.5 + Viewport.TopLeftY
Z = Viewport.MinDepth + Z * (Viewport.MaxDepth - Viewport.MinDepth)

Tutorial 1 creates a 640 × 480 viewport using D3D10_VIEWPORT and by calling ID3D10Device::RSSetViewports.

    D3D10_VIEWPORT vp[1];
    vp[1].Width = 640.0f;
    vp[1].Height = 480.0f;
    vp[1].MinDepth = 0;
    vp[1].MaxDepth = 1;
    vp[1].TopLeftX = 0;
    vp[1].TopLeftY = 0;
    g_pd3dDevice->RSSetViewports( 1, vp );

The viewport description specifies the size of the viewport, the range to map depth to (using MinDepth and MaxDepth), and the placement of the top left of the viewport. MinDepth must be less than or equal to MaxDepth; the range for both MinDepth and MaxDepth is between 0.0 and 1.0, inclusive. It is common for the viewport to map to a render target but it is not necessary; additionally, the viewport does not have to have the same size or position as the render target.

You can create an array of viewports, but only one can be applied to a primitive output from the geometry shader. Only one viewport can be set active at a time. The pipeline uses a default viewport (and scissor rectangle, discussed in the next section) during rasterization. The default is always the first viewport (or scissor rectangle) in the array. To perform a per-primitive selection of the viewport in the geometry shader, specify the ViewportArrayIndex semantic on the appropriate GS output component in the GS output signature declaration.

The maximum number of viewports (and scissorrects) that can be bound to the rasterizer stage at any one time is 16 (specified with #define by D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE).

Set the Scissor Rectangle

A scissor rectangle gives you another opportunity to reduce the number of pixels that will be sent to the output merger stage. Pixels outside of the scissor rectangle are discarded. Only one scissor rectangle at a time can be set to active in the geometry shader. The size of the scissor rectangle is specified in integers.

To enable the scissor rectangle, use the ScissorEnable member (in D3D10_RASTERIZER_DESC). The default scissor rectangle is an empty rectangle; that is, all rect values are 0. In other words, if you do not set up the scissor rectangle and scissor is enabled, you will not send any pixels to the output-merger stage. The most common setup is to initialize the scissor rectangle to the size of the viewport.

To set an array of scissor rectangles to the device, call ID3D10Device::RSSetScissorRects with D3D10_RECT.xml.

D3D10_RECT rects[1];
  rects[0].left = 0;
  rects[0].right = 640;
  rects[0].top = 0;
  rects[0].bottom = 480;

  D3DDevice->RSSetScissorRects( 1, rects );

This method takes two parameters: (1) the number of rectangles in the array and (2) an array of rectangles.

The pipeline uses a default scissor rectangle index during rasterization (the default is a zero-size rectangle with clipping disabled). To override this, specify the SV_ViewportArrayIndex semantic to a GS output component in the GS output signature declaration. This will cause the GS stage to mark this GS output component as a system-generated component with this semantic. The rasterizer stage recognizes this semantic and will use the parameter it is attached to as the scissor rectangle index to access the array of scissor rectangles. Don't forget to tell the rasterizer stage to use the scissor rectangle that you define by enabling the ScissorEnable value in the rasterizer description before creating the rasterizer object.

Set Rasterizer State

In Direct3D 10, rasterizer state is encapsulated in a rasterizer state object. You may create up to 4096 rasterizer state objects which can then be set to the device by passing a handle to the state object.

Use ID3D10Device::CreateRasterizerState to create a rasterizer state object.

    ID3D10RasterizerState * g_pRasterState;

    D3D10_RASTERIZER_DESC rasterizerState;
    rasterizerState.FillMode = D3D10_FILL_SOLID;
    rasterizerState.CullMode = D3D10_CULL_FRONT;
    rasterizerState.FrontCounterClockwise = true;
    rasterizerState.DepthBias = false;
    rasterizerState.DepthBiasClamp = 0;
    rasterizerState.SlopeScaledDepthBias = 0;
    rasterizerState.DepthClipEnable = true;
    rasterizerState.ScissorEnable = true;
    rasterizerState.MultisampleEnable = false;
    rasterizerState.AntialiasedLineEnable = false;
    pd3dDevice->CreateRasterizerState( &rasterizerState, &g_pRasterState );

This example set of state accomplishes perhaps the most basic rasterizer setup:

  • Solid fill mode
  • Cull out — that is, remove back faces; assume counter-clockwise winding order for primitives
  • Turn off depth bias but enable depth buffering and enable the scissor rectangle
  • Turn off multisampling and line antialiasing

In addition, basic rasterizer operations, always include the following: clipping (to the view frustum), perspective divide, and the viewport Scale. After successfully creating the rasterizer state object, set it to the device like this:

    pd3dDevice->RSSetState(g_pRasterState);


Output-Merger Stage (Direct3D 10)

The output-merger (OM) stage generates the final rendered pixel color using a combination of pipeline state, the pixel data generated by the pixel shaders, the contents of the render targets, and the contents of the depth/stencil buffers. The OM stage is the final step for determining which pixels are visible (with depth-stencil testing) and blending the final pixel colors.

  • Depth-Stencil Testing
  • Blending

Depth-Stencil Testing

A depth-stencil buffer, which is created as a texture resource, can contain both depth data and stencil data. The depth data is used to determine which pixels lie closest to the camera, and the stencil data is used to mask which pixels can be updated. Ultimately, both the depth and stencil values data are used by the output-merger stage to determine if a pixel should be drawn or not. This flow chart shows conceptually how depth-stencil testing is done.

Figure 1. Depth-Stencil Testing Block Diagram

To configure depth-stencil testing, see Configuring Depth-Stencil Functionality (Direct3D 10). A depth-stencil object encapsulates depth-stencil state. An application can specify depth-stencil state, or the OM stage will use default values. Blending operations are performed on a per-pixel basis if multisampling is disabled. If multisampling is enabled, blending occurs on a per-multisample basis.

The process of using the depth buffer to determine which pixel should be drawn is called depth buffering, also sometimes called z-buffering.

Blending

Blending combines one or more pixel values to create a final pixel color. The following conceptual diagram describes the process involved in blending pixel data.

Figure 2. Blending Block Diagram

Conceptually, you can visualize this flow chart implemented twice in the output-merger stage: the first one blends RGB data, while in parallel, a second one blends alpha data. To see how to use the API to create and set blend state, see Configuring Blending Functionality (Direct3D 10).


Configuring Depth-Stencil Functionality (Direct3D 10)

This section covers the steps for setting up the depth-stencil buffer, and depth-stencil state for the output-merger stage.

  • Create a Depth-Stencil Resource
  • Create Depth-Stencil State
  • Bind Depth-Stencil Data to the OM Stage

Once you know how to use the depth-stencil buffer and the corresponding depth-stencil state, refer to advanced stencil techniques.

Create a Depth-Stencil Resource

Create the depth-stencil buffer using a texture resource.

ID3D10Texture2D* pDepthStencil = NULL;
D3D10_TEXTURE2D_DESC descDepth;
descDepth.Width = backBufferSurfaceDesc.Width;
descDepth.Height = backBufferSurfaceDesc.Height;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = pDeviceSettings->d3d10.AutoDepthStencilFormat;
descDepth.SampleDesc.Count = 1;
descDepth.SampleDesc.Quality = 0;
descDepth.Usage = D3D10_USAGE_DEFAULT;
descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL;
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;
hr = pd3dDevice->CreateTexture2D( &descDepth,       // Texture desc
                                  NULL,                  // Initial data
                                  &pDepthStencil ); // [out] Texture

Create Depth-Stencil State

The depth-stencil state tells the output-merger stage how to perform the depth-stencil test. The depth-stencil test determines whether or not a given pixel should be drawn.

D3D10_DEPTH_STENCIL_DESC dsDesc;

// Depth test parameters
dsDesc.DepthEnable = true;
dsDesc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
dsDesc.DepthFunc = D3D10_COMPARISON_LESS;

// Stencil test parameters
dsDesc.StencilEnable = true;
dsDesc.StencilReadMask = 0xFFFFFFFF;
dsDesc.StencilWriteMask = 0xFFFFFFFF;

// Stencil operations if pixel is front-facing
dsDesc.FrontFace.StencilFailOp = D3D10_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilDepthFailOp = D3D10_STENCIL_OP_INCR;
dsDesc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;

// Stencil operations if pixel is back-facing
dsDesc.BackFace.StencilFailOp = D3D10_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilDepthFailOp = D3D10_STENCIL_OP_DECR;
dsDesc.BackFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilFunc = D3D10_COMPARISON_ALWAYS;

// Create depth stencil state
ID3D10DepthStencilState * pDSState;
pDevice->CreateDepthStencilState(dsDesc, &pDSState);

Bind Depth-Stencil Data to the OM Stage

Bind the depth-stencil state.

// Bind depth stencil state
pDevice->OMSetDepthStencilState(pDSState, 1);

Bind the depth-stencil resource using a view.

D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;
descDSV.Format = DXGI_FORMAT_D32_FLOAT;
descDSV.ResourceType = D3D10_RESOURCE_TEXTURE2D;
descDSV.Texture2D.FirstArraySlice = 0;
descDSV.Texture2D.ArraySize = 1;
descDSV.Texture2D.MipSlice = 0;

// Create the depth stencil view
ID3D10DepthStencilView* pDSV;
hr = pd3dDevice->CreateDepthStencilView( pDepthStencil, // Depth stencil texture
                                         &descDSV, // Depth stencil desc
                                         &pDSV );  // [out] Depth stencil view

// Bind the depth stencil view
pd3dDevice->OMSetRenderTargets( 1,          // One rendertarget view
                                &pRTV,      // Render target view, created earlier
                                pDSV );     // Depth stencil view for the render target

An array of rendertarget views may be passed into ID3D10Device::OMSetRenderTargets, however all of those rendertarget views will correspond to a single depth stencil view.

Rendertargets must all be the same type of resource. If multisample antialiasing is used, all bound rendertargets and depth buffers must be have the same sample counts.

When a buffer is used as a rendertarget, depth-stencil testing and multiple rendertargets are not supported.

  • As many as 8 render targets can be bound simultaneously.
  • All rendertargets must have the same size in all dimensions (width and height, and depth for 3D or array size for *Array types).
  • Each rendertarget may have a different data format.
  • Write masks control what data gets written to a rendertarget. The output write masks control on a per-rendertarget, per-component level what data gets written to the rendertarget(s).

Advanced Stencil Techniques

The stencil portion of the depth-stencil buffer can be used for creating rendering effects such as compositing, decaling, and outlining.

  • Compositing
  • Decaling
  • Outlines and Silhouettes
  • Two-Sided Stencil

Compositing

Your application can use the stencil buffer to composite 2D or 3D images onto a 3D scene. A mask in the stencil buffer is used to occlude an area of the rendering target surface. Stored 2D information, such as text or bitmaps, can then be written to the occluded area. Alternately, your application can render additional 3D primitives to the stencil-masked region of the rendering target surface. It can even render an entire scene.

Games often composite multiple 3D scenes together. For instance, driving games typically display a rear-view mirror. The mirror contains the view of the 3D scene behind the driver. It is essentially a second 3D scene composited with the driver's forward view.

Decaling

Direct3D applications use decaling to control which pixels from a particular primitive image are drawn to the rendering target surface. Applications apply decals to the images of primitives to enable coplanar polygons to render correctly.

For instance, when applying tire marks and yellow lines to a roadway, the markings should appear directly on top of the road. However, the z values of the markings and the road are the same. Therefore, the depth buffer might not produce a clean separation between the two. Some pixels in the back primitive may be rendered on top of the front primitive and vice versa. The resulting image appears to shimmer from frame to frame. This effect is called z-fighting or flimmering.

To solve this problem, use a stencil to mask the section of the back primitive where the decal will appear. Turn off z-buffering and render the image of the front primitive into the masked-off area of the render-target surface.

Multiple texture blending can be used to solve this problem.

Outlines and Silhouettes

You can use the stencil buffer for more abstract effects, such as outlining and silhouetting.

If your application does two render passes - one to generate the stencil mask and second to apply the stencil mask to the image, but with the primitives slightly smaller on the second pass - the resulting image will contain only the primitive's outline. The application can then fill the stencil-masked area of the image with a solid color, giving the primitive an embossed look.

If the stencil mask is the same size and shape as the primitive you are rendering, the resulting image contains a hole where the primitive should be. Your application can then fill the hole with black to produce a silhouette of the primitive.

Two-Sided Stencil

Shadow Volumes are used for drawing shadows with the stencil buffer. The application computes the shadow volumes cast by occluding geometry, by computing the silhouette edges and extruding them away from the light into a set of 3D volumes. These volumes are then rendered twice into the stencil buffer.

The first render draws forward-facing polygons, and increments the stencil-buffer values. The second render draws the back-facing polygons of the shadow volume, and decrements the stencil buffer values. Normally, all incremented and decremented values cancel each other out. However, the scene was already rendered with normal geometry causing some pixels to fail the z-buffer test as the shadow volume is rendered. Values left in the stencil buffer correspond to pixels that are in the shadow. These remaining stencil-buffer contents are used as a mask, to alpha-blend a large, all-encompassing black quad into the scene. With the stencil buffer acting as a mask, the result is to darken pixels that are in the shadows.

This means that the shadow geometry is drawn twice per light source, hence putting pressure on the vertex throughput of the GPU. The two-sided stencil feature has been designed to mitigate this situation. In this approach, there are two sets of stencil state (named below), one set each for the front-facing triangles and the other for the back-facing triangles. This way, only a single pass is drawn per shadow volume, per light.

An example of two-sided stencil implementation can be found in the ShadowVolume10 Sample.


Configuring Blending Functionality (Direct3D 10)

Blending operations are performed on every pixel shader output (RGBA value) before the output value is written to a render target. If multisampling is enabled, blending is done on each multisample; otherwise, blending is performed on each pixel.

  • Create the Blend State
  • Bind the Blend State

Create the Blend State

The blend state is a collection of states used to control blending. These states (defined in D3D10_BLEND_DESC) are used to create the blend state object by calling ID3D10Device::CreateBlendState.

For instance, here is a very simple example of blend-state creation that disables alpha blending and uses no per-component pixel masking.

ID3D10BlendState* g_pBlendStateNoBlend = NULL;

D3D10_BLEND_DESC BlendState;
ZeroMemory(&BlendState, sizeof(D3D10_BLEND_DESC));
BlendState.BlendEnable[0] = FALSE;
BlendState.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
pd3dDevice->CreateBlendState(&BlendState, &g_pBlendStateNoBlend);

This example is from the HLSLWithoutFX10 Sample.

Bind the Blend State

Once the blend-state object is created, bind the blend-state object to the output-merger stage by calling ID3D10Device::OMSetBlendState.

float blendFactor = 0;
UINT sampleMask   = 0xffffffff;

pd3dDevice->OMSetBlendState(g_pBlendStateNoBlend, blendFactor, sampleMask);

This API takes three parameters: the blend-state object, a four-component blend factor, and a sample mask. You may pass in NULL for the blend-state object (which tells the runtime to use default blend state - see ID3D10Device::OMSetBlendState) or pass in a blend-state object as shown here. The blend factor gives you per-component control over blending the new per-pixel values with the existing value. The sample mask is a user-defined mask that determines how to sample the existing rendertarget before updating it. The default sampling mask is 0xffffffff which designates point sampling.

Advanced Blending Topics

  • Alpha-To-Coverage
  • Dual Source Color Blending

Alpha-To-Coverage

Alpha-to-coverage is a multisampling technique that is most useful for situations such as dense foliage where there are several overlapping polygons. It can be turned on by setting the AlphaToCoverageEnable variable to true in the D3D10_BLEND_DESC. Alpha-to-coverage will work regardless of whether or not multisampling is also turned on in the rasterizer state (by setting MultisampleEnable to true or false).

Alpha-to-coverage works by taking the alpha component of an rgba value after it is output from a pixel shader and converting it into an n-step coverage mask (where n is the sample count). This n-step coverage mask is then ANDed with the multisample coverage mask and the result is used to determine which samples should get updated for all of the rendertargets currently bound to the output merger. The original alpha value in the output of the pixel shader is not changed when that alpha value is used to create the n-step coverage mask (alpha blending will still occur on a per-sample basis). Alpha-to-coverage multisampling is essentially the same as regular multisampling except that the n-step coverage mask is generated and ANDed with the multisample coverage mask.

For an example of alpha-to-coverage, see the Instancing10 Sample.

Dual Source Color Blending

This feature enables the output merger to use both the pixel shader outputs simultaneously as input sources to a blending operation with the single rendertarget at slot 0.

Additional options are available for the SrcBlend, DestBlend, SrcBlendAlpha or DestBlendAlpha terms in the blend equation. The presence of any of the following choices in the blend equation means that dual source color blending is enabled:

D3D10_BLEND_SRC1COLOR
D3D10_BLEND_INVSRC1COLOR
D3D10_BLEND_SRC1ALPHA
D3D10_BLEND_INVSRC1ALPHA

When dual source color blending is enabled, the pixel shader must have only a single rendertarget bound, at slot 0, and must output both SV_TARGET0 and SV_TARGET1. Writing SV_Depth is still valid when performing dual source color blending.

The configured blend equation and the rendertarget write mask at slot 0 imply exactly which components from pixel shader outputs must be present. If the expected output components are not present, results are undefined. If extra components are output, they are ignored.

Examples:

There are times when a Shader computes 2 results that are useful on a single pass, but needs to combine one into the destination with a multiply and the other in with an add. This would look like:

SrcBlend = D3D10_BLEND_ONE;
DestBlend = D3D10_BLEND_SRC1COLOR;

Next is a blend mode setup that takes pixel shader output color SV_TARGET0 as source color, and uses pixel shader output color SV_TARGET1 to blend with the destination color.

SrcBlend = D3D10_BLEND_SRC1COLOR;
DestBlend = D3D10_BLEND_INVSRC1COLOR;

Example illustrating expected outputs from the pixel shader:

SrcBlend = D3D10_BLEND_SRC1ALPHA;
DestBlend = D3D10_BLEND_SRCCOLOR;
RenderTargetWriteMask[0] = ( D3D10_COLOR_WRITE_ENABLE_RED |
                             D3D10_COLOR_WRITE_ENABLE_ALPHA );


Resources (Direct3D 10)

A resource is an area in memory that can be accessed by the Direct3D pipeline. In order for the pipeline to access memory efficiently, data that is provided to the pipeline (such as input geometry, shader resources, textures etc) must be stored in a resource. There are two types of resources from which all Direct3D resources derive: a buffer or a texture.

Each application will typically create many resources. Examples of resource include: vertex buffers, index buffer, constant buffer, textures, and shader resources. There are several options that determine how resources can be used. You can create resources that are strongly typed or typeless; you can control whether resources have both read and write access; you can make resources accessible to only the CPU, GPU, or both. Naturally, there will be speed vs. functionality tradeoff - the more functionality you allow a resource to have, the less performance you should expect.

Since an application often uses many textures, Direct3D also introduces the concept of a texture array to simplify texture management. A texture array contains one or more textures (all of the same type and dimensions) that can be indexed from within an application or by shaders. Texture arrays allow you to use a single interface with multiple indexes to access many textures. You can create as many texture arrays to manage different texture types as you need.

Once you have created the resources that your application will use, you connect or bind each resource to the pipeline stages that will use them. This is accomplished by calling a bind API, which takes a pointer to the resource. Since more than one pipeline stage may need access to the same resource, Direct3D 10 introduces the concept of a resource view. A view identifies the portion of a resource that can be accessed. You can create m views or a resource and bind them to n pipeline stages, assuming you follow binding rules for shared resource (the runtime will generate errors at compile time if you don't).

A resource view provides a general model for access to a resource (textures, buffers, etc.). Because you can use a view to tell the runtime what data to access and how to access it, resource views allow you create typeless resources. That is, you can create resources for a given size at compile time, and then declare the data type within the resource when the resource gets bound to the pipeline. Views expose many new capabilities for using resources, such as the ability to read back depth/stencil surfaces in the shader, generating dynamic cubemaps in a single pass, and rendering simultaneously to multiple slices of a volume.

To find out more about the basic resource types, texture arrays, and how to create and use resources, see these other topics:

  • Resource Types
  • Choosing a Resource
  • Creating Buffer Resources
  • Creating Texture Resources
  • Copying and Accessing Resource Data
  • Memory Structure and Views


Resource Types (Direct3D 10)

All resources used by the Direct3D pipeline derive from two basic resource types: buffers and textures. A buffer is a collection of elements; a texture is a collection of texels.

  • Buffer Resource
  • Texture Resource

There are two ways to fully specify the layout (or memory footprint) of a resource:

  • Typed - fully specify the type when the resource is created.
  • Typeless - fully specify the type when the resource is bound to the pipeline.

Buffer Resource

A buffer resource is a collection of data; each piece of data is called an element. Each element can be of a different type, or even a different format. For example, an application could store both index and vertex information in the same buffer. When the buffer is bound to the pipeline, an application specifies the information necessary to read and interpret buffer data.

A buffer is created as an unstructured resource (in essence just a big chunk of memory) which is interpreted when it is bound to a pipeline stage. Unlike a texture resource, a buffer cannot be filtered, does not contain multiple subresources, and cannot be multisampled.

Buffer Element

An element is the smallest unit of memory that can be read or written by the pipeline. An element can be read by a shader or set as state in a Direct3D device. Some examples of an element could be: a position, a vertex normal, or a texture coordinate in a vertex buffer, and index in an index buffer, or a single state, such as depth/stencil.

An element is made up of 1 to 4 components. Examples of an element include: a packed data value (like R8G8B8A8), a single 8-bit integer, four 32-bit float values, etc. Specifically, an element is any one of the DXGI formats.

Although this description of elements applies to both buffers and textures, the documentation will use the term element when referring to buffers, and texel (short for texture element) when referring to textures for the sake of clarity.

  • Vertex Buffer
  • Index Buffer
  • Shader-Constant Buffer

Vertex Buffer

A vertex buffer is a collection of elements. A vertex buffer which contains position data can be visualized like this.

Figure 1. Single-Element Vertex Buffer

More often, a vertex buffer contains all the data needed to fully specify 3D vertices. This data is usually organized as structures of elements, which can be visualized like this.

Figure 2. Multi-Element Vertex Buffer

This vertex buffer contains eight vertices; the data for each vertex is made up of three elements (position, normal, and texture coordinates). The position and normal are typically specified using three 32-bit floats (DXGI_FORMAT_R32G32B32_FLOAT) and the texture coordinates using two 32-bit floats (DXGI_FORMAT_R32G32_FLOAT). Every element in a vertex buffer has an identical data structure to every other element.

To access data from a vertex buffer you need to know which vertex to access and these other buffer parameters:

  • Offset - the number of bytes from the start of the buffer to the data for the first vertex. The offset is supplied to ID3D10Device::IASetVertexBuffers.
  • BaseVertexLocation - the number of bytes from the offset to the first vertex used by the appropriate draw call (see Draw APIs).

To create a buffer resource that can be used as a vertex buffer, see Create a Vertex Buffer.

Index Buffer

An index buffer contains a sequential set of indices; each index is used to identify a vertex in a vertex buffer. Using an index buffer with one or more vertex buffers to supply data to the IA stage is called indexing. An index buffer can be visualized like this.

Figure 3. Index Buffer

The sequential indices stored in an index buffer are located with the following parameters:

  • Offset - the number of bytes from the start of the buffer to the first index. The offset is supplied to ID3D10Device::IASetIndexBuffer.
  • StartIndexLocation - the number of bytes from the offset to the first vertex used by the appropriate draw call (see Draw APIs).
  • IndexCount - the number of indices to render.

An index buffer contains 16-bit or 32-bit indices. To create an index buffer, see Create an Index Buffer.

Shader-Constant Buffer

Direct3D 10 introduced a new buffer for supplying shader constants. It is called a shader-constant buffer. Conceptually, it looks just like a vertex buffer).

To create a shader-constant buffer, specify the constant-buffer bind flag (D3D10_BIND_CONSTANT_BUFFER). Once created, read the buffer using the Load (Direct3D 10 HLSL) intrinsic function. Each shader stage allows up to 15 slots for shader-constant buffers; each buffer can hold up to 4096 constants.

Texture Resource

A texture resource is a structured collection of data designed to store texture data. The data in a texture resource is made up of one or more subresources, which are themselves organized into arrays of texels. Unlike buffers, textures can be filtered by texture samplers as they are read by shader units. The type of texture impacts how the texture is filtered.

  • Texels
  • Texture1D and Texture1DArray Resource
  • Texture2D and Texture2DArray Resource
  • Texture3D Resource

Texels

A texel (or texture element) represents the smallest unit of a texture that can be read or written to by the pipeline. Each texel contains 1 to 4 components, arranged in one of the DXGI formats.

Individual texel components cannot be fetched (read) directly. The entire texel must be fetched by the runtime before an application can access a specific component. For example, a shader cannot fetch just the green component of an R8G8B8A8 texture; it would need to fetch the entire texel first and then access the green component.

Texture1D and Texture1DArray Resource

A Texture1D resource is a one-dimension texture which consists of an array of elements. Unlike buffer resources, texture1D resources must be created with a texel type , may be filtered, and may contain one or more mipmap levels. Conceptually, a texture1D resource looks like this:

Figure 4. Texture1D Resource

Figure 2 illustrates a Texture1D resource with 3 mipmap levels. The top-most mipmap level is the largest level; each successive level is a power of 2 (on each side) smaller. In this example, since the top-level texture width is 5 elements, there are two mipmap levels before the texture width is reduced to 1. Each element in each mipmap level is addressable by the u vector (which is commonly called a texture coordinate).

Each element in each mipmap level contains a single texel, or texture value. The data type of each element is defined by the texel format which is once again a DXGI_FORMAT value. A texture resource may be typed or typeless at resource-creation time, but when bound to the pipeline, its interpretation must be provided in a view.

A Texture1DArray resource is a homogenous array of 1D textures. It looks like an array of 1D textures.

Figure 5. Texture1DArray Resource

This texture array contains three textures. Each of the three textures has a texture width of 5 (which is the number of elements in the 1st layer). Each texture also contains a 3 layer mipmap.

All texture arrays in Direct3D are a homogenous array of textures; this means that every texture in a texture array must have the same data format and size (including texture width and number of miplevels). You may create texture arrays of different sizes, as long as all the textures in each array match in size.

Subresources

One interesting feature with Direct3D texture resources (including textures and texture arrays) is that they are made up of subresources. A subresource is a texture and mipmap-level combination. For a single texture, a subresource is a single mipmap level. This 1D texture is made up of 3 subresources.

Figure 6. Texture1D Subresource

For a texture array, a subresource is an array slice and a particular mipmap level. Here is an example of an array of subresources, within a 2D texture array.

Figure 7. Texture1DArray Subresource

This array of subresources contains the top mipmap levels of all three textures in the texture array resource. Direct3D uses a resource view to access this array of texture subresources in a texture array.

Indexing Subresources

A texture array can contain multiple textures, each with multiple mipmap levels. Each subresource is a mipmap-level in a single texture. When accessing a particular subresource, this is how the subresources are indexed within the texture array.

Figure 8. Indexing Subresources in a Texture1DArray

The index (which is an unsigned integer) starts at zero in the first texture in the array, and increments through the mipmap levels for that texture. Subresource indices in 2D texture arrays follow the same pattern as 1D texture arrays.

Subresources are indexed somewhat differently in a 3D texture resource (also known as a volume texture). Each subresource is a mipmap level in the Texture3D.

Figure 9. Indexing Subresources in a Texture3D

The index starts at zero in the first mipmap level in the Texture3D and increments through the mipmap levels for the rest of the texture.

Use D3D10CalcSubresource to Compute a Subresource Index

Many texture access methods require the application to specify a particular subresource. The helper function D3D10CalcSubresource (defined in D3D10.h) computes the subresource index from three pieces of information: the array slice, the mip slice, and the number of miplevels. The method is defined as follows:

UINT D3D10CalcSubresource( UINT MipSlice, UINT ArraySlice, UINT MipLevels )
{
  return MipSlice + ArraySlice * MipLevels;
}

Texture2D and Texture2DArray Resource

A Texture2D resource contains a 2D grid of texels. Each texel is addressable by a u, v vector. Since it is a texture resource, it may contain mipmap levels, and subresources. A fully populated 2D texture resource looks like this:

Figure 10. Texture2D Resource

This texture resource contains a single 3x5 texture with three mipmap levels.

A Texture2DArray resource is a homogeneous array of 2D textures; that is, each texture has the same data format and dimensions (including mipmap levels). It has a similar layout as the Texture1DArray resource except that the textures now contain 2D data, and therefore looks like this:

Figure 11. Texture2DArray Resource

This texture array contains three textures; each texture is 3x5 with two mipmap levels.

Using a Texture2DArray as a Texture Cube

A texture cube is a Texture2DArray that contains 6 textures, one for each face of the cube. A fully populated texture cube looks like this:

Figure 12. Array of 2D Textures Representing a Texture Cube

A Texture2DArray that contains 6 textures may be read from within shaders with the cube map intrinsic functions, after they are bound to the pipeline with a cube-texture view. Texture cubes are addressed from the shader with a 3D vector pointing out from the center of the texture cube.

Texture3D Resource

A Texture3D resource (also known as a volume texture) contains a 3D volume of texels. Since it is a texture resource, it may contain mipmap levels. A fully populated Texture3D resource looks like this:

Figure 13. Texture3D Resource

When a Texture3D mipmap slice is bound as a rendertarget output, (by creating a rendertarget view), the Texture3D behaves identically to a Texture2DArray with n array slices where n is the depth (3rd dimension) of the Texture3D. The particular slice in the Texture3D to render is chosen from the geometry shader stage, by declaring a scalar component of output data as the SV_RenderTargetArrayIndex system-value.

There is no concept of an array of Texture3D resources; therefore a Texture3D subresource is a single mipmap level.


Choosing a Resource (Direct3D 10)

A resource is a collection of data that is used by the 3D pipeline. Creating resources and defining their behavior is the first step toward programming your application. This guide covers basic topics for choosing the resources required by your application.

  • Identify Pipeline Stages That Need Resources
  • Identify How Each Resource Will Be Used
  • Binding Resources to Pipeline Stages

Identify Pipeline Stages That Need Resources

The first step is to choose the pipeline stage (or stages) that will use a resource. That is, identify each stage that will read data from a resource as well as the stages that will write data out to a resource. Knowing the pipeline stages where the resources will be used determines the APIs that will be called to bind the resource to the stage.

This table lists the types of resources that can be bound to each pipeline stage. It includes whether the resource can be bound as an input or an output, as well as the bind API.

Pipeline Stage | In/Out | Resource | Resource Type | Bind API
Input Assembler | In | Vertex Buffer | Buffer | ID3D10Device::IASetVertexBuffers
Input Assembler | In | Index Buffer | Buffer | ID3D10Device::IASetIndexBuffer
Shader Stages | In | Shader-ResourceView | Texture1D, Texture2D, Texture3D | ID3D10Device::VSSetShaderResources, ID3D10Device::GSSetShaderResources, ID3D10Device::PSSetShaderResources
Shader Stages | In | Shader-Constant Buffer | Buffer | ID3D10Device::VSSetConstantBuffers, ID3D10Device::GSSetConstantBuffers, ID3D10Device::PSSetConstantBuffers
Stream Output | Out | Buffer | Buffer | ID3D10Device::SOSetTargets
Output Merger | Out | Rendertarget View | Buffer, Texture1D, Texture2D, Texture3D | ID3D10Device::OMSetRenderTargets
Output Merger | Out | Depth/Stencil View | Texture1D, Texture2D | ID3D10Device::OMSetRenderTargets

Identify How Each Resource Will Be Used

Once you have chosen the pipeline stages that your application will use (and therefore the resources that each stage will require), the next step is to determine how each resource will be used, that is, whether a resource can be accessed by the CPU or the GPU.

The hardware that your application is running on will have a minimum of at least one CPU and one GPU. To pick a usage value, consider which type of processor needs to read or write to the resource from the following options (see D3D10_USAGE).

Resource Usage | Can be updated by | Frequency of Update
Default | GPU | infrequently
Dynamic | CPU | frequently
Staging | GPU | n/a
Immutable | CPU (only at resource creation time) | n/a

Default usage should be used for a resource that is expected to be updated by the CPU infrequently (less than once per frame). Ideally, the CPU would never write directly to a resource with default usage so as to avoid potential performance penalties.

Dynamic usage should be used for a resource that the CPU updates relatively frequently (once or more per frame). A typical scenario for a dynamic resource would be to create dynamic vertex and index buffers that would be filled at runtime with data about the geometry visible from the point of view of the user for each frame. These buffers would be used to render only the geometry visible to the user for that frame.

Staging usage should be used to copy data to and from other resources. A typical scenario would be to copy data in a resource with default usage (which the CPU cannot access) to a resource with staging usage (which the CPU can access).

Immutable resources should be used when the data in the resource will never change.

If you are unsure what usage to choose, start with the default usage as it is expected to be used most often.

Binding Resources to Pipeline Stages

A resource can be bound to more than one pipeline stage at the same time as long as the restrictions specified when the resource was created (usage flags, bind flags, cpu access flags) are met. More specifically, a resource can be bound as an input and an output simultaneously as long as reading and writing part of a resource cannot happen at the same time.

When binding a resource, think about how the GPU and the CPU will access the resource. Resources that are designed for a single purpose (do not use multiple usage, bind, and cpu access flags) will more than likely result in better performance.

For example, consider the case of a render target used as a texture multiple times. It may be faster to have two resources: a render target and a texture used as a shader resource. Each resource would use only one bind flag (D3D10_BIND_RENDER_TARGET or D3D10_BIND_SHADER_RESOURCE). The data would be copied from the render-target texture to the shader texture using ID3D10Device::CopyResource or ID3D10Device::CopySubresourceRegion. This may improve performance by isolating the render-target write from the shader-texture read. Of course, the only way to be sure is to implement both approaches and measure the performance difference in your particular application.


Creating Buffer Resources (Direct3D 10)

A resource is a collection of data that is used by the 3D pipeline. The size of a resource is limited by D3D10_REQ_RESOURCE_SIZE_IN_MEGABYTES. Creating resources and defining their behavior is the first step towards the rendering of geometric data.

  • Creating Vertex Buffers
  • Create an Index Buffer

Creating Vertex Buffers

The steps to creating a vertex buffer are as follows.

  • Initialize a buffer description to describe the data to be stored in the buffer.
  • Initialize a subresource description to fill the buffer with data.
  • Create the buffer using both of these descriptions.

A Buffer Description

When creating a vertex buffer, a buffer description (see D3D10_BUFFER_DESC) is used to define how data is organized within the buffer, how the pipeline can access the buffer, and how the buffer will be used.

The following example demonstrates how to create a buffer description for a single triangle with vertices that contain position and color values.

struct SimpleVertex
{
    D3DXVECTOR3 Position;
    D3DXVECTOR3 Color;
};

D3D10_BUFFER_DESC bufferDesc;
bufferDesc.Usage            = D3D10_USAGE_DEFAULT;
bufferDesc.ByteWidth        = sizeof( SimpleVertex ) * 3;
bufferDesc.BindFlags        = D3D10_BIND_VERTEX_BUFFER;
bufferDesc.CPUAccessFlags   = 0;
bufferDesc.MiscFlags        = 0;

In this example, the buffer description is initialized with almost all default settings for usage, CPU access and miscellaneous flags. The other settings are for the bind flag which identifies the resource as a vertex buffer only, and the size of the buffer.

The usage and CPU access flags are important for performance. These two flags together determine how often a resource gets accessed, what type of memory the resource could be loaded into, and what processor needs to access the resource. Default usage this resource will not be updated very often. Setting CPU access to 0 means that the CPU will not need to either read or write the resource. Taken in combination, this means that the runtime can load the resource into the highest performing memory for the GPU since the resource does not require CPU access.

As expected, there is a tradeoff between best performance and any-time accessibility by either processor. For example, the default usage with no CPU access means that the resource can be made available to the GPU exclusively. This could include loading the resource into memory not directly accessible by the CPU. The resource could only be modified with ID3D10Device::UpdateSubresource.

A Subresource Description

A resource is made up of subresources. Applications can optionally provide some initial data when the buffer is created to both create it and initialize it at the same time. This is accomplished by using D3D10_SUBRESOURCE_DATA. The subresource description points to the actual resource data, and also contains information about the size and layout of that data.

Resources created with the D3D10_USAGE_IMMUTABLE flag (see D3D10_USAGE) must be initialized at creation time; resources that use any of the other creation flags can be updated after initialization. This can be accomplished using ID3D10Device::CopyResource, ID3D10Device::CopySubresourceRegion, ID3D10Device::UpdateSubresource, or by accessing its underlying memory using the resource's Map method.

A buffer is just a collection of elements and is laid out as a 1D array. As a result, the system memory pitch and system memory slice pitch are both the same; the size of the vertex data declaration.

This description gives the pipeline a clear idea of how to access the elements in the resource.

Create a Vertex Buffer

To create a vertex buffer, call ID3D10Device::CreateBuffer with the buffer description and a subresource description.

The following code snippet demonstrates how to create a vertex buffer from an array of vertex data declared by the application. First, a buffer description is created and filled with information about the data to be stored in the vertex buffer and how that data will be used. Next, a subresource description is created and filled with the actual information the vertex buffer will be initialized with. Finally, the vertex buffer is created by calling ID3D10Device::CreateBuffer

struct SimpleVertexCombined
{
    D3DXVECTOR3 Pos;
    D3DXVECTOR3 Col;
};

ID3D10InputLayout* g_pVertexLayout = NULL;
ID3D10Buffer*      g_pVertexBuffer[2] = { NULL, NULL };
ID3D10Buffer*      g_pIndexBuffer = NULL;

    SimpleVertexCombined verticesCombo[] =
    {
        D3DXVECTOR3( 0.0f, 0.5f, 0.5f ),
        D3DXVECTOR3( 0.0f, 0.0f, 0.5f ),
        D3DXVECTOR3( 0.5f, -0.5f, 0.5f ),
        D3DXVECTOR3( 0.5f, 0.0f, 0.0f ),
        D3DXVECTOR3( -0.5f, -0.5f, 0.5f ),
        D3DXVECTOR3( 0.0f, 0.5f, 0.0f ),
    };

    D3D10_BUFFER_DESC bufferDesc;
    bufferDesc.Usage            = D3D10_USAGE_DEFAULT;
    bbufferDescd.ByteWidth      = sizeof( SimpleVertexCombined ) * 3;
    bufferDesc.BindFlags        = D3D10_BIND_VERTEX_BUFFER;
    bufferDesc.CPUAccessFlags   = 0;
    bufferDesc.MiscFlags        = 0;

    D3D10_SUBRESOURCE_DATA InitData;
    InitData.pSysMem = verticesCombo;
    InitData.SysMemPitch = 0;
    InitData.SysMemSlicePitch = 0;
    hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBuffer[0] );

Create an Index Buffer

To create an index buffer, call ID3D10Device::CreateBuffer with the buffer description and a subresource description. Creating an index buffer is very similar to creating a vertex buffer. The main difference is that the BindFlags member of the D3D10_BUFFER_DESC structure must be set to D3D10_BIND_INDEX_BUFFER.

The following code snippet demonstrates how to create an index buffer from an array of index data. First, a buffer description is created and filled with information about the data to be stored in the index buffer and how that data will be used. Next, a subresource description is created and filled with the actual information the index buffer will be initialized with.

ID3D10Buffer *g_pIndexBuffer = NULL;

// Create indices
unsigned int indices[] = { 0, 1, 2 };

D3D10_BUFFER_DESC bufferDesc;
bufferDesc.Usage           = D3D10_USAGE_DEFAULT;
bufferDesc.ByteWidth       = sizeof( unsigned int ) * 3;
bufferDesc.BindFlags       = D3D10_BIND_INDEX_BUFFER;
bufferDesc.CPUAccessFlags  = 0;
bbufferDescd.MiscFlags     = 0;

D3D10_SUBRESOURCE_DATA InitData;
InitData.pSysMem = indices;
InitData.SysMemPitch = 0;
InitData.SysMemSlicePitch = 0;
hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pIndexBuffer );
if( FAILED( hr ) )
  return hr;

g_pd3dDevice->IASetIndexBuffer( g_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0 );


Creating Texture Resources (Direct3D 10)

A texture resource is a structured collection of data. Typically, color values are stored in textures and accessed during rendering by the pipeline at various stages for both input and output. Creating textures and defining how they will be used is an important part of rendering interesting-looking scenes in Direct3D 10.

Even though textures typically contain color information, creating textures using different formats enables them to store different kinds of data. This data can then be leveraged by the Direct3D 10 pipeline in non-traditional ways.

All textures have limits on how much memory they consume, and how many texels they contain. These limits are specified by resource constants.

  • Creating Textures from Files
  • Creating Empty Textures
  • Multiple Rendertargets

Creating Textures from Files

In Direct3D 10, textures cannot be used directly by the pipeline. Instead, a shader-resource view must be created which refers to the particular texture. This shader-resource view can then be bound to the pipeline during rendering. D3DX provides a useful function (see D3DX10CreateShaderResourceViewFromFile)to both load a texture from a file and create the accompanying shader-resource view at the same time, as shown below.

ID3D10ShaderResourceView *pTextureRV = NULL;
D3DXCreateShaderResourceViewFromFile( pDevice, L"myTexture.bmp", &pTextureRV );

The ID3D10ShaderResourceView interface returned by the D3DX10CreateShaderResourceViewFromFile function can later be used to retrieve the original ID3D10Resource interface if it is needed. This can be done by calling the ID3D10View::GetResource method. If you know the type of texture you're loading (1D, 2D, or 3D), then you can cast this pointer directly to the desired type.

On the other hand, a generic texture manager may implement something like the following to handle different the texture types.

ID3D10Resource pResource = NULL;
pTextureRV->GetResource( &pResource );
D3D10_RESOURCE_DIMENSION type;
pResource->GetType( &type );

switch( type )
{
    case D3D10_RESOURCE_DIMENSION_TEXTURE1D:
    {
        pTexture1D = (ID3D10Texture1D*)pResource;
        // ...
        break;
    }

    case D3D10_RESOURCE_DIMENSION_TEXTURE2D:
    {
        pTexture2D = (ID3D10Texture2D*)pResource;
        // ...
        break;
    }

    case D3D10_RESOURCE_DIMENSION_TEXTURE3D:
    {
        pTexture3D = (ID3D10Texture3D*)pResource;
        break;
    }

    default:
    {
        // error
        break;
    }
}

Creating Empty Textures

Sometimes applications will want to create a texture and compute the data to be stored in the texture, or use the graphics pipeline to render to this texture and later use the results in other processing. These textures could be updated by the graphics pipeline or by the application itself, depending on what kind of usage was specified for the texture when it was created.

Rendering to a texture

The most common case of creating an empty texture to be filled with data during runtime is the case where an application wants to render to a texture and then use the results of the rendering operation in a subsequent pass. Textures created with this purpose should specify default usage.

The following code sample creates an empty texture that the pipeline can render to and subsequently use as an input to shader.

// Create the render target texture
D3D10_TEXTURE2D_DESC desc;
ZeroMemory( &desc, sizeof(desc) );
desc.Width = 256;
desc.Height = 256;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
desc.SampleDesc.Count = 1;
desc.Usage = D3D10_USAGE_DEFAULT;
desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;

ID3D10Texture2D pRenderTarget = NULL;
pDevice->CreateTexture2D( &desc, NULL, &pRenderTarget );

Creating the texture requires the application to specify some information about the properties the texture will have. The width and height of the texture in texels is set to 256. For this render target, a single miplevel is all we need. Only one render target is required so the array size is set to 1. Each texel contains four 32-bit floating point values, which can be used to store very precise information (see DXGI_FORMAT). One sample per pixel is all that will be needed. The usage is set to default because this allows for the most efficient placement of the render target in memory. Finally, the fact that the texture will be bound as a render target and a shader resource at different points in time is specified.

Textures cannot be bound for rendering to the pipeline directly. Because of this, a render-target view must first be created to describe to the pipeline how to access the render target texture. This can be seen in the following code sample.

D3D10_RENDER_TARGET_VIEW_DESC rtDesc;
rtDesc.Format = desc.Format;
rtDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
rtDesc.Texture2D.MipSlice = 0;

ID3D10RenderTargetView pRenderTargetView = NULL;
pDevice->CreateRenderTargetView( pRenderTarget, &rtDesc, &pRenderTargetView );

The format of the render-target view is simply set to the format of the original texture. The information in the resource should be interpreted as a 2D texture, and we only want to use the first miplevel of the render target.

Similarly to how a render-target view must be created so that the render target can be bound for output to the pipeline, a shader-resource view must be created so that the render target can be bound to the pipeline as an input. The following code sample demonstrates this.

// Create the shader-resource view
D3D10_SHADER_RESOURCE_VIEW_DESC srDesc;
srDesc.Format = desc.Format;
srDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
srDesc.Texture2D.MostDetailedMip = 0;
srDesc.Texture2D.MipLevels = 1;

ID3D10ShaderResourceView pShaderResView = NULL;
pDevice->CreateShaderResourceView( pRenderTarget, &srDesc, &pShaderResView );

The parameters of shader-resource view descriptions are very similar to those of render-target view descriptions and were chosen for the same reasons.

Filling Textures Manually

Sometimes applications would like to compute values at runtime, put them into a texture manualy and then have the graphics pipeline use this texture in later rendering operations. To do this, the application must create an empty texture in such a way to allow the CPU to access the underlying memory. This is done by creating a dynamic texture and gaining access to the underlying memory by calling a particular method. The following code sample demonstrates how to do this.

D3D10_TEXTURE2D_DESC desc;
desc.Width = 256;
desc.Height = 256;
desc.MipLevels = desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D10_USAGE_DYNAMIC;
desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
ID3D10Texture2D* pTexture = NULL;
pd3dDevice->CreateTexture2D( &desc, NULL, &pTexture );

Note that the format is set to a 32 bits per pixel where each component is defined by 8 bits. The usage parameter is set to dynamic while the bind flags are set to specify the texture will be accessed by a shader. The rest of the texture description is similar to creating a render target.

Calling ID3D10Texture2D::Map enables the application to access the underlying memory of the texture. The pointer retrieved is then used to fill the texture with data. This can be seen in the following code sample.

D3D10_MAPPED_TEXTURE2D mappedTex;
pTexture->Map( D3D10CalcSubresource(0, 0, 1), D3D10_MAP_WRITE_DISCARD, 0, &mappedTex );

UCHAR* pTexels = (UCHAR*)mappedTex.pData;
for( UINT row = 0; row < desc.Height; row++ )
{
    UINT rowStart = row * mappedTex.RowPitch;
    for( UINT col = 0; col < desc.Width; col++ )
    {
        UINT colStart = col * 4;
        pTexels[rowStart + colStart + 0] = 255; // Red
        pTexels[rowStart + colStart + 1] = 128; // Green
        pTexels[rowStart + colStart + 2] = 64;  // Blue
        pTexels[rowStart + colStart + 3] = 32;  // Alpha
    }
}

pTexture->Unmap( D3D10CalcSubresource(0, 0, 1) );

Multiple Rendertargets

Up to eight rendertarget views can be bound to the pipeline at a time (with a call to ID3D10Device::OMSetRenderTargets). For each pixel (or each sample if multisampling is enabled), the blend process will be done on each rendertarget view bound to the output merger. Two of the blend state variables - BlendEnable and RenderTargetWriteMask - are arrays of eight, with each member of the arrays corresponding to each rendertarget view set to the output merger. When setting multiple rendertargets to the output merger, each rendertarget must be the same type of resource (i.e. buffer, texture1D[array], texture2D[array], texture3D) and must have the same size in all dimensions (width, height, depth for texture3Ds, and array size for texture arrays). If the rendertargets are multisampled textures, then they must all have the same number of samples per pixel.

There can only be one Depth/Stencil buffer active, regardless of how many RenderTargets are active. Should resource views of TextureArray(s) be set as RenderTarget(s), the resource view of Depth/Stencil (if bound) must also be the same dimensions and array size. Note that this does not mean that the Resources, themselves, need to be of the same dimensions (including array size). Only that the views that are used together must be of the same effective dimensions.

The rendertargets need not be the same texture format.


Copying and Accessing Resource Data (Direct3D 10)

It is no longer necessary to think about resources as being created in either video memory or system memory. Or whether or not the runtime should manage the memory. Thanks to the architecture of the new WDDM (Windows Display Driver Model), applications now create Direct3D 10 resources with different usage flags to indicate how the application intends on using the resource data. The new driver model virtualizes the memory used by resources; it then becomes the responsibility of the operating system/driver/memory manager to place resources in the most performant area of memory possible given the expected usage.

The default case is for resources to be available to the GPU. Of course, having said that, there are times when the resource data needs to be available to the CPU. Copying resource data around so that the appropriate processor can access it without impacting performance requires some knowledge of how the API methods work.

  • Copying Resource Data
  • Accessing Resource Data

Copying Resource Data

Resources are created in memory when Direct3D executes a Create call. They can be created in video memory, system memory, or any other kind of memory. Since WDDM driver model virtualizes this memory, applications no longer need to keep track of what kind of memory resources are created in.

Ideally, all resources would be located in video memory so that the GPU can have immediate access to them. However, it is sometimes necessary for the CPU to read the resource data or for the GPU to access resource data the CPU has written to. Direct3D 10 handles these different scenarios by requesting the application specify a usage type, and then offers several methods for copying resource data when necessary.

Depending on how the resource was created, it is not always possible to directly access the underlying data. This may mean that the resource data must be copied from the source resource to another resource that is accessible by the appropriate processor. In terms of Direct3D 10, default resources can be accessed directly by the GPU, dynamic and staging resources can be directly accessed by the CPU.

Once a resource has been created, its usage cannot be changed. Instead, copy the contents of one resource to another resource that was created with a different usage. Direct3D 10 provides this functionality with three different methods. The first two methods( ID3D10Device::CopyResource and ID3D10Device::CopySubresourceRegion) are designed to copy resource data from one resource to another. The third method (ID3D10Device::UpdateSubresource) is designed to copy data from memory to a resource.

There are two main kinds of resources: mappable and non-mappable. Resources created with dynamic or staging usages are mappable, while resources created with default or immutable usages are non-mappable.

Copying data among non-mappable resources is very fast because this is the most common case and has been optimized to perform well. Since these resources are not directly accessible by the CPU, they are optimized so that the GPU can manipulate them quickly.

Copying data among mappable resources is more problematic because the performance will depend on the usage the resource was created with. For example, the GPU can read a dynamic resource fairly quickly but cannot write to them, and the GPU cannot read or write to staging resources directly.

Applications that wish to copy data from a resource with default usage to a resource with staging usage (to allow the CPU to read the data -- i.e. the GPU readback problem) must do so with care. See Accessing Resource Data for more details on this last case.

Accessing Resource Data

Accessing a resource requires mapping the resource; mapping essentially means the application is trying to give the CPU access to memory. The process of mapping a resource so that the CPU can access the underlying memory can cause some performance bottlenecks and for this reason, care must be taken as to how and when to perform this task.

Performance can grind to a halt if the application tries to map a resource at the wrong time. If the application tries to access the results of an operation before that operation is finished, a pipeline stall will occur.

Performing a map operation at the wrong time could potentially cause a severe drop in performance by forcing the GPU and the CPU to synchronize with each other. This synchronization will occur if the application wants to access a resource before the GPU is finished copying it into a resource the CPU can map.

The CPU can only read from resources created with the D3D10_USAGE_STAGING flag. Since resources created with this flag cannot be set as outputs of the pipeline, if the CPU wants to read the data in a resource generated by the GPU, the data must be copied to a resource created with the staging flag. The application may do this by using the ID3D10Device::CopyResource or ID3D10Device::CopySubresourceRegion methods to copy the contents of one resource to another. The application can then gain access to this resource by calling the appropriate Map method. When access to the resource is no longer needed, the application should then call the corresponding Unmap method. For example, ID3D10Texture2D::Map and ID3D10Texture2D::Unmap. The different Map methods return some specific values depending on the input flags. See Map Remarks section for details.

Performance Considerations

It is best to think of a PC as a machine running as a parallel architecture with two main types of processors: one or more CPU's and one or more GPU's. As in any parallel architecture, the best performance is achieved when each processor is scheduled with enough tasks to prevent it from going idle and when the work of one processor is not waiting on the work of another.

The worst-case scenario for GPU/CPU parallelism is the need to force one processor to wait for the results of work done by another. Direct3D 10 tries to remove this cost by making the ID3D10Device::CopyResource and ID3D10Device::CopySubresourceRegion methods asynchronous; the copy has not necessarily executed by the time the method returns. The benefit of this is that the application does not pay the performance cost of actually copying the data until the CPU accesses the data, which is when Map is called. If the Map method is called after the data has actually been copied, no performance loss occurs. On the other hand, if the Map method is called before the data has been copied, then a pipeline stall will occur.

Asynchronous calls in Direct3D 10 (which are the vast majority of methods, and especially rendering calls) are stored in what is called a command buffer. This buffer is internal to the graphics driver and is used to batch calls to the underlying hardware so that the costly switch from user mode to kernel mode in Microsoft Windows occurs as rarely as possible.

The command buffer is flushed, thus causing a user/kernel mode switch, in one of four situations, which are as follows.

  1. IDXGISwapChain::Present is called.
  2. ID3D10Device::Flush is called.
  3. The command buffer is full; its size is dynamic and is controlled by the Operating System and the graphics driver.
  4. The CPU requires access to the results of a command waiting to execute in the command buffer.

Of the four situations above, number four is the most critical to performance. If the application issues a ID3D10Device::CopyResource or ID3D10Device::CopySubresourceRegion call, this call is queued in the command buffer. If the application then tries to map the staging resource that was the target of the copy call before the command buffer has been flushed, a pipeline stall will occur because not only does the Copy method call need to execute, but all other buffered commands in the command buffer must execute as well. This will cause the GPU and CPU to synchronize because the CPU will be waiting to access the staging resource while the GPU is emptying the command buffer and finally filling the resource the CPU needs. Once the GPU finishes the copy, the CPU will begin accessing the staging resource, but during this time, the GPU will be sitting idle.

Doing this frequently at runtime will severely degrade performance. For that reason, mapping of resources created with default usage should be done with care. The application needs to wait long enough for the command buffer to be emptied and thus have all of those commands finish executing before it tries to map the corresponding staging resource. How long should the application wait? At least two frames because this will enable parallelism between the CPU(s) and the GPU to be maximally leveraged. The way the GPU works is that while the application is processing frame N by submitting calls to the command buffer, the GPU is busy executing the calls from the previous frame, N-1.

So if an application wants to map a resource that originates in video memory and calls ID3D10Device::CopyResource/ID3D10Device::CopySubresourceRegion at frame N, this call will actually begin to execute at frame N+1, when the application is submitting calls for the next frame. The copy should be finished when the application is processing frame N+2.

The following table summarizes this discussion.

Frame GPU/CPU Status
N
  • CPU issues render calls for current frame.
N+1
  • GPU executing calls sent from CPU during frame N.
  • CPU issues render calls for current frame.
N+2
  • GPU finished executing calls sent from CPU during frame N. Results ready.
  • GPU executing calls sent from CPU during frame N+1.
  • CPU issues render calls for current frame.
N+3
  • GPU finished executing calls sent from CPU during frame N+1. Results ready.
  • GPU executing calls sent from CPU during frame N+2.
  • CPU issues render calls for current frame.
N+4 ...


Memory Structure and Views (Direct3D 10)

Direct3D 10 enables memory to be allocated and accessed in very flexible ways. How the runtime accesses resources is determined in large part by how the memory is allocated.

Memory Structure

Resources can be created with varying types of memory structures. Less restrictive memory structures offer applications more flexibility in how they use the data stored in resources, but may not be optimal for performance.

Unstructured Resources

Unstructured resources are essentially resources allocated with a single contiguous block of memory. This memory is allocated without any knowledge of the type of data that will be stored in it. Only buffers can be allocated as unstructured resources.

Structured Resources

Textures are created as a structured resource. These are split into two groups.

  • Typeless
  • Typed

Typeless

In a structured, yet typeless resource, the data types of individual texels are not supplied when the resource is first created. The application must choose from the available typeless formats. This allows the runtime to allocate the appropriate amount of memory and generate a full mipmap chain. However, the exact data format (whether the memory will be interpreted as integers, floating point values, unsigned integers etc.) is not determined until the resource is bound to the pipeline with a view.

The format of each element in a typeless resource is specified when the resource is bound to a pipeline stage using a view. Because the resource is weakly typed storage, limited reuse or reinterpretation of the memory is enabled, as long as the component bit counts remain the same.

The same resource may be bound to multiple slots in the graphics pipeline with a view of different, fully qualified formats at each location. For example, a resource created with the format DXGI_FORMAT_R32G32B32A32_TYPELESS could be used as an DXGI_FORMAT_R32G32B32A32_FLOAT and an DXGI_FORMAT_R32G32B32A32_UINT at different locations in the pipeline simultaneously. Please see binding resources for more details.

Typed

Creating a fully typed resource restricts the resource to the format it was created with. This enables the runtime to optimize access, especially if the resource is created with flags indicating that it cannot be mapped by the application.

Since the resource is created with a specific type, any views used with this type of resource must have identical formats as the resource itself. Resources created with a specific type cannot be reinterpreted using the view mechanism.

Views

  • Render-Target Views
  • Depth Stencil Views
  • Shader Resource Views

In Direct3D 10, texture resources are accessed with a view, which is a mechanism for hardware interpretation of a resource in memory. A view allows a particular pipeline stage to access only the subresources it needs, in the representation desired by the application.

A view supports the notion of a typeless resource - that is, the resource is created is of a certain size, but exactly how the memory is interpreted is determined when the resource is bound to the pipeline. See typeless resources for more details.

Here is an example of binding a Texture2DArray resource with 6 textures two different ways through two different views. (Note: a subresource cannot be bound as both input and output to the pipeline simultaneously.)

The Texture2DArray can be used as a shader resource by creating a shader resource view for it. The resource is then addressed as an array of textures.

Figure 1. Texture2DArray Viewed as 6 2D Textures

Using a Texture2DArray as a render target. The resource can be viewed as an array of 2D textures (6 in this case) with mipmap levels (3 in this case).

Create a view object for a rendertarget by calling calling CreateRenderTargetView. Then call OMSetRenderTargets to set the rendertarget view to the pipeline. Render into the rendertargets by calling Draw and using the RenderTargetArrayIndex to index into the proper texture in the array. You can use a subresource (a mipmap level, array index combination) to bind to any array of subresources. So you could bind to the second mipmap level and only update this particular mipmap level if you wanted like this:

Figure 2. Views can access an array of Subresources

Render-Target Views

Creating a rendertarget view for a resource will enable the user to bind the resource to the pipeline as a rendertarget. A rendertarget is a resource that will be written to by the output merger stage at the end of a render pass; after a render pass the rendertargets contain the color information of a rendered image. When creating a rendertarget view, only one mipmap level of a texture resource may be used as a rendertarget. When binding a rendertarget view to the pipeline, there will be a corresponding depth stencil view that will be used with the rendertarget in the output merger stage.

Depth Stencil Views

Creating a depth stencil view for a resource will enable the user to use the resource as depth stencil. A depth stencil view is bound to the output merger stage along with a corresponding rendertarget view.

Shader Resource Views

A shader resource view enables the user to bind a resource to a shader stage. A shader resource view can interpret a resource as something different from when it was created. For example, a shader resource view may interpret a Texture2DArray with six textures as a cube map. By binding this cube map view to a shader stage, the shader will sample the Texture2DArray as a cube map.

Differences between Direct3D 9 and Direct3D 10:

In Direct3D 10, you no longer bind a resource directly to the pipeline, you create a view of a resource, and then set the view to the pipeline. This allows validation and mapping in the runtime and driver to occur at view creation, minimizing type checking at bind-time.


Shaders (Direct3D 10)

This page has been deprecated. See Shaders.


Matrices and Vectors in HLSL (Direct3D 10)

This page has been deprecated. See Data Types (DirectX HLSL).


Declaring HLSL Shader Variables (Direct3D 10)

This page has been deprecated. See Variables (DirectX HLSL).


Using HLSL Shaders in Direct3D 10 (Direct3D 10)

This page has been deprecated. See Shaders.


DirectX 10 HLSL Compiler (Direct3D 10)

This page has been deprecated. See Effect-Compiler Tool.


Shader Features (Direct3D 10)

This page has been deprecated. See Shader Model 4 (DirectX HLSL).


Common-Shader Core (Direct3D 10)

This page has been deprecated. See Common-Shader Core (DirectX HLSL).


Shader Constant Variables (Direct3D 10)

This page has been deprecated. See Shader Constants (DirectX HLSL).


Designing a Geometry Shader (Direct3D 10)

This page has been deprecated. See Geometry-Shader Object (DirectX HLSL).


System-Generated Values (Direct3D 10)

This page has been deprecated. See Shader Semantics (DirectX HLSL).


Shader Signatures (Direct3D 10)

This page has been deprecated. See Signatures (DirectX HLSL).


Shader Textures (Direct3D 10)

This page has been deprecated. See Texture Object (DirectX HLSL).


Pixel Shader Interpolation Modifiers (Direct3D 10)

This page has been deprecated. See Function Arguments (DirectX HLSL).


Effects (Direct3D 10)

A DirectX effect is a collection of pipeline state. Effects are written using the high-level shading language.

You can choose to use an effect to organize the state necessary to initialize the pipeline. Once the effect is created, you can use the effect framework (the set of effect APIs) to render. Effect functionality can range from something as simple as a vertex shader that transforms geometry and a pixel shader that outputs a solid color, to a rendering technique that requires multiple passes, uses every stage of the graphics pipeline, and maniulates shader state as well as the pipeline state not associated with the programmable shaders.

The first step is to organize the state you want to control in an effect. This includes shader state (vertex, geometry and pixel shaders), texture and sampler state used by the shaders, and other non-programmable pipeline state. You can create an effect in memory as a text string, but typically, the size gets large enough that it is handy to store effect state in an effect file (a text file that ends in a .fx extension). To use an effect, you must compile it (to check HLSL syntax as well as effect framework syntax), initialize effect state by connecting the parameters in your application that will update the effect variables, and then modify your render loop to render the effect.

  • Organizing State in an Effect
  • Effect System Interfaces
  • Specializing Interfaces
  • Rendering an Effect

One very nice feature with effects is that effects save and restore state. When an effect is rendered, the runtime stores the existing pipeline state in one or more state blocks. Then when the effect is finished rendering, the state blocks are used to restore the pipeline to its previous state. This functionality is designed to allow you to encapsulate all of the render state required by for a particular effect into a single rendering function called a technique. This makes it easy to debug new functionality as it is independent of existing functionality.

Extending this further, effects also layer in additional functionality by supporting techniques and passes. A pass is a sub-set of a technique; however, it is a set of render state. To implement a multiple pass rendering effect in an effect, you can implement one or more passes. For example, say you wanted to render some geometry with one set of depth/stencil buffers, and then draw some sprites on top of that. You could implement the geometry rendering in the first pass, and the sprite drawing in the second pass. To render the effect, you simply render both passes in your render loop. Techniques are independent sets of rendering functionality within an effect. You can implement any number of techniques in an effect. Of course, the greater the number of techniques, the greater the compile time for the effect. One way to exploint this functonality is to create effects with techniques that are designed to run on different hardware. This allows an application to gracefully downgrade performance based on the hardware capabilities detected.

See Also

Programming Guide (Direct3D 10)


Organizing State in an Effect (Direct3D 10)

An effect is a collection of pipeline state. An effect includes rendering state or course, but it includes much more state than just rendering state. A better way to think about it is that an effect contains whatever state is required to initialize all the pipeline stages. With DX10, the state required for each state has largely been encapsulated into chunks, making is simpler to keep track of what state is required.

For many stages, the pipeline uses a corresponding structure to encapsulate state.

Pipeline State | State Structure
Input Assembler | D3D10_INPUT_ELEMENT_DESC
Rasterization | D3D10_RASTERIZER_DESC
Stream Output |
Output Merger | D3D10_BLEND_DESC and D3D10_DEPTH_STENCIL_DESC

For the shader stages, where the number of state changes need to be more controlled by an application, the state has been divided up into constant buffer state, sampler state, and shader resource state for performance reasons. By splitting the state up, an application that is carefully designed, can update only the state that is changing; this will lead to improved performance by reducing the amount of data that needs to be passed to the GPU.

So how do you organize the pipeline state in an effect?

The answer is, the order doesn't matter. Global variables do not have to be located at the top. However, all the samples in the SDK follow the same order, as it is good practice to organize the data the same way. So this is a brief description of the data ordering in the DX SDK sample effects.

  • Global Variables
  • Shaders
  • Techniques and Passes

Global Variables

Just like standard C practice, global variables are declared first, at the top of the file. Most often, these are variables that will be initialized by an application, and then used in an effect. Sometimes they are initialized and never changed, other times they are updated every frame. Just like C function scope rules, effect variables declared outside of the scope of effect functions are visible throughout the effect; any variable declared inside of an effect function is only visible within that function.

Here is an example of the variables declared in BasicHLSL10.fx.

// Global variables
float4 g_MaterialAmbientColor;      // Material's ambient color

Texture2D g_MeshTexture;            // Color texture for mesh

float    g_fTime;                   // App's time in seconds
float4x4 g_mWorld;                  // World matrix for object
float4x4 g_mWorldViewProjection;    // World * View * Projection matrix

// Texture samplers
SamplerState MeshTextureSampler
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

The syntax for effect variables is more fully detailed in Effect Variable Syntax (Direct3D 10). The syntax for effect texture samplers is more fully detailed in Effect Sampler Syntax (Direct3D 10).

Shaders

Shaders are small executable programs. You can think of shaders as encapsulating shader state, since the HLSL code implements the shader functionality. The pipeline uses three different kinds of shaders.

  • Vertex shaders - Operate on vertex data. One vertex in yields one vertex out.
  • Geometry shaders - Operate on primitive data. One primitive in may yield 0, 1, or many primitives out.
  • Pixel shaders - Operate on pixel data. One pixel in yields 1 pixel out (unless the pixel is culled out of a render).

Shaders are local functions and follow C style function rules. When an effect is compiled, each shader is compiled and a pointer to each shader function is stored internally. An ID3D10Effect interface is returned when compilation is successful. At this point the compiled effect is in an intermediate format (add LINK).

To find out more information about the compiled shaders, you will need to use shader reflection. This is essentially like asking the runtime to deomcompile the shaders, and return information back to you about the shader code.

struct VS_OUTPUT
{
    float4 Position   : SV_POSITION; // vertex position
    float4 Diffuse    : COLOR0;      // vertex diffuse color
    float2 TextureUV  : TEXCOORD0;   // vertex texture coords
};

VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
                         float3 vNormal : NORMAL,
                         float2 vTexCoord0 : TEXCOORD,
                         uniform int nNumLights,
                         uniform bool bTexture,
                         uniform bool bAnimate )
{
    VS_OUTPUT Output;
    float3 vNormalWorldSpace;

    ....

    return Output;
}

struct PS_OUTPUT
{
    float4 RGBColor : SV_Target;  // Pixel color
};

PS_OUTPUT RenderScenePS( VS_OUTPUT In,
                         uniform bool bTexture )
{
    PS_OUTPUT Output;

    if( bTexture )
        Output.RGBColor = g_MeshTexture.Sample(MeshTextureSampler, In.TextureUV) * In.Diffuse;
    ....

    return Output;
}

The syntax for effect shaders is more fully detailed in Effect Function Syntax (Direct3D 10).

Techniques and Passes

A technique is a collection of rendering passes (there must be at least one pass). Each effect pass (which is similar in scope to a single pass in a render loop) defines the shader state and any other pipeline state necessary to render geometry.

Here is an example of one technique (which includes one pass) from BasicHLSL10.fx.

technique10 RenderSceneWithTexture1Light
{
    pass P0
    {
        SetVertexShader( CompileShader( vs_4_0, RenderSceneVS( 1, true, true ) ) );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_4_0, RenderScenePS( true ) ) );
    }
}

The syntax for effect shaders is more fully detailed in Effect Technique Syntax (Direct3D 10).

See Also

Effects (Direct3D 10)


Effect System Interfaces (Direct3D 10)

The effect system defines several interfaces for managing effect state. There are two types of interfaces: those used by the runtime to render an effect and reflection interfaces for getting and setting effect variables.

  • Effect Runtime Interfaces
  • Effect Reflection Interfaces

Effect Runtime Interfaces

Use runtime interfaces to render an effect.

Runtime Interfaces | Description
ID3D10Effect Interface | Collection of one or more techniques for rendering.
ID3D10Include Interface | An interface for adding custom behaviors when reading include files.
ID3D10EffectPass Interface | A collection of state assignments.
ID3D10EffectPool Interface | Create a memory location for variables to be shared between effects.
ID3D10EffectTechnique Interface | A collection of one or more passes.

Effect Reflection Interfaces

Reflection is implemented in the effect system to support reading (and writing) effect state. There are multiple ways to access effect variables.

Setting Groups of Effect State

Use these interfaces to get and set a group of state.

Reflection Interfaces | Description
ID3D10EffectBlendVariable Interface | Get and set blend state.
ID3D10EffectDepthStencilVariable Interface | Get and set depth-stencil state.
ID3D10EffectRasterizerVariable Interface | Get and set rasterizer state.
ID3D10EffectSamplerVariable Interface | Get and set sampler state.

Setting Effect Resources

Use these interfaces to get and set resources.

Reflection Interfaces | Description
ID3D10EffectConstantBuffer Interface | Access data in a texture buffer or constant buffer.
ID3D10EffectDepthStencilViewVariable Interface | Access data in a depth-stencil resource.
ID3D10EffectRenderTargetViewVariable Interface | Access data in a render target.
ID3D10EffectShaderResourceVariable Interface | Access data in a shader resource.

Setting Other Effect Variables

Use these interfaces to get and set state by the variable type.

Reflection Interfaces | Description
ID3D10EffectMatrixVariable Interface | Get and set a matrix.
ID3D10EffectScalarVariable Interface | Get and set a scalar.
ID3D10EffectShaderVariable Interface | Get and set a shader variable.
ID3D10EffectStringVariable Interface | Get and set a string.
ID3D10EffectType Interface | Get a variable type.
ID3D10EffectVectorVariable Interface | Get and set a vector.

All reflection interfaces derive from ID3D10EffectVariable Interface.

See Also

Programming Guide (Direct3D 10)


Specializing Interfaces (Direct3D 10)

ID3D10EffectVariable Interface has a number of methods for casting the interface into the particular type of interface you need. The methods are of the form AsType and include a method for each type of effect variable (such as AsBlend, AsConstantBuffer etc..)

For example, suppose you have an effect with two global variables: time and a world transform.

float    g_fTime;
float4x4 g_mWorld;

Here is an example (from SimpleSample10 Sample) that gets these variables:

ID3D10EffectVariable* g_pVariable;
ID3D10EffectMatrixVariable* g_pmWorld;
ID3D10EffectScalarVariable* g_pfTime;

g_pVariable = g_pEffect10->GetVariableByName("g_mWorld");
g_pmWorld = g_pVariable->AsMatrix();
g_pfTime = g_pEffect10->GetVariableByName("g_fTime");
g_pfTime = g_pVariable->AsScalar();

By specializing the interfaces, you could reduce the code to a single call.

g_pmWorld = (g_pEffect10->GetVariableByName("g_mWorld"))->AsMatrix();
g_pfTime = (g_pEffect10->GetVariableByName("g_fTime"))->AsScalar();

Interfaces that inherit from ID3D10EffectVariable Interface also have these methods, but they have been designed to return invalid objects; only calls from ID3D10EffectVariable Interface return valid objects. Applications can test the returned object to see if it is valid by calling ID3D10EffectVariable::IsValid.


Rendering an Effect (Direct3D 10)

An effect can be used to store information, or you can use it to render an effect in an application. Each technique specifies vertex, geoemtry, pixel shaders, shader state, sampler and texture state and other pipeline state. So once you have organized state into an effect, you can excapsulate the rendering effect that results from that state by creating and rendering the effect.

There are a few steps for preparing an effect for rendering. The first is compiling, which checks the HLSL like code against the HLSL language syntax and the effect framework rules. You can compile an effect from your application using API calls or you can compile an effect offline using the effect compiler utility. Once your effect has successfully compiled, create it by calling a different (but very similar) set of APIs.

After the effect is created, there are two remaining steps for using it. First, you must initialize the effect state values (the values of the effect variables) using a number of methods for setting state. For some variables this can be done once when an effect is created; others must be updated each time your application calls the render loop. Once the effect variables are set, you tell the runtime to render the affect by applying a technique. These topics are all discussed in further detail below.

  • Compile an Effect (Direct3D 10)
  • Create an Effect (Direct3D 10)
  • Set Effect State (Direct3D 10)
  • Apply a Technique (Direct3D 10)

Naturally there are performance considerations for using effects. These considerations are largely the same if you are not using an effect. Things like, minimizing the amount of state changes, or organizing the variables that need to be updated by frequency. These tactics are used to minimize the amount of data that needs to be sent from the CPU to the GPU, and therefore minimize potential synchronization problems.

See Also

Effects (Direct3D 10)


Compile an Effect (Direct3D 10)

Once an effect has been authored, the first step is to compile the code to check for syntax problems. This is done by calling one of the compile APIs (like D3DX10CompileEffectFromFile, D3DX10CompileEffectFromResource, D3DX10CompileEffectFromMemory). These API's invoke the effect compiler fxc.exe which is the compiler used to compile HLSL code. This is why the syntax for code in an effect looks very much like HLSL code (there are a few exceptions that will be handled later). By the way, the effect compiler/hlsl compiler (fxc.exe) is in the SDK in the utilities folder so that you can compile your shaders (or effects) offline if you choose. See the documentation for running the compiler from the command line.

  • Includes
  • Macros
  • HLSL Shader Flags
  • FX Flags
  • Threading
  • Checking Errors

Here's an example of compiling an effect file (from the BasicHLSL10 sample).

WCHAR str[MAX_PATH];
DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL10.fx" );

D3DX10CreateEffectFromFile( str, NULL, NULL,
    D3D10_SHADER_ENABLE_STRICTNESS, 0, pd3dDevice, NULL, NULL,
    &g_pEffect10, NULL );

Includes

One parameter is an include interface. Generate one of these if you want to include a customized behavior when reading an include file. This custom behavior is executed each time an effect (that uses the include pointer) is created or when an effect (that uses the include pointer) is compiled. To implement customized include behavior, derive a class from the Include interface. This provides your class two methods: Open and Close. Implement the custom behavior in the Open and Close methods.

Macros

Effect compilation can also take a pointer to macros that are defined elsewhere. For example, suppose you were to modify the effect in BasicHLSL10, to use two macros: zero and one. The effect code that uses the two macros is shown here.

if( bAnimate )
    vAnimatedPos += float4(vNormal, zero) *
        (sin(g_fTime+5.5)+0.5)*5;

    Output.Diffuse.a = one;

Here is the declaration for the two macros.

D3D10_SHADER_MACRO Shader_Macros[3] = { "zero", "0", "one", "1.0f", NULL, NULL };

The macros are a NULL terminated array of macros; where each macro is defined with a D3D10_SHADER_MACRO struct.

Lastly, modify the compile effect call to take a pointer to the macros.

D3DX10CreateEffectFromFile( str, Shader_Macros, NULL,
    D3D10_SHADER_ENABLE_STRICTNESS, 0, pd3dDevice, NULL, NULL,
    &g_pEffect10, NULL );

HLSL Shader Flags

Shader flags specify shader constrants to the HLSL compiler. These flags impact the code generated by the shader compiler including:

  • Size considerations: optimize the code.
  • Debug considerations: including debug information, preventing flow control.
  • Hardware considerations: the compile target and whether or not a shader can run on legacy hardware.

In general, these flags can be logically combined, assuming you have not specified two conflicting characteristics. For a listing of the flags see Effect Constants (Direct3D 10).

FX Flags

These flags used when creating an effect to define either compilation behavior or runtime effect behavior. For a listing of the flags see Effect Constants (Direct3D 10).

Threading

To be written...

Checking Errors

If during compilation, an error occurs, the API returns an interface which contains the errors returned from the effect compiler. This interface is called ID3D10Blob. It is not directly readable, however, by returning a pointer to the buffer that contains the data (which is a string), you can see any compilation errors.

In this example, an error was introduced into the BasicHLSL.fx effect by copying the first variable declaration twice.

//-------------------------------------------------------------------
// Global variables
//-------------------------------------------------------------------
float4 g_MaterialAmbientColor;      // Material's ambient color

// Declare the same variable twice
float4 g_MaterialAmbientColor;      // Material's ambient color

This caused the compiler to return the following error, as shown in the watch window in visual studio.

Since the error is returned in a LPVOID pointer, cast it to a character string in the watch window.

Here is the code used to return the error from the failed compile.

// Read the D3DX effect file
WCHAR str[MAX_PATH];
ID3D10Blob*	l_pBlob_Effect = NULL;
ID3D10Blob*	l_pBlob_Errors = NULL;
hr = DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL10.fx" );
hr = D3DX10CompileEffectFromFile( str, NULL, NULL,
    D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
    &l_pBlob_Effect, &l_pBlob_Errors );

LPVOID l_pError = NULL;
if( l_pBlob_Errors )
{
    l_pError = l_pBlob_Errors->GetBufferPointer();
    // then cast to a char* to see it in the locals window
}

See Also

Rendering an Effect (Direct3D 10)


Create an Effect (Direct3D 10)

An effect is created by loading it into the effects framework. If the effect has never been compiled, it will be compiled when it is created. Effects that are already loaded into memory can be created by calling D3DX10CreateEffectFromMemory. The following code example uses D3DX10CreateEffectFromFile to create an effect from a file.

ID3D10Effect* g_pEffect10 = NULL;

// Read the effect file
D3DX10CreateEffectFromFile( "BasicHLSL10.fx", NULL, NULL,
  D3D10_SHADER_ENABLE_STRICTNESS, 0, pd3dDevice, NULL, NULL,
  &g_pEffect10, NULL );

Reading an effect requires the same parameters as compiling an effect, plus a device and a pool.

See Also

Rendering an Effect (Direct3D 10)


Set Effect State (Direct3D 10)

Some effect constants only need to be initialized. Once initialized, the effect state is set to the device for the entire render loop. Other variables need to be updated each time the render loop is called. The basic code for setting effect variables is shown below, for each of the types of variables.

An effect encapsulates all of the render state required to do a rendering pass. In terms of the API, there are three types of state encapsulated in an effect.

  • Constant State
  • Shader State
  • Texture State

Constant State

First, declare variables in an effect using HLSL data types.

//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
float4 g_MaterialAmbientColor;      // Material's ambient color
float4 g_MaterialDiffuseColor;      // Material's diffuse color
int g_nNumLights;

float3 g_LightDir[3];               // Light's direction in world space
float4 g_LightDiffuse[3];           // Light's diffuse color
float4 g_LightAmbient;              // Light's ambient color

Texture2D g_MeshTexture;            // Color texture for mesh

float    g_fTime;                   // App's time in seconds
float4x4 g_mWorld;                  // World matrix for object
float4x4 g_mWorldViewProjection;    // World * View * Projection matrix

Second, declare variables in the application that can be set by the application, and will then update the effect variables.

    D3DXMATRIX  mWorldViewProjection;
    D3DXVECTOR3 vLightDir[MAX_LIGHTS];
    D3DXVECTOR4 vLightDiffuse[MAX_LIGHTS];
    D3DXMATRIX  mWorld;
    D3DXMATRIX  mView;
    D3DXMATRIX  mProj;

    // Get the projection and view matrix from the camera class
    mWorld = g_mCenterMesh * *g_Camera.GetWorldMatrix();
    mProj = *g_Camera.GetProjMatrix();
    mView = *g_Camera.GetViewMatrix();

OnD3D10CreateDevice()
{
  ...
    g_pLightDir = g_pEffect10->GetVariableByName( "g_LightDir" )->AsVector();
    g_pLightDiffuse = g_pEffect10->GetVariableByName( "g_LightDiffuse" )->AsVector();
    g_pmWorldViewProjection = g_pEffect10->GetVariableByName(
        "g_mWorldViewProjection" )->AsMatrix();
    g_pmWorld = g_pEffect10->GetVariableByName( "g_mWorld" )->AsMatrix();
    g_pfTime = g_pEffect10->GetVariableByName( "g_fTime" )->AsScalar();
    g_pMaterialAmbientColor = g_pEffect10->GetVariableByName("g_MaterialAmbientColor")->AsVector();
    g_pMaterialDiffuseColor = g_pEffect10->GetVariableByName(
        "g_MaterialDiffuseColor" )->AsVector();
    g_pnNumLights = g_pEffect10->GetVariableByName( "g_nNumLights" )->AsScalar();
}

Third, use the update methods to set the value of the variables in the application in the effect variables.

OnD3D10FrameRender()
{
    ...
    g_pLightDir->SetRawValue( vLightDir, 0, sizeof(D3DXVECTOR3)*MAX_LIGHTS );
    g_pLightDiffuse->SetFloatVectorArray( (float*)vLightDiffuse, 0, MAX_LIGHTS );
    g_pmWorldViewProjection->SetMatrix( (float*)&mWorldViewProjection );
    g_pmWorld->SetMatrix( (float*)&mWorld );
    g_pfTime->SetFloat( (float)fTime );
    g_pnNumLights->SetInt( g_nNumActiveLights );
}

Two Ways to Get the State in an Effect Variable

There are two ways to get the state contained in an effect variable. Given an effect that has been loaded into memory.

One way is to get the sampler state from an ID3D10EffectVariable Interface that has been cast as a sampler interface.

D3D10_SAMPLER_DESC sampler_desc;
ID3D10EffectVariable* l_pD3D10EffectVariable = NULL;
if( g_pEffect10 )
{
    l_pD3D10EffectVariable = g_pEffect10->GetVariableByName( "MeshTextureSampler" );
    if( l_pD3D10EffectVariable )
        hr = (l_pD3D10EffectVariable->AsSampler())->GetBackingStore( 0,
            &sampler_desc );
}

The other way is to get the sampler state from an ID3D10SamplerState Interface.

ID3D10SamplerState* l_ppSamplerState = NULL;
D3D10_SAMPLER_DESC sampler_desc;
ID3D10EffectVariable* l_pD3D10EffectVariable = NULL;
if( g_pEffect10 )
{
    l_pD3D10EffectVariable = g_pEffect10->GetVariableByName( "MeshTextureSampler" );
    if( l_pD3D10EffectVariable )
    {
        hr = (l_pD3D10EffectVariable->AsSampler())->GetSampler( 0,
            &l_ppSamplerState );
        if( l_ppSamplerState )
            l_ppSamplerState->GetDesc( &sampler_desc );
    }
}

Shader State

Shader state is declared and assigned in an effect technique, within a pass.

technique10 RenderSceneWithTexture1Light
{
    pass P0
    {
        SetVertexShader( CompileShader( vs_4_0, RenderSceneVS( 1, true, true ) ) );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_4_0, RenderScenePS( true ) ) );
    }
}

This works just like it would if you were not using an effect. There are three calls, one for each type of shader (vertex, geometry, and pixel). The first one, SetVertexShader, calls ID3D10Device::VSSetShader. CompileShader is a special effect function that takes the shader profile(vs_4_0) and the name of the vertex shader function (RenderVS). In other words, each of these SetXXXShader calls compiles their associated shader function and returns a pointer to the compiled shader.

Texture State

Texture state is a little more complex than setting a variable, because texture data is not simply read like a variable, it is sampled from a texture. Therefore, you must define the texture variable (just like a normal variable except it uses a texture type) and you must define the sampling conditions. Here is an example of a texture variable declaration and the corresponding sampling state declaration.

Texture2D g_MeshTexture;            // Color texture for mesh

SamplerState MeshTextureSampler
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

Here is an example of setting a texture from an application. In this example, the texture is stored in the mesh data, that was loaded when the effect was created.

The first step is getting a pointer to the texture from the effect (from the mesh).

ID3D10EffectShaderResourceVariable* g_ptxDiffuse = NULL;

    // Obtain variables
    g_ptxDiffuse = g_pEffect10->GetVariableByName( "g_MeshTexture" )->AsShaderResource();

The second step is specifying a view for accessing the texture. The view defines a general way to access the data from the texture resource.

OnD3D10FrameRender()
{
  ID3D10ShaderResourceView* pDiffuseRV = NULL;

   ...
   pDiffuseRV = g_Mesh10.GetMaterial(pSubset->MaterialID)->pDiffuseRV10;
   g_ptxDiffuse->SetResource( pDiffuseRV );
   ...
}

For more information about viewing resources, see Memory Structure and Views (Direct3D 10).

See Also

Rendering an Effect (Direct3D 10)


Apply a Technique (Direct3D 10)

With the constants, textures, and shader state declared and initialized, the only thing left to do is to set the effect state in the device.

Set Non-Shader State in the Device

Some pipeline state is not set by an effect. For example clearing a render target prepares the render target for data. Before setting the effect state in the device, here is an example of clearing output buffers.

    // Clear the render target and depth stencil
    float ClearColor[4] = { 0.0f, 0.25f, 0.25f, 0.55f };
    ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView();
    pd3dDevice->ClearRenderTargetView( pRTV, ClearColor );
    ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView();
    pd3dDevice->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 );

Set Effect State in the Device

Setting effect state is done by applying the effect state within the render loop. This is done from the outside in. That is, select a technique, and then set the state for each of the passes (depending on your desired result).

    D3D10_TECHNIQUE_DESC techDesc;
    pRenderTechnique->GetDesc( &techDesc );
    for( UINT p = 0; p < techDesc.Passes; ++p )
    {
        }
            ....
            pRenderTechnique->GetPassByIndex( p )->Apply(0);
            pd3dDevice->DrawIndexed( (UINT)pSubset->IndexCount, 0,
                 (UINT)pSubset->VertexStart );
        }
    }

An effect doesn't render anything, it simply sets effect state to the device. The rendering code is called after the effect state updates device state. In this example, the DrawIndexed call performs the rendering.

See Also

Rendering an Effect (Direct3D 10)


Performance Considerations (Direct3D 10)

Using Effect Pools

It is common for rendering pipelines to use many shaders to render different object types and special effects. The shader are a mixture of states that a common among all the shaders such as a world matrix or a light position, and other state that is specific to each shader such as an object's diffuse color, or specular highlight calculation. An effect pool is a place in memory to store state that is used across many shaders, as well as common device objects such as shaders, render state objects and constant buffers. The preformance improvement results from updating the common state once for all the shaders that need that state.

An effect pool is a shared memory location for effect state. A pool is created similarly to an effect; it can be created from memory (or a file or a resource). This leads to two different types of effects: a global effect that does not depend on state in other effect versus a child effect which depends on state in another effect.

You specify whether an effect is a global effect (the default case) or a child effect (by supplying the D3D10_COMPILE_CHILD_EFFECT flag) when the effect is created. A global effect can serve as an effect pool; a child effect cannot be an effect pool.

See Also

Effects (Direct3D 10)


Direct3D 9 to Direct3D 10 Considerations (Direct3D 10)

The following page provides a basic outline of key differences between Direct3D 9 and Direct3D 10. This documentation is preliminary and incomplete; it serves as a prelude to a comprehensive Direct3D 9 to Direct3D 10 porting and cross-platform development guide which will be provided in a future release of the DirectX SDK. The outline below provides some initial insight to assist developers with Direct3D 9 experience to explore and relate to Direct3D 10.

  • Overview of the Major Structural Changes in Direct3D 10
  • Engine Abstractions / Separation
  • Tricks for Quickly Resolving Application Build Issues
  • Driving the Direct3D 10 API
  • Porting Textures
  • Porting Shaders
  • Additional Direct3D 10 Differences to Watch For

Overview of the Major Structural Changes in Direct3D 10

  • Removal of Fixed Function
  • Device Object Creation Time Validation

The process of rendering using the Direct3D 10 device is structurally similar to Direct3D 9.

  • Set a vertex stream source
  • Set input layout in Direct3D 10 (Set vertex stream declaration in Direct3D 9)
  • Declare primitive topology
  • Set textures
  • Set state objects
  • Set shaders
  • Draw

The Draw call ties the operations together; the ordering of calls prior to the Draw call is arbitrary. The major differences in the Direct3D 10 API design are as follows:

  • Removal of Fixed Function
  • Removal of CAPS bits - Direct3D 10's base feature set is guaranteed
  • Stricter management of: resource access, device state, shader constants, shader linkage (inputs and outputs to shaders) between stages
  • API entry point names changes reflect the virtualization of GPU memory (Map() instead of Lock()).
  • A debug layer can be added to the device at creation time
  • The primitive topology is now an explicit state (separated from the Draw call)
  • Explicit shader constants are now stored in constant buffers
  • Shader authoring is done entirely in HLSL. The HLSL compiler now resides in the primary Direct3D 10 DLL.
  • New programmable stage - the geometry shader
  • Removal of BeginScene()/EndScene()
  • Common 2D, focus and adapter-management functionality refactored into a new component: DXGI

Removal of Fixed Function

It is sometimes surprising that even in a Direct3D 9 engine that fully exploits the programmable pipeline, there remains a number of areas that depend on the fixed-function (FF) pipeline. The most common areas are usually related to screen-space aligned rendering for UI. It is for this reason that you are likely to need to build a FF emulation shader or set of shaders which provide the necessary replacement behaviors.

This documentation contains a whitepaper containing replacement shader sources for the most common FF behaviors (see Fixed Function EMU Sample). Some fixed-function pixel behavior including alpha test has been moved into shaders.

Device Object Creation Time Validation

The Direct3D 10 pipeline has been redesigned from the ground up in hardware and software with a primary intention to reduce CPU overhead (at Draw time). To reduce costs, all types of device data have been assigned an object with explicit creation methods provided by the device itself. This enables strict data validation at object creation time instead of during the Draw call as it often does with Direct3D 9.

Engine Abstractions / Separation

Applications, including Games, that wish to support both Direct3D 9 and Direct3D 10 need to have the rendering layers abstracted from the rest of the code base. There are many ways to achieve this but key to all of them is the design of the abstraction layer for the lower-level Direct3D device. All systems should communicate to the hardware through the common layer which is designed to provide GPU resource and low-level type management.

Direct Removal of Direct3D 9 Dependencies

When porting large, previously tested code bases, it is important to minimize the amount of code changes to those which are absolutely necessary to preserve previously tested behaviors in the code. Best practices include clearly documenting where items change using comments. It's often useful to have a commenting standard for this work which enables quick navigation through the code base.

The following is an example list of standard single line / start block comments which could be used for this work.

// Direct3D 10 REMOVED
Use this where lines / blocks of code are removed
// Direct3D 10 NEEDS UPDATE
It helps to added additional notes to the NEED UPDATE comment that suggests what work / new API should be used for later visits to the code for behavior conversion. Heavy use of assert(false) should also be used where \\ Direct3D 10 NEEDS UPDATE occurs to ensure you do not unknowingly run errant code
// Direct3D 10 CHANGED
Areas where major changes have occurred should be kept for future reference but commented out
// Direct3D 10 END
End code block qualifier

For multiple lines of source you should use the C style /* */ comments too but add the relevant start / end comments around these areas.

Tricks for Quickly Resolving Application Build Issues

  • Overriding Direct3D 9 Types
  • Resolving Link Issues
  • Simulating Device CAPs

Overriding Direct3D 9 Types

It may be useful to insert a high level header file containing type definitions / overrides for Direct3D 9 base types which are no longer supported by the Direct3D 10 headers. This will help you minimize the amount of changes in the code and interfaces where there is a direct mapping from a Direct3D 9 type to the newly defined Direct3D 10 type. This approach is also useful for keeping code behaviors together in one source file. In this case, it is a good idea to define version neutral / generally named types which describe common constructs used for rendering yet span both Direct3D 9 and Direct3D 10 APIs. For example:

#if defined(D3D9)
typedef IDirect3DIndexBuffer9   IDirect3DIndexBuffer;
typedef IDirect3DVertexBuffer9  IDirect3DVertexBuffer;
#else //D3D10
typedef ID3D10Buffer            IDirect3DIndexBuffer;
typedef ID3D10Buffer            IDirect3DVertexBuffer
#endif

Other Direct3D 10 specific examples of this include:

typedef ID3D10TextureCube 	IDirect3DCubeTexture;
typedef ID3D10Texture3D 	IDirect3DVolumeTexture;
typedef D3D10_VIEWPORT 		D3DVIEWPORT;
typedef ID3D10VertexShader 	IDirect3DVertexShader;
typedef ID3D10PixelShader 	IDirect3DPixelShader;

Resolving Link Issues

It is advisable to develop Direct3D 10 and Windows Vista applications using the latest version of Microsoft Visual Studio. However, it is possible to build a Windows Vista application which depends on Direct3D 10 using the earlier 2003 version of Visual Studio. Direct3D 10 is a Windows Vista platform component which has dependencies (as with the Server 2003 SP1 platform SDK) on the following lib: BufferOverflowU.lib is needed to solve any buffer_security check linker issues.

Simulating Device CAPs

Many applications contain areas of code which depend on device CAPS data being available. Work around this be overriding device enumeration and forcing device CAPS to sensible values. Plan to re-visit areas where there are dependencies on CAPS later for full removal of CAPS where possible.

Driving the Direct3D 10 API

This section focuses on the behavior changes caused by the Direct3D 10 API.

  • Resource Creation
  • Views
  • Static versus Dynamic Resource Access
  • Direct3D 10 Effects
  • HLSL without Effects
  • Shader Compilation
  • Creation of Shader Resources
  • Shader Reflection Layer Interface
  • Input Assembler Layouts - Vertex Shader / Input Stream Linkage
  • Impact of Shader Dead Code Removal
  • Vertex Shader Input Structure Example
  • State Object Creation

Resource Creation

The Direct3D 10 API has designed resources as generic buffer types which have specific bind flags according to the planned usage. This design point was chosen to facilitate near ubiquitous access of resources in the Pipeline for scenarios such as rendering to a vertex buffer then instantly drawing the results without interrupting the CPU. The following example demonstrates allocation of vertex buffers and index buffer where you can see that the resource description only differs by the GPU resource bind flags.

The Direct3D 10 API has provided texture helper methods for explicitly creating texture type resources but as you can imagine, these are really helper functions.

  • CreateTexture2D()
  • CreateTextureCube()
  • CreateTexture3D()

When targeting Direct3D 10, you are likely to want to allocate more items during resource creation time than you are used to with Direct3D 9. This will become most apparent with the creation of Render Target buffers and Textures where you need to also create a view for accessing the buffer and setting the resource on the device.

Tutorial 1: Direct3D 10 Basics

Views

A view is a specifically typed, interface to data stored in a pixel buffer. A resource can have several views allocated on it at once and this feature is highlighted in the Single Pass Render to Cubemap sample contained in this SDK.

Programmers Guide page on Resource Access

CubeMap Sample

Static versus Dynamic Resource Access

For best performance, applications should partition their data use in terms of the static vs dynamic nature of the data. Direct3D 10 has been designed to take advantage of this approach and as such, the access rules for resources have been significantly tightened up over Direct3D 9. For static resources you should ideally populate the resource with its data during creation time. If your engine has been architected around the Create, Lock, Fill, Unlock design point of Direct3D 9, you may defer population from Create time by using a staging resource and the UpdateSubResource method on the resource interface.

Direct3D 10 Effects

Use of the Direct3D 10 Effects system is outside the scope of this article. The system has been written to take full advantage of the architectural benefits that Direct3D 10 provides. See the Unknown Topic section for more detail on its use.

HLSL without Effects

The Direct3D 10 Shader pipeline may be driven without the use of the Direct3D 10 Effects system. Note that in this instance, all constant buffer, shader, sampler and texture binding must be managed by the application itself. See the sample link and following sections of this document for more detail:

Direct3D 10 without Effects sample

Shader Compilation

The Direct3D 10 HLSL compiler brings enhancements to the HLSL language definition and therefore has the ability to operate in 2 modes. For complete support of Direct3D 9 style intrinsics and semantics, compilation should be invoked using the COMPATIBILITY MODE flag which can be specified on a per compile basis.

The Direct3D 10 shader model 4.0 specific HLSL language semantics and intrinsics can be found at the link referenced below. Major changes in syntax from Direct3D 9 HLSL to take the most notice of are in the area of texture access. The new syntax is the only form supported by the compiler outside of compatibility mode. For more details, see HLSL.

Creation of Shader Resources

The creation of compiled shader instances outside of the Direct3D 10 Effects system is done in a very similar manner to Direct3D 9 however, in Direct3D 10, it is important to keep the Shader Input signature around for later use. The signature is returned by default as part of the shader blob but may be extracted to reduce the memory requirements if needed. For more details, see Using Shaders in Direct3D 10.

Shader Reflection Layer Interface

The shader reflection layer is the interface by which information about the shader requirements may be obtained. This is particularly useful when creating Input Assembly linkages (see below) where you may need to traverse the shader input requirements to ensure you are supplying the correct input structure to the shader. You can create an instance of the reflection layer interface at the same time as creating an instance of a compiled shader.

Input Assembler Layouts - Vertex Shader / Input Stream Linkage

The Input Assembler (IA) replaces the Direct3D 9 style Vertex Stream Declaration and it's description structure is very similar in form. The main difference that the IA brings is that the IA layout object created must directly map to a specific format of shader input signature. The mapping object created to link the input stream to shader may be used across any number of shaders where the shader input signature matches that of the shader used to create the Input Layout.

To best drive the pipeline with static data, you should consider the permutations of input stream format to possible shader input signatures and create the IA layout object instances as early as is possible and reuse them where possible.

Impact of Shader Dead Code Removal

The following section details a significant difference between Direct3D 9 and Direct3D 10 that is likely to require careful handling in your engine code. Shaders which contain conditional expressions often have certain code paths removed as part of the compilation process. In Direct3D 9, any input elements that match the associated code removed are also from their shader input structure. This no longer occurs in Direct3D 10 as the intention is to allow the same Input Signature to be used across all possible permutations of the shader code without invoking the rather costly change of Input Layout. This has an impact on the engine when handling large shaders and creating Input Layouts. Elements which are removed by dead code optimizations in the compiler must still be declared in the Input Structure. The following example demonstrates this situation:

Vertex Shader Input Structure Example

typedef struct
{
float4 pos: SV_Position;
float2 uv1 : Texcoord1;
float2 uv2 : Texcoord2; *
} VS_INPUT;

* Direct3D 9 dead code removal would remove the declaration in the shader due to conditional dead code removal

float4x4  g_WorldViewProjMtx;
bool      g_bLightMapped = false;

VS_INPUT main(VS_INPUT i)
{
    VS_INPUT o;
    o.pos = mul( i.pos, g_ WorldViewProjMtx);
    o.uv1 = i.uv1;
    if ( g_bLightMap )
    {
        o.uv2 = i.uv2;
    }
}

In the above example, under Direct3D 9, the uv2 element would be removed due to dead code optimizations in the compiler. Under Direct3D 10, the dead code will still be removed but the shader Input Assembler layout requires the definition of the input data to exist. The shader reflection layer provides the means to handle this situation in a generic manner whereby you can traverse the Shader Input requirements and ensure that you provide a full description of the Input Stream to shader signature mapping. The following code snippet demonstrates use of the reflection layer to determine shader requirements during Input Assembler layout specification:

// This example helper function checks the Shader Signature to see if
// it expects a particular semantic
// The HardwareShader_t input structure contains a pointer to a
// previously acquired shader reflection layer as follows:
//
typedef struct HardwareShader_s
{
  ID3D10Blob *pShaderBlobwithSignature;
  ID3D10ShaderReflection	*IReflect;

  // DEBUG - helps to keep the shader filename around for debugging
  #ifdef _DEBUG
  char	filename[MAX_PATH];
   #endif

} HardwareShader_t;

bool CheckShaderSignatureExpectations(const HardwareShader_t *pShader,
  const LPCSTR pSemantic)
{
    D3D10_SHADER_DESC               shaderDesc;
    D3D10_SIGNATURE_PARAMETER_DESC	paramDesc;

    Assert(pShader);
    Assert(pSemantic);
    Assert(pShader->IReflect);

    pShader->IReflect->GetDesc(&shaderDesc);

    for (UINT k=0; k<shaderDesc.InputParameters; k++)
    {
        pShader->IReflect->GetInputParameterDesc( k, &paramDesc);
        if (wcscmp( pSemantic, paramDesc.SemanticName)==0)
            return true;
    }

    return false;
}

State Object Creation

When porting engine code, it may help to initially use a default set of state objects and disable all Direct3D 9 device render state / texture state setting. This will cause rendering artifacts but is the quickest way to get things up and running. You can later construct a state object management system which can use a compound key to enable maximum reuse of the number of state objects being used.

Porting Textures

The following table shows the mapping of texture formats from Direct3D 9 to Direct3D 10. Any content in formats not available in DXGI will need to be converted by utility routines.

Direct3D 9 Format | Direct3D 10 Format
D3DFMT_UNKNOWN | DXGI_FORMAT_UNKNOWN
D3DFMT_R8G8B8 | Not available
D3DFMT_A8R8G8B8 | Not available
D3DFMT_X8R8G8B8 | Not available
D3DFMT_R5G6B5 | Not available
D3DFMT_X1R5G5B5 | Not available
D3DFMT_A1R5G5B5 | Not available
D3DFMT_A4R4G4B4 | Not available
D3DFMT_R3G3B2 | Not available
D3DFMT_A8 | DXGI_FORMAT_A8_UNORM
D3DFMT_A8R3G3B2 | Not available
D3DFMT_X4R4G4B4 | Not available
D3DFMT_A2B10G10R10 | DXGI_FORMAT_R10G10B10A2
D3DFMT_A8B8G8R8 | DXGI_FORMAT_R8G8B8A8_UNORM & DXGI_FORMAT_R8G8B8A8_UNORM_SRGB
D3DFMT_X8B8G8R8 | Not available
D3DFMT_G16R16 | DXGI_FORMAT_R16G16_UNORM
D3DFMT_A2R10G10B10 | Not available
D3DFMT_A16B16G16R16 | DXGI_FORMAT_R16G16B16A16_UNORM
D3DFMT_A8P8 | Not available
D3DFMT_P8 | Not available
D3DFMT_L8 | DXGI_FORMAT_R8_UNORM Note: Use .r swizzle in shader to duplicate red to other components to get D3D9 behavior.
D3DFMT_A8L8 | Not available
D3DFMT_A4L4 | Not available
D3DFMT_V8U8 | DXGI_FORMAT_R8G8_SNORM
D3DFMT_L6V5U5 | Not available
D3DFMT_X8L8V8U8 | Not available
D3DFMT_Q8W8V8U8 | DXGI_FORMAT_R8G8B8A8_SNORM
D3DFMT_V16U16 | DXGI_FORMAT_R16G16_SNORM
D3DFMT_W11V11U10 | Not available
D3DFMT_A2W10V10U10 | Not available
D3DFMT_UYVY | Not available
D3DFMT_R8G8_B8G8 | DXGI_FORMAT_G8R8_G8B8_UNORM (in DX9 the data was scaled up by 255.0f, but this can be handled in shader code).
D3DFMT_YUY2 | Not available
D3DFMT_G8R8_G8B8 | DXGI_FORMAT_R8G8_B8G8_UNORM (in DX9 the data was scaled up by 255.0f, but this can be handled in shader code).
D3DFMT_DXT1 | DXGI_FORMAT_BC1_UNORM & DXGI_FORMAT_BC1_UNORM_SRGB
D3DFMT_DXT2 | DXGI_FORMAT_BC1_UNORM & DXGI_FORMAT_BC1_UNORM_SRGB Note: DXT1 and DXT2 are the same from an API/hardware perspective... only difference was 'premultiplied alpha', which can be tracked by an application and doesn't need a separate format.
D3DFMT_DXT3 | DXGI_FORMAT_BC2_UNORM & DXGI_FORMAT_BC2_UNORM_SRGB
D3DFMT_DXT4 | DXGI_FORMAT_BC2_UNORM & DXGI_FORMAT_BC2_UNORM_SRGB Note: DXT3 and DXT4 are the same from an API/hardware perspective... only difference was 'premultiplied alpha', which can be tracked by an application and doesn't need a separate format.
D3DFMT_DXT5 | DXGI_FORMAT_BC3_UNORM & DXGI_FORMAT_BC3_UNORM_SRGB
D3DFMT_D16 & D3DFMT_D16_LOCKABLE | DXGI_FORMAT_D16_UNORM
D3DFMT_D32 | Not available
D3DFMT_D15S1 | Not available
D3DFMT_D24S8 | Not available
D3DFMT_D24X8 | Not available
D3DFMT_D24X4S4 | Not available
D3DFMT_D16 | DXGI_FORMAT_D16_UNORM
D3DFMT_D32F_LOCKABLE | DXGI_FORMAT_D32_FLOAT
D3DFMT_D24FS8 | Not available
D3DFMT_S1D15 | Not available
D3DFMT_S8D24 | DXGI_FORMAT_D24_UNORM_S8_UINT
D3DFMT_X8D24 | Not available
D3DFMT_X4S4D24 | Not available
D3DFMT_L16 | DXGI_FORMAT_R16_UNORM Note: Use .r swizzle in shader to duplicate red to other components to get D3D9 behavior.
D3DFMT_INDEX16 | DXGI_FORMAT_R16_UINT
D3DFMT_INDEX32 | DXGI_FORMAT_R32_UINT
D3DFMT_Q16W16V16U16 | DXGI_FORMAT_R16G16B16A16_SNORM
D3DFMT_MULTI2_ARGB8 | Not available
D3DFMT_R16F | DXGI_FORMAT_R16_FLOAT
D3DFMT_G16R16F | DXGI_FORMAT_R16G16_FLOAT
D3DFMT_A16B16G16R16F | DXGI_FORMAT_R16G16B16A16_FLOAT
D3DFMT_R32F | DXGI_FORMAT_R32_FLOAT
D3DFMT_G32R32F | DXGI_FORMAT_R32G32_FLOAT
D3DFMT_A32B32G32R32F | DXGI_FORMAT_R32G32B32A32_FLOAT
D3DFMT_CxV8U8 | Not available
D3DDECLTYPE_FLOAT1 | DXGI_FORMAT_R32_FLOAT
D3DDECLTYPE_FLOAT2 | DXGI_FORMAT_R32G32_FLOAT
D3DDECLTYPE_FLOAT3 | DXGI_FORMAT_R32G32B32_FLOAT
D3DDECLTYPE_FLOAT4 | DXGI_FORMAT_R32G32B32A32_FLOAT
D3DDECLTYPED3DCOLOR | Not available
D3DDECLTYPE_UBYTE4 | DXGI_FORMAT_R8G8B8A8_UINT Note: Shader gets UINT values, but if Direct3D 9 style integral floats are needed (0.0f, 1.0f... 255.f), UINT can just be converted to float32 in shader.
D3DDECLTYPE_SHORT2 | DXGI_FORMAT_R16G16_SINT Note: Shader gets SINT values, but if Direct3D 9 style integral floats are needed, SINT can just be converted to float32 in shader.
D3DDECLTYPE_SHORT4 | DXGI_FORMAT_R16G16B16A16_SINT Note: Shader gets SINT values, but if Direct3D 9 style integral floats are needed, SINT can just be converted to float32 in shader.
D3DDECLTYPE_UBYTE4N | DXGI_FORMAT_R8G8B8A8_UNORM
D3DDECLTYPE_SHORT2N | DXGI_FORMAT_R16G16_SNORM
D3DDECLTYPE_SHORT4N | DXGI_FORMAT_R16G16B16A16_SNORM
D3DDECLTYPE_USHORT2N | DXGI_FORMAT_R16G16_UNORM
D3DDECLTYPE_USHORT4N | DXGI_FORMAT_R16G16B16A16_UNORM
D3DDECLTYPE_UDEC3 | Not available
D3DDECLTYPE_DEC3N | Not available
D3DDECLTYPE_FLOAT16_2 | DXGI_FORMAT_R16G16_FLOAT
D3DDECLTYPE_FLOAT16_4 | DXGI_FORMAT_R16G16B16A16_FLOAT

For uncompressed formats, DXGI has limited the support for arbitrary pixel format patterns; all uncompressed formats must be of type RGBA. This may require swizzling of existing assets pixel formats which we advise that you compute as an offline pre-process pass where possible.

Porting Shaders

Direct3D 10 Shaders are Authored in HLSL

Direct3D 10 limits the use of assembly language to that of debugging purposes only, therefore any hand written assembly shaders used in Direct3D 9 will need to be converted to HLSL.

Shader Signatures and Linkage

We have already discussed the requirements for Input Assembly linkages to Vertex shader input signatures earlier in this document (see above). Note that the Direct3D 10 runtimes have also tightened the requirements for stage to stage linkage between shaders. This change will affect shader sources where the binding between stages may not have been fully described under Direct3D 9. For example:

VS_OUTPUT                       PS_INPUT
float4   pos : SV_POSITION;     float4 pos : SV_POSITION;
float4   uv1 : TEXCOORD1;       float4 uv1 : TEXCOORD1;
float4x3 tangentSp : TEXCOORD2; float4 tangent : TEXCOORD2; *
float4   Color : TEXCOORD6;     float4 color : TEXCOORD6;

* Broken VS - PS Linkage - even though the Pixel Shader may not be interested in the full matrix, the linkage must specify the full float4x3.

Note, the linkage semantics between stages must match exactly however, the target stages inputs may be a prefix of the values being output. In the example above, the pixel shader could have position and texcoord1 as the only inputs, but it could not have the position and texcoord2 as the only inputs due to the ordering constraints.

HLSL Shader Stage linkages

Linkages between shaders may occur at any of the following points in the pipeline:

  • Input Assembler to Vertex Shader
  • Vertex Shader to Pixel Shader
  • Vertex Shader to Geometry Shader
  • Vertex Shader to Stream Output
  • Geometry Shader to Pixel Shader
  • Geometry Shader to Stream Out

Constant Buffers

For ease of porting content from Direct3D 9 an initial approach to constant management outside of the Effects system might involve the creation of a single constant buffer containing all the required constants. It is important for performance to order constants into buffers by the expected frequency of update. This organization will reduce the amount of redundant constant sets to a minimum.

Additional Direct3D 10 Differences to Watch For

Integers as Input

In Direct3D 9, there was no real hardware support for integer data types, however in Direct3D 10 hardware supports explicit integer types. If you have floating point data in your vertex buffer, then you must have a float input. Otherwise the "int" will be the bit pattern representation of the floating point value. Integer inputs are also not allowed as input to a pixel shader unless the value is marked constinterp which is due to the interpolation for the pixel shader not being an integer interpolation.

Mouse Cursors

On previous versions of Windows, the standard GDI mouse cursor routines did not operate correctly on all full-screen exclusive devices. The IDirect3DDevice9::SetCursorProperties, IDirect3DDevice9::ShowCursor, and IDirect3DDevice9::SetCursorPosition APIs were added to handle these cases. Since Windows Vista's version of GDI fully understands DXGI surfaces, there is no need for this specialized mouse cursor API so there is no Direct3D 10 equivalent. Direct3D 10 applications should instead use the standard GDI mouse cursor routines for mouse cursors.

Reference Counting Behavior Changes

Unlike previous Direct3D versions, the various Set functions will not hold a reference to the devices objects. This means that the application must ensure that it holds a reference on the object for as long as it would like that object to be bound to the pipeline. When the ref count of the object drops to zero, then the object will be unbound from the pipeline as it is destroyed. This style of reference holding is also known as weak-reference holding, so therefore each bind location on the Device object holds a weak-reference to the interface/ object. Unless explicitly mentioned otherwise, this behavior should be assumed for all Set methods. Whenever destruction of an object causes a bind point to be NULL'ed out, the Debug Layer will issue a warning. Note, calls to device Get methods such as ID3D10Device::OMGetRenderTargets will increase the reference count of objects being returned.

Test Cooperative Level

The functionality of the D3D9 API IDirect3DDevice9::TestCooperativeLevel is analogous to setting the DXGI_PRESENT_TEST when calling IDXGISwapChain::Present.

See Also

Programming Guide (Direct3D 10)


DXGI Overview (Direct3D 10)

DirectX Graphics Infrastructure (DXGI) recognizes that some parts of graphics evolve more slowly than others. The primary goal of DXGI is to manage low-level tasks that can be independent of the DirectX graphics runtime. DXGI provides a common framework for future graphics components, the first component that takes advantage of DXGI is Direct3D 10.

In previous versions of Direct3D, low-level tasks like enumeration of hardware devices, presenting rendered frames to an output, controlling gamma, and managing a full-screen transition were included in the 3D runtime. These tasks are now implemented in DXGI.

DXGI's purpose is to communicate with the kernel mode driver and the system hardware.

An application has the option of talking to DXGI directly, or calling the Direct3D APIs in D3D10Core (which handles the communications with DXGI for you). You may want to work with DXGI directly if your application needs to enumerate devices or control how data is presented to an output.

Enumerating Adapters

An adapter is an abstraction of the hardware and the software capability of your computer. There are generally many adapters on your machine. Some devices are implemented in hardware (like your video card) and some are implemented in software (like the Direct3D reference rasterizer). Adapters implement functonality used by a graphic application. The following diagram shows a system with a single computer, two adapters (video cards) and three output monitors.

When enumerating these pieces of hardware, DXGI creates an IDXGIOutput interface for each output (or monitor) and an IDXGIAdapter interface for each video card (even if it is a video card built into a motherboard). Enumeration is done by using an IDXGIFactory interface in two stages. First, call IDXGIFactory::EnumAdapters to return a set of IDXGIAdapter interfaces that represent the video hardware. Second, call IDXGIAdapter::CheckInterfaceSupport to see if the video hardware is associated with a driver that supports the API you wish to use (such as Direct3D 10).

If your application is calling Direct3D, there is no need to enumerate devices since the DirectX runtime will create a default adapter interface when D3D10CreateDevice is called.

Presentation

Your application's job is to render frames and ask DXGI to present those frames to the output. For performance, this requires at least two buffers so that the application can render one buffer while presenting another one. There may be more than two buffers required depending on the time it takes to render a frame or the desired frame rate for presentation. The set of buffers created is called a swap chain.

Figure 1. Swap Chain

A swap chain has one front buffer and one or more back buffers. Each application is responsible for creating its own swap chain. To maximize the speed of the presentation of the data to an output, a swap chain is almost always created in the memory in a display sub-system.

Figure 2. Display Sub-System

The display sub-system (which is often a video card but could be implemented on a motherboard) contains a GPU, a digital to analog converter (DAC) and memory. The swap chain is allocated within this memory to make presentation very fast. The display sub-system is responsible for presenting the data in the front buffer to the output.

Create a Swap Chain

Differences between Direct3D 9 and Direct3D 10:

Direct3D 10 is the first graphics component to use DXGI. DXGI has some different swap chain behaviors.

  • In DXGI, a swap chain is tied to a window when the swap chain is created. This change improves performance and saves memory. Previous versions of Direct3D allowed the swap chain to change the window that the swap chain is tied to.
  • In DXGI, a swap chain is tied to a rendering device on creation. A change to the rendering device requires the swap chain to be recreated.

A swap chain's buffers are created at a particular size and in a particular format. The application specifies these values (or you can inherit the size from the target window) at startup, and can then optionally modify them as the window size changes in response to user input or program events.

Once the swapchain has been created, you will typically want to render images into it. Here's a code fragment that sets up a Direct3D10 context to render into a swapchain. This code extracts a buffer from the swapchain, creates a render-target-view from that buffer, then sets it on the device:

ID3D10Resource * pBB;
ThrowFailure( pSwapChain->GetBuffer(0, __uuidof(pBB),
  reinterpret_cast<void**>(&pBB)), "Couldn't get back buffer");
ID3D10RenderTargetView * pView;
D3D10_RENDER_TARGET_VIEW_DESC rtd;
rtd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
rtd.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
rtd.Texture2D.MipSlice = 0;
ThrowFailure( pD3D10Device->CreateRenderTargetView(pBB, &rtd, &pView),
  "Couldn't create view" );
pD3D10Device->OMSetRenderTargets(1, &pView, 0);

Care and Feeding of the Swap Chain

A swap chain is a gentle beast. Once you've rendered your image, call IDXGISwapChain::Present and go render the next image. That is the extent of your responsibility.

If you've previously called IDXGIFactory::MakeWindowAssociation, the user can press the Alt-Enter key combination and DXGI will transition your application between windowed and fullscreen mode . Or you can disable Alt-Enter by not calling IDXGIFactory::MakeWindowAssociation. IDXGIFactory::MakeWindowAssociation is recommended, because a standard control mechanism for the user is strongly desired.

While you don't have to write any more code than has been described, a few simple steps can make your application more responsive. The most important consideration is the resizing of the swap chain's buffers in response to the resizing of the output window. Naturally, the application's best route is to respond to WM_SIZE, and call IDXGISwapChain::ResizeBuffers, passing the size contained in the message's parameters. This behavior obviously makes your application respond well to the user when he or she drags the window's borders, but it is also exactly what enables a smooth fullscreen transition. Your window will receive a WM_SIZE message whenever such a transition happens, and calling IDXGISwapChain::ResizeBuffers is the swap chain's chance to re-allocate the buffers' storage for optimal presentation. This is why the application is required to release any references it has on the existing buffers before it calls IDXGISwapChain::ResizeBuffers.

Failure to call IDXGISwapChain::ResizeBuffers in response to switching to fullscreen (most naturally, in response to WM_SIZE), can preclude the optimization of flipping, wherein DXGI can simply swap which buffer is being displayed, rather than copying a screen's full of data around.

IDXGISwapChain::Present will inform you if your output window is entirely occluded via DXGI_STATUS_OCCLUDED. When this occurs, it is recommended that your application go into standby mode (by calling IDXGISwapChain::Present with DXGI_PRESENT_TEST) since resources used to render the frame are wasted. Using DXGI_PRESENT_TEST will prevent any data from being presented while still performing the occlusion check. Once IDXGISwapChain::Present returns S_OK, you should exit standby mode; do not use the return code to switch to standby mode as doing so can leave the swapchain unable to relinquish fullscreen mode.

Choosing the DXGI Output and Size

By default, DXGI chooses the output that contains most of the client area of the window. This is the only option available to DXGI when it goes fullscreen itself in response to alt-enter. If the application chooses to go fullscreen by itself, then it can call IDXGISwapChain::SetFullscreenState and pass an explicit IDXGIIOutput (or NULL, if the application is happy to let DXGI decide).

To resize the output while either fullscreen or windowed, then it's advisable to call IDXGISwapChain::ResizeTarget, since this method resizes the target window also. Since the target window is resized, WM_SIZE is sent, and your code will naturally call IDXGISwapChain::ResizeBuffers in response. It's thus a waste of effort to resize your buffers, and then subsequently resize the target.

Mode Switches

The DXGI swap chain might change the display mode of an output when making a full-screen transition. To enable the automatic display mode change, you must specify DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH in the swap-chain description. If the display mode autoatically changes, DXGI will choose the most modest mode (size and resolution will not change, but the color depth may). Resizing swap chain buffers will not cause a mode switch. The swap chain makes an implicit promise that if you choose a back buffer that exactly matches a display mode supported by the target output, then it will switch to that display mode when entering fullscreen mode on that output. Consequently, you choose a display mode by choosing your back buffer size and format.


Linking Static and Dynamic Libraries (Direct3D 10)

For an applicaiton to run properly, the host computer must have the appropriate DLLs installed. These DLLs may be provided by either the operating system, or the applications' redistributable package.

Libraries Load Appropriate DLLs

The libraries included with the DirectX SDK will automatically load the proper DLLs at runtime. The exception to this rule is d3dx10.lib/d3dx10d.lib, which will load the d3dx10.dll that was shipped with that version of the SDK. For example, if the downloaded SDK includes d3dx10.dll and d3dx10_1.dll, then the d3dx10.lib that shipped with that SDK will load d3dx10_1.dll. If a subsequent SDK is installed later containing d3dx10_2.lib, the d3dx10.lib from the previous SDK will still load d3dx10_1.dll. The d3dx10.lib from the newer SDK will load d3dx10_2.lib

Redistributing Binaries

Only d3dx10.dll (and subsequent versions of the same file) can be redistributed. See Installing DirectX with DirectSetup for details on putting together a redistributable package. All other necessary binaries are included in Windows Vista. The only binaries that can be redistributed are those located in the following directory.

(SDK root)\Redist

The following table describes the binaries developers should be aware of.

Direct3D 10 Binaries | Description
d3dx10.dll/d3dx10d.dll | Retail and debug D3DX10 components. Can be redistributed and are contained in the corresponding CAB file.
d3d10d.dll | Debug version of d3d10.dll. Only included as part of the DirectX SDK and cannot be redistributed.
d3d10ref.dll | Reference Rasterizer. Provides software implementation of the graphics pipeline. Only included as part of the DirectX SDK and cannot be redistributed. The Reference Rasterizer is intended for debugging only. Explicit linking is not necssary; attempting to create a reference device (see D3D10CreateDevice) will load this dll if it is present.


Tutorials and Samples

The SDK provides several sources of sample code.

Tutorials are built from the ground up and contain only those API calls necessary to exercise Direct3D functionality.
Samples demonstrate Direct3D 10 features. All of the samples are built on top of DXUT.


Tutorials

The following tutorials demonstrate the basic functionality of Direct3D 10:

Basic Tutorials
DXUT Tutorials
Shader Tutorials
State Tutorials

The sample code in these tutorials is from source projects whose location is provided in each tutorial. The sample files in these tutorials are written in C++. If you are using a C compiler, you must make the appropriate changes to the files for them to successfully compile. At the very least, you need to add the vtable and pointers to the interface methods.


Basic Tutorials

The following tutorials were designed to teach a programmer the basics of the Direct3D 10 API. They cover basic setup and procedures to accomplish the fundamental tasks, such as rendering and transformations.

The intended audience is those familiar with programming, but relatively new to 3D graphics programming. The beginning tutorials will be a walkthrough to create the bare framework for Direct3D, as well as serve to explain simple concepts behind 3D rendering, such as vertices, transformations, and animations.

Experienced users migrating to Direct3D 10 can skip over the explanations and observe the changes made to this iteration of the API.

Tutorial 0: Win32 Basics
Tutorial 1: Direct3D 10 Basics
Tutorial 2: Rendering a Triangle
Tutorial 3: Shaders and Effect System
Tutorial 4: 3D Spaces
Tutorial 5: 3D Transformation
Tutorial 06: Lighting
Tutorial 7: Texture Mapping and Constant Buffers


Tutorial 0: Win32 Basics

Summary

In this preliminary tutorial, we will go through the elements necessary to create a Win32 application. We will be setting up an empty window to prepare for Direct3D 10.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial00

Setting Up The Window

Every Windows application requires at least one window object. Before even getting to the Direct3D 10 specifics, our application must have a working window object. Three things are involved:

  1. Register a window class.
        //
    // Register class
    //
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, (LPCTSTR)IDI_TUTORIAL1);
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_TUTORIAL1);
    if( !RegisterClassEx(&wcex) )
    return FALSE;
  2. Create a window object.
        //
    // Create window
    //
    g_hInst = hInstance; // Store instance handle in our global variable
    RECT rc = { 0, 0, 640, 480 };
    AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
    g_hWnd = CreateWindow( szWindowClass, L"Direct3D 10 Tutorial 0: Setting Up Window", WS_OVERLAPPEDWINDOW,
                           CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL,
                           hInstance, NULL);

    if( !g_hWnd )
        return FALSE;

    ShowWindow( g_hWnd, nCmdShow );
  3. Retrieve and dispatch messages for this window.
        //
    // Main message loop
    //
    MSG msg = {0};
    while( GetMessage( &msg, NULL, 0, 0 ) )
    {
        TranslateMessage( &msg );
        DispatchMessage( &msg );
    }

        LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
    {
        PAINTSTRUCT ps;
        HDC hdc;

        switch (message)
        {
            case WM_PAINT:
                hdc = BeginPaint(hWnd, &ps);
                EndPaint(hWnd, &ps);
                break;

            case WM_DESTROY:
                PostQuitMessage(0);
                break;

            default:
                return DefWindowProc(hWnd, message, wParam, lParam);
        }

        return 0;
    }

These are the minimal necessary steps to set up a window object that are required by every Windows application. If we compile and run this code, we will see a window with a blank white background.


Tutorial 1: Direct3D 10 Basics

Summary

In this first tutorial, we will go through the elements necessary to create a minimal Direct3D 10 application. Every Direct3D 10 application must have these elements to function properly. The elements include setting up a window and a device object then displaying a color on the window.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial01

Setting Up The Direct3D 10 Device

Now that we have a window displaying, we can continue to set up a Direct3D 10 device, which is necessary if we are going to render any 3D scene. The first thing to do is to create two objects: a device and a swap chain.

The device object is used by the application to perform rendering onto a buffer. The device also contains methods to create resources

The swap chain then is responsible for taking the buffer that the device renders to and displaying the content on the actual monitor screen. The swap chain contains two or more buffers, mainly the front and the back. These are textures that the device renders to, for displaying on the monitor. The front buffer is what the user currently is looking at. This buffer is read-only and cannot be modified. The back buffer is the render target that the device will draw to. Once it finishes the drawing operation, the swap chain will present the backbuffer, by swapping the two buffers. The back buffer becomes the front buffer, and vice versa.

To create the swap chain, we fill out a DXGI_SWAPCHAIN_DESC structure that describes the swap chain we are about to create. A few fields are worth mentioning. BackBufferUsage is the usage flag of the back buffer backing the swap chain. The usage flag is used to indicate how a Direct3D 10 resource will be used. Since the back buffer will be rendered on, it requires the DXGI_USAGE_RENDER_TARGET_OUTPUT usage flag to work properly. The OutputWindow field represents the window that the swap chain will use to present images on the screen. SampleDesc is used to enable multi-sampling. Since this tutorial does not use multi-sampling, SampleDesc's Count is set to 1 and Quality to 0 to have multi-sampling disabled.

Once the description has been filled out, we can call the function to create both the device and the swap chain for us. The code to create a device and a swap chain is listed below:

    DXGI_SWAP_CHAIN_DESC sd;
    ZeroMemory( &sd, sizeof(sd) );
    sd.BackBufferCount = 1;
    sd.BackBufferDesc.Width = 640;
    sd.BackBufferDesc.Height = 480;
    sd.BackBufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BackBufferDesc.RefreshRate.Numerator = 60;
    sd.BackBufferDesc.RefreshRate.Denominator = 1;
    sd.BackBufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = g_hWnd;
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.Windowed = TRUE;

    if( FAILED( D3D10CreateDeviceAndSwapChain( NULL,
                                                D3D10_DRIVER_TYPE_REFERENCE,
                                                NULL,
                                                0,
                                                D3D10_SDK_VERSION,
                                                &sd,
                                                &g_pSwapChain,
                                                &g_pd3dDevice ) ) )
    {
        return FALSE;
    }

The next thing that we need to do is to create a render target view. A render target view is a type of resource view in Direct3D 10. A resource view allows a resource to be bound to the graphics pipeline at a specific stage. Think of resource views as typecast in C. A chunk of raw memory in C can be cast to any data type. We can cast that chunk of memory to an array of integers, an array of floats, a structure, an array of structures, so on. The raw memory itself is not very useful to us if we don't know its type. Direct3D 10 resource views act in a similar way. For instance a 2D texture, analogous to the raw memory chunk, is the raw underlying resource. Once we have that resource we can create different resource views to bind that texture to different stages in the graphics pipeline with different formats: as a render target to render to, as a depth stencil buffer that will receive depth information, or as a texture resource. Where C typecasts allow a memory chunk to be used in different manner, so do Direct3D 10 resource views.

We need to create a render target view because we would like to bind the back buffer of our swap chain as a render target, so that Direct3D 10 can render onto it. We first call GetBuffer() to obtain the back buffer object. Optionally, we can fill in a D3D10_RENDERTARGETVIEW_DESC structure that describes the render target view to be created. This description is normally the second parameter to CreateRenderTargetView. However, for these tutorials, the default render target view will suffice. The default render target view can be obtained by passing NULL as the second parameter. Once we have created the render target view, we can call OMSetRenderTargets() to bind it to the pipeline so that the output that the pipeline renders gets written to the back buffer. The code to create and set the render target view is listed below:

    // Create a render target view
    ID3D10Texture2D *pBackBuffer;
    if( FAILED( g_pSwapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), (LPVOID*)&pBackBuffer ) ) )
        return FALSE;
    hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView );
    pBackBuffer->Release();
    if( FAILED( hr ) )
        return FALSE;
    g_pd3dDevice->OMSetRenderTargets( 1, &g_pRenderTargetView, NULL );

The last thing that we need to set up before Direct3D 10 can render is initialize viewport. The viewport maps clip space coordinates, where X and Y range from -1 to 1 and Z ranges from 0 to 1, to render target space, sometimes known as pixel space. In Direct3D 9, a default viewport is set up to be the same size as the render target if the application does not set up any. In Direct3D 10, no viewport is set by default. Therefore, we must do so before we can see anything on the screen. Since we would like to use the entire render target for the output, we set the top left point to (0, 0) and width and height to be identical to the render target's size. The code to do so is shown below:

    D3D10_VIEWPORT vp;
    vp.Width = 640;
    vp.Height = 480;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0;
    vp.TopLeftY = 0;
    g_pd3dDevice->RSSetViewports( 1, &vp );

Modifying the Message Loop

We have set up the window and Direct3D 10 device, and we are ready to render. However, there is still a problem with our message loop: it uses GetMessage() to obtain messages. The problem with GetMessage() is that if there is no message in the queue for the application window, GetMessage() blocks and does not return until a message is available. Thus, instead of doing something like rendering, our application is waiting within GetMessage() when the message queue is empty. We can solve this problem by using PeekMessage() instead of GetMessage(). PeekMessage() can retrieve a message like GetMessage() does, but when there is no message waiting, PeekMessage() returns immediately instead of blocking. We can then take this time to do some rendering. The modified message loop, which uses PeekMessage(), looks like this:

    MSG msg = {0};
    while( WM_QUIT != msg.message )
    {
        if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
        else
        {
            Render();  // Do some rendering
        }
    }

The Rendering Code

Rendering is done in the Render() function. In this tutorial, we will render the simplest scene possible, which is to fill the screen with a single color. In Direct3D 10, an easy way to fill the render target with a single color is to use the device's ClearRenderTargetView() method. We first define a D3D10_COLOR structure that describes the color we would like to fill the screen with, then pass it to ClearRenderTargetView(). In the tutorial's code, the color ( 0.0, 0.125, 0.3, 1.0 ) is chosen, which represents a dark blue shade. Once we have filled our back buffer, we call the swap chain's Present() method to complete the rendering. Present() is responsible for displaying the swap chain's back buffer content onto the screen so that the user can see it. The Render() function looks like below:

    void Render()
    {
        //
        // Clear the backbuffer
        //
        float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; //red,green,blue,alpha
        g_pd3dDevice->ClearRenderTargetView( g_pRenderTargetView, ClearColor );

        g_pSwapChain->Present( NULL, NULL, NULL, 0, 0, 0 );
    }


Tutorial 2: Rendering a Triangle

Summary

In the previous tutorial, we built a minimal bare bone Direct3D 10 application that outputs a single color to the window. In this tutorial, we will extend the application to render a single triangle on the screen. We will go through the process to setup the data structures associated with a triangle.

The outcome of this tutorial is a window with a triangle rendered to the center of it.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial02

Navigation

  • Elements of a Triangle
  • Input Layout
  • Rendering the Triangle

Elements of a Triangle

A triangle is defined by its three points, also called vertices. A set of three vertices with unique positions define a unique triangle. In order for GPUs to render a triangle, we must tell it about the position of three vertices. For a 2D example, let's say we wish to render a triangle such as that in figure 1. We would pass three vertices with the positions (0, 0) (0, 1) and (1, 0) to the GPU, and then the GPU has enough information to render the triangle that we want.

Figure 1. A triangle in 2D defined by its three vertices

So now we know that we must pass three positions to the GPU in order to render a triangle. How do we pass this information to the GPU? In Direct3D 10, vertex information such as position is stored in a buffer resource. A buffer that is used to store vertex information is called, not surprisingly, vertex buffer. We must create a vertex buffer large enough for three vertices and fill it with the vertex positions. In Direct3D 10, the application must specify a buffer size in bytes when creating a buffer resource. We know the buffer has to be large enough for three vertices, but how many bytes does each vertex need? To answer that question requires an understanding of vertex layout.

Input Layout

A vertex has a position. More often than not, it also has other attributes as well, such as a normal, one or more colors, texture coordinates (used for texture mapping), and so on. Vertex layout defines how these attributes lie in memory: what data type each attribute uses, what size each attribute has, and the order of the attributes in memory. Because the attributes usually have different types, similar to the fields in a C structure, a vertex is usually represented by a structure. The size of the vertex is conveniently obtained from the size of the structure.

In this tutorial, we are only working with the position of the vertices. Therefore, we define our vertex structure with a single field of the type D3DXVECTOR3. This type is a vector of 3 floating-points components, which is typically the data type used for position in 3D.

    struct SimpleVertex
    {
        D3DXVECTOR3 Pos;  // Position
    };

We now have a structure that represents our vertex. That takes care of storing vertex information in system memory in our application. However, when we feed the GPU the vertex buffer containing our vertices, we are just feeding it a chunk of memory. The GPU must also know about the vertex layout in order to extract correct attributes out from the buffer. To accomplish this requires the use of input layout.

In Direct3D 10, an input layout is a Direct3D object that describes the structure of vertices in a way that can be understood by the GPU. Each vertex attribute can be described with the D3D10_INPUT_ELEMENT_DESC structure. An application defines one or more D3D10_INPUT_ELEMENT_DESC, then uses that array to create the input layout object which describes the vertex as a whole. We will now look at the fields of D3D10_INPUT_ELEMENT_DESC in details.

SemanticName | Semantic name is a string containing a word that describes the nature or purpose (or semantics) of this element. The word can be in any form that a C identifier can, and can be anything that we choose. For instance, a good semantic name for the vertex's position is POSITION. Semantic names are not case-sensitive.
SemanticIndex | Semantic index supplements semantic name. A vertex may have multiple attributes of the same nature. For example, it may have 2 sets of texture coordinates or 2 sets of colors. Instead of using semantic names that have numbers appended, such as "COLOR0" and "COLOR1", the two elements can share a single semantic name, "COLOR", with different semantic indices 0 and 1.
Format | Format defines the data type to be used for this element. For instance, a format of DXGI_FORMAT_R32G32B32_FLOAT has three 32-bit floating point numbers, making the element 12-byte long. A format of DXGI_FORMAT_R16G16B16A16_UINT has four 16-bit unsigned integers, making the element 8-byte long.
InputSlot | As mentioned previously, a Direct3D 10 application passes vertex data to GPU via the use of vertex buffer. In Direct3D 10, multiple vertex buffers can be fed to the GPU simultaneously, 16 to be exact. Each vertex buffer is bound to an input slot number ranging from 0 to 15. The InputSlot field tells the GPU which vertex buffer it should fetch for this element.
AlignedByteOffset | A vertex in vertex buffer is simply a chunk of memory. The AlignedByteOffset field tells the GPU where in that chunk of memory it should start fetching for this element.
InputSlotClass | This field usually has the value D3D10_INPUT_PER_VERTEX_DATA. When an application uses instancing, it can set an input layout's InputSlotClass to D3D10_INPUT_PER_INSTANCE_DATA to work with vertex buffer containing instance data. Instancing is an advanced Direct3D topic and will not be discussed here. For our tutorial, we will use D3D10_INPUT_PER_VERTEX_DATA exclusively.
InstanceDataStepRate | This field is used for instancing. Since we are not using instancing, this field is not used and must be set to 0.

Now we can define our D3D10_INPUT_ELEMENT_DESC array and create the input layout:

    // Define the input layout
    D3D10_INPUT_ELEMENT_DESC layout[] =
    {
        { L"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    };
       UINT numElements = sizeof(layout)/sizeof(layout[0]);

Vertex Layout

In the next tutorial, we will explain the technique object and the associated shaders. For now, we will just concentrate on creating the Direct3D 10 vertex layout object for the technique. However, we will learn that the technique and shaders are tightly coupled with this vertex layout. The reason is that creating a vertex layout object requires the vertex shader's input signature. We first call the technique's GetPassByIndex() method to obtain an effect pass object that represents the first pass of the technique. Then, we call the pass object's GetDesc() method to obtain a pass description structure. Within this structure is a field named pIAInputSignature that points to the binary data that represents the input signature of the vertex shader used in this pass. Once we have this data, we can call ID3D10Device::CreateInputLayout() to create a vertex layout object, and ID3D10Device::IASetInputLayout() to set it as the active vertex layout. The code to do all of that is shown below:

    // Create the input layout
    D3D10_PASS_DESC PassDesc;
    g_pTechnique->GetPassByIndex( 0 )->GetDesc( &PassDesc );
    if( FAILED( g_pd3dDevice->CreateInputLayout( layout, numElements, PassDesc.pIAInputSignature, &g_pVertexLayout ) ) )
        return FALSE;
    // Set the input layout
    g_pd3dDevice->IASetInputLayout( g_pVertexLayout );

Creating Vertex Buffer

One thing that we will also need to do during initialization is to create the vertex buffer that holds the vertex data. To create a vertex buffer in Direct3D 10, we fill in two structures, D3D10_BUFFER_DESC and D3D10_SUBRESOURCE_DATA, and then call ID3D10Device::CreateBuffer(). D3D10_BUFFER_DESC describes the vertex buffer object to be created, and D3D10_SUBRESOURCE_DATA describes the actual data that will be copied to the vertex buffer during creation. The creation and initialization of the vertex buffer is done at once so that we don't need to initialize the buffer later. The data that will be copied to the vertex buffer is vertices, array of 3 SimpleVertex. The coordinates in the vertices array are chosen so that we see a triangle in the middle of our application window when rendered with our shaders. After the vertex buffer is created, we can call ID3D10Device::IASetVertexBuffers() to bind it to the device. The complete code is shown here:

    // Create vertex buffer
    SimpleVertex vertices[] =
    {
        D3DXVECTOR3( 0.0f, 0.5f, 0.5f ),
        D3DXVECTOR3( 0.5f, -0.5f, 0.5f ),
        D3DXVECTOR3( -0.5f, -0.5f, 0.5f ),
    };
    D3D10_BUFFER_DESC bd;
    bd.Usage = D3D10_USAGE_DEFAULT;
    bd.ByteWidth = sizeof( SimpleVertex ) * 3;
    bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = 0;
    bd.MiscFlags = 0;
    D3D10_SUBRESOURCE_DATA InitData;
    InitData.pSysMem = vertices;
    if( FAILED( g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBuffer ) ) )
        return FALSE;

    // Set vertex buffer
    UINT stride = sizeof( SimpleVertex );
    UINT offset = 0;
    g_pd3dDevice->IASetVertexBuffers( 0, 1, &g_pVertexBuffer, &stride, &offset );

Primitive Topology

Primitive topology refers to how the GPU obtains the three vertices it requires to render a triangle. We discussed above that in order to render a single triangle, the application needs to send three vertices to the GPU. Therefore, the vertex buffer has three vertices in it. How about rendering two triangles? One way is to send 6 vertices to the GPU. The first 3 represent the first triangle, and the other 3 represent the second triangle. This topology, called triangle list, and is to understand. However, two successive triangles that are rendered often share some vertices. For instance, figure 3a left shows a square made up of two triangles: A B C and C B D. (By convention, triangles are typically defined by its vertices in a clockwise manner.) If we send these two triangles to the GPU using triangle list, our vertex buffer would like this:

    A B C C B D

Notice that B and C appear twice in the vertex buffer because they are shared by both triangles.

Figure 3. a) A square made up of two triangles; b) A pentagonal shape made up of three triangles

We can make the vertex buffer smaller if we can tell the GPU that when rendering the second triangle, instead of fetching all 3 vertices from the vertex buffer, use 2 of the vertices from the previous triangle and fetch only 1 vertex from the vertex buffer. As it turns out, this is supported by Direct3D, and the topology is called triangle strip. When rendering a triangle strip, the very first triangle is defined by the first three vertices in the vertex buffer. The next triangle is defined by the last two vertices of the previous triangle plus the next vertex in the vertex buffer. Taking the square in figure 3a as an example, using triangle strip, the vertex buffer would look like:

    A B C D

The first 3 vertices, A B C, define the first triangle. The second triangle is defined by B and C, the last two vertices of the first triangle, plus D. Thus, by using the triangle strip topology, the vertex buffer size has gone from 6 vertices to 4 vertices. Similarly, for three triangles such as those in figure 3b, using triangle list would require a vertex buffer such as:

    A B C C B D C D E

Using triangle strip, the size of the vertex buffer is dramatically reduced:

    A B C D E

You may have noticed that in the triangle strip example, the second triangle is defined as B C D. These 3 vertices do not form a clockwise order. This is a natural phenomenon from using triangle strips. To overcome this, the GPU automatically swaps the order of the two vertices coming from the previous triangle. It only does this for the second triangle, fourth triangle, sixth triangle, eighth triangle, and so on. This ensures that every triangle is defined by vertices in the correct winding order (clockwise, in this case). Besides triangle list and triangle strip, Direct3D 10 supports many other types of primitive topology. We will not discuss them in this tutorial.

In our code, we have one triangle, so it doesn't really matter what we specify. However, we must specify something, so we chose a triangle list.

    // Set primitive topology
    g_pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

Rendering the Triangle

The final item missing is the code that does the actual rendering of the triangle. As mentioned earlier, this tutorial will use the effect system. We start by calling ID3D10EffectTechnique::GetDesc() on the technique object obtained earlier to receive a D3D10FX_TECHNIQUE_DESC structure which describes the technique. One of the members of D3D10FX_TECHNIQUE_DESC, Passes, indicates the number of passes the technique contains. To correctly render using this technique, the application should loop the same number of times as there are passes. Within the loop, we must first call the technique's GetPassByIndex() method to obtain the pass object, then call its Apply() method to have the effect system bind the associated shaders and render states to the graphics pipeline. The next thing that we do is call ID3D10Device::Draw(), which commands the GPU to render using the current vertex buffer, vertex layout, and primitive topology. The first parameter to Draw() is the number of vertices to send to the GPU, and the second parameter is the index of the first vertex to begin sending. Because we are rendering one triangle and we are rendering from the beginning of the vertex buffer, we use 3 and 0 for the two parameters, respectively. The entire triangle-rendering code looks like the following:

    //
    // Render a triangle
    //
    D3D10_TECHNIQUE_DESC techDesc;
    g_pTechnique->GetDesc( &techDesc );
    for( UINT p = 0; p < techDesc.Passes; ++p )
    {
        g_pTechnique->GetPassByIndex( p )->Apply(0);
        g_pd3dDevice->Draw( 3, 0 );
    }


Tutorial 3: Shaders and Effect System

Summary

In the previous tutorial, we setup a vertex buffer and passed one triangle to the GPU. Now, we will actually step through the graphics pipeline and look at how each stage works. The concept of shaders and the effect system will be explained.

Note that this tutorial shares the same source code as the previous one, but will emphasize a different section.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial03

Navigation

  • The Graphics Pipeline
  • Shaders
  • Effect System
  • Putting It Together

The Graphics Pipeline

In the previous tutorial, we setup the vertex buffer, and then we associated a vertex layout with a technique object. Now, we will explain the technique object and the shaders that compose it. To fully understand the individual shaders, we will take a step back and look at the whole graphical pipeline.

In Tutorial 2, when we called Apply from the technique, we actually bound our shader to a stage in the pipeline. Then, when we called Draw, we start processing the vertex data passed into the graphics pipeline. The follow sections will describe in better detail what happens after the Draw command.

Shaders

In Direct3D 10, shaders reside in different stages of the graphics pipeline. They are short programs that, executed by the GPU, take certain input data, process that data, and then output the result to the next stage of the pipeline. Direct3D 10 supports 3 types of shaders: vertex shader, geometry shader, and pixel shader. A vertex shader takes a vertex as input. It is run once for every vertex passed to the GPU via vertex buffers. A geometry shader takes a primitive as input, and is run once for every primitive passed to the GPU. A primitive is a point, a line, or a triangle. A pixel shader takes a pixel (or sometimes called a fragment) as input, and is run once for each pixel of a primitive that we wish to render. Together, vertex, geometry, and pixel shaders are where the meat of the action occurs. When rendering with Direct3D 10, the GPU must have a valid vertex shader and pixel shader. Geometry shader is an advanced feature in Direct3D 10 and is optional, so we will not discuss geometry shaders in this tutorial.

Vertex Shaders

Vertex shaders are short programs to be executed by GPU on vertices. Think of vertex shaders as C functions that take each vertex as input, process the input, and then output the modified vertex. After the application passes vertex data to the GPU in the form of a vertex buffer, the GPU iterates through the vertices in the vertex buffer, and executes the active vertex shader once for each vertex, passing the vertex's data to the vertex shader as input parameters.

While a vertex shader can be used to carry out many tasks, the most important job of a vertex shader is transformation. Transformation is the process of converting vectors from one coordinate system to another. For example, a triangle in a 3D scene may have its vertices at the positions (0, 0, 0) (1, 0, 0) (0, 1, 0). When the triangle is drawn on a 2D texture buffer, the GPU has to know the 2D coordinates of the points on the buffer that the vertices should be drawn at. It is transformation that helps us accomplish this. Transformation will be discussed in detail in the next tutorial. For this tutorial, we will be using a simple vertex shader that does nothing except passing the input data through as output.

In the Direct3D 10 tutorials, we will write our shaders in High-Level Shading Language (HLSL), and the applications will use these shaders with the effect system. Recall that our vertex data has a 3D position element, and the vertex shader will do no processing on the input at all. The resulting vertex shader looks like the following:

    float4 VS( float4 Pos : POSITION ) : SV_POSITION
    {
        return Pos;
    }

This vertex shader looks a lot like a C function. HLSL uses C-like syntax to make learning easier for C/C++ programmers. We can see that this vertex shader, named VS, takes a parameter of float4 type and returns a float4 value. In HLSL, a float4 is a 4-component vector where each component is a floating-point number. The colons define the semantics of the parameter as well as the return value. As mentioned above, the semantics in HLSL describe the nature of the data. In our shader above, we choose POSITION as the semantics of the Pos input parameter because this parameter will contain the vertex position. The return value's semantics, SV_POSITION, is a pre-defined semantics with special meaning. This semantics tells the graphics pipeline that the data associated with the semantics defines the clip-space position. This position is needed by the GPU in order to drawn pixels on the screen. (We will discuss clip-space in the next tutorial.) In our shader, we take the input position data and output the exact same data back to the pipeline.

Pixel Shaders

Modern computer monitors are commonly raster display, which means the screen is actually a two-dimensional grid of small dots call pixels. Each pixel can light with its own color independent of any other pixels. When we render a triangle on the screen, we don't really render a triangle as one entity. Rather, we light up the group of pixels that are covered by the triangle's area. Figure 2 shows an illustration of this.

Figure 2. Left: What we would like to draw. Right: What is actually on the screen.

The process of converting a triangle defined by three vertices to a bunch of pixels covered by the triangle is called rasterization. The GPU first determines what pixels are covered by the triangle being rendered. Then it invokes the active pixel shader for each of these pixels. A pixel shader's primary purpose is to compute the color that each pixel should have. The shader takes certain input about the pixel being colored, computes the pixel's color, then outputs that color back to the pipeline. The input that it takes comes from the active geometry shader, or, if a geometry shader is not present, such as the case in this tutorial, the input comes directly from the vertex shader.

The vertex shader we created above outputs a float4 with the semantics SV_POSITION. This will be the input of our pixel shader. Since pixel shaders output color values, the output of our pixel shader will be a float4. We give the output the semantics SV_TARGET to signify outputting to the render target format. The pixel shader looks like the following:

    float4 PS( float4 Pos : SV_POSITION ) : SV_Target
    {
        return float4( 1.0f, 1.0f, 0.0f, 1.0f );    // Yellow, with Alpha = 1
    }

Effect System

Our effect file consists of the two shaders, vertex shader and pixel shader, and the technique definition. The technique definition will set the corresponding shaders to each section. In addition, there is also the semantic to compile the shader. Note that the geometry shader is left NULL because it's not required and will be covered later.

    // Technique Definition
    technique10 Render
    {
        pass P0
        {
            SetVertexShader( CompileShader( vs_4_0, VS() ) );
            SetGeometryShader( NULL );
            SetPixelShader( CompileShader( ps_4_0, PS() ) );
        }
    }

Creating the Effect and Effect Technique

In the application code, we will need to create an effect object. This effect object represents our effect file, and is created by calling D3D10CreateEffectFromFile(). Once we have created the effect object, we can call the ID3D10Effect::GetTechniqueByName() method, passing in "Render" as the name, to obtain the technique object that we will be using to do the actual rendering. The code is demonstrated below:

    // Create the effect
    if( FAILED( D3DX10CreateEffectFromFile( L"Tutorial03.fx", NULL, NULL, D3D10_SHADER_ENABLE_STRICTNESS, 0, g_pd3dDevice, NULL, NULL, &g_pEffect, NULL ) ) )
        return FALSE;

    // Obtain the technique
    g_pTechnique = g_pEffect->GetTechniqueByName( "Render" );

Putting It Together

After walking through the graphics pipeline, we can start to understand the process of rendering the triangle we created at the beginning of Tutorial 2. Creating Direct3D applications requires two distinct steps. The first would be creating the source data in vertex data, as we've done in Tutorial 2; the second stage would be to create the shaders which would transform that data for rendering, which we showed in this Tutorial.


Tutorial 4: 3D Spaces

Summary

In the previous tutorial, we have successfully rendered a triangle in the center of our application window. We haven't paid much attention to the vertex positions that we have picked in our vertex buffer. In this tutorial, we will delve into the details of 3D positions and transformation.

The outcome of this tutorial will be a 3D object rendered to screen. Whereas previous tutorials focused on rendering a 2D object onto a 3D world, here we show a 3D object.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial04

Navigation

  • 3D Spaces
  • Space-To-Space Transformation
  • Using Transformation

3D Spaces

In the previous tutorial, the vertices of the triangle were placed strategically to perfectly align itself on the screen. However, this will not always be the case, and thus, we need a system to denote objects in 3D space and a system to display them.

In the real world, objects exist in 3D space. This means that to place an object in a particular position in the world, we would need to use a coordinate system and define three coordinates that correspond to the position. In computer graphics, 3D spaces are most commonly in Cartesian coordinate system. In this coordinate system, three axes, X, Y, and Z, perpendicular to each other, dictate the coordinate that each point in the space has. This coordinate system is further divided into left-handed and right-handed systems. In a left-handed system, when X axis points to the right and Y axis points to up, Z axis points forward. In a right-handed system, with the same X and Y axes, Z axis points backward. Figure 1 shows an illustration of the left-handed and right-handed systems.

Figure 1. Left-handed versus right-handed coordinate systems

Now that we have talked about the coordinate system, let's talk about 3D spaces. Spaces refer to the frame of references. A point has different coordinates in different spaces. As an example in 1D, suppose we have a ruler and we note the point, P, at the 5-inch mark of the ruler, as shown in figure 2. Now, if we move the ruler 1 inch to the right, the same point lies on the 4-inch mark. By moving the ruler, the frame of reference has changed, and therefore, while the point hasn't moved, it has a new coordinate.

Figure 2. Spaces illustration in 1D

In 3D, a space is typically defined by an origin and three unique axes from the origin: X, Y and Z. There are several spaces commonly used in computer graphics: object space, world space, view space, projection space, and screen space.

Figure 3. A cube defined in object space

Object Space

Object space, also called model space, refers to the space used by artists when they create the 3D models. Usually, artists create models that are centered around the origin so that it is easier to perform transformations such as rotations to the models, as we will see when we discuss transformation. Figure 3 shows a cube object defined in object space. Note that the cube is centered on the origin. The 8 vertices have the following coordinates:

    (-1,  1, -1)
    ( 1,  1, -1)
    (-1, -1, -1)
    ( 1, -1, -1)
    (-1,  1,  1)
    ( 1,  1,  1)
    (-1, -1,  1)
    ( 1, -1,  1)

Because object space is what artists typically use when they design and create models, the models that are stored on disk are also in object space. An application can create a vertex buffer to represent such a model and initialize the buffer with the model data. Therefore, the vertices in the vertex buffer will usually be in object space as well. This also means that the vertex shader receives input vertex data in object space.

World Space

World space is a space shared by every object in the scene. It is used to define spatial relationship between objects that we wish to render. To visualize world space, we could imagine that we are standing in the south-western corner of a rectangular room facing north. We define the corner that our feet are standing at to be the origin, (0, 0, 0). The X axis goes to our right; the Y axis goes up; and the Z axis goes forward, the same direction as we are facing. When we do this, every position in the room can be identified with a set of XYZ coordinates. For instance, there may be a chair 5 feet in front and 2 feet to the right of us. There may be a light on the 8-foot-high ceiling directly on top of the chair. We can then refer to the position of the chair as (2, 0, 5) and the position of the light as (2, 8, 5). As we see, world space is so-called because they tell us where objects are in relation to each other in the world.

View Space

View space, sometimes called camera space, is similar to world space in that it is typically used for the entire scene. However, in view space, the origin is at the viewer or camera. The view direction (where the viewer is looking) defines the positive Z axis. An "up" direction defined by the application becomes the positive Y axis. Figure 4 illustrates the relationship between world space and view space in a scene.

Figure 4. The same object in world space (left) and in view space (right)

In figure 4, the left image shows a scene that consists of a human-like object and a viewer (camera) looking at the object. The origin and axes that are used by world space are shown in red. The right image shows the view space in relation to world space. The view space axes are shown in blue. For clearer illustration, the view space does not have the same orientation as the world space in the left image to readers. Note that in view space, the viewer is looking in the Z direction.

Projection Space

Projection space refers to the space after applying projection transformation from view space. In this space, visible content has X and Y coordinates ranging from -1 to 1, and Z coordinate ranging from 0 to 1.

Screen Space

Screen space is often used to refer to locations in the frame buffer. Because frame buffer is usually a 2D texture, screen space is a 2D space. The top-left corner is the origin with coordinates (0, 0). The positive X goes to right and positive Y goes down. For a buffer that is w pixels wide and h pixels high, the most lower-right pixel has the coordinates (w - 1, h - 1).

Space-To-Space Transformation

Transformation is most commonly used to convert vertices from one space to another. In 3D computer graphics, there are logically 3 such transformations in the pipeline: world, view, and projection transformation. Individual transformation operations such as translation, rotation, and scaling are covered in the next Tutorial.

World Transformation

World transformation, as the name suggests, converts vertices from object space to world space. It usually consists of one or more scaling, rotation, and translation, based on the size, orientation, and position we would like to give to the object. Every object in the scene has its own world transformation matrix. This is because each object has its own size, orientation, and position.

View Transformation

After vertices are converted to world space, view transformation converts those vertices from world space to view space. Recall from earlier discussion that view space is what the world appears from the viewer's (or camera's) perspective. In view space, the viewer is located at origin looking out along the positive Z axis.

It is worth noting that although view space is the world from the viewer's frame of reference, view transformation matrix is applied to vertices, not the viewer. Therefore, the view matrix must perform the opposite transformation that we apply to our viewer or camera. For example, if we want to move the camera 5 units towards the -Z direction, we would need to compute a view matrix that translates vertices for 5 units along the +Z direction. Although the camera has moved backward, the vertices, from the camera's point of view, have moved forward. In Direct3D a convenient API call D3DXMatrixLookAtLH() is often used to compute a view matrix. We would simply need to tell it where the viewer is, where it's looking at, and the direction representing the viewer's top, also called the up-vector, to obtain a corresponding view matrix.

Projection Transformation

Projection transformation converts vertices from 3D spaces such as world and view spaces to projection space. In projection space, X and Y coordinates of a vertex are obtained from the X/Z and Y/Z ratios of this vertex in 3D space. To understand why, we will examine figure 9, which illustrates projection.

Figure 5. Projection

In 3D space, things appear in perspective. That is, closer objects look bigger than when they are further away. Therefore, where we perceive an object appears depends on the ratio of the distance from the object to the view line, to the distance from that object to the eye along the view line. In figure 9, the tip of a tree that is h units tall at d units away from the viewer's eye will appear at the same point as the tip of another tree 2h units tall and 2d units away. Therefore, where a vertex appears on a 2D screen is directly related to its X/Z and Y/Z ratios.

Vision in 3D has a field of view. This is an angle from view direction that objects outside are no longer visible. For example, human eyes can only see those objects that are somewhat in front. We can't see objects that are at our side or behind. We are also unable to see things if they are too close or too far from our eyes. Therefore, there is a region that only objects inside can be visible to the viewer. In computer graphics, this region is called the view frustum, as illustrated in figure 10. The view frustum is defined by 6 planes in 3D. Two of these planes are parallel to the XY plane. These are called the near-Z and far-Z planes. The other 4 planes are defined by the viewer's horizontal and vertical field of view. The wider the FOV is, the wider the frustum volume is, and the more objects the viewer sees.

The GPU filters out objects that are outside the view frustum so that it does not have to spend time rendering something that will not be displayed. This process is called clipping. As we can see in figure 10, the view frustum in 3D space is a 4-sided pyramid with its top cut off. Clipping against this volume is complicated because to clip against one view frustum plane, the GPU must compare every vertex to the plane's equation. Instead, the GPU generally performs projection transformation first, and then clips against the view frustum volume. The effect of projection transformation on the view frustum is that the pyramid shaped view frustum becomes a box in projection space. This is because, as mentioned above, in projection space the X and Y coordinates are based on the X/Z and Y/Z in 3D space. Therefore, point a and point b in figure 10 will have the same X and Y coordinates in projection space, which is why the view frustum becomes a box.

Figure 6. View Frustum

Now, looking at figure 9, let's suppose that the tips of the two trees lie exactly on the top view frustum edge. Further suppose that d = 2h. The Y coordinate along the top edge in projection space will then be 0.5 (because h/d = 0.5). Therefore, any Y values post-projection that are greater than 0.5 will be clipped by the GPU. The problem here is that 0.5 is determined by the vertical field of view chosen by the program, and different FOV values result in different values that the GPU has to clip against. To make the process more convenient, 3D programs generally scale the projected X and Y values of vertices so that the visible X and Y values range from -1 to 1. In other words, anything with X or Y coordinate that's outside the [-1 1] range will be clipped out. To make this clipping scheme work, the projection matrix must scale the X and Y coordinates of projected vertices by the inverse of h/d, or d/h. d/h is also the cotangent of half of FOV. With scaling, the top of the view frustum becomes h/d * d/h = 1. Anything greater than 1 will be clipped by the GPU. This is what we want.

A similar tweak is generally done for the Z coordinate in projection space as well. We would like the near and far Z planes to be at 0 and 1 in projection space, respectively. When Z = near-Z value in 3D space, Z should be 0 in projection space; when Z = far-Z in 3D space, Z should be 1 in projection space. After this is done, any Z values outside [0 1] will be clipped out by the GPU.

In Direct3D 10, the easiest way to obtain a projection matrix is to call the D3DXMatrixPerspectiveFovLH() method. We simply supply 4 parameters--FOVy, Aspect, Zn, and Zf--and get back a matrix that does everything necessary as mentioned above. FOVy is the field of view in Y direction. Aspect is the aspect ratio, which is ratio of view space width to height. From FOVy and Aspect, FOVx can be computed. This aspect ratio is usually obtained from the ratio of the render target width to height. Zn and Zf are the near and far Z values in view space, respectively.

Using Transformation

In the previous tutorial, we wrote a program that renders a single triangle to screen. When we create the vertex buffer, the vertex positions that we use are directly in projection space so that we don't have to perform any transformation. Now that we have an understanding of 3D space and transformation, we are going to modify the program so that the vertex buffer is defined in object space, as it should be. Then, we will modify our vertex shader to transform the vertices from object space to projection space.

Modifying the Vertex Buffer

Since we started representing things in 3 dimensions, we have changed the flat triangle from the previous tutorial to a cube. This will allow us to demonstrate these concepts much clearer.

    SimpleVertex vertices[] =
    {
        { D3DXVECTOR3( -1.0f,  1.0f, -1.0f ), D3DXVECTOR4( 0.0f, 0.0f, 1.0f, 0.0f ) },
        { D3DXVECTOR3(  1.0f,  1.0f, -1.0f ), D3DXVECTOR4( 0.0f, 1.0f, 0.0f, 0.0f ) },
        { D3DXVECTOR3(  1.0f,  1.0f,  1.0f ), D3DXVECTOR4( 0.0f, 1.0f, 1.0f, 0.0f ) },
        { D3DXVECTOR3( -1.0f,  1.0f,  1.0f ), D3DXVECTOR4( 1.0f, 0.0f, 0.0f, 0.0f ) },
        { D3DXVECTOR3( -1.0f, -1.0f, -1.0f ), D3DXVECTOR4( 1.0f, 0.0f, 1.0f, 0.0f ) },
        { D3DXVECTOR3(  1.0f, -1.0f, -1.0f ), D3DXVECTOR4( 1.0f, 1.0f, 0.0f, 0.0f ) },
        { D3DXVECTOR3(  1.0f, -1.0f,  1.0f ), D3DXVECTOR4( 1.0f, 1.0f, 1.0f, 0.0f ) },
        { D3DXVECTOR3( -1.0f, -1.0f,  1.0f ), D3DXVECTOR4( 0.0f, 0.0f, 0.0f, 0.0f ) },
    };

If you notice, all we did was specify the eight points on the cube, but we didn't actually describe the individual triangles. If we passed this in as is, the output would not be what we expect. We will need to specify the triangles that form the cube through these eight points.

On a cube, many triangles will be sharing the same vertex and it would be a waste of space to redefine the same points over and over again. As such, there is a method to specify just the eight points, and then let Direct3D know which points to pick for a triangle. This is done through an index buffer. An index buffer will contain a list, which will refer to the index of vertices in the buffer, to specify which points to use in each triangle. The code below shows which points make up each of our triangles.

    // Create index buffer
    DWORD indices[] =
    {
        3,1,0,
        2,1,3,

        0,5,4,
        1,5,0,

        3,4,7,
        0,4,3,

        1,6,5,
        2,6,1,

        2,7,6,
        3,7,2,

        6,4,5,
        7,4,6,
    };

As you can see, the first triangle is defined by points 3, 1, and 0. This means that the first triangle has vertices at: ( -1.0f, 1.0f, 1.0f ),( 1.0f, 1.0f, -1.0f ), and ( -1.0f, 1.0f, -1.0f ) respectively. There are six faces on the cube, and each face is comprised of two triangles, thus, you see twelve total triangles defined here.

Since each vertex is explicitly listed, and no two triangles are sharing edges (at least, in the way it has been defined), this is considered a triangle list. In total, for 12 triangles in a triangle list, we will require a total of 36 vertices.

The creation of the index buffer is very similar to the vertex buffer, where we specified parameters such as size and type in a structure, and called CreateBuffer. The type is D3D10_BIND_INDEX_BUFFER, and since we declared our array using DWORD, we will use sizeof(DWORD).

    bd.Usage = D3D10_USAGE_DEFAULT;
    bd.ByteWidth = sizeof( DWORD ) * 36;        // 36 vertices needed for 12 triangles in a triangle list
    bd.BindFlags = D3D10_BIND_INDEX_BUFFER;
    bd.CPUAccessFlags = 0;
    bd.MiscFlags = 0;
    InitData.pSysMem = indices;
    if( FAILED( g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pIndexBuffer ) ) )
        return FALSE;

Once we created this buffer, we will need to set it so that Direct3D knows to refer to this index buffer when generating the triangles. We specify the pointer to the buffer, the format, and the offset in the buffer to start referencing from.

    // Set index buffer
    g_pd3dDevice->IASetIndexBuffer( g_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0 );

Modifying the Vertex Shader

In our vertex shader from the previous tutorial, we take the input vertex position and output the same position without any modification. We can do this because the input vertex position is already defined in projection space. Now, because the input vertex position is defined in object space, we must transform it before outputting from the vertex shader. We do this with 3 steps: transform from object to world space, transform from world to view space, and transform from view to projection space. The first thing that we need to do is declare 3 constant buffer variables. Constant buffers are used to store data that the application needs to pass to shaders. Before rendering, the application usually writes important data to constant buffers, and then during rendering the data can be read from within the shaders. In an FX file, constant buffer variables are declared like global variables in C++. The 3 variables that we will use are the world, view, and projection transformation matrices of the HLSL type "matrix".

Once we have declared the matrices that we will need, we update our vertex shader to transform the input position by using the matrices. A vector is transformed by multiplying the vector by a matrix. In HLSL, this is done using the mul() intrinsic function. Our variable declaration and new vertex shader are shown below:

    matrix World;
    matrix View;
    matrix Projection;

    //
    // Vertex Shader
    //
    VS_OUTPUT VS( float4 Pos : POSITION, float4 Color : COLOR )
    {
        VS_OUTPUT output = (VS_OUTPUT)0;
        output.Pos = mul( Pos, World );
        output.Pos = mul( output.Pos, View );
        output.Pos = mul( output.Pos, Projection );
        output.Color = Color;
        return output;
    }

In the vertex shader, each mul() applies one transformation to the input position. The world, view, and projection transformations are applied in that order sequentially. This is necessary because vector and matrix multiplication is not commutative.

Setting up the Matrices

We have updated our vertex shader to transform using matrices, but we also need to define 3 matrices in our program. These three matrices will store the transformation to be used when we render. Before rendering, we copy the values of these matrices to the shader constant buffer. Then when we initiate the rendering by calling Draw(), our vertex shader reads the matrices stored in the constant buffer. In addition to the matrices, we also need to define 3 ID3D10EffectMatrixVariable pointers. ID3D10EffectMatrixVariable is an object that represents a matrix in the constant buffer. We can use these 3 objects to copy the matrices to the constant buffer. Therefore, our global variables have the following addition:

    ID3D10EffectMatrixVariable* g_pWorldVariable = NULL;
    ID3D10EffectMatrixVariable* g_pViewVariable = NULL;
    ID3D10EffectMatrixVariable* g_pProjectionVariable = NULL;
    D3DXMATRIX                  g_World;
    D3DXMATRIX                  g_View;
    D3DXMATRIX                  g_Projection;

To initialize the 3 ID3D10EffectMatrixVariable objects, we call ID3D10Effect::GetVariableByName() after creating the effect, passing the name of the variable we are interested in. GetVariableByName() returns an ID3D10EffectVariable interface, even though the underlying object is specific to the variable type defined in the FX file. In this case, the underlying objects are ID3D10EffectMatrixVariable. To get an ID3D10EffectMatrixVariable interface from an ID3D10EffectVariable, we can call its AsMatrix() method:

    g_pWorldVariable = g_pEffect->GetVariableByName( "World" )->AsMatrix();
    g_pViewVariable = g_pEffect->GetVariableByName( "View" )->AsMatrix();
    g_pProjectionVariable = g_pEffect->GetVariableByName( "Projection" )->AsMatrix();

The next thing that we need to do is coming up with 3 matrices which we will use to do the transformation. We want the triangle to be sitting on origin, parallel to the XY plane. This is exactly how it is stored in the vertex buffer in object space. Therefore, the world transformation needs to do nothing, and we initialize the world matrix to an identity matrix. We would like to set up our camera so that it is situated at [0 1 -5], looking at the point [0 1 0]. We can call D3DXMatrixLookAtLH() to conveniently compute a view matrix for us using the up vector [0 1 0] since we would like the +Y direction to always stay at top. Finally, to come up with a projection matrix, we call D3DXMatrixPerspectiveFovLH(), with a 90 degree vertical field of view (pi/2), an aspect ratio of 640/480 which is from our back buffer size, and near and far Z at 0.1 and 100, respectively. This means that anything closer than 0.1 or further than 100 will not be visible on the screen. These three matrices are stored in the global variables g_World, g_View, and g_Projection.

Updating Constant Buffers

We have the matrices, and now we must write them to the constant buffer when rendering so that the GPU can read them. Constant buffers are covered in depth in a later tutorial. For now, consider them the containers for constants passed to shaders. Because we are writing matrices to the constant buffer, we call ID3D10EffectMatrixVariable's SetMatrix() method, passing to it the matrix to be written to the buffer. This has to be done before we issue the Draw() call.

    //
    // Update variables
    //
    g_pWorldVariable->SetMatrix( (float*)&g_World );
    g_pViewVariable->SetMatrix( (float*)&g_View );
    g_pProjectionVariable->SetMatrix( (float*)&g_Projection );


Tutorial 5: 3D Transformation

Summary

In the previous tutorial, we rendered a cube from model space to the screen. In this tutorial, we will extend the concept of transformations and demonstrate simple animation that can be achieved with these transformations.

The outcome of this tutorial will be an object that orbits around another. It would be useful to demonstrate the transformations and how they can be combined to achieve the desired effect. Future tutorials will be building on this foundation as we introduce new concepts.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial05

Transformation

In 3D graphics, transformation is often used to operate on vertices and vectors. It is also used to convert them in one space to another. Transformation is performed via multiplication with a matrix. There are typically three types of primitive transformation that can be performed on vertices: translation (where it lies in space relative to the origin), rotation (its direction in relation to the x, y, z frame), and scaling (its distance from origin). In addition to those, projection transformation is used to go from view space to projection space. The D3DX library contains APIs that can conveniently construct a matrix for many purposes such as translation, rotation, scaling, world-to-view transformation, view-to-projection transformation, etc. An application can then use these matrices to transform vertices in its scene. A basic understanding of matrix transformations is required. We will briefly look at some examples below.

Translation

Translation refers to moving or displacing for a certain distance in space. In 3D, the matrix used for translation has the form

    1  0  0  0
    0  1  0  0
    0  0  1  0
    a  b  c  1

where (a, b, c) is the vector that defines the direction and distance to move. For example, to move a vertex -5 unit along the X axis (negative X direction), we can multiply it with this matrix:

    1  0  0  0
    0  1  0  0
    0  0  1  0
   -5  0  0  1

If we apply this to a cube object centered at origin, the result is that the box is moved 5 units towards the negative X axis, as figure 5 shows, after translation is applied.

Figure 1. The effect of translation

In 3D, a space is typically defined by an origin and three unique axes from the origin: X, Y and Z. There are several spaces commonly used in computer graphics: object space, world space, view space, projection space, and screen space.

Figure 2. A cube defined in object space

Rotation

Rotation refers to rotating vertices about an axis going through the origin. Three such axes are the X, Y, and Z axes in the space. An example in 2D would be rotating the vector [1 0] 90 degrees counter-clockwise. The result from the rotation is the vector [0 1]. The matrix used for rotating ? clockwise about the Y axis looks like this:

    cos?  0  -sin?   0
     0    1     0    0
    sin?  0   cos?  0
     0    0     0    1

Figure 6 shows the effect of rotating a cube centered at origin for 45 degrees about the Y axis.

Figure 3. The effect of rotation about the Y axis

Scaling

Scaling refers to enlarge to shrink the size of vector components along axis directions. For example, a vector can be scaled up along all directions or scaled down along the X axis only. To scale, we usually apply the scaling matrix below:

    p  0  0  0
    0  q  0  0
    0  0  r  0
    0  0  0  1

where p, q, and r are the scaling factor along the X, Y, and Z direction, respectively. Figure 7 shows the effect of scaling by 2 along the X direction and scaling by 0.5 along the Y direction.

Figure 4. The effect of Scaling

Multiple Transformations

To apply multiple transformations to a vector, we can simply multiply the vector to the first transformation matrix, then multiply the resulting vector to the second transformation matrix, and so on. Because vector and matrix multiplication is associative, we can also multiply all of the matrices first, then multiply the vector to the product matrix and obtain identical result. Figure 8 shows how the cube would end up if we combine a rotation and a translation transformation together.

Figure 5. The effect of rotation and translation

Creating the Orbit

In this tutorial, we will be transforming two cubes. The first one will rotate in place, while the second one will rotate around the first, while spinning on its own axis. The two cubes will have its own world transformation matrix associated with it, and this matrix will be reapplied to it in every frame rendered.

There are functions within D3DX that will assist in the creation of the rotation, translation, and scaling matrices.

  • Rotations performed around the X, Y and Z axis are accomplished with the functions D3DXMatrixRotationX, D3DXMatrixRotationY, and D3DXMatrixRotationZ respectively. They create basic rotation matrices which rotate around one of the primary axis. Complex rotations around other axis can be done by multiplying together several of them.
  • Translations can be performed in by invoking the D3DXMatrixTranslation function. This function will create a matrix that will translate points specified by the parameters.
  • Scaling is done with D3DXMatrixScaling. It scales only along the primary axes. If scaling along arbitrary axis is desired, then the scaling matrix can be multiplied with an appropriate rotation matrix to achieve the effect.

The first cube will be spinning in place and act as the center for the orbit. The cube has a rotation along the Y axis applied to the associated world matrix. This is done by calling the D3DXMatrixRotationY function shown below. The cube is rotated by a set amount each frame. Since the cubes are suppose to continuously rotate, the value in which the rotation matrix is based on gets incremented with every frame.

    // 1st Cube: Rotate around the origin
    D3DXMatrixRotationY( &g_World1, t );

The second cube will be orbiting around the first one. To demonstrate multiple transformations, a scaling factor, and its own axis spin will be added. The formula used is shown right below the code (in comments). First the cube will be scale down to 30% size, and then it will be rotated along its spin axis (the Z axis in this case). To simulate the orbit, it will get translated away from the origin, and then rotated along the Y axis. The desired effect can be achieved by utilizing four separate matrices with its individual transformation (mScale, mSpin, mTranslate, mOrbit), then multiplied together.

    // 2nd Cube:  Rotate around origin
    D3DXMATRIX mTranslate;
    D3DXMATRIX mOrbit;
    D3DXMATRIX mSpin;
    D3DXMATRIX mScale;
    D3DXMatrixRotationZ( &mSpin, -t );
    D3DXMatrixRotationY( &mOrbit, -t*2.0f );
    D3DXMatrixTranslation( &mTranslate, -4.0f, 0.0f, 0.0f );
    D3DXMatrixScaling( &mScale, 0.3f, 0.3f, 0.3f );

    D3DXMatrixMultiply( &g_World2, &mScale, &mSpin );
    D3DXMatrixMultiply( &g_World2, &g_World2, &mTranslate );
    D3DXMatrixMultiply( &g_World2, &g_World2, &mOrbit );
    //g_World2 = mScale * mSpin * mTranslate * mOrbit;

An important point to note is that these operations are not commutative. The order in which the transformations are applied matter. Experiment with the order of transformation and observe the results.

Since all the transformation functions will create a new matrix from the parameters, the amount at which they rotate has to be incremented. This is done by updating the "time" variable.

    // Update our time
    t += D3DX_PI * 0.0125f;

Before the rendering calls are made, the technique must collect the variables for the shaders. Here, the world, view, and projection matrices are bound to the technique. Note that the world matrix is unique to each cube, and thus, changes for every object that gets passed into it.

    //
    // Render the first cube
    //
    D3D10_TECHNIQUE_DESC techDesc;
    g_pTechnique->GetDesc( &techDesc );
    for( UINT p = 0; p < techDesc.Passes; ++p )
    {
        g_pTechnique->GetPassByIndex( p )->Apply(0);
        g_pd3dDevice->DrawIndexed( 36, 0, 0 );
    }

    //
    // Update variables for the second cube
    //
    g_pWorldVariable->SetMatrix( (float*)&g_World2 );
    g_pViewVariable->SetMatrix( (float*)&g_View );
    g_pProjectionVariable->SetMatrix( (float*)&g_Projection );

    //
    // Render the second cube
    //
    for( UINT p = 0; p < techDesc.Passes; ++p )
    {
        g_pTechnique->GetPassByIndex( p )->Apply(0);
        g_pd3dDevice->DrawIndexed( 36, 0, 0 );
    }

The Depth Buffer

There is one other important addition to this tutorial, and that is the depth buffer. Without it, the smaller orbiting cube would still be drawn on top of the larger center cube when it went around the back of the latter. The depth buffer allows Direct3D to keep track of the depth of every pixel drawn to the screen. The default behavior of the depth buffer in Direct3D 10 is to check every pixel being drawn to the screen against the value stored in the depth buffer for that screen-space pixel. If the depth of the pixel being rendered is less than or equal to the value already in the depth buffer, the pixel is drawn and the value in the depth buffer is updated to the depth of the newly drawn pixel. On the other hand, if the pixel being draw has a depth greater than the value already in the depth buffer, the pixel is discarded and the depth value in the depth buffer remains unchanged.

The following code in the sample creates a depth buffer (a DepthStencil texture). It also creates a DepthStencilView of the depth buffer so that Direct3D 10 knows to use it as a Depth Stencil texture.

    // Create depth stencil texture
    D3D10_TEXTURE2D_DESC descDepth;
    descDepth.Width = width;
    descDepth.Height = height;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_D32_FLOAT;
    descDepth.SampleDesc.Count = 1;
    descDepth.SampleDesc.Quality = 0;
    descDepth.Usage = D3D10_USAGE_DEFAULT;
    descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;
    hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil );
    if( FAILED(hr) )
        return hr;

    // Create the depth stencil view
    D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;
    descDSV.Format = descDepth.Format;
    descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
    descDSV.Texture2D.MipSlice = 0;
    hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView );
    if( FAILED(hr) )
        return hr;

In order to use this newly created depth stencil buffer, the tutorial must bind it to the device. This is done by passing the depth stencil view to the third parameter of the OMSetRenderTargets function.

    g_pd3dDevice->OMSetRenderTargets( 1, &g_pRenderTargetView, g_pDepthStencilView );

As with the render target, we must also clear the depth buffer before rendering. This ensures that depth values from previous frames do not incorrectly discard pixels in the current frame. In this the tutorials is actually setting the depth buffer to be the maximum amount (1.0).

    //
    // Clear the depth buffer to 1.0 (max depth)
    //
    g_pd3dDevice->ClearDepthStencilView( g_pDepthStencilView, D3D10_CLEAR_DEPTH, 1.0f, 0 );


Tutorial 06: Lighting

Summary

In the previous tutorials, the world looks boring because all the objects are lit in the same way. This tutorial will introduce the concept of simple lighting and how it can be applied. The technique use will be lambertian lighting.

The outcome of this tutorial will modify the previous example to include a light source. This light source will be attached to the cube in orbit. The effects of the light can be seen on the center cube.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial06

Lighting

In this tutorial, the most basic type of light will be introduced: lambertian lighting. Lambertian lighting has uniform intensity irrespective of the distance away from the light. When the light hits the surface, the amount of light reflected is calculated by the angle of incidence the light has on the surface. When a light is shined directly on a surface, it is shown to reflect all the light back, with maximum intensity. However, as the angle of the light is increased, the intensity of the light will fade away.

To calculate the intensity that a light has on a surface, the angle between the light direction and the normal of the surface has to be calculated. The normal for a surface is defined as a vector that is perpendicular to the surface. The calculation of the angle can be done with a simple dot product, which will return the projection of the light direction vector onto the normal. The wider the angle, the smaller the projection will be. Thus, this gives us the correct function to modulate the diffused light with.

The light source used in this tutorial is an approximation of directional lighting. The vector which describes the light source determines the direction of the light. Since it's an approximation, no matter where an object is, the direction in which the light shines towards it is the same. An example of this light source is the sun; the sun is always seen to be shining in the same direction for all objects in a scene. In addition, the intensity of the light on individual objects is not taken into consideration.

Other types of light include point lights, which radiate uniform light from its center, and spot lights, which are directional but not uniform across all objects.

Initializing the Lights

In this tutorial, there will be two light sources. One will be statically placed above and behind the cube, and another one will be orbiting the center cube. Note that the orbiting cube in the previous tutorial has been replaced with this light source.

Since lighting is computed by the shaders, the variables would have to be declared and then bound to the variables within the technique. In this sample, we just require the direction of the light source, as well as its color value. The first light is grey and not moving, while the second one is an orbiting red light.

    // Setup our lighting parameters
    D3DXVECTOR4 vLightDirs[2] =
    {
        D3DXVECTOR4( -0.577f, 0.577f, -0.577f, 1.0f ),
        D3DXVECTOR4( 0.0f, 0.0f, -1.0f, 1.0f ),
    };
    D3DXVECTOR4 vLightColors[2] =
    {
        D3DXVECTOR4( 0.5f, 0.5f, 0.5f, 0.0f ),
        D3DXVECTOR4( 0.5f, 0.0f, 0.0f, 0.0f )
    };

The orbiting light is rotated just like the cube in the last tutorial. The rotation matrix applied will change the direction of the light, to show the effect that it is always shining towards the center. Note that function D3DXVec3Transform is utilized to multiply a matrix with a vector. In the previous tutorial we were multiplying just the transformation matrices into the world matrix, then passed into the shader for transformation; but in this case, we're actually doing the world transform of the light in the CPU, for simplicity's sake.

    //rotate the second light around the origin
    D3DXMATRIX mRotate;
    D3DXVECTOR4 vOutDir;
    D3DXMatrixRotationY( &mRotate, -2.0f*t );
    D3DXVec3Transform( &vLightDirs[1], (D3DXVECTOR3*)&vLightDirs[1], &mRotate );

The lights' direction and color are both passed into the shader just like the matrices. The associated variable is called to set, and the parameter is passed in.

    //
    // Update lighting variables
    //
    g_pLightDirVariable->SetFloatVectorArray( (float*)vLightDirs, 0,    2 );
    g_pLightColorVariable->SetFloatVectorArray( (float*)vLightColors, 0,    2 );

Rendering the Lights in the Pixel Shader

Once we have all the data setup and the shader properly fed with data, we can compute the lambertian lighting term on each pixel from the light sources. We'll be using the dot product rule discussed above.

Once we've taken the dot product of the light versus the normal, it can then be multiplied with the color of the light to calculate the effect of that light. That value is passed through the saturate function, which converts the range to [0, 1]. Finally, the results from the two separate lights are summed together to create the final pixel color.

Consider that the material of the surface itself is not factored into this light calculation; the final color of the surface is a result of the light's colors.

    //
    // Pixel Shader
    //
    float4 PS( PS_INPUT input) : SV_Target
    {
        float4 finalColor = 0;

        //do NdotL lighting for 2 lights
        for(int i=0; i<2; i++)
        {
            finalColor += saturate( dot( (float3)vLightDir[i],input.Norm) * vLightColor[i] );
        }
        return finalColor;
    }

Once through the pixel shader, the pixels will have been modulated by the lights and you can see the effect of each light on the cube surface. Note that the light in this case looks flat because pixels on the same surface will have the same normal. Diffuse is a very simple and easy lighting model to compute; more complex lighting models can be used to achieve richer and more realistic materials.


Tutorial 7: Texture Mapping and Constant Buffers

Summary

In the previous tutorial we introduced lighting to our project; now we will build on top of that by adding textures to our cube. In addition, we will be introducing the concept of constant buffers and how they can be used to speed up processing by minimizing bandwidth usage.

The outcome of this tutorial will modify the center cube to have a texture mapped onto it.

This tutorial concludes the introduction of the basic concepts in Direct3D 10. The tutorials following will build upon these concepts by introducing DXUT, mesh loading, as well an example of each shader.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial07

Navigation

  • Texture mapping
  • Constant Buffers

Texture mapping

Texture mapping refers to the projection of a 2D image onto 3D geometry. We can think of it as wrapping a present, by placing decorative paper over an otherwise bland box. To do this, we have to specify how the points on the surface of the geometry correspond with the 2D image.

The trick is to properly align the coordinates of the model with the texture. For complex models, it is difficult to determine the coordinates for the textures by hand. Thus, 3D modeling packages generally will export models with corresponding texture coordinates. Since our example is a cube, it is easy to determine the coordinates needed to match the texture. Texture coordinates are defined at the vertices and then interpolated for individual pixels on a surface.

Loading the Texture

The texture is a 2D image that is retrieved from file and loaded into memory.

// Load the Texture
ID3D10Resource *pRes = NULL;
hr = D3DX10CreateTextureFromFile( g_pd3dDevice, L"seafloor.dds",
    NULL, NULL, &pRes );
if( FAILED(hr) )
    return hr;

Once the texture has been loaded, and the texture resource created, an associated shader-resource view has to be associated with it so it can be read from our shader. The parameters passed are just the default values for a 2D texture.

D3D10_TEXTURE2D_DESC desc;
g_pTexture->GetDesc( &desc );
D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc;
ZeroMemory( &SRVDesc, sizeof(SRVDesc) );
SRVDesc.Format = desc.Format;
SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Texture2D.MipLevels = desc.MipLevels;
hr = g_pd3dDevice->CreateShaderResourceView( g_pTexture,
   &SRVDesc, &g_pTextureRV );
if( FAILED(hr) )
    return hr;

Defining the Coordinates

Before we can map the image onto our cube, we must first define the texture coordinates on each of the vertices of the cube. Since images can be of any size, the coordinate system used has been normalized to [0, 1]. The top left corner of the texture corresponds to (0,0) and the bottom right corner maps to (1,1).

In this example, we're having the whole texture spread across each side of the cube. This simplifies the definition of the coordinates, without confusion. However, it is entirely possible to specify the texture to stretch across all 6 faces, although it's more difficult to define the points, and will appear stretched and distorted.

First, we updated the structure used to define our vertices to include the texture coordinates.

struct SimpleVertex
{
    D3DXVECTOR3 Pos; // Position
    D3DXVECTOR2 Tex; // Texture Coordinate
};

Next, we updated the input layout to the shaders to also include these coordinates.

// Define the input layout
D3D10_INPUT_ELEMENT_DESC layout[] =
{
    { L"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
        D3D10_INPUT_PER_VERTEX_DATA, 0 },
    { L"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12,
        D3D10_INPUT_PER_VERTEX_DATA, 0 },
};

Since the input layout changed, the corresponding vertex shader input must also be modified to match the addition.

struct VS_INPUT
{
    float4 Pos : POSITION;
    float2 Tex : TEXCOORD;
};

Finally, we are ready to include texture coordinates in our vertices we defined back in tutorial 4. Note the second parameter input is a D3DXVECTOR2 containing the texture coordinates. Each vertex on the cube will correspond to a corner of the texture. This creates a simple mapping where each vertex gets (0,0) (0,1) (1,0) or (1,1) as the coordinate.

// Create vertex buffer
SimpleVertex vertices[] =
{
    { D3DXVECTOR3( -1.0f,  1.0f, -1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) },
    { D3DXVECTOR3(  1.0f,  1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) },
    { D3DXVECTOR3(  1.0f,  1.0f,  1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) },
    { D3DXVECTOR3( -1.0f,  1.0f,  1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) },

    { D3DXVECTOR3( -1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) },
    { D3DXVECTOR3(  1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) },
    { D3DXVECTOR3(  1.0f, -1.0f,  1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) },
    { D3DXVECTOR3( -1.0f, -1.0f,  1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) },

    { D3DXVECTOR3( -1.0f, -1.0f,  1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) },
    { D3DXVECTOR3( -1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) },
    { D3DXVECTOR3( -1.0f,  1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) },
    { D3DXVECTOR3( -1.0f,  1.0f,  1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) },

    { D3DXVECTOR3( 1.0f, -1.0f,  1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) },
    { D3DXVECTOR3( 1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) },
    { D3DXVECTOR3( 1.0f,  1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) },
    { D3DXVECTOR3( 1.0f,  1.0f,  1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) },

    { D3DXVECTOR3( -1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) },
    { D3DXVECTOR3(  1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) },
    { D3DXVECTOR3(  1.0f,  1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) },
    { D3DXVECTOR3( -1.0f,  1.0f, -1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) },

    { D3DXVECTOR3( -1.0f, -1.0f, 1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) },
    { D3DXVECTOR3(  1.0f, -1.0f, 1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) },
    { D3DXVECTOR3(  1.0f,  1.0f, 1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) },
    { D3DXVECTOR3( -1.0f,  1.0f, 1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) },
};

When we sample the texture, we will need to modulate it with a material color for the geometry underneath.

Bind Texture as Shader Resource

A texture is an object like the matrices and vectors that we have seen in previous tutorials. Before they can be used by the shader, they need to be set to the Effect. This can be done by getting a pointer to the variable, and then setting it as a shader resource.

g_pDiffuseVariable =
    g_pEffect->GetVariableByName("txDiffuse")->AsShaderResource();

After the resource pointer has been retrieved, it can be used to hook the 2D texture resource view that we had initialized earlier.

g_pDiffuseVariable->SetResource( g_pTextureRV );

There we go, now we're ready to use the texture within the shader.

Applying the Texture (fx)

To actually map the texture on top of the geometry, we will be calling a texture lookup function within the pixel shader. The function, Sample will perform a texture lookup of a 2D texture, then return the sampled color. The pixel shader shown below calls this function and multiplies by the underlying mesh color (or material color) and then outputs the final color.

  • txDiffuse is the object storing our texture that we passed in from the code above, when we bound the resource view g_pTextureRV to it.
  • samLinear will be described below, it is the sampler specifications for the texture lookup.
  • input.Tex is the coordinates of the texture that we have specified in the source
// Pixel Shader
float4 PS( PS_INPUT input) : SV_Target
{
    return txDiffuse.Sample( samLinear, input.Tex ) * vMeshColor;
}

The variable samLinear is a structure that contains the information to tell the pixel shader how to sample the texture provided. In our case, we have a linear filter, and both our addresses wrap. These settings would be useful for simple textures, and an explanation of filters is beyond the scope of this tutorial.

SamplerState samLinear
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

Another thing we must remember to do is to pass the texture coordinates through the vertex shader, or else the data is lost when it gets to the pixel shader. Here, we just copy the input's coordinates to the output, and let the hardware handle the rest.

// Vertex Shader
PS_INPUT VS( VS_INPUT input )
{
    PS_INPUT output = (PS_INPUT)0;
    output.Pos = mul( input.Pos, World );
    output.Pos = mul( output.Pos, View );
    output.Pos = mul( output.Pos, Projection );
    output.Tex = input.Tex;

    return output;
}

Constant Buffers

Starting with Direct3D 10, applications use constant buffers to set shader constants (shader variables). Constant buffers are declared using a syntax similar to C-style structs.

The best way to efficiently use constant buffers is to organize shader variables into constant buffers based on their frequency of update. This allows an application to minimize the bandwidth required for updating shader constants. As an example, this tutorial groups constants into three structures: one for variables that change every frame, one for variables that change only when a window size is changed, and one for variables that are set once and then do not change.

    cbuffer cbNeverChanges
    {
        matrix View;
    };

    cbuffer cbChangeOnResize
    {
        matrix Projection;
    };

    cbuffer cbChangesEveryFrame
    {
        matrix World;
        float4 vMeshColor;
    };


DXUT Tutorials

This section serves as an introduction to DXUT. DXUT is a robust framework to create their own custom applications in, and lets developers forego the tedious process behind setting up the environment. DXUT provides users with a simplified process of creating of a window, selection and creation of a Direct3D device, and handling Windows messages.

This section picks up right after Tutorial 7 in the Basic Tutorials section. It converts the work created up to Tutorial 7 to DXUT, and starts from there.

Tutorial 8: Introduction to DXUT
Tutorial 9: Meshes in DXUT
Tutorial 10: Advanced DXUT


Tutorial 8: Introduction to DXUT

Summary

This tutorial will introduce DXUT. DXUT is a layer built on top of Direct3D to help make samples, prototypes, tools, and professional games more robust and easier to build. It simplifies Windows and Direct3D APIs based on typical usage.

The outcome of this tutorial will be a sample that matches the previous tutorial however, will be implemented differently on the backend.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial08

DXUT

DXUT provides users with a simplified process of creating of a window, selecting and creating a Direct3D device, and handling Windows messages. This allows the programmer to spend less time worrying about how to create a window, how to create a device, how to process Windows messages, or when to handle device events.

DXUT for Direct3D 10 is also highly componentized. The core component of DXUT contains the standard window creation, device creation, and management functionalities while optional components of DXUT such as camera functionality, a GUI system, and mesh handling. The DXUT core component is described in this tutorial, and the optional components are described in the next two tutorials. Features introduced in this tutorial include device creation, the main loop, and simple keyboard input.

DXUT exposes a wide range of callback functions that the user can hook and use. The callbacks are called by DXUT at logical points during program execution. In the callbacks, users can insert custom code to build the application, while allowing DXUT to fulfill the backend window and device management requirements.

DXUT now supports applications that contain Direct3D 9 and/or Direct3D 10 code paths. This allows DXUT to pick the best code path for the system the application is running on. However, since the tutorials are focused on Direct3D 10 development, this tutorial will cover the requirements for Direct3D 10 rendering. For an example of how make a dual Direct3D 9 and Direct3D 10 application on top of DXUT, see the BasicHLSL10 sample in the DirectX SDK.

Setting Callback Functions

The first thing that is modified is the WinMain function of an application. In previous tutorials, this function invoked the initialization function, and then entered the message loop. Within the DXUT framework, this function behaves similarly.

First, the callback functions are set by the application. These are functions which DXUT will call during specific events during execution. Notable events include device creation, swap chain creation, keyboard entry, frame move, and frame render.

    // Direct3D10 callbacks
    DXUTSetCallbackD3D10DeviceAcceptable( IsD3D10DeviceAcceptable );
    DXUTSetCallbackD3D10DeviceCreated( OnD3D10CreateDevice );
    DXUTSetCallbackD3D10SwapChainResized( OnD3D10ResizedSwapChain );
    DXUTSetCallbackD3D10SwapChainReleasing( OnD3D10ReleasingSwapChain );
    DXUTSetCallbackD3D10DeviceDestroyed( OnD3D10DestroyDevice );
    DXUTSetCallbackD3D10FrameRender( OnD3D10FrameRender );

    DXUTSetCallbackMsgProc( MsgProc );
    DXUTSetCallbackKeyboard( KeyboardProc );
    DXUTSetCallbackFrameMove( OnFrameMove );
    DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );

Then the application sets any additional DXUT settings as desired:

    // Show the cursor and clip it when in full screen
    DXUTSetCursorSettings( true, true );

Finally, like in previous tutorials, the initialization functions are called. The difference here is that since the device and window creation is handled by DXUT, the developer only has to deal with application specific code during initialization. Application specific code can be inserted during each of the associated callback functions, which DXUT will invoke as it progresses through the initialization process.

    // Initialize DXUT and create the desired Win32 window and Direct3D
    // device for the application. Calling each of these functions is optional, but they
    // allow you to set several options which control the behavior of the framework.
    DXUTInit( true, true ); // Parse the command line, handle the default hotkeys, and show msgboxes
    DXUTCreateWindow( L"Tutorial8" );
    DXUTCreateDevice( true, 640, 480 );

Debugging with DXUTTrace

DXUTTrace is a macro that can be called to create debug output for the application. It functions much like the standard debug output functions but allows a variable number of arguments. For example:

    DXUTTRACE( L"Hit points left: %d\n", nHitPoints );

In this tutorial, it is placed by function entry to report the state of the application. For instance, at the beginning of OnD3D10ResizedSwapChain(), the debugger would output "SwapChain Reset called".

    DXUTTRACE( L"SwapChain Reset called\n" );

Device Management and Initialization

DXUT provides various methods for creating and configuring the window and Direct3D device. The ones used in this tutorial are listed below. They are sufficient for a moderately complex Direct3D application.

The procedure inside InitDevice() and CleanupDevice() from the previous tutorial has been split and properly managed into the follow functions. Since not all resources are created at the same time, it makes better sense to minimize the overhead by reducing the amount of repeated calls, by only recreating resources that are context dependant. For the sake of simplicity the previous tutorials recreated everything whenever the screen was resized.

IsD3D10DeviceAcceptable Callback

This function is invoked for each combination of valid device settings found on the system to let the application accept or reject each of those combinations. For example, the application could reject all REF devices or could reject full screen device setting combinations.

In this tutorial, all devices are acceptable since it does not need any advanced functionality.

ModifyDeviceSettings Callback

This callback function allows the application to change any device settings right before DXUT creates the device. In this tutorial, this advanced functionality is not needed so nothing needs to be done in the callback.

OnD3D10CreateDevice Callback

This function is called after the creation of the ID3D10Device. Once the device as been created, an application can use this callback to allocate resources, set buffers, and handle other creations necessary.

In this tutorial, the majority of the function InitDevice() from the previous tutorial is copied into this callback function. Since the actual device and swap chain creation is handled by DXUT that code has been omitted. This function will create the Effect, the vertex/index buffers, textures, and transformation matrices. The code has been copied directly from the previous tutorial with minimal alterations, to demonstrate the ease of transition, and to provide logical cohesion with previous tutorials.

OnD3D10DestroyDevice Callback

This callback function is called right before the ID3D10Device is released by DXUT. This callback is where the application releases any resources used by the device.

In this tutorial, this function will release the resources created by the OnD3D10CreateDevice function. Items of note include the vertex/index buffers, the layout, the textures, and the effect. This code is ported over from the CleanupDevice() function, with the change to use the SAFE_RELEASE macro.

Rendering

For rendering, DXUT provides two callback functions in which to initiate rendering for your application. The first, OnFrameMove, is called before each frame is rendered, and is meant for advancing time in the application. The second, OnD3D10FrameRender is called as the rendering function for DXUT.

These two functions split the work of the Render() function into more logical steps. OnFrameMove updates all the matrices for animation, and OnD3D10FrameRender actually houses the rendering calls.

OnFrameMove Callback

This function is called before a frame is rendered, and it is used for the processing of the world state. However, its update frequency is dependent on the speed of the system. Therefore on faster systems, this function will be called more often per second so any state update code must be regulated by time or it will end up performing differently on different speed systems.

In this tutorial, every time the function is called the world will be updated once, and the mesh color will be adjusted. This code is migrated directly from the Render() function in the previous tutorial. Note that none of the rendering calls have migrated to this function.

OnD3D10FrameRender Callback

This function is called whenever a frame is to be redrawn. Within this function, the effects would be applied, the resources associated, and the drawing for the scene called.

In this tutorial, this function contains the calls to clear the back buffer and stencil buffer, sets up the matrices, and draws the cubes.

Message Processing

Message processing is an intrinsic property of all windows application, and DXUT exposes these messages for advanced applications.

MsgProc Callback

This is a callback function that DXUT invokes when window messages are received. It gives the application a chance to handle these messages as it sees fit.

In this tutorial, no additional messages need to be handled.

KeyboardProc Callback

This callback function is invoked by DXUT when a key is pressed. It can be used as a simple function to process keyboard commands.

In this tutorial, it is unused since no keyboard interaction is necessary. However, there is a skeleton case for F1, which can be experimented on. Try to insert code to toggle the rotation of the cubes.

Summary

The functions covered in this tutorial are the basics to get started with a project within the DXUT. Tutorials 9 and 10 will cover more features available with DXUT, but the essentials have been shown.

To start a new project using DXUT, you can use the Sample Browser to copy and optionally rename any sample project in the DirectX SDK. The "EmptyProject" sample is a good blank starting point for DXUT applications, or you can pick with another more advanced sample to begin with.


Tutorial 9: Meshes in DXUT

Summary

This tutorial will introduce the concept of using meshes to import source art. It will demonstrate the method using the help of DXUT. However, concepts covered here can also be applied without it.

The outcome of this tutorial is that the cube in the center will be replaced by a model imported from a file. It will already contain a texture with mapped coordinates.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial09

Meshes

It is apparent that listing each vertex within the source code will become a tedious and crude method to define source art. As such, there are methods available to import pre-constructed models into your application.

Meshes are collections of predefined vertex data. Usually, they also contain useful information such as normals, color, material, and texture coordinates. As long the format of the file is known beforehand, it can be imported and rendered.

The concept behind meshes is that it is often beneficial to reuse source art, and thus, should not be tied directly to an application code. Therefore, they are often stored in separate files. In fact, rarely are they generated in the application, but rather, created in 3D authoring software. The cube that is generated in previous tutorials can be saved into a separate file, and loaded. However, we would like to demonstrate how importing can be much more efficient, as the mesh scales in complexity. One of the biggest benefits is the ability to import the texture coordinates, which can easily be specified in authoring applications, so that they match up perfectly.

DXUT handles meshes through the CDXUTMesh10 class, which is a wrapper for the D3DX Mesh class. This class provides function to import, render, and destroy, amongst other things. The file format we will use for importing is the .X file. There are many freely available converters that will convert other model formats to the .X format. The DirectX SDK includes .X format exporters for 3D Studio Max and Maya.

Creating the Mesh

To begin importing the model, we will need to create a CDXUTMesh10 object. It's called g_Mesh in this case, but applications should be naming it after the source art, since the object would be associated with that model.

    CDXUTMesh10 g_Mesh;

Next, we call the Create function to read the X file and store it into the object. The Create function requires that we pass in the D3D10Device, the name of the X file holding our mesh, the layout, as well the number of elements in the layout. There is also an optional parameter called optimize, which will call D3DX functions to reorder a given mesh's faces and vertices to improve rendering performance.

In this case, we're importing a file called "tiny.x". The format for the vertices that define this mesh contain vertex coordinates, normals, and texture coordinates. As such, we have to specify our input layout to match that, which is shown below.

    // Define the input layout
    const D3D10_INPUT_ELEMENT_DESC layout[] =
    {
        { L"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { L"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { L"TEXCOORD0", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    };

With the layout defined, we can call the Create function to import the model. The last parameter is the number of elements in the vertex format, and since we have coordinates, normal, and texture coordinates, we specified 3.

    // Load the mesh
    V_RETURN( g_Mesh.Create( pd3dDevice, L"tiny.x", (D3D10_INPUT_ELEMENT_DESC*)layout, 3 ) );

Assuming there were no errors, g_Mesh now contains the vertex and index buffer, as well as textures and materials, for our newly imported mesh. Let's begin rendering!

Rendering the Mesh

In the previous tutorials, since we had explicit control of our vertex buffer and index buffers, we had to properly set them up before every frame. However, with a mesh, since those elements are abstracted, we merely have to provide the Effects Technique we want to use to render the mesh, and it will do all the work.

The delta from the previous tutorial is that we removed the portion of OnD3DFrameRender where it began rendering the cube, and replaced it with the mesh rendering call. Even though it is not important in this tutorial, it is good practice to ensure that you set the correct input layout before any mesh is rendered. This way it ensures that the mesh's layout matches with the input assembler.

    //
    // Set the Vertex Layout
    //
    pd3dDevice->IASetInputLayout( g_pVertexLayout );

The actual rendering is done by calling the Render function inside the CDXUTMesh10 class. Once the technique's buffers have been correctly associated, it can be rendered. To render, we have to pass in the D3D10Device, the Effect, and the Technique within that effect.

    //
    // Render the mesh
    //
    g_Mesh.Render( pd3dDevice, g_pEffect, g_pTechnique );

Assuming the world matrix has been properly set for the model, we can now see that the cube in our previous example has been replaced by this more complicated mesh. You might also notice that she's much bigger than the cube. Try applying a scale to the world matrix to get her to fit the screen better.

Destroying the Mesh

Like all objects, the CDXUTMesh10 object must be destroyed after usage. This is done by calling the Destroy function.

    g_Mesh.Destroy();


Tutorial 10: Advanced DXUT

Summary

This tutorial will cover the more advanced aspects related to DXUT. Most of the functionality shown in this tutorial are optional, and are used to enhance your application with minimal costs. DXUT provides a simple sprite based GUI system and a device settings dialog. In addition, it provides a few types of camera classes.

The outcome of this tutorial will be a fully functional GUI to modify settings with the device and scene. There will be buttons, sliders, and text to demonstrate these capabilities.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial10

Navigation

  • DXUT Camera
  • DXUT Dialogs
  • Resource Manager Initialization
  • 3D Settings Dialog
  • Text Rendering

DXUT Camera

The CModelViewerCamera class within DXUT is provided to simplify the management of the view and projection transformations, as well as GUI functionality.

    CModelViewerCamera g_Camera;  // A model viewing camera

The first function provided by the camera is the creation of the view and projection matrix. With the camera, there is no need to worry about these matrices. Instead, you specify where you are, what you're looking at, and the size of the window. Then, you pass these parameters to the camera object, who will create the matrices behind the scene.

Here we're setting the view portion of the camera. We specify where we are, and what we're looking at.

    // Initialize the camera
    D3DXVECTOR3 Eye( 0.0f, 0.0f, -800.0f );
    D3DXVECTOR3 At( 0.0f, 0.0f, 0.0f );
    g_Camera.SetViewParams( &Eye, &At );

Next, we specify the projection portion of the camera. Namely, we need to provide the viewing angle, the aspect ratio, and the near and far clipping planes for the view frustum. This is the same information you provided in previous tutorials, however, you do not have to worry about how to create the matrices themselves.

    // Setup the camera's projection parameters
    float fAspectRatio = pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height;
    g_Camera.SetProjParams( D3DX_PI/4, fAspectRatio, 0.1f, 5000.0f );
    g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height );

In addition, the camera also creates masks for simple mouse feedback. Here, we specify three mouse buttons we want to utilize for the provided mouse operations: model rotation, zooming, and camera rotation. Try compiling the project and playing with each button to understand what each operation does.

    g_Camera.SetButtonMasks( MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_MIDDLE_BUTTON );

With these buttons set, the camera will be listening for these inputs and act accordingly. To respond to the user input, they'll need to add a listening to the MsgProc callback function, which DXUT routes messages to.

    // Pass all remaining windows messages to camera so it can respond to user input
    g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam );

Finally, after inputting all the data into the camera, it's time to extract the actual matrices for the transformations. Here we grab the projection matrix and the view matrix with the associated functions. The camera object will be responsible for computing the matrices themselves.

    g_pProjectionVariable->SetMatrix( (float*)g_Camera.GetProjMatrix() );
    g_pViewVariable->SetMatrix( (float*)g_Camera.GetViewMatrix() );

DXUT Dialogs

User interaction can be done using the class CDXUTDialog, which contain controls in a dialog that accept user input, and pass them through to the application to handle. First, the dialog class has to be instantiated, and then each individual control can be added.

Declarations

In this tutorial, two dialogs will be added, one called g_HUD which shares the same code as the Direct3D 10 samples, and another called g_SampleUI which will be used to demonstrate functions specific to this tutorial. The second dialog in this case is used to control the "puffiness" of the model, which is used to set a variable that is passed into the shaders.

    CDXUTDialog g_HUD;      // manages the 3D UI
    CDXUTDialog g_SampleUI; // dialog for sample specific controls

The dialogs are controlled by a class called the CDXUTDialogResourceManager. The manager will be the one that passes messages and handles shared resources between the dialogs.

    CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs

Finally, a new callback function is associated with the actual events processed by the GUI. This function is used to handle the interaction between the controls.

    void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );

Dialog Initialization

Since there are a lot more utilities that have been introduced, and need to be initialized, this tutorial has moved the actual initialization of these modules to a separate function, called InitApp().

Inside this function is where the controls for each dialog are initialized. Each of the dialogs needs to call their Init function, and pass in the resource manager to specify who to give control to. Also, they set the callback function in which to process the GUI responses. In this case, the callback function associated is OnGUIEvent.

    g_HUD.Init( &g_DialogResourceManager );
    g_SampleUI.Init( &g_DialogResourceManager );
    g_HUD.SetCallback( OnGUIEvent );
    g_SampleUI.SetCallback( OnGUIEvent );

Once they have been initialized, each of the dialogs can insert their controls that they wish to use. The HUD adds three buttons for the basic functionality: toggle fullscreen, toggle reference (software) renderer, and change device.

To add a button, you specify the IDC identifier you wish to use, a string to display, and the coordinates, the width and length, and optionally a hotkey to associate with it. The hotkey is used for the keyboard to quickly toggle these buttons.

Note that the coordinates specified are relative to the dialog's anchor.

    int iY = 10;
    g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 );
    g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22 );
    g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 );

Similarly for the sample UI, three controls are added, one static text, one slider, and one checkbox.

The parameters passed in for the static text are IDC identifier, the string, the coordinates, and the width and height.

The slider parameters are the IDC identifier, the coordinates, the width and height, then the min and max values of the slider, and finally the variable to store the result.

The checkbox contains the IDC identifier, a string label, the coordinates, the width and height, and the Boolean variable to store the result.

    iY = 10;
    WCHAR sz[100];
    iY += 24;
    StringCchPrintf( sz, 100, L"Puffiness: %0.2f", g_fModelPuffiness );
    g_SampleUI.AddStatic( IDC_PUFF_STATIC, sz, 35, iY += 24, 125, 22 );
    g_SampleUI.AddSlider( IDC_PUFF_SCALE, 50, iY += 24, 100, 22, 0, 2000, (int)(g_fModelPuffiness*100.0f) );

    iY += 24;
    g_SampleUI.AddCheckBox( IDC_TOGGLESPIN, L"Toggle Spinning", 35, iY += 24, 125, 22, g_bSpinning );

Once initialized, the actual dialog themselves have to be placed on the screen. This is done during the OnD3D10ResizedSwapChain call since the screen coordinates could change every time the swap chain is recreated (possibly due to resizing the window).

    g_HUD.SetLocation( pBackBufferSurfaceDesc->Width-170, 0 );
    g_HUD.SetSize( 170, 170 );
    g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width-170, pBackBufferSurfaceDesc->Height-300 );
    g_SampleUI.SetSize( 170, 300 );

The final location where the dialogs need to identify themselves is the OnD3D10FrameRender function. What good is a dialog if you don't draw it and the user can't see it?

    //
    // Render the UI
    //
    g_HUD.OnRender( fElapsedTime );
    g_SampleUI.OnRender( fElapsedTime );

Resource Manager Initialization

The resource manager needs to be initialized at every callback associated with initialization and destruction. This is because the GUI needs to be recreated every time a device is created, or a swap chain has been recreated. The CDXUTDialogResourceManager class contains functions corresponding to each of those callbacks, with the exact same name. Thus, it is merely inserting the code to call them at the appropriate places.

    V_RETURN( g_DialogResourceManager.OnD3D10CreateDevice( pd3dDevice ) );
    V_RETURN( g_DialogResourceManager.OnD3D10ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
    g_DialogResourceManager.OnD3D10ReleasingSwapChain();
    g_DialogResourceManager.OnD3D10DestroyDevice();

Responding to GUI Events

Once everything has been initialized, we can finally start writing code to handle the actual GUI interaction. During our initialization of the dialogs, we set the callback function of these dialogs to be OnGUIEvent. Now we're going to create the OnGUIEvent function, which will listen and process the events related to the GUI (which is invoked by the framework).

It is a simple function that contains a case statement for each IDC identifier that was listed when the dialogs were created. Inside each case statement will be the handler code, with the assumption that the user interacted with that control in some way. The code here is very similar to Win32 code which handles controls.

The controls related to the HUD actually call functions which are built into DXUT. There is a DXUT function related to toggling fullscreen, toggling the reference software renderer, and changing the device settings (which invokes the 3D settings dialog described below).

The SampleUI dialog contains custom code to manipulate the variables associated with that slider. It will gather the value, update the text associated with it, and pass that value to the shader.

    void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
    {

        switch( nControlID )
        {
            case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break;
            case IDC_TOGGLEREF:        DXUTToggleREF(); break;
            case IDC_CHANGEDEVICE:     g_D3DSettingsDlg.SetActive( !g_D3DSettingsDlg.IsActive() ); break;

            case IDC_TOGGLESPIN:
            {
                g_bSpinning = g_SampleUI.GetCheckBox( IDC_TOGGLESPIN )->GetChecked();
                break;
            }

            case IDC_PUFF_SCALE:
            {
                g_fModelPuffiness = (float) (g_SampleUI.GetSlider( IDC_PUFF_SCALE )->GetValue() * 0.01f);

                WCHAR sz[100];
                StringCchPrintf( sz, 100, L"Puffiness: %0.2f", g_fModelPuffiness );
                g_SampleUI.GetStatic( IDC_PUFF_STATIC )->SetText( sz );

                g_pPuffiness->SetFloat( g_fModelPuffiness );
                break;
            }
        }

    }

Updating Message Processing

Since we now have dialog messages and user interactions, there will be message passed to the application that will need to be dispatched by the dialogs, if applicable. That code is handled within the MsgProc callback that is provided by DXUT. In previous tutorials, this section is empty since there are no messages to be processed. Now however, we will need to make sure messages intended for the resource manager and dialogs are properly routed.

No special message processing code is required; we only have to call the MsgProcs for each of the dialogs to ensure the message is handled. This is done by calling each individual class' corresponding MsgProc function. It should be noted that the function provides a flag to notify the framework that no further processing of that message is required, and thus, can exit.

    LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext )
    {
        // Always allow dialog resource manager calls to handle global messages
        // so GUI state is updated correctly
        *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam );
        if( *pbNoFurtherProcessing )
            return 0;

        if( g_D3DSettingsDlg.IsActive() )
        {
            g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
            return 0;
        }

        // Give the dialogs a chance to handle the message first
        *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam );
        if( *pbNoFurtherProcessing )
            return 0;
        *pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam );
        if( *pbNoFurtherProcessing )
            return 0;

        if( uMsg == WM_CHAR && wParam == '1' )
            DXUTToggleFullScreen();

        return 0;
    }

3D Settings Dialog

There is a special built in dialog that can be used to control the settings of the D3DDevice. This dialog is provided by DXUT as the CD3DSettingsDlg. It functions like a custom dialog, but it will provide a user with all the options they need to modify the settings.

    CD3DSettingsDlg         g_D3DSettingsDlg;       // Device settings dialog

Initialization is much like other dialogs, you call the Init function. However, every time Direct3D changes its swap chain or device, the dialog must also be updated. Thus, it must include a call within OnD3D10CreateDevice and OnD3D10ResizedSwapChain, named correspondingly, to reflect these changes. Likewise, changes to destroyed objects must also be notified, thus, the need for calls in OnD3D10DestroyDevice.

    g_D3DSettingsDlg.Init( &g_DialogResourceManager );

    V_RETURN( g_D3DSettingsDlg.OnD3D10CreateDevice( pd3dDevice ) );
    V_RETURN( g_D3DSettingsDlg.OnD3D10ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );

    g_D3DSettingsDlg.OnD3D10DestroyDevice();

On the rendering side, since the appearance of the dialog can be toggled, it is switched by a flag called IsActive(). If this flag is set to false, then the panel will not be rendered. The toggling of this panel is actually handled by the HUD dialog from above. The IDC_CHANGEDEVICE associated with the HUD controls this flag, as shown above.

    if( g_D3DSettingsDlg.IsActive() )
    {
        g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
        return 0;
    }

Once these initialization steps are complete, you can include this dialog into your application. Try compiling the tutorial and interacting with the Change Settings panel to see its effect. The actual reconstruction of the D3DDevice or swap chain is done internally by DXUT.

Text Rendering

An application would not be very interesting if the user has no idea what to do. So DXUT includes a utility class for drawing 2D text onto the screen, for feedback to the user. This class, CDXUTD3D10TextHelper, will allow you to draw lines of text anywhere on the screen, with simple string inputs. To start, we will need to instantiate the class. Since text rendering can be isolated from most of the initialization procedures, we keep most of the code within RenderText10 in the tutorial.

    CDXUTD3D10TextHelper txtHelper( g_pFont, g_pSprite, 15 );

Initialization

The first parameter we pass in is the font that we wish to draw in. This font is of the type ID3DXFont, provided by D3DX. To initialize this font, you call D3DX10CreateFont, and you pass in the device, height, width, weight, mipmap levels (generally 1), italics, character set, precision, quality, pitch and family, font face name, and the pointer to your object. While it seems like many characters, only the first four and the last two are really significant.

    V_RETURN( D3DX10CreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
                                OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
                                L"Arial", &g_pFont ) );

The second parameter requires that we initialize an ID3DXSprite class. To do this, we call D3DX10CreateSprite (notice the trend here?). The only things the function requires as parameters are the device, the maximum number of sprites we'll ever draw in one frame, and the pointer to the object.

    // Initialize the sprite
    V_RETURN( D3DX10CreateSprite( pd3dDevice, MAX_SPRITES, &g_pSprite ) );

Of course, like all other objects, the font and sprite must be destroyed once we're done. This can be accomplished with the familiar SAFE_RELEASE macro.

    SAFE_RELEASE( g_pFont );
    SAFE_RELEASE( g_pSprite );

Rendering

The text contained within this sample includes statistics on the rendering done. In addition, there is a help section that will display how to manipulate the model with the mouse.

The rendering calls must be done within OnD3D10FrameRender, and in this tutorial, it is done by calling RenderText10 within the frame render call.

The first section is always rendered, thus, it is done first. The first call to the text render is Begin(). This notifies the engine that we would like to start outputting text to the screen. After that, we set the position of the "cursor", the color of text, and we're ready to draw.

Outputting a string of text is done by calling DrawTextLine. You pass in the string, and it will output that at the current position. It increments the cursor as text is written, thus, if it contains a \n, it will automatically shift the pointer to the next line.

    // Output statistics
    txtHelper.Begin();
    txtHelper.SetInsertionPos( 2, 0 );
    txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) );
    txtHelper.DrawTextLine( DXUTGetFrameStats() );
    txtHelper.DrawTextLine( DXUTGetDeviceStats() );

There is another method to output text, which is similar to the printf commonly used. You format the string with special characters, and then you can insert variables into the string. This is done through DrawFormattedTextLine.

    txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) );
    txtHelper.DrawFormattedTextLine( L"fTime: %0.1f  sin(fTime): %0.4f", fTime, sin(fTime) );

Since the help is drawn in a similar fashion, there isn't need to cover that portion of the code. Do note that you can reposition the pointer at any time by calling SetInsertionPos.

Finally, once you're satisfied with the text output, call End() to notify the engine that you're done.


Shader Tutorials

This section will focus on the shader stages within the graphics pipeline. Programmable shaders have become the emphasis for Direct3D 10. The tutorials in this section are meant to show the users the capabilities of each stage, by implementing a simple technique in each of those. They serve as a purpose to familiarize a developer with the concepts.

Specific techniques are not demonstrated, rather, they can be explored in the Direct3D 10 Samples included in the SDK.

Tutorial 11: Vertex Shaders
Tutorial 12: Pixel Shaders
Tutorial 13: Geometry Shaders


Tutorial 11: Vertex Shaders

Summary

This tutorial will emphasize on the capabilities of the vertex shader. It is meant to show the users the possibilities of allowing manipulation of vertices.

The outcome of this tutorial will be a wave effect imposed on the character model from the previous tutorial. This effect is done entirely by the GPU with no CPU interaction with the data.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial11

Vertex Shader

While previous tutorials already have shown the use of the vertex shader, this tutorial is meant to emphasize this stage in the pipeline. Vertices contain various types of information such as coordinates, normals, texture coordinates, materials, colors, and even custom data. For example, if you look under the ParticlesGS sample, you will see that each vertex passed into the pipeline will also contain a variable called Timer, which can vary the appearance of the particle over time.

The purpose of the vertex shader is to offload intensive calculations from the CPU, onto the GPU. This frees up the CPU to accomplish other tasks within the application. For example, games often offload the graphics processing to the GPU, while the AI and physics is done on the CPU itself.

This tutorial is meant to show the possibilities of the vertex shader, rather than to teach specific techniques. It is encouraged that you try new effects and experiment with the results. For specific methods to achieve effects, refer to the samples included with the SDK. However, do note that they are more complex in nature and apply much more advanced concepts.

Creating the Wave Effect

The wave effect on the model is created by modulating the x position of each point by a sine wave. The sine wave is controlled by the y position, thus creating a wave along the model. However, to make the wave move and appear animated, the sine wave is also modulated by a time variable.

Finally, there is a variable to control the amount of displacement by the vertex shader, and that is the waviness variable specified. This variable is passed into the shader and controlled by a GUI slider.

    output.Pos.x += sin( output.Pos.y*0.1f + Time )*Waviness;

After this manipulation is done, the vertex shader will still have to prepare the vertices for display. Thus, there is still the transformation of the world, view, and projection matrices. However, we chose to do the world transformation before the wave effect, as it would be easier to determine the effects on the screen, since the x and y axis are apparent.

    output.Pos = mul( output.Pos, View );
    output.Pos = mul( output.Pos, Projection );


Tutorial 12: Pixel Shaders

Summary

This tutorial focuses on the pixel shader and its capabilities. There are many things that can be accomplished with the pixel shader, and some of the more common functions are listed. The pixel shader will apply an environment map to the object.

The outcome of the tutorial is that the model will become shiny, and it will reflect its surrounding environment.

Source

SDK root\Samples\C++\Direct3D10\Tutorials\Tutorial12

Pixel Shaders

Pixel shaders are used to manipulate the final color of a pixel before it reaches the output merger. Each pixel that is rendered will be passed through this shader before output. Once the pixel has passed through the pixel shader, the only operations that can be performed are those performed by the output merger, such as alpha blending, depth testing, stencil testing, and so on.

The pixel shader evolved from the texture mapping found in early hardware. Instead of just a simple texture lookup, it is possible to compute the final color from multiple sources, as well as alter it according to the vertex data. For general applications, however, a pixel shader does multiple lookups on different textures.

Environment Map

On surfaces which are reflective, it is not possible to just do a texture lookup on fixed texture coordinates to determine its final color. This is because whenever the object or viewer moves, the reflection alters. Thus, we must update reflection every time something moves.

An effective method to trick the observer to believe it's a dynamic reflection of the environment is to generate a special texture that can wrap around the object. This texture is referred as a cube map. A cube map is effectively placing an object in the middle of a cube, with each face of the cube being a texture. An environment map is a cube map which has the textures which correspond to the view of the environment on that face. If the environment is static, these environment maps can be pre-generated. If the environment is dynamic, the cubemap needs to be updated on-the-fly. See the CubeMapGS sample for an illustration of how to do this.

From this environment map, we can calculate what a camera will see as the reflection. First we can find the direction the camera is viewing the object, and from that, reflect it off the normal of each pixel and perform a lookup based on that reflected vector.

Setting up the Environment Map

The setup of the environment map is not the emphasis of this tutorial. The procedure to follow is very similar to that of a normal texture map. Please refer to Tutorial 7, Texture Mapping and Constant Buffers, for an explanation of how to properly initialize a texture map and its associated resource view.

    // Load the Environment Map
    ID3D10Resource *pResource = NULL;
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Lobby\\LobbyCube.dds" ) );
    V_RETURN( D3DX10CreateTextureFromFile( pd3dDevice, str, NULL, NULL, &pResource ) );
    if(pResource)
    {
        g_pEnvMap = (ID3D10Texture2D*)pResource;
        pResource->Release();
        D3D10_TEXTURECUBE_DESC desc;
        g_pEnvMap->GetDesc( &desc );
        D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc;
        ZeroMemory( &SRVDesc, sizeof(SRVDesc) );
        SRVDesc.Format = desc.Format;
        SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURECUBE;
        SRVDesc.TextureCube.MipLevels = desc.MipLevels;
        SRVDesc.TextureCube.MostDetailedMip = 0;
        V_RETURN(pd3dDevice->CreateShaderResourceView( g_pEnvMap, &SRVDesc, &g_pEnvMapSRV ));
    }

    // Set the Environment Map
    g_pEnvMapVariable->SetResource( g_pEnvMapSRV );

Implementing the Lookup

We will step through the simple algorithm described above and perform a proper lookup of an environment map. The calculations are done in the vertex shader and then interpolated to the pixel shader for the lookup. It is better to compute it in the vertex shader and interpolate to the pixel shader since there are fewer computations necessary.

To compute the reflected vector for the lookup, we require two pieces of information. First is the normal of the pixel in question, second is the direction of the eye.

Since the operation is done in view space, we must transform the pixel's normal to proper viewing space.

    float3 viewNorm = mul( input.Norm, (float3x3)View );

Next we need to find the direction of the camera. Note, however, that we are already in view space, and thus, the camera's direction is that of the Z-axis (0,0,-1.0), since we are staring directly at the object.

Now that we have our two pieces of information, we can calculate the reflection of the vector with the reflect command. The variable ViewR is used to store the resulting reflection for processing in the pixel shader.

    output.ViewR = reflect( viewNorm, float3(0,0,-1.0) );

Once the correct vector has been calculated in the vertex shader, we can process the environment map in the pixel shader. This is done by calling a built-in function to sample the environment map and return the color value from that texture.

    // Load the environment map texture
    float4 cReflect = g_txEnvMap.Sample( samLinearClamp, viewR );

Since it is all normalized (and texture coordinates range from 0 to 1), the x and y coordinates will correspond directly to the texture coordinates that it needs to look up.

As a bonus, we included the code to do the original flat texture lookup, and computed that as the diffuse term. To play with the amount of reflection, you can modulate cReflect by a scaling factor against cDiffuse and experiment with the results. You can have a very reflective character or a somewhat dull character.


Tutorial 13: Geometry Shaders

Summary

This tutorial will explore a part of the graphics pipeline that has not been touched in the previous tutorials. We will be touching upon some basic geometry shader functionality.

The outcome of this tutorial is that the model will have a second layer extruded from the model. Note that the original model is still preserved at the center.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial13

Geometry Shader

The benefit of the geometry shader that it allows manipulation of meshes on a per-primitive basis. Instead of running a computation on each vertex individually, there is the option to operate on a per-primitive basis. That is, vertices can be passed in as a single vertex, a line segment (two vertices), or as a triangle (three vertices).

By allowing manipulation on a per-primitive level, new ideas can be approached, and there is more access to data to allow for that. In the tutorial, you will see that we have calculated the normal for the face. By knowing the position of all three vertices, we can find the face normal.

In addition to allowing access to whole primitives, the geometry shader can create new primitives on the fly. Previously in Direct3D, the graphics pipeline was only able to manipulate existing content, and could amplify or deamplify data. The geometry shader in Direct3D 10 can read in a single primitive (with optional edge-adjacent primitives) and emit zero, one, or multiple primitives based on that.

It is possible to emit a different type of geometry than the input source. For instance, it is possible to read in individual vertices, and generate multiple triangles based on those. This allows a wide range of new ideas to be executed on the graphics pipeline without CPU intervention.

The geometry shader exists between the vertex and the pixel shaders in the graphics pipeline. Since new geometry can potentially be created by the geometry shader, we must ensure that they are also properly transformed to projection space before we pass them off to the pixel shader. This can either be done by the vertex shader before it enters the geometry shader, or it can be done within the geometry shader itself.

Finally, the output of the GS can be rerouted to a buffer. You can read in a bunch of triangles, generate new geometry, and store them in a new buffer. However, the concept of Stream Output is beyond the scope of tutorials, and is best shown in the samples found on the SDK.

Many of the samples found in the Direct3D 10 SDK illustrate specific techniques which can be achieved with the geometry shader. If you want a basic sample to get started, you can try ParticlesGS. ParticlesGS simulates and renders a dynamic particle system (creating, exploding, and destroying particles) entirely on the GPU.

Formatting a Geometry Shader

Unlike the VS and the PS, the geometry shader does not necessarily produce a static number of outputs per input. As such, the format to declare the shader is different from the other two.

The first parameter is maxvertexcount. This parameter will describe the maximum number of vertices that can be outputted each time the shader is run. This is followed by the geometry shader name, which has been aptly named GS.

The function name is followed by the parameters passed into the function. The first one contains the keyword triangle, which specifies that the GS will operate on triangles as input. Following that is the vertex format, and the identifier (with the number signifying the size of the array, 3 for triangles, 2 for line segments). The second parameter is the output format and stream. TriangleStream signifies that the output will be in triangles (triangle strips to be exact), then the format is specified in the angled brackets. Finally, the identifier for the stream is denoted.

    [maxvertexcount(3)]
    void GS( triangle GSPS_INPUT input[3], inout TriangleStream<GSPS_INPUT> TriStream )

If you start emitting vertices to a TriangleStream, it will assume that it's all linked together as a strip. To end a strip, you will need to call RestartStrip() command within the stream. To create a TriangleList, you have to make sure you call RestartStrip() after every triangle.

Exploding the Model

In this tutorial, we will cover the basic functions of the geometry shader. To illustrate this, we will create an explosion effect on our model. This effect is created by extruding each vertex in the direction of that triangle's normal.

Note that a similar effect has been implemented in previous tutorials, whereby we extrude each vertex by its normal, controlled by the puffiness slider. This tutorial will demonstrate the usage of the full triangle's information to generate the face normal. The difference of using the face normal is that you will see gaps in between the exploded triangles. Because vertices on different triangles are shared, they will actually be passed twice into the geometry shader. Moreover, since each time it will extrude it in the normal of the triangle, as opposed to the vertex, the two final vertices may end up in different positions.

Calculating the face normal

To calculate the normal for any plane, we first need two vectors which reside on the plane. Since we are given a triangle, we can subtract any two vertices of the triangle to get the relative vectors. Once we have the vectors, we take the cross product to get the normal. We must also normalize the normal since we will be scaling it later.

    //
    // Calculate the face normal
    //
    float3 faceEdgeA = input[1].Pos - input[0].Pos;
    float3 faceEdgeB = input[2].Pos - input[0].Pos;
    float3 faceNormal = normalize( cross(faceEdgeA, faceEdgeB) );

Once we have the face normal, we can extrude each point of the triangle in that direction. To do so, we will utilize a loop, which will step through three times and operate on each vertex. The position of the vertex will be extruded by the normal, multiplied by a factor. Then, since the vertex shader has not transformed the vertices to proper projection space, we must also do that in the geometry shader. Finally, once we package the rest of the data, we can append this new vertex to our TriangleStream.

    for( int v=0; v<3; v++ )
    {
        output.Pos = input[v].Pos + float4(faceNormal*Explode,0);
        output.Pos = mul( output.Pos, View );
        output.Pos = mul( output.Pos, Projection );

        output.Norm = input[v].Norm;

        output.Tex = input[v].Tex;

        TriStream.Append( output );
    }

Once the three vertices have been emitted, we can cut the strip and restart. In this tutorial, we want to extrude each triangle separately, so we end up with a triangle list.

    TriStream.RestartStrip();

This new triangle stream is then sent to the pixel shader, who will operate on this data and draw it to the render target.


State Tutorials

This section will focus on the state settings and management within the graphics pipeline. State changes affect how rendered primitives interact with the render target, the depth stencil buffer, and with each other.

Tutorial 14: State Management


Tutorial 14: State Management

Summary

This tutorial will explore a very important, but often overlooked aspect of Direct3D 10 programming, state. While not as glamorous or as flashy as shaders, state changes are indispensibly important when it comes to graphics programming. In fact, the same shader can have drastically different visual results base solely upon the state of the device at the time of rendering.

In this tutorial we will explore 3 main types of state objects, BlendStates, DepthStencilStates, and RasterizerStates. At the end of the tutorial, you should have a much better understanding of the way in which states interact to produce different representations of the same scene.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Tutorial14

Blend States

Have you ever heard the term Alpha Blending? Alpha Blending involves modifying color of a pixel being drawn to a certain screen location using the color of the pixel that already exists in that location. Blend States (ID3D10BlendState when used directly from the API and BlendState when used with FX) allow the developer to specify this interaction between new and old pixels. With the Blend State set to default, pixels just overwrite any pixels that already exist at the given screen coordinates during rasterization. Any information about the previous pixel that was drawn there is lost.

To give an example, pretend that your application is drawing the view of a city from inside a taxi cab. You've drawn thousands of buildings, sidewalks, telephone poles, trash cans, and other objects that make up a city. You have even drawn the interior of the cab. Now, as your last step, you want to draw the windows of the cab to make it look like as though you're actually peering through glass. Unfortunately, the pixels draw during rasterization of the glass mesh completely overwrite the pixels alread at those locations on the screen. This includes your beautiful city scene along with the sidewalks, telephone poles, and all of your other city objects. Wouldn't it be great if we could include the information that was already on the screen when drawing the glass windows of the cab? Wouldn't it also be great if we could do this with minimal changes in our current pixel shader code?

This is exactly what Blend States give you. To demonstrate this, our scene consists of a model and a quad.

    // Load the mesh
    V_RETURN( g_Mesh.Create( pd3dDevice, L"Tiny\\tiny.x", (D3D10_INPUT_ELEMENT_DESC*)layout, 3 ) );

Note that our quad has a different vertex format and therefore needs a different input layout description

    // Create a screen quad
    const D3D10_INPUT_ELEMENT_DESC quadlayout[] =
    {
        { L"POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { L"TEXCOORD0", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    };

    g_pTechniqueQuad[0]->GetPassByIndex( 0 )->GetDesc( &PassDesc );
    V_RETURN( pd3dDevice->CreateInputLayout( quadlayout, 2, PassDesc.pIAInputSignature, &g_pQuadLayout ) );

    ...

    D3D10_SUBRESOURCE_DATA InitData;
    InitData.pSysMem = svQuad;
    InitData.SysMemPitch = 0;
    InitData.SysMemSlicePitch = 0;
    V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, &InitData, &g_pScreenQuadVB ) );

When we render our scene we see the model of a person, with a quad drawn over the top.

Imagine that this person represents our city and the quad is really a pane of glass. When we launch the application, the situation is exactly as we described it above, we can't see through the glass. However, by selecting a different Quad Render Mode from the drop down box, we can suddenly see through the quad. It's as if it's a plane of glass.

In fact, all that the application is doing when we select a different Quad Render Mode is changing which technique in the FX file we're using to render the quad. For example, RenderQuadSolid in the combo box refers to the following technique in the FX file.

    technique10 RenderQuadSolid
    {
        pass P0
        {
            SetVertexShader( CompileShader( vs_4_0, QuadVS() ) );
            SetGeometryShader( NULL );
            SetPixelShader( CompileShader( ps_4_0, QuadPS() ) );

            SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
        }
    }

The SetVertexShader, SetGeometryShader, and SetPixelShader functions should all look familiar at this point. If not, please review tutorials 10 through 12. The last line is what we're focusing on for now. In an FX file, this is how you set the Blend State. NoBlending actually refers to a state structure defined at the top of the FX file. The structure disables blending for the first (0) render target.

    BlendState NoBlending
    {
        BlendEnable[0] = FALSE;
    };

As we said before, this Blend State does nothing interesting. Because alpha blending is disabled, the pixels of the quad simply overwrite the existing pixels placed on the screen when rendering the person. However, things get more interesting when we select RenderQuadSrcAlphaAdd from the Quad Render Mode combo box. This changes the quad to be rendered with the RenderQuadSrcAlphaAdd technique.

    technique10 RenderQuadSrcAlphaAdd
    {
        pass P0
        {
            SetVertexShader( CompileShader( vs_4_0, QuadVS() ) );
            SetGeometryShader( NULL );
            SetPixelShader( CompileShader( ps_4_0, QuadPS() ) );

            SetBlendState( SrcAlphaBlendingAdd, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
        }
    }

A close look at this technique reveals two differences between it and the RenderQuadSolid technique. The first is the name. The second, and vitally important, difference is the Blend State passed into SetBlendState. Instead of passing in the NoBlending Blend State, we're passing in the SrcAlphBlendingAdd Blend State which is defined at the top of the FX file.

    BlendState SrcAlphaBlendingAdd
    {
        BlendEnable[0] = TRUE;
        SrcBlend = SRC_ALPHA;
        DestBlend = ONE;
        BlendOp = ADD;
        SrcBlendAlpha = ZERO;
        DestBlendAlpha = ZERO;
        BlendOpAlpha = ADD;
        RenderTargetWriteMask[0] = 0x0F;
    };

This blend state is a little more complex than the last one. Blending is enabled on the first (0) render target. For a thorough description of all Blend State parameters, refer to the documentation for D3D10_BLEND_DESC. Here is a quick overview of what this function is telling Direct3D 10 to do. When rendering the quad using this technique, the pixel about to be rendered to the framebuffer does not simply replace the existing pixel. Instead its color is modified using the following formula.

    outputPixel = ( SourceColor*SourceBlendFactor ) BlendOp ( DestColor*DestinationBlendFactor )

    SourceColor is a pixel being rendered when we draw the quad.
    DestColor is the pixel that already exists in the framebuffer (from drawing the person)
    BlendOp is the BlendOp from the SrcAlphaBlendingAdd blend structure
    SourceBlendFactor is SrcBlend in the SrcAlphaBlendingAdd blend structure
    DestinationBlendFactor is DestBlend in the SrcAlphaBlendingAdd blend structure

By using the SrcAlphaBlendingAdd structure above, we can translate the equation into the following

    OutputPixel = ( SourceColor.rgba * SourceColor.aaaa ) ADD ( DestColor.rgba * (1,1,1,1) )

Graphically this can be displayed by the following diagram.

Thus, the output color is dependent on the the color that was already in the framebuffer at the time of drawing. Different selections in the combo box will result in the quad being draw with different techniques, and hence, different Blend States. Each Blend State changes the variables to the equation, so be sure to experiment with them all. See if you can predict what will happen just by looking at the Blend State.

Rasterizer states

You may have noticed that no matter which Blend State was selected, the figure in the middle looked a little off. Some polygons were showing up where they shouldn't have been. Sometimes the legs looked as though you were looking at an upright tube cut in half. This brings us to our next state object, Rasterizer State.

The Rasterizer State ( ID3D10RasterizerState when used through the API and RasterizerState when used through the FX framework ) controls how the triangles are actually rendered on the screen. Unlike the previous section on Blend States, we are not going to control Rasterizer States through the FX interface. This does not mean that they cannot be used through the FX system. In fact, it's just as easy to use Rasterizer States through FX as it is to use Blend States through FX. However, we're going to take this opportunity to learn about non-FX state management using the Direct3D 10 APIs.

As the name implies, Rasterizer State controls how polygons are rasterized on the screen. When the tutorial starts up, the polygons are not culled. This means that where the polygons are pointing in your direction or pointing away from you, they all get draw equally. This is why some dark polygons are "poking" through in the figure. In order to change this behavior we must first create a Rasterizer State that defines the behavior we want. Since we're doing this through the API and not the FX interface the process is a little different than for Blend States. The following code is from the LoadRasterizerStates function.

    D3D10_FILL_MODE fill[MAX_RASTERIZER_MODES] =
    {
        D3D10_FILL_SOLID,
        D3D10_FILL_SOLID,
        D3D10_FILL_SOLID,
        D3D10_FILL_WIREFRAME,
        D3D10_FILL_WIREFRAME,
        D3D10_FILL_WIREFRAME
    };
    D3D10_CULL_MODE cull[MAX_RASTERIZER_MODES] =
    {
        D3D10_CULL_NONE,
        D3D10_CULL_FRONT,
        D3D10_CULL_BACK,
        D3D10_CULL_NONE,
        D3D10_CULL_FRONT,
        D3D10_CULL_BACK
    };

    for( UINT i=0; i<MAX_RASTERIZER_MODES; i++ )
    {
        D3D10_RASTERIZER_DESC rasterizerState;
        rasterizerState.FillMode = fill[i];
        rasterizerState.CullMode = cull[i];
        rasterizerState.FrontCounterClockwise = true;
        rasterizerState.DepthBias = false;
        rasterizerState.DepthBiasClamp = 0;
        rasterizerState.SlopeScaledDepthBias = 0;
        rasterizerState.DepthClipEnable = true;
        rasterizerState.ScissorEnable = false;
        rasterizerState.MultisampleEnable = false;
        rasterizerState.AntialiasedLineEnable = false;
        pd3dDevice->CreateRasterizerState( &rasterizerState, &g_pRasterStates[i] );

        g_SampleUI.GetComboBox(IDC_SCENERASTERIZER_MODE)->AddItem( g_szRasterizerModes[i], (void*)(UINT64)i );
    }

All this code is doing is filling in a D3D10_RASTERIZER_DESC structure with the necessary information and then calling ID3D10Device::CreateRasterizerState to get a pointer to an ID3D10RasterizerState object. The loop creates one state for each type of Rasterizer State we want to show off. Notice that the first state, which uses D3D10_FILL_SOLID as the fill mode and D3D10_CULL_NONE as the cull mode is what is causing our figure to look weird. To change this, we can select the second rasterizer state from Scene Rasterizer Mode combo box. This object can then be used to set the state before we render. This is how the currently selected Rasterizer State is set in OnD3D10FrameRender.

    //
    // Update the Cull Mode (non-FX method)
    //
    pd3dDevice->RSSetState(g_pRasterStates[ g_eSceneRasterizerMode ]);

It must be noted any state set "persists" through all subsequent drawing operations until a different state is set or the device is destroyed. This means that when we set the rasterizer state in OnD3D10FrameRender, that same Rasterizer State is applied to any and all drawing operations that come after until a different Rasterizer State is set.

When we selected the second option from the Scene Rasterizer Mode combo box our figure got a lot worse and the quad just dissappeared.

This is because we selected a cull mode that told Direct3D 10 not to draw triangles that are facing forward. The next Rasterizer State ( D3D10_CULL_BACK and D3D10_FILL_SOLID ) should give us the results we want ( with the exception of some stray black triangles around the head which we'll discuss in the next section ).

In addition to which triangles to draw and not draw, Rasterizer States can control many other aspects of rendering. A more thorough explanation of the function of each part of the state structure can be found in the Direct3D 10 documentation under Feel free to experiment with the different Scene Rasterizer Mode selections or to even change the code in LoadRasterizerStates to see what happens.

Depth Stencil states

In the last section, setting the cull mode to D3D10_CULL_BACK and the fill mode to D3D10_FILL_SOLID gave a decent looking figure in the middle. However, there were still some black polygons showing up around the face. This is because those polygons were still classified as pointing to the front even though they were on the other side of the head. This is where the Depth Stencil State comes into play. This state object actually controls two different parts of the Direct3D 10 pipeline. The first is the Depth Buffer.

On a basic level the depth buffer stores values representation of the distance of the pixel from the view plane. The greater the value, the greater the distance. The depth buffer is the same resolution (height and width) as the backbuffer. By itself, this doesn't seem very useful to our situation. However, the Depth Stencil State lets us modify the current pixel based upon the depth of the pixel already at that location in the framebuffer.

The Depth Stencil States are created in the LoadDepthStencilStates function. This function is similar to the LoadRasterizerStates. We will discuss some of the parameters of the D3D10_DEPTH_STENCIL_DESC structure. The most important of which is the DepthEnable. This determines whether the Depth Test is even functioning. As we can see, when the app starts up, the Depth Test is disabled. This is why the front facing hair spikes on the far side of the head still show up.

Setting the Depth Stencil State is also very similar to setting the Rasterizer State with one exception. There is an extra parameter. This parameter is the StencilRef which will be explained in the next section.

    //
    // Update the Depth Stencil States (non-FX method)
    //
    pd3dDevice->OMSetDepthStencilState(g_pDepthStencilStates[ g_eSceneDepthStencilMode ], 0);

The second Depth Stencil State in the Scene Depth/Stencil Mode combo enables the Depth Test. When you enable the Depth Test, you need to tell Direct3D 10 what type of test to do. The equation boils down to the following.

    DrawThePixel? = DepthOfCurrentPixel D3D10_COMPARISON CurrentDepthInDepthBuffer

    D3D10_COMPARISON is the comparison function in the DepthFunc parameter of the D3D10_DEPTH_STENCIL_DESC

By substituting the value of the DepthFunc from the second Depth Stencil State, we get the following for the equation.

    DrawThePixel? = DepthOfCurrentPixel D3D10_COMPARISON_LESS CurrentDepthInDepthBuffer

In English, this means "Draw the current pixel only if it's depth is LESS than the depth already stored at this location." Additionally, we set the DepthWriteMask to D3D10_DEPTH_WRITE_MASK_ALL to ensure that our depth is put into the depth buffer at this location (should we pass the test) so that any subsequent pixels will have to be closer than our depth value to be drawn.

This results in the figure being drawn without any black marks. The forward facing hair spikes in the rear never show through. They are either overwritten by closer triangles in the near side of the face, or they are never draw because the near triangles have a closer depth value. You will also notice that this reveals something about the quad. All this time it looked like it was in front of the figure. Now, we realize that it is actually intersecting the figure.

Try playing around with the DepthFunc values and see what happens.

Rendering Using the Stencil Buffer

The Stencil parameters are part of the Depth Stencil State, but, because of their complexity, they deserve their own section.

The Stencil buffer can be thought of as a buffer like the Depth Buffer. Like the depth buffer, it has the same dimensions as the Render Target. However, instead of storing depth values, the stencil buffer stores integer values. These values have meaning only to the application. The Stencil part of the Depth Stencil State determines how these values get there and what they mean to the application.

Like the Depth Buffer's Depth Test, the Stencil Buffer has a Stencil Test. This Stencil Test can compare the incoming value of the pixel to the current value in the Stencil Buffer. However, it can also augment this comparison with results from the Depth Test. Let's go through one of the Stencil Test setups to see what this means. The following information is from the fifth iteration of the loop in the LoadDepthStencilStates funciton. This reflects the 5th Depth Stencil State in the Scene Depth/Stencil Mode combo box.

    D3D10_DEPTH_STENCIL_DESC dsDesc;
    dsDesc.DepthEnable = TRUE;
    dsDesc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
    dsDesc.DepthFunc = D3D10_COMPARISON_LESS;

    dsDesc.StencilEnable = TRUE
    dsDesc.StencilReadMask = 0xFF;
    dsDesc.StencilWriteMask = 0xFF;

    // Stencil operations if pixel is front-facing
    dsDesc.FrontFace.StencilFailOp = D3D10_STENCIL_OP_KEEP;
    dsDesc.FrontFace.StencilDepthFailOp = D3D10_STENCIL_OP_INCR;
    dsDesc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
    dsDesc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;

    // Stencil operations if pixel is back-facing
    dsDesc.BackFace.StencilFailOp = D3D10_STENCIL_OP_KEEP;
    dsDesc.BackFace.StencilDepthFailOp = D3D10_STENCIL_OP_INC;
    dsDesc.BackFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
    dsDesc.BackFace.StencilFunc = D3D10_COMPARISON_ALWAYS;

From the previous section, you should know that the Depth Test is set to let any pixel through that is closer to the plane than the previous depth value at that location. However, now, we've enabled the Stencil Test by setting StencilEnable to TRUE. We've also set the StencilReadMask and StencilWriteMask to values that ensure we read from and write to all bits of the stencil buffer.

Now comes the meat of the Stencil settings. The stencil operation can have different effects depending on whether the triangle being rasterized is front facing or back facing. (Remember that we can select to draw only front or back facing polygons using the Rasterizer State.) For simplicity, we're going to use the same operations for both front and back facing polygons, so we'll only discuss the FrontFace operations. The FrontFace.StencilFailOp is set to D3D10_STENCILL_OP_KEEP. This means that if the Stencil Test fails, we keep the current value in the stencil buffer. The FrontFace.StencilDepthFailOp is set to D3D10_STENCIL_OP_INC. This means that if we fail the depth test, we increment the value in the stencil buffer by 1. The FrontFace.STencilPassOp is set to D3D10_STENCIL_OP_KEEP, meaning that on passing the Stencil Test we keep the current value. Finally FrontFace.StencilFunc represents the comparison used to determine if we actually pass the Stencil Test (not the Depth Test). This can be any of the D3D10_COMPARISON values. For example, D3D10_COMPARISON_LESS would only pass the Stencil Test if the current stencil value was less than the incumbant stencil value in the Stencil Buffer. But where does this current test value come from? It's the second parameter to the OMSetDepthStencilState function (the StencilRef parameter).

    //
    // Update the Depth Stencil States (non-FX method)
    //
    pd3dDevice->OMSetDepthStencilState(g_pDepthStencilStates[ g_eSceneDepthStencilMode ], 0);

For this example, the StencilRef parameter doesn't matter in the stencil comparison function. Why? Because we've set the StencilFunc to D3D10_COMPARISON_ALWAYS, meaning we ALWAYS pass the test.

What you may have already determined from looking at this Depth Stencil State is that any pixel that FAILS the Depth Test will cause the value in the Stencil Buffer to increment (for that location in the buffer). If we fill the stencil buffer with zeroes (which we do at the beginning of OnD3D10FrameRender), then any non-zero value in the stencil buffer is a place where a pixel failed the depth test.

If we could actually visualize this Stencil Buffer, we could determine all of the places in the scene where we attempted to draw something, but something else was closer. In essence, we could tell where we tried to draw something behind and object already there.

Unfortunately, there is no Direct3D 10 function called ShowMeTheStencilBuffer. Fortunately, we can create an FX Technique that does the same thing. To show that the Depth Stencil State can be just as easily set through the FX system as it can be through the Direct3D 10 APIs, we're show how to use a Depth Stencil State in FX to view the contents of the stencil buffer.

After both the figure and the quad have been drawn, we render another quad that covers the entire viewport. Because we cover the entire viewport, we can access every pixel that could possibly be touched by our previous rendering operations. THe technique used to render this quad is RenderWithStencil in the FX file.

    technique10 RenderWithStencil
    {
        pass P0
        {
            SetVertexShader( CompileShader( vs_4_0, ScreenQuadVS() ) );
            SetGeometryShader( NULL );
            SetPixelShader( CompileShader( ps_4_0, QuadPS() ) );

           SetBlendState( NoBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
            SetDepthStencilState( RenderWithStencilState, 0 );
        }
    }

Notice that in addition to setting the Blend State, we also set the Depth Stencil State to RenderWithStencilState. The second parameter sets the StencilRef value to 0. Let's take a look at the RenderWithStencilState as defined at the top of the FX file.

    DepthStencilState RenderWithStencilState
    {
        DepthEnable = false;
        DepthWriteMask = ZERO;
        DepthFunc = Less;

        // Setup stencil states
        StencilEnable = true;
        StencilReadMask = 0xFF;
        StencilWriteMask = 0x00;

        FrontFaceStencilFunc = Not_Equal;
        FrontFaceStencilPass = Keep;
        FrontFaceStencilFail = Zero;

        BackFaceStencilFunc = Not_Equal;
        BackFaceStencilPass = Keep;
        BackFaceStencilFail = Zero;
    };

The first thing you should notice is that this is similar to the D3D10_DEPTH_STENCIL_DESC you'd find in the LoadDepthStencilStates function in the cpp file. The values are different, but the members are the same. First, we disable the depth test. Secondly, we enable the Stencil Test, BUT we set our StencilWriteMask to 0. We only want to read the stencil value. Last we set the StencilFunc to Not_Equal, the StencilPass to Keep, and the StencilFail to Zero for both front and back faces. Remember that the Stencil Test tests the current incoming value with the value already stored in the Stencil Buffer. In this case, we set the incoming value (the StencilRef) to 0 when we called SetDepthStencilState( RenderWithStencilState, 0 ); Thus, we can translate this state to mean that the stencil test passes where the Stencil Buffer is not equal to 0 (StencilRef). On pass we get to Keep the incoming pixel from the pixel shader and write it out to the frame buffer. On a fail, we discard the incoming pixel, and it never gets drawn. Thus, our screen covering quad is only drawn in places where the Stencil Buffer is non-zero.

Selecting different items in the Scene Depth/Stencil Mode combo box change how the Depth and Stencil buffers are filled, and thus how much of the Screen Sized quad that's drawn last actually makes it onto the screen. Some of these combinations won't produce any output. Some will produce bizarre effects. Try to see which ones will do what before you apply them.


Workshops

This section will focus on Direct3D 10 related workshops and presentations.

Direct3D 10 Shader Model 4.0 Workshop
Advanced Shader Authoring Workshop GDC 2007
Performance Workshop GDC 2007


Direct3D 10 Shader Model 4.0 Workshop

Summary

This workshop is based upon the Direct3D 10 Shader Model 4.0 Workshop presented at GDC 2006. The workshop guides the student through 7 exercises aimed at teaching the basics of Shader Model 4.0 HLSL. Students are expected to have a working knowledge of the Direct3D 10 graphics pipeline and HLSL. Exercise05 will require knowledge of C programming.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Direct3D10Workshop

General Exercise Guidelines

While the exercises do build upon each other, they are meant to be self-contained. With the exception of Exercise05, the student will be working with .fx files to complete each exercise. Comments are located throughout the code to guide the student. Comments are highlighted by a collection of ascii characters known as "Breakdancin Bob" and take the following form:

//-----------------------------------------------------------------
// o/__   <-- BreakdancinBob TODO: Todos are areas where you need
//  |  (\ 		to change or implement code.  This is where
//			the actual exercise work will happen.
//-----------------------------------------------------------------

//-----------------------------------------------------------------
// o/__   <-- BreakdancinBob NOTE:  Notes are code snippets of
//  |  (\		interest.  No work needs to be done.  Just
//			look.
//-----------------------------------------------------------------

//-----------------------------------------------------------------
// o/__   <-- BreakdancinBob HINT:  Hints may be found near Todo
//  |  (\		comments.  Hints can help you if you are
//			stuck with the exercise.
//-----------------------------------------------------------------

Solutions to the exercises are found in the folders with _Solved appended to the end.

Exercise00 - Debugging Practice

The goal of Exercise00 is to familiarize the user with the act of debugging shader problems. The solution will compile, but during run time, an error box will appear telling the user that the shader could not be compiled. Look in the Visual Studio output window for debug spew from the shader compiler to determine the cause of the error.

Exercise01 - Introduction to the Geometry Shader

The goal of Exercise01 is to teach basic usage of the Geometry Shader, a new shader type for Direct3d 10. The exercise teaches the student to use the Geometry Shader to append any elements needed by the pixel shader to the output vertex stream.

Exercise02 - Finding Silhouette Edges

This exercise teaches the principle of finding silhouette edges. When the student opens the exercise, the shader calculates and displays a silhouette with respect to the viewer. Only edges with one face facing the viewer and one face facing away from the viewer are drawn. The goal of Exercise02 is to change this calculation to happen with respect to the light source. This is an essential step for doing stencil shadow volumes. The following diagram illustrates this more clearly.

Exercise03 - Shadow Volumes

Exercise03 builds upon the silhouette edges found in Exercise02 to create extruded shadow volumes. While this exercise does not do capping and does not use the stencil buffer to actually do shadowing, it illustrates the second essential step for implementing stencil shadow volumes. The following diagram illustrates how to extrude a shadow volume from a selected edge.

Exercise04 - Creating New Geometry

The previous exercises showed off one of the main strengths of the Geometry Shader, operating on whole primitives with adjacency information. The remaining exercises illustrate two other strengths of the Geometry Shader. These are geometry amplification and destruction, and stream output. In Exercise04, the geometry shader is used to create new triangles based upon information contained in the vertex stream. At specific faces on the mesh, a new triangle is created and moved away from the original face in the direction of the normal.

Exercise05 - Feedback and Stream Out

This exercise demonstrates procedural geometry generation using geometry amplification through the Geometry Shader. The amplified geometry is then fed back through the Geometry Shader during subsequent passes to grow an entire tree from a small piece of seed geometry. This exercise deals only with the cpp file and requires knowledge of C to complete.

Exercise06

Exercise06 is a very simple exercise showing how to add some randomness and variation to tree created in Exercise05. A buffer of random numbers is generated and then sampled in the shader to control the growth of the tree.


Advanced Shader Authoring Workshop GDC 2007

Summary

This workshop is based upon the Advanced Shader Authoring Workshop presented at GDC 2007. The workshop guides the student through 6 exercises aimed at teaching Shader Model 4.0 techniques. The exercises build upon each other to create a music visualization program. Students are expected to have a working knowledge of the Direct3D 10 graphics pipeline and HLSL. The workshops are meant to be completed with the help of the accompanying powerpoint presentation in the workshop folder.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\Direct3D10WorkshopGDC2007

General Exercise Guidelines

While the exercises do build upon each other, they are meant to be self-contained. With the exception of Exercise02 and Exercise04, the student will be working with .fx files to complete each exercise. Comments are located throughout the code to guide the student. Comments are highlighted by a collection of ascii characters known as "Breakdancin Bob" and take the following form:

//-----------------------------------------------------------------
// o/__   <-- BreakdancinBob TODO: Todos are areas where you need
//  |  (\ 		to change or implement code.  This is where
//			the actual exercise work will happen.
//-----------------------------------------------------------------

//-----------------------------------------------------------------
// o/__   <-- BreakdancinBob NOTE:  Notes are code snippets of
//  |  (\		interest.  No work needs to be done.  Just
//			look.
//-----------------------------------------------------------------

//-----------------------------------------------------------------
// o/__   <-- BreakdancinBob HINT:  Hints may be found near Todo
//  |  (\		comments.  Hints can help you if you are
//			stuck with the exercise.
//-----------------------------------------------------------------

Solutions to the exercises are found in the folders with _Solved appended to the end.

Exercise01 - Drawing the Bars

The goal of Exercise01 is to familiarize the user with Shader Model 4.0 syntax. Initially the application will load a flat line of bars. Press the "Start Playback" button to start playback of the wave file. The user can also load different waves using the Load Wave button. The goal of Exercise01 is to get the bars drawn on-screen to react to the sound.

Exercise02 - Performance

Exercise02 introduces PIX for Windows. The application is rendering very slowly in this instance. It is up to the user to use PIX for Windows to identify the bottleneck.

Exercise03 - Geometry Amplification

In Exercise03, the user must use Geometry Amplification to create extra geometry that reacts to the sound.

Exercise04 - More Performance

In Exercise04, PIX for Windows is used to determine the "possible" negative performance impact of doing too much geometry amplification.

Exercise05 - Floor Effect

In Exercise05, the user must implement a floor effect. The amplified parts of the bars are rendered into a texture that is then applied to a plane underneath the bars. A simple effect that blurs and moves the texture away from the bars is already implemented. It is up to the user to create a more interesting effect.

Exercise06 - Floor Effect

The final exercise involves creating a full-screen effect similar to those seen in many other music visualization programs. The lessons learned from Exercise05 should apply here as well.


Performance Workshop GDC 2007

Summary

This workshop is based upon the Performance Workshop presented at GDC 2007. The workshop guides the student through 3 exercises aimed at teaching the basics of performance analysis. Students are expected to have a working knowledge of c++ and Direct3D. The workshops are meant to be completed with the help of the accompanying powerpoint presentation in the workshop folder.

Source

(SDK root)\Samples\C++\Direct3D10\Tutorials\PIXWorkshopGDC2007

General Exercise Guidelines

While the exercises do build upon each other, they are meant to be self-contained. The student will be working with .cpp files to complete each exercise. Comments are located throughout the code to guide the student. Comments are highlighted by a collection of ascii characters known as "Breakdancin Bob" and take the following form:

//-----------------------------------------------------------------
// o/__   <-- BreakdancinBob TODO: Todos are areas where you need
//  |  (\ 		to change or implement code.  This is where
//			the actual exercise work will happen.
//-----------------------------------------------------------------

//-----------------------------------------------------------------
// o/__   <-- BreakdancinBob NOTE:  Notes are code snippets of
//  |  (\		interest.  No work needs to be done.  Just
//			look.
//-----------------------------------------------------------------

//-----------------------------------------------------------------
// o/__   <-- BreakdancinBob HINT:  Hints may be found near Todo
//  |  (\		comments.  Hints can help you if you are
//			stuck with the exercise.
//-----------------------------------------------------------------

Solutions to the exercises are found in the folders with _Solved appended to the end.

Exercise01 - CPU Bound in Application Code

At the beginning of Exercise01, the application is severely CPU bound. Regardless of what is being drawn, the frame-rate remains constant. Using a CPU profiler the student must determine where the bottleneck occurs and fix it.

Exercise02 - CPU Bound in the Driver

At the beginning of Exercise02, the application is again CPU bound, but this time in the driver. Using PIX for Windows, the user should be able to see that the number of draw calls remains constant regardless of the view. The student must find the place in code where culling isn't working and fix it. After this point, the user can again use PIX for Windows to determine that the number of draw calls now changes with the view. There should also be a correlation between draw calls and frame rate.

Exercise03 - GPU Bound

Exercise03 picks up where Exercise02 left off. The application is now GPU bound. The bottleneck seems to be in the grass rendering code. The user can verify this by disabling the rendering of grass and noticing the resulting framerate increase. PIX for Windows can be used to take a single-frame capture of a representative scene and use pixel debugging to determine the cost of drawing certain pixels on the screen. By viewing pixels on far-off mountain features, the user can determine grass rendering is, indeed the culprit as it's being draw in the distance where is has no visual impact on the scene.


Samples

These samples demonstrate the newest techniques incorporated into Direct3D 10:

BasicHLSL10 Sample
ContentStreaming Sample
CubeMapGS Sample
DDSWithoutD3DX Sample
DisplacementMapping10 Sample
Draw Predicated Sample
Effect Pools Sample
EmptyProject10 Sample
FixedFuncEMU Sample
GPUSpectrogram Sample
HDRFormats10 Sample
HLSLWithoutFX10 Sample
Instancing10 Sample
MotionBlur10 Sample
MultiMon10 Sample
MultiStreamRendering Sample
ParticlesGS Sample
PipesGS Sample
ShadowVolume10 Sample
SimpleSample10 Sample
Skinning10 Sample
SoftParticles Sample
SparseMorphTargets Sample


BasicHLSL10 Sample

Path

Source: | (SDK root)\Samples\C++\Direct3D10\BasicHLSL10
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\BasicHLSL10.exe

Sample Overview

This sample simply loads a mesh, creates an effect from a file, and then uses the effect to render the mesh. The effect that is used is a simple vertex shader that animates the vertices based on time. It uses DXUT to switch between Direct3D 9 and Direct3D 10 codepaths. Only the Direct3D 10 codepath will be described here. The Direct3D 9 codepath is similar and can be found in the Direct3D 9 documentation.

How the Sample Works

First the sample calls D3DX10CreateEffectFromFile to create an effect from the supplied FX file.

Secondly, the sample loads the effect techniques and effect variables from the FX file and stores them for later use.

Third, the sample creates an input layout that matches the input layout of the mesh that will be loaded. This will be the same for all meshes loaded through CDXUTMesh10. After this the sample loads the geometry using the CDXUTMesh10 class. Internally this calls OptimizeInplace() to optimize the mesh for the vertex cache, then loads the textures using D3DX10CreateTextureFromFile.

In OnD3D10FrameRender, sets variables used by the technique such as the World*View*Projection matrix and the time variable with various ID3DX10Effect::Set* calls. Then the sample sets the current input layout to be used by the device using ID3D10Device::IASetInputLayout. Next, the number of passes in the selected rendering technique are determined by calling ID3D10Technique::GetDesc. For each pass contained within the technique, the pass is applied to the device with ID3D10EffectPass::Apply and the mesh is rendered.


CubeMapGS Sample

The CubeMapGS sample demonstrates rendering a cubic texture render target with a single DrawIndexed() call using two new features in Direct3D 10: render target array and geometry shader. A render target array allows multiple render target and depth stencil textures to be active simultaneously. By using an array of six render targets, one for each face of the cube texture, all six faces of the cube can be rendered together. When the geometry shader emits a triangle, it can control which render target in the array the triangle gets rasterized on. For every triangle that gets passed to the geometry shader, six triangles are generated in the shader and output to the pixel shader, one triangle for each render target.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\CubeMapGS
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\CubeMapGS.exe

Sample Overview

Environment mapping is a popular and well-supported technique in 3D graphics. Traditionally, dynamic cubic environment maps are created by obtaining a surface for each face of a cube texture and setting that surface as the render target to render the scene once for each face of the cube. The cube texture can then be used to render environment-mapped objects. This method, while it works, increases the number of rendering passes from one to seven, greatly reducing the application frame rate. In Direct3D 10, applications can use geometry shaders and render target arrays to alleviate this problem.

How the Sample Works

A geometry shader in Direct3D 10 is a piece of code that runs for each primitive to be rendered. In each invocation, the geometry shader can output zero or more primitives to be rasterized and processed in the pixel shader. For each output primitive, the geometry shader can also control to which element slice of the render target array the primitive gets emitted.

The render target array in Direct3D 10 is a feature that enables an application to render onto multiple render targets simultaneously at the primitive level. The application uses a geometry shader to output a primitive and select which render target in the array should receive the primitive. This sample uses a render target array of 6 elements for the 6 faces of the cube texture. The following code fragment creates the render target view used for rendering to the cube texture.

// Create the 6-face render target view
D3D10_RENDER_TARGET_VIEW_DESC DescRT;
DescRT.Format = dstex.Format;
DescRT.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2DARRAY;
DescRT.Texture2DArray.FirstArraySlice = 0;
DescRT.Texture2DArray.ArraySize = 6;
DescRT.Texture2DArray.MipSlice = 0;
pd3dDevice->CreateRenderTargetView( g_pEnvMap, &DescRT, &g_pEnvMapRTV );

By setting DescRT.TextureCube.FirstArraySlice to 0 and DescRT.TextureCube.ArraySize to 6, this render target view represents an array of 6 render targets, one for each face of the cube texture. When the sample renders onto the cube map, it sets this render target view as the active view by calling ID3D10Device::OMSetRenderTargets() so that all 6 faces of the texture can be rendered at the same time.

// Set the env map render target and depth stencil buffer
ID3D10RenderTargetView* aRTViews[ 1 ] = { g_apEnvMapOneRTV[view] };
pd3dDevice->OMSetRenderTargets( sizeof(aRTViews) / sizeof(aRTViews[0]),
    aRTViews, g_pEnvMapOneDSV );

Rendering the CubeMap

At the top level, rendering begins in Render(), which calls RenderSceneIntoCubeMap() and RenderScene(), in that order. RenderScene() takes a view matrix a projection matrix, then renders the scene onto the current render target. RenderSceneIntoCubeMap() handles rendering of the scene onto a cube texture. This texture is then used in RenderScene() to render the environment-mapped object.

In RenderSceneIntoCubeMap(), the first necessary task is to compute the 6 view matrices for rendering to the 6 faces of the cube texture. The matrices have the eye point at the camera position and the viewing directions along the -X, +X, -Y, +Y, -Z, and +Z directions. A boolean flag, m_bUseRenderTargetArray, indicates the technique to use for rendering the cube map. If false, a for loop iterates through the faces of the cube map and renders the scene by calling RenderScene() once for each cube map face. No geometry shader is used for rendering. This technique is essentially the legacy method used in Direct3D 9 and prior. If m_bUseRenderTargetArray is true, the cube map is rendered with the RenderCubeMap effect technique. This technique uses a geometry shader to output each primitive to all 6 render targets. Therefore, only one call to RenderScene() is required to draw all 6 faces of the cube map.

The vertex shader that is used for rendering onto the cube texture is VS_CubeMap, as shown below. This shader does minimal work of transforming vertex positions from object space to world space. The world space position will be needed in the geometry shader.

struct VS_OUTPUT_CUBEMAP
{
    float4 Pos : SV_POSITION;    // World position
    float2 Tex : TEXCOORD0;      // Texture coord
};
VS_OUTPUT_CUBEMAP VS_CubeMap( float4 Pos : POSITION, float3 Normal : NORMAL, float2 Tex : TEXCOORD )
{
    VS_OUTPUT_CUBEMAP o = (VS_OUTPUT_CUBEMAP)0.0f;

    // Compute world position
    o.Pos = mul( Pos, mWorld );

    // Propagate tex coord
    o.Tex = Tex;

    return o;
}

One of the two geometry shaders in this sample, GS_CubeMap, is shown below. This shader is run once per primitive that VS_CubeMap has processed. The vertex format that the geometry shader outputs is GS_OUTPUT_CUBEMAP. The RTIndex field of this struct has a special semantic: SV_RenderTargetArrayIndex. This semantic enables the field RTIndex to control the render target to which the primitive is emitted. Note that only the leading vertex of a primitive can specify a render target array index. For all other vertices of the same primitive, RTIndex is ignored and the value from the leading vertex is used. As an example, if the geometry shader constructs and emits 3 vertices with RTIndex equal to 2, then this primitive goes to element 2 in the render target array.

At the top level, the shader consists of a for loop that loops 6 times, once for each cube face. Inside the loop, another loop runs 3 times per cube map to construct and emit three vertices for the triangle primitive. The RTIndex field is set to f, the outer loop control variable. This ensures that in each iteration of the outer loop, the primitive is emitted to a distinct render target in the array. Another task that must be done before emitting a vertex is to compute the Pos field of the output vertex struct. The semantic of Pos is SV_POSITION, which represents the projected coordinates of the vertex that the rasterizer needs to properly rasterize the triangle. Because the vertex shader outputs position in world space, the geometry shader needs to transform that by the view and projection matrices. In the loop, the view matrix used to transform the vertices is g_mViewCM[f]. This array of matrix is filled by the sample and contains the view matrices for rendering the 6 cube map faces from the environment-mapped object's perspective. Thus, each iteration uses a different view transformation matrix and emits vertices to a different render target. This renders one triangle onto 6 render target textures in a single pass, without calling DrawIndexed() multiple times.

struct GS_OUTPUT_CUBEMAP
{
    float4 Pos : SV_POSITION;     // Projection coord
    float2 Tex : TEXCOORD0;       // Texture coord
    uint RTIndex : SV_RenderTargetArrayIndex;
};

[maxvertexcount(18)]
void GS_CubeMap( triangle VS_OUTPUT_CUBEMAP In[3], inout TriangleStream<GS_OUTPUT_CUBEMAP> CubeMapStream )
{
    for( int f = 0; f < 6; ++f )
    {
        // Compute screen coordinates
        GS_OUTPUT_CUBEMAP Out;
        Out.RTIndex = f;
        for( int v = 0; v < 3; v++ )
        {
            Out.Pos = mul( In[v].Pos, g_mViewCM[f] );
            Out.Pos = mul( Out.Pos, mProj );
            Out.Tex = In[v].Tex;
            CubeMapStream.Append( Out );
        }
        CubeMapStream.RestartStrip();
    }
}

The pixel shader, PS_CubeMap, is rather straight-forward. It fetches the diffuse texture and applies it to the mesh. Because the lighting is baked into this texture, no lighting is performed in the pixel shader.

Rendering the Reflective Object

Three techniques are used to render the reflective object in the center of the scene. All three fetch texels from the cubemap just as they would from a cubemap that wasn't rendered in a single pass. In short, this technique is orthogonal to the way in which the resulting cubemap is used. The three techniques differ mainly in how they use the cubemap texels. RenderEnvMappedScene uses an approximated fresnel reflection function to blend the colors of the car paint with reflection from the cubemap. RenderEnvMappedScene_NoTexture does the same, but without the paint material. RenderEnvMappedGlass adds transparency to RenderEnvMappedScene_NoTexture.

Higher Order Normal Interpolation

Traditional normal interpolation has been linear. This means that the normals calculated in the vertex shader are linearly interpolated across the face of the triangle. This causes the reflections in the car to appear to slide when the direction of the normal changes rapidly across the face of a polygon. To mitigate this, this sample uses a quadratic normal interpolation. In this case, 3 extra normals are calculated in the geometry shader. These normals are placed in the center of each triangle edge and are the average of the two normals at the vertices that make up the edge. In addition, the geometry shader calculates a barycentric coordinate for each vertex that is passed down to the pixel shader and used to interpolate between the six normals.

In the pixel shader, these 6 normals weighted by six basis functions and added together to create the normal for that particular pixel. The basis functions are as follows.

2x^2 + 2y^2 + 4xy -3x -3y + 1
-4x^2 -4xy + 4x
2x^2 - x
-4y^2 -4xy + 4y
2y^2 - y
4xy


ContentStreaming Sample

The ContentStreaming sample demonstrates streaming content in the background for applications that need to display more data than can fit in video or system ram at any given time.

Path

Source: | SDK root\Samples\C++\Direct3D10\ContentStreaming
Executable: | SDK root\Samples\C++\Direct3D10\Bin\platform\ContentStreaming.exe

Sample Overview

With games growing more complex and gamers demanding more expansive worlds, more content, and just more game in general, the ability to render a large and seamless world while staying within fixed memory limits has become essential. When game-level resources do not fit into GPU memory or game data does not fit into system memory, one solution is to reduce the size of these assets. However, this is not always the best solution. Sometimes, we want high-quality and high-quantity. The ContentStreaming sample attempts to show how best to load only the assets that are visible or will be visible in the near future, while having the main render thread stall a little a possible.

Before we get into the details of loading data, we need to discuss some underlying concepts that are used by the various streaming methods. These concepts are the resource reuse cache, memory-mapped I/O, and placeholder meshes. After these are explained, we can then move onto the various methods of streaming data in on-demand.

Resource Reuse Cache

In order to limit the number of GPU resources created by the application while loading in new data, the sample uses a resource reuse cache. The resource reuse cache allocates a fixed number of GPU resources up front using a profile of the application created ahead of time. For example, an applictaion may need on average ten 1024×1024 DXT1/BC1 textures, five 1024×1024 DXT5/BC3 textures, two 2048×2048 L8 textures, and thirty-two 512×512 DXT1 textures. A profile can be created that the resource reuse cache loads at startup to create a pool of these resources (ten 1024×1024 DXT1/BC1 textures, and so on).

When the application needs to load a resource, it simply looks for a compatible resource in the cache that isn't currently in use and uses that instead. If no resources of the appropriate type can be found, the application can do one of two things: It can either attempt to create a new resource of that type and add it to the resource cache, or it can wait to load the resource until a compatible resource frees up. This latter possibility is an option that can be toggled in the sample by selecting or clearing the Limit Resource Count box. By limiting the resource count you force the application to never attempt to create a new texture if one isn't found in the resource cache. The advantages of this approach are that it keeps the render thread from stalling while trying to create a new texture, and that the application can keep its memory use to a known value. The main disadvantage is that temporary objects or textures may be visible in the game until free resource can be found.

Memory-Mapped I/O

Memory-mapped I/O differs from conventional I/O in that ReadFile is never called to move data into memory. Instead, the file is mapped into the virtual address space of the application and paged in as needed. To use memory-mapped I/O, you open a file as your normally would, using CreateFile. Instead of reading data from this file directly, you then call CreateFileMapping on the file handle. This function creates a file mapping object, but it does not map any data on the disk into the virtual address space of the application. In order to to this, the application needs to call MapViewOfFile. MapViewOfFile returns an actual pointer to the virtual address that represents the start of the file.

There are some caveats with using memory-mapped I/O. The first is that the appliction can run out of virtual address space by specifying ranges that are too large when calling MapViewOfFile. For example, take the following scenario. An application has a 4-GB packed file containing all of its assets. The application then tries to map the entire contents of this file to its virtual address space using MapViewOfFile and passing in 4 GB as the number of bytes to map. A 32-bit application would fail, as Windows cannot find enough virtual address space to handle a mapping this large. However, a 64-bit application would not have this problem.

To combat the lack of address space on 32-bit platforms, the application should use multiple file mappings when accessing large files. For example, the 4-GB file could be mapped with a sliding window that only maps 500 MB at a time. When the player moves on to the next area, the file mapping would slide that area in the packed file. Multiple file mappings can be used within the same file, but care must be taken to ensure that the mappings do not eat up all of the virtual address space. The sample uses multiple mappings based upon the chunk size of the file. A LRU scheme is used to determine which chunk to unmap when a new chunk needs to be mapped.

Another caveat is that MapViewOfFile can only map data aligned on the memory allocation granularity boundaries. On most systems this is 64 k. This has many implications when packing data into a packed file. For a 4-GB packed file with all files tightly packed together, mapping a 500-MB chunk may not work if the start of that chunk isn't on a 64-k boundary. To combat this, the packed file used in this sample creates predefined areas to be mapped called chunks. Each chunk contains a grouping of resource files. The chunks are located on 64-k boundaries so that they can be easily mapped using MapViewOfFile.

Packed Files

To ensure easy installation, consistent disk access, and compression, games will often pack resources into a single packed file. The nature of the packed file changes depending on the game. For this sample, we forego compression, and create a simple packed file consisting mainly of assets in the media folder. The packed file is created the first time the sample is run. It is stored in a User Account Control friendly per-user directory. In this case, it is stored in CSIDL_LOCAL_APPDATA + "\ContentStreaming". The packed file contains an index which gives the locations and sizes of all of the files in the pack. Following the index, the resources files are packed together into chunks. The chunk size is set to ensure that the application does not run out of virtual address space when using memory-mapped I/O. As noted above, these chunks must be 64-k aligned in order to be mapped with MapViewOfFile.

At runtime, the index of the packed file is loaded into memory using ReadFile. This is done regardless of whether we're using memory-mapped I/O. When retrieving a packed file, the CPackedFile class first consults the index to see if the file is resident in the packed file. It it is, the CPackedFile class either uses ReadFile to fill the supplied buffer with the file data, in the case of normal I/O, or returns a memory-mapped pointer, in the case of memory-mapped I/O.

Placeholder Meshes

Because the sample is streaming in data as needed, there may be times when the data that needs to rendered isn't available yet. In this case, the sample employs the use of a placeholder mesh. The placeholder mesh is guaranteed to be loaded, and it is drawn in place of the real object in the event that the object hasn't fully loaded. In most applications the placeholder mesh should be inconspicuous and might even closely match the object it's filling in for. However, in this sample, the placeholder mesh is a box with a bright red and white checkerboard pattern that has the word "Loading" printed on it.

On-Demand Single-Threaded Loading

Single-threaded loading is basically serial loading. When the resource is needed, the application immediately tries to load that resource. No other processing can be done while the resource is loading. To make this type of loading as efficient and painless as possible, the application uses the resource reuse cache. The resource reuse cache allows the application to lock and fill an existing resource instead of creating a new resource from scratch. Locking and filling an existing resource is less costly than creating an entirely new resource.

On-Demand Multi-Threaded Loading

Although the resource reuse cache does improve the performance of on-demand single threaded loading, there will still be hiccups in rendering as the application pauses to load the data from disk (or read from memory-mapped I/O) and do the actual copy to the device object. A more optimal solution would cause the rendering thread to pause as little as possible. On Direct3D 9, it is possible to only have the rendering thread stop for two things: locking a resource and unlocking a resource. On Direct3D 10, we can ensure that the graphics thread only has to pause for one thing, calling UpdateSubresource on an object. The acts of loading the resource from disk and copying data to the device objects can be done in separate threads.

Three types of threads come into play. The first is the render thread. The render thread's main job is to draw the scene without stalling. Lesser jobs of the rendering thread include sending I/O requests to the I/O thread by way of the request queue, and handling lock/unlock requests from the I/O thread. To keep the render thread from stalling, both of these lesser jobs are handled when it is convenient for the render thread.

The second type of thread is the I/O thread. The I/O thread handles requests from the render thread. It also either loads files from the packed file or gets memory-mapped pointers to them. The I/O thread handles communications with the various process threads and also places lock/unlock requests into the lock/unlock queue for consumption by the render thread. In addition, on Direct3D 9, the I/O thread does the actual copying of bits into the device object. There is generally one I/O thread for each storage device that will be used on the system. Because the I/O thread may potentially spend a lot of time waiting for I/O requests to come back from various storage devices, it may be acceptible to put this thread to share a hardware thread with one of the process threads.

The last type of thread is the process thread. Process threads handle the dirty work of processing the data after it has been loaded from disk by the I/O thread. Process threads can decompress data, prefetch data when using memory-mapped I/O, or handle other operations such as swizzling that may need to be performed on the data before it is copied into the device object. There should generally be one process thread per available hardware thread.

The following diagram illustrates all of the threads used in multi-threaded loading.

Figure 1. Threads in Multi-Threaded Loading

The typical chain of events is as follows:

  1. The I/O thread and the process threads are sleeping, waiting for something to do. The graphics thread is rendering away.

  2. The graphics thread determines that a resource is going to be visible sometime in the near future. It places a resource request on the request queue.

  3. The I/O thread picks this request up and loads the data from the packed file. If using memory-mapped I/O, a memory-mapped pointer is returned.

  4. The I/O thread then sends a process request to one of the waiting process threads. The processing thread performs some computation on the data. If using memory-mapped I/O, and pre-fetching data is enabled, the process thread will touch 1 byte in every 4 k of the data being processed, to ensure that the resource is fully paged into memory before being used.

  5. When the process thread is done processing, it puts a lock request into the lock/unlock queue.

  6. When the render thread feels like it, it picks up the lock request, finds an available resource from the resource reuse cache, and locks the resource.

  7. The render thread then sends the request back to the I/O thread. On Direct3D 9, the I/O thread copies the data into the device object.

  8. Then the I/O thread puts an unlock request in the lock/unlock queue.

  9. When the render thread feels like it, it picks up the unlock request and unlocks the resource. The resource is now ready to use.

Load Everything

This final method of loading is only available on Direct3D 10. The "load everything" method does just that — it loads all resources that could possibly be needed up front. It then lets the driver take over which resources need to be put into video memory or taken out. This is all possible because the driver model in Windows Vista implements a type of virtual memory for GPU resources. System memory becomes a backing store for GPU resource, and resources are loaded into and out of video memory from system memory based upon demand.


DDSWithoutD3DX Sample

This sample demonstrates loading a DDS file into a texture without using D3DX helper functions. This is useful for applications that do not want to take a dependency on D3DX.

Path

Source: | SDK root\Samples\C++\Direct3D10\DDSWithoutD3DX
Executable: | SDK root\Samples\C++\Direct3D10\Bin\platform\DDSWithoutD3DX.exe

How the Sample Works

The interesting code for this sample is in DDSTextureLoader.cpp. There are two overloaded CreateDDSTextureFromFile functions, one for Direct3D 9 and one for Direct3D 10. Each of these loads the DDS data from disk and then creates a texture specific to the Direct3D version being used.

Loading the DDS File

The LoadTextureDataFromFile function loads a DDS from disk into specific DDS structures in memory. The DDS file is split into 3 major parts. First there is the magic number that identifies the file as a DDS file. Second is a DDSURFACEDESC2 structure. Finally, there is the actual image data stored in the format specified by the DDSURFACEDESC2 structure.

    // DDS files always start with the same magic number
    DWORD dwMagicNumber = *(DWORD*)(*ppHeapData);
    if( dwMagicNumber != 0x20534444 )
        return FALSE;

    // setup the pointers in the process request
    *ppSurfDesc = (DDSURFACEDESC2_32BIT*)( *ppHeapData + sizeof(DWORD) );
    *ppBitData  = *ppHeapData + sizeof(DWORD) + sizeof(DDSURFACEDESC2_32BIT);
    *pBitSize   = FileSize.LowPart - sizeof(DWORD) - sizeof(DDSURFACEDESC2_32BIT);

Note that the sample does not use the DDSURFACEDESC2 structure but its own internal DDSURFACEDESC2_32BIT structure. This is because the DDSURFACEDESC2 structure contains a pointer and is different sizes on 32-bit and 64-bit systems. Since DDS files are all stored assuming that the pointer is 32 bits wide, the sample uses a structure with a 32-bit-sized pointer regardless of the native system pointer size. Because the application does not use this pointer, this is a safe operation.

Creating a Direct3D 9 Texture

Once we have loaded the data from disk, the sample uses this data to create a device texture. In Direct3D 9 version of CreateTextureFromDDS, the sample gets the Direct3D 9 specific texture format from the ddpfPixelFormat member of the DDSURFACEDESC2 structure. The GetD3D9Format helper function contains conversions for some of the more common texture formats.

With the format and height, width, and mipmap information from the DDSURFACEDESC, the sample creates two Direct3D 9 texture. One is a staging texture, and one is the texture that will actually be used. Since a standard DEFAULT_POOL texture cannot be locked, a staging texture must be used in order to get the data into the DEFAULT_POOL texture. Each mipmap of staging texture is filled, and then the entire staging texture is copied to the DEFAULT_POOL texture using UpdateTexture.

Creating a Direct3D 10 Texture

Creating a Direct3D 10 texture is similar to create a Direct3D 9 texture. GetD3D9Format is used to create a D3DFMT from the ddpfPixelFormat member of the DDSURFACEDESC2 structure. Then ConvertToDXGI_FORMAT converts the D3DFMT to the nearest compatible DXGI_FORMAT. Some Direct3D 9 formats may not be compatible with Direct3D 10. Formats such as D3DFMT_X8R8G8B8 and D3DFMT_A8R8G8B8 will have to be converted to DXGI_FORMAT_R8G8B8A8_UNORM, which requires that some of the components be rearranged.

    // swizzle if it's a format that may not be completely compatible with D3D10
    if( D3DFMT_X8R8G8B8 == fmt ||
        D3DFMT_A8R8G8B8 == fmt )
    {
        for( UINT i=0; i<BitSize; i+=4 )
        {
            BYTE a = pBitData[i];
            pBitData[i] = pBitData[i+2];
            pBitData[i+2] = a;
        }
    }

When creating a Direct3D 10 texture, the sample does not need to create a staging texture. Instead a D3D10_SUBRESOURCE_DATA structure is created for each mipmap in the texture. The pSysMem member of the structure is set to the start of the the data for that mipmap, and the SysMemPitch member is set to the stride in bytes of that mipmap's data. When creating the texture, the array of D3D10_SUBRESOURCE_DATA structures is passed in as the second parameter, and the texture is automatically initialized with this data. The function then creates the resource view necessary to use the texture in a shader.


DisplacementMapping10 Sample

This sample implements displacement mapping by ray tracing through geometry extruded from a base mesh. The sample uses Direct3D 10 and the geometry shader to extrude prisms which are then decomposed into three tetrahedra for each triangle in the mesh. The pixel shader ray traces through the tetrahedra to intersect the displacement map. The diffuse color and normal values are then calculated for this point and used to set the final color of the pixel on screen. This sample is an adaptation of a paper from Microsoft Research Asia ( Wang, Xi, Xin Tong, Stephen Lin, Shimin Hu, Baining Guo, and Heung-Yeung Shum. 2004. Generalized Displacement Maps. In Eurographics Symposium on Rendering 2004, pp. 227-234. )

Path

Source: | (SDK root)\Samples\C++\Direct3D10\DisplacementMapping10
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\DisplacementMapping10.exe

Sample Overview

There have been many approaches to displacement mapping in recent history. Many rely on tessellating the geometry to a high level of detail and then displacing this geometry based upon a height value stored in a height map. DisplacementMapping10 uses a different approach. Instead of producing detail by displacing highly tessellated geometry, the sample creates three tetrahedra for every input triangle and uses a per-pixel ray tracing approach to evaluate the geometry.

Extruding Geometry

For every triangle on the mesh, a triangular prism is extruded. The prism is constructed by extruding the vertices of the triangle along the directions of their normals by an amount specified to be the maximum displacement. The XY texture coordinates at the top of the prism remain the same as the bottom; however, the Z coordinate becomes 1 to represent the maximum displacement. A naive approach would be to ray trace through this extruded prism by finding the texture coordinates where the eye ray enters and exits the prism. By taking an evenly spaced sampling of a height map texture between the entry and exit points, one could easily determine where the ray intersects the height map.

Unfortunately, there are two problems with this approach.

Problem 1

Because of varying curvature in the mesh, the four points that make up each side of the prism are not guaranteed to be coplanar. When extruding the prism, each side will be split into two triangles. Any neighboring face will also share this edge as an edge of its extruded prism. If the neighboring triangle does not create the sides of its prism in a way that correlates to how the current triangle creates the same edge, cracks may appear in the final rendering.

Problem 2

It's very difficult to calculate the exit texture coordinate for an eye ray traveling through a triangular prism. The entry point, on the other hand is easy. Because of depth-buffering, the nearest triangle to the eye will always be drawn. The graphics hardware will automatically interpolate the entry texture coordinate across the draw faces. The rear exit point is a different story. One could do ray-plane intersections to get the distance to the rear of the prism. This is a good start, but still doesn't give us the texture coordinates. Calculating barycentrics for a triangle are costly in the shader. One could pass down an un-normalized tangent basis frame (TBN matrix) and transform the view vector into this frame, add it to the input texture coordinate, and achieve the exit texture coordinate. Unfortunately, this breaks down when the mesh deforms since under high deformation, the un-normalized tangent frame is non-constant across the prism.

Using Tetrahedra

The two problems above can be solve by decomposing the the prism into three tetrahedra and by using the VertexID generated by the input assembler to order the vertices when creating the tetrahedra.

The distance to the rear of a tetrahedron is computed by intersecting the eye ray with the planes of the tetrahedron facing away from the eye and choosing the smallest distance. Now, the only problem left is to determine the texture coordinates at the exit point.

A nice property of a tetrahedron is that by using the texture coordinates of the 4 points, a constant texture gradient can be found across the tetrahedron. By using this gradient, the entry texture coordinate (computed easily during rasterization), and the distance to the rear of the tetrahedron, the shader can compute the exit texture coordinates.

Intersecting the Displacement Map

Once the entry and exit texture coordinates are known, it's only a matter of stepping from one to the other. While stepping along the ray from the entry to the exit coordinates, the XY components are used to lookup into the displacement map. The Z component represents the height from the base triangle. This is compared against the height value returned by the lookup into the displacement map. If the Z component of the ray is less than the height returned by the displacement map, the sample assumes that an intersection has taken place and stop searching. If no intersection is found before reaching the exit texture coordinate, the pixel is discarded.

Once the intersection point is found, all that is left is to determine the color and normal at the point of intersection. Again, if no intersection point is found, the pixel is simply discarded. The diffuse color at the intersection point can be found by sampling the diffuse texture at the XY coordinates of the ray where the ray intersected the displacement map. While the displacement map provides enough information to determine the normal at the point of intersection (using finite differencing), this sample encodes a normal map as the rgb components of the displacement texture (displacement is stored in alpha). Thus, the last sample along the entry/exit ray contains the normal for the point of intersection.

Problems

One problem with this technique is also a problem with most displacement mapping techniques. In areas of high concave curvature, the extruded prism can actually fold in on itself and flip. This causes the tetrahedra and resulting ray trace to be incorrect. The solution that the sample employs is to detect these cases and reduce the amount of displacement for the offending triangle.

Another problem with this technique is sampling artifacts. If the number of steps per ray is too small, some high-frequency details can be missed. For very low sampling rates, this can cause details to pop in and out as the camera or object moves. Although geometry based displacement mapping also has frequency issues, the connectivity between the triangles ensure that there is always a smooth transition between different height values. Furthemore, geometry based methods are not dependent on the orientation of the view ray, so no popping of detail occurs when the object or camera moves.

Comparison with Normal Mapping

In this section, we compare normal mapping with displacement mapping.

Notice the lack of self-occlusion or definition on the silhouette of the object.


Draw Predicated Sample

This sample uses the occlusion predicate query to avoid drawing unnecessary geometry.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\DrawPredicated
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\DrawPredicated.exe

How the Sample Works

The scene contains four meshes, the center columne mesh, the microscope mesh, the city mesh, and the microscope occlusion mesh. The microscope mesh is a high resolution mesh that comprises the focus of the scene. Because of the large number of vertices, this mesh is costly to draw especially when duplicated 6 times throughout the scene. The microscope occlusion mesh is a much lower resolution mesh that is used as an approximation of the microscope. For games, this could be a mesh created specifically for occlusion purposes or a collision mesh. When the camera traverses the scene, the city mesh occludes the microscope mesh. Traditionally, the vertex processing cost of the 6 microscope meshes would still be present even when the meshes are completely occluded by the city mesh.

The DrawPredicated sample removes the vertex processing cost by using the D3D10_QUERY_OCCLUSION_PREDICATEquery type in Direct3D 10. This query allows a drawing operation to succeed or fail based upon whether pixels from a previous draw operation were visible. Because the predicate query is created with D3D10_QUERY_MISC_PREDICATEHINT, the result of the query can be used to draw or not draw geometry without waiting for the result to be transferred from the GPU to the CPU.

Creating the Query

//
// Create 6 occlusion predicate queries
//
ID3D10Predicate		* g_pPredicate;
...
D3D10_QUERY_DESC qdesc;
qdesc.MiscFlags = D3D10_QUERY_MISC_PREDICATEHINT;
qdesc.Query = D3D10_QUERY_OCCLUSION_PREDICATE;
for( int i=0; i<NUM_MICROSCOPE_INSTANCES; i++ )
{
    V_RETURN(pd3dDevice->CreatePredicate( &qdesc, &g_pPredicate[i] ));
}

Issuing the Query

// Render the occluder mesh
g_pPredicate[i]->Begin();
g_OccluderMesh.Render( pd3dDevice, g_pRenderOccluder );
g_pPredicate[i]->End();

Drawing based upon the results

//
// Render the vertex heavy meshes
//

// Render the vertex heavy mesh (but only if the predicate passed)
pd3dDevice->SetPredication( g_pPredicate[i], FALSE );
...
g_HeavyMesh.Render( pd3dDevice, g_pRenderTextured, g_pDiffuseTex );
...
pd3dDevice->SetPredication( NULL, FALSE );

Limitations

Predicate hints are non-stalling and are therefore not guaranteed. Because the hardware may not have finished drawing the occluding mesh before the result of the predicate is needed, the vertex-laden meshes may draw even though the occluder mesh is completely hidden. In anticipation of this, application should be careful that the depth and stencil buffers contain the correct information regardless of whether the rendering occurs. In the case of occlusion culling, this integrity is maintained. To ensure that the results of the predicate hints are useful, the application should ensure that enough drawing takes place between the issue of the query and the use of the query to ensure synchronization.

Another limitation is only drawing and execution APIs honor predication; state-setting APIs do not. Commands that honor predication are as follows:

  • Draw
  • DrawIndexed
  • DrawInstanced
  • DrawIndexedInstanced
  • ClearRenderTargetView
  • ClearDepthStencilView
  • CopySubresourceRegion
  • CopyResource
  • UpdateSubresource

Commands that do not honor predication include:

  • IASetPrimitiveTopology
  • IASetInputLayout
  • IASetVertexBuffers
  • IASetIndexBuffer
  • Present
  • Map/Unmap
  • Any Create calls


Effect Pools Sample

This sample demonstrates the use of effect pools on Direct3D 9 and Direct3D 10.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\EffectPools
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\EffectPools.exe

How the Sample Works

One of the downsides to using multiple effects in a single application is that many effect variables need to be set for each effect. It is often the case that many of these variables are common between effects. Without a method for sharing variables or shaders between effects, many rendundant set calls will need to be made setting data that is exactly the same for each effect. Effect pools are meant to solve this problem. Effect pools allow different effects to share variables, textures, and shaders between them. This means that for common variables, the data needs to be set only once per frame, rather than once per effect invocation. An effect pool effectively consists of two parts. There is the effect pool itself, and the effects that are part of the pool. These effects that are part of the same pool are call child effects.

This sample uses 3 effect files to render 3 spheres. The effect files share light direction (g_LightDir), light diffuse color (g_LightDiffuse), the viewproj matrix (g_mViewProj), and texture uv offset (g_TexMove) between them. In addition, they share the same diffuse texture resource, and pixel shader. However, these effect do have their differences, and therefore need their their own vertex shaders as well as world matrices (g_mWorld) and diffuse colors (g_MaterialDiffuseColor). The common variables are defined in an include file, EffectPools.fxh, while the individual child effect files (EffectPools1-3.fx) include EffectPools.fxh, but define their own unique variables and shaders.

Include Files and Shared Variables

The benefit of using effect pools is that you can share data between different effect files. While you can include the same header file in each separate effect, without using effect pools, the variables and shaders are just duplicated between effects. If you change variable A in one effect file, you still need to change the same variable in the other effect file in order for it to have the correct data. Effect pools allow "shared" variables. Shared variables can be used by all effect files in the pool. When you set the value of a shared variable for an effect pool, you don't need to redundantly set the same variable for each effect in the pool. A good example of this is the viewproj matrix. In many cases, the viewproj matrix is constant over an entire frame. However, we may have several hundred effects being used in the scene. Each one needs the viewproj matrix. Without using effect pools, we would have to set this variable once for each effect. However, by using effect pools, we set this variable once, period.

An easy way to use shared variables is to use an include file for your shaders. The include file contains all of the variables and shaders that will be shared by the application effects. These variables and shaders must be marked as "shared" in order for the effect system to know that they are shared variables and can be used by multiple effects in the pool. The shared keyword usage varies a little between Direct3D 9 and Direct3D 10.

On Direct3D 9 each variable needs to be preceeded by the shared keyword. Sampleer cannot be shared on Direct3D 9.

shared float3 g_LightDir;               // Light's direction in world space
shared float4 g_LightDiffuse;           // Light's diffuse color
shared float4x4 g_mViewProj;            // View * Projection matrix
shared float  g_TexMove;                // random variable that offsets the V texcoord

shared texture2D g_txDiffuse;
sampler2D MeshTextureSampler = sampler_state
{
    Texture = (g_txDiffuse);
    MinFilter = Linear;
    MagFilter = Linear;
    AddressU = WRAP;
    AddressV = WRAP;
};

On Direct3D 10 shared constants must be grouped into constant buffers. Only entire constant buffers can be shared. You are not limited to one constant shared constant buffer. In addition, because samplers are separate objects in shader model 4.0, samplers can be shared.

shared cbuffer cbShared
{
float3 g_LightDir;                  // Light's direction in world space
float4 g_LightDiffuse;              // Light's diffuse color
float4x4 g_mViewProj;               // View * Projection matrix
float  g_TexMove;                   // random variable that offsets the V texcoord
};

shared texture2D g_txDiffuse;
shared sampler2D MeshTextureSampler = sampler_state
{
    Texture = (g_txDiffuse);
    MinFilter = Linear;
    MagFilter = Linear;
    AddressU = WRAP;
    AddressV = WRAP;
};

In either Direct3D 9 or Direct3D 10 shaders can be shared by placing the shared keyword in front of the shader declaration.

shared float4 ScenePS( PS_INPUT input ) : COLOR0
{
    ...
}

Child Effects

In order for a child effect to use the shared variables it has to include the header file. Nothing else needs to be done. Variables and shaders are accessed as if they were variables local to the effect.

An include file is not necessary to share variables. Child effects can declare variables as shared inside the effect file. However, care must be taken to ensure that the shared variables names are identical between shaders. It is often easier just to use an include file.

Creating the Effect Pool

The actual creation of the effect pool varies between Direct3D 9 and Direct3D 10. In Direct3D 9, the effect pool is created by the device, but contains no initial information about shared variables. This information is later collected when child effects are added to the effect pool.

    V_RETURN( D3DXCreateEffectPool( &g_pEffectPool ) );

In Direct3D 10, the effect pool can be created from a file. This will likely be the header file used for all of the child effect files.

    V_RETURN( D3DX10CreateEffectPoolFromFile( str,
                                              NULL,
                                              NULL,
                                              "fx_4_0",
                                              D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY,
                                              0,
                                              pd3dDevice,
                                              NULL,
                                              &g_pEffectPool,
                                              NULL,
                                              NULL ) );

Creating the Child Effects

The creation of child effects is similar between both APIs. On Direct3D 9, the effect is compiled normally, but the effect pool is passed in as one of the parameters. This makes the effect a child effect.

    V_RETURN( D3DXCreateEffectFromFile( pd3dDevice,
                                        str,
                                        NULL,
                                        NULL,
                                        dwShaderFlags,
                                        g_pEffectPool,
                                        &g_EffectData[i].pEffect,
                                        NULL ) );

LIkewise, in Direct3D 10, the effect pool is passed in as a parameter. However, the childe must also be compiled with the D3D10_EFFECT_COMPILE_CHILD_EFFECT flag set.

    V_RETURN( D3DX10CreateEffectFromFile( str,
                                          NULL,
                                          NULL,
                                          "fx_4_0",
                                          dwShaderFlags,
                                          D3D10_EFFECT_COMPILE_CHILD_EFFECT,
                                          pd3dDevice,
                                          g_pEffectPool,
                                          NULL,
                                          &g_EffectData[i].pEffect,
                                          NULL,
                                          NULL ) );

Pre-Compiled Effects

Effects pools are not limited to effects that are compiled at runtime. Most applications can gain signification performance improvements by compiling their effects offline. Pre-compiled effects can be loaded as child effects in exactly the same way as text effect files. However, the files must be precompiled as child effects for them to work in effect pools. Precompiled effects can be used as child effects alongside text effects.

The sample uses fxc.exe to precompile EffectPools3.fx in a custom build step and saves the compiled output to EffectPools3.fxo9 or EffectPools3.fxo10 depending on API. This is then loaded in place of EffectPools3.fx at runtime. In order to precompile an effect as a child effect using fxc.exe, the following command line options must be used. On Direct3D 9, the effect needs simply to compiled with /Fo to turn it into a binary output file. On Direct3D 10, to remain analogous to the D3D10_EFFECT_COMPILE_CHILD_EFFECT paradigm of the API, the effect also needs to be compiled with /Gch. This flag compiles the effect as a child effect for fx_4_0 targets.


EmptyProject10 Sample

Path

Source: | (SDK root)\Samples\C++\Direct3D10\EmptyProject10
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\EmptyProject10.exe

Sample Overview

This sample is a bare-bones Direct3D application provided as a convenient starting point for your own project.

How the Sample Works

This sample uses DXUT to initialize and run a basic Direct3D application. Functions are included as stubs with implementation left for the user.


FixedFuncEMU Sample

This sample attempts to emulate certain aspects of the Direct3D 9 fixed function pipeline in a Direct3D 10 environment.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\FixedFuncEMU
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\FixedFuncEMU.exe

How the Sample Works

This sample attempts to emulate the following aspects of the Direct3D 9 fixed-function pipeline:

  • Fixed-function Transformation Pipeline
  • Fixed-function Lighting Pipeline
  • AlphaTest
  • User Clip Planes
  • Pixel Fog
  • Gouraud and Flat shade modes
  • Projected texture lookups (texldp)
  • Multi-Texturing
  • D3DFILL_POINT fillmode
  • Screen space UI rendering

Fixed-function Transformation Pipeline

The Direct3D 9 fixed-function transformation pipeline required 3 matrices to transform the raw points in 3d space into their 2d screen representations. These were the World, View, and Projection matrices. Instead of using SetTransform( D3DTS_WORLD, someMatrix ), we pass the matrices in as effect variables. The shader multiplies the input vertex positions by each of the World, View, and Projection matrices to get the same transformation that would have been produced by the fixed-function pipeline.

//output our final position in clipspace
float4 worldPos = mul( float4( input.pos, 1 ), g_mWorld );
float4 cameraPos = mul( worldPos, g_mView ); //Save cameraPos for fog calculations
output.pos = mul( cameraPos, g_mProj );

Fixed-function Lighting Pipeline

ColorsOutput CalcLighting( float3 worldNormal, float3 worldPos, float3 cameraPos )
{
    ColorsOutput output = (ColorsOutput)0.0;

    for(int i=0; i<8; i++)
    {
        float3 toLight = g_lights[i].Position.xyz - worldPos;
        float lightDist = length( toLight );
        float fAtten = 1.0/dot( g_lights[i].Atten, float4(1,lightDist,lightDist*lightDist,0) );
        float3 lightDir = normalize( toLight );
        float3 halfAngle = normalize( normalize(-cameraPos) + lightDir );

        output.Diffuse += max(0,dot( lightDir, worldNormal ) * g_lights[i].Diffuse * fAtten) + g_lights[i].Ambient;
        output.Specular += max(0,pow( dot( halfAngle, worldNormal ), 64 ) * g_lights[i].Specular * fAtten );
    }

    return output;
}

AlphaTest

Alpha test is perhaps the simplest Direct3D 9 functionality to emulate. It does not require the user to set a alpha blend state. Instead the user can simply choose to discard a pixel based upon its alpha value. The following pixel shader does not draw the pixel if the alpha value is less than 0.5.

//
// PS for rendering with alpha test
//
float4 PSAlphaTestmain(PSSceneIn input) : COLOR0
{
    float4 color =  tex2D( g_samLinear, g_txDiffuse, input.tex ) * input.colorD;
    if( color.a < 0.5 )
        discard;
    return color;
}

User Clip Planes

User Clip Planes are emulated by specifying a clip distance output from the Vertex Shader with the SV_ClipDistance[n] flag, where n is either 0 or 1. Each component can hold up to 4 clip distances in x, y, z, and w giving a total of 8 clip distances.

In this scenario, each clip planes is defined by a plane equation of the form:

Where <A,B,C> is the normal of the plane, and D is the distance of the plane from the origin. Plugging in any point <x,y,z> into this equation gives its distance from the plane. Therefore, all points <x,y,z> that satisfy the equation Ax + By + Cz + D = 0 are on the plane. All points that satisfy Ax + By + Cz + D < 0 are below the plane. All points that satisfy Ax + By + Cz + D > 0 are above the plane.

In the Vertex Shader, each vertex is tested against each plane equation to produce a distance to the clip plane. Each of the three clip distances are stored in the first three components of the output component with the semantic SV_ClipDistance0. These clip distances get interpolated over the triangle during rasterization and clipped if the value every goes below 0.

Pixel Fog

Pixel fog uses a fog factor to determine how much a pixel is obscured by fog. In order to accurately calculate the fog factor, we must have the distance from the eye to the pixel being rendered. In Direct3D 9, this was approximated by using the Z-coordinate of a point that has been transformed by both the World and View matrices. In the vertex shader, this distance is stored in the fogDist member of the PSSceneIn struct for all 3 vertices of a triangle. It is then interpolated across the triangle during rasterization and passed to the pixel shader.

The pixel shader takes this fogDist value and passes it to the CalcFogFactor function which calculates the fog factor based upon the current value of g_fogMode.

//
// Calculates fog factor based upon distance
//
// E is defined as the base of the natural logarithm (2.71828)
float CalcFogFactor( float d )
{
    float fogCoeff = 1.0;

    if( FOGMODE_LINEAR == g_fogMode )
    {
        fogCoeff = (g_fogEnd - d)/(g_fogEnd - g_fogStart);
    }
    else if( FOGMODE_EXP == g_fogMode )
    {
        fogCoeff = 1.0 / pow( E, d*g_fogDensity );
    }
    else if( FOGMODE_EXP2 == g_fogMode )
    {
        fogCoeff = 1.0 / pow( E, d*d*g_fogDensity*g_fogDensity );
    }

    return clamp( fogCoeff, 0, 1 );
}

Finally, the pixel shader uses the fog factor to determine how much of the original color and how much of the fog color to output to the pixel.

return fog * normalColor + (1.0 - fog)*g_fogColor;

Gouraud and Flat shade modes

Gouraud shading involves calculating the color at the vertex of each triangle and interpolating it over the face of the triangle. By default Direct3D 10 uses D3D10_INTERPOLATION_MODE D3D10_INTERPOLATION_LINEAR to interpolate values over the face of a triangle during rasterization. Because of this, we can emulate Gouraud shading by calculating the lighting using Lambertian lighting ( dot( Normal, LightDir ) ) at each vertex and letting Direct3D 10 interpolate these values for us. By the time the color gets to the pixel shader, we simply use it as our lighting value and pass it through. No further work is needed.

Direct3D 10 also provides another way to interpolate data across a triangle, D3D10_INTERPOLATION_CONST. A naive approach would be to use this to calculate the color at the first vertex and allow that color to be spread across the entire face during rasterization. However, there is a problem with using this approach. Consider the case where the same sphere mesh needs to be rendered in both Gouraud and Flat shaded modes. To give the illusion of a faceted mesh being smooth, the normals at the vertices are averages of the normals of the adjacent faces. In short, on a sphere, no vertex will have a normal that is exactly perpendicular to any face it is a part of. For Gouraud shading, this is intentional. This is what allows the sphere to look smooth even though it is comprised of a finite number of polygons. However, for flat shading, this will give ill results as shown by the diagram below.

D3D10_INTERPOLATION_CONST takes the value of the color calculated at the first vertex and spreads it across the entire triangle giving us shading that looks as if the normal was bent compared to the orientation of the triangle. A better method using the geometry shader to calculate the normal is shown below.

The second method gives more accurate results. The following code snippet illustrates how the geometry shader constructs a normal from the input world positions (wPos) of the triangle vertices. The lighting value is then calculated from this normal and spread to all vertices of the triangle.

//
// Calculate the face normal
//
float3 faceEdgeA = input[1].wPos - input[0].wPos;
float3 faceEdgeB = input[2].wPos - input[0].wPos;

//
// Cross product
//
float3 faceNormal = cross(faceEdgeA, faceEdgeB);

Projected Texture Lookups

Projected texturing simply divides the <x,y,z> coordinates of a 4d texture coordinate by the w coordinate before using it in a texture lookup operation. However, without the discussion of projected texturing, it becomes unclear why this functionality is useful.

Projecting a texture onto a surface can be easily illustrated by imagining how a projector works. The projector projects an image onto anything that happens to be in front of the projector. The same effect could be taken care of in the fixed-function pipeline by carefully setting up texture coordinate generation and texture stage states. In Direct3D 10, it is handled in shaders.

To tackle projected texturing, we must think about the problem in reverse. Instead of projecting a texture onto geometry, we simply render the geometry, and for each point, determine where that point would be hit by the projector texture. To do this, we only need to know the position of the point in world space as well as the view and projection matrices of the projector.

By multiplying the world space coordinate by the view and projection matrices of the light, we now have a point that is in the space of the projection of the light. Unfortunately, because we are converting this to texture coordinates, we would really like this point in some sort of [0..1] range. This is where the w coordinate comes into play. After the projection into the projector space, the w coordinate can be thought of as how much this vertex was scaled from a [-1..1] range to get to its current position. To get back to this [-1..1] range, we simply divide by the w coordinate. However, the projected texture is in the [0..1] range, so we must bias the result by halving it and adding 0.5.

//calculate the projected texture coordinate for the current world position
float4 cookieCoord = mul( float4(input.wPos,1), g_mLightViewProj );

//since we don't have texldp, we must perform the w divide ourselves befor the texture lookup
cookieCoord.xy = 0.5 * cookieCoord.xy / cookieCoord.w + float2( 0.5, 0.5 );

Multi-Texturing

The texture stages from the fixed-function pipeline are officially gone. In there place is the ability to load textures arbitrarily in the pixel shader and to combine them in any way that the math operations of the language allow. The FixedFuncEMU sample emulates the D3DTOP_ADD texture blending operation. The first color is loaded from the diffuse texture at the texture coordinates defined in the mesh and multiplied by the input color.

float4 normalColor = tex2D( g_samLinear, g_txDiffuse, input.tex ) * input.colorD + input.colorS;

The second color is loaded from the projected texture using the projected coordinates described above.

cookieColor = tex2D( g_samLinear, g_txProjected, cookieCoord.xy );

D3DTOP_ADD is simply emulated by adding the projected cookie texture to the normal texture color

normalColor += cookieColor;

For D3DTOP_MODULATE, the shader would simply multiply the colors together instead of adding them. The effects file can also be extended to handle traditional lightmapping pipeline by passing a second set of texture coordinates stored in the mesh all the way down the pixel shader. The shader would then lookup into a lightmap texture using the second set of texture coordinates instead of the projected coordinates.

Screen space UI rendering

Rendering objects in screen space in Direct3D 10 requires that the user scale and bias the input screen coordinates against the viewport size. For example, a screen space coordinate in the range of <[0..639],[0..479]> needs to be transformed into the range of <[-1..1],[-1..1]>. So that it can be transformed back by the viewport transform.

The vertex shader code below performs this transformation. Note that the w coordinate of the position is explicitly set to 1. This ensures that the coordinates will remain the same when the w-divide occurs. Additionally, the Z position is passed into the shader in clip-space, meaning that it is in the [0..1] range, where 0 represents the near plane, and 1 represents the far plane.

//output our final position
output.pos.x = (input.pos.x / (g_viewportWidth/2.0)) -1;
output.pos.y = -(input.pos.y / (g_viewportHeight/2.0)) +1;
output.pos.z = input.pos.z;
output.pos.w = 1;

D3DFILL_POINT fillmode

The emulation of point fillmode requires the use of the geometry shader to turn one triangle of 3 vertices into 6 triangles of 12 vertices. For each vertex of the input triangle, the geometry shader emits 4 vertices that comprise a two-triangle strip at that position. The positions of these vertices are displaced such that the screen-space size in pixels is equal to the g_pointSize variable.

This sample does not show how to emulate point sprite functionality, which is closely related to point rendering. For point sprite rendering please see the ParticlesGS sample.


GPUSpectrogram Sample

This sample demonstrates how to perform data processing on the GPU without creating a window or swapchain. In this case, it constructs a spectrogram from wav data using the GPU.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\GPUSpectrogram
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\GPUSpectrogram.exe

General-Purpose Processing on the GPU

GPUSpectrogram demonstrates how to use the power of the GPU for non-graphics related tasks. In this case, the GPU creates a spectrogram from data in a wave file. The application does not create a window or swap chain and makes use of Render-to-Texture type operations for computation.

A spectrogram represents sound data as a graph. The vertical axis represents the frequency components of the sound, while the horizontal axis represents time. The colors represent the intensity and phase shift of that particular frequency.

In a wave file, the data is stored as a one dimensional array, where each value represents air pressure (or amplitude) and each index represents a distinct time step.

In order to convert from the amplitude versus time domain to the frequency versus time domain, the sample employs the use of the Discrete Fourier Transforms (DFTs). Specifically, the sample uses a subset of Discrete Fourier Transforms known as Fast Fourier Transforms (FFTs). They are considered fast because their O(N*log(N)) complexity is much lower than the O(N*N) complexity of general DFTs.

FFTs only convert amplitude versus time data into frequency data. In order to get frequency data over time, we must split the incoming audio data into windows. Each window consists of a subsequent set of N audio samples, where N is the window size. For example, if the window size is 16 samples, then the first window consists of samples 0 to 15. The second consists of samples 16-31, and so on.

Because each window represents the amplitudes encountered during a specific time interval, the FFT of any particular window will represent the frequencies encountered during that specific time interval. Putting these FFTs next to each other on a graph gives a plot of frequency components versus time.

How the Sample Works

Loading Audio Data

The CAudioData class handles loading the sound data from the wave file. Internally it utilizes the CWaveFile sample class to load the actual data from the wave file. The CAudioData class splits the wave data into channels and stores the data as floating point numbers regardless of the internal format of the wave file.

Getting Audio Data onto the GPU

The audio data loaded from the CAudioData class is placed into a texture. Because the FFT works on complex numbers, the texture contains two color channels, red and green. Red represents the real components corresponding to the amplitudes in the wave file. Green represents the imaginary components and is set to 0 when the texture is populated with wave data. For GPUSpectrogram, two such textures are used. One is used as the render target while the other is bound as a texture input. When the operation is complete, the two are switched.

The texture is exactly N elements wide, where N is the size of the window. Each row of the texture contains exactly N audio samples. For a wave file that contains M audio samples, the texture will be N by ceil(M/N) texels in size. This allows the GPU to perform an FFT on each row of the texture in parallel.

GPU FFT Algorithm

The bulk of the GPUSpectrogram calculations are performed using Render-to-Texture type operations. In these operations, the viewport is set to the exact size of the texture. The texture with the most recent data is bound as the input texture, while the other texture is bound as the render target. A quad that has texture coordinates that correspond exactly with the input texture is draw to exactly cover the render target. When the operation completes, the render target texture contains the most recent data.

GPUSpectrogram leverages the Danielson-Lanczos FFT algorithm. This document will not go into the details of the algorithm, only the GPU implementation of it. The first part of the algorithm sorts the audio data according to the reverse bit order of the column index. This is handled in the PSReverse pixel shader. This shader uses the subroutine ReverseBits to find the location of the data that will fill the current position after the sort.

uint ReverseBits( uint x )
{
    //uses the SWAR algorithm for bit reversal of 16bits
    x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
    x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
    x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));	//8bits

    //uncomment for 9 bit reversal
    //x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));	//16bits
    //push us back down into 9 bits
    //return (x >> (16-9) & 0x000001ff;

    return x;
}

//
// PSReverse
//
float4 PSReverse( PSQuadIn input ) : COLOR
{
    uint iCurrentIndex = input.tex.x;
    uint iRevIndex = ReverseBits( iCurrentIndex );

    float2 fTex = float2( (float)iRevIndex, (float)input.tex.y );
    fTex /= g_TextureSize;
    return tex2D( g_samPointClamp, g_txSource, fTex ).xyyy;
}

After the reverse sort, the actual FFT takes place. The outer two loops of the Daneilson-Lanczos algorithm are performed on the CPU and consist of setting various shader constants. The inner-loop is performed on the GPU. The final result is that the most recent render target contains the results of the FFT on the data.

    //outer two loops
    UINT iterations = 0;
    float wtemp,wr,wpr,wpi,wi,theta;
    UINT n = g_uiTexX;
    UINT mmax = 1;
    while( n > mmax )
    {
        UINT istep = mmax << 1;
        theta = 6.28318530717959f / ((float)mmax*2.0f);
        wtemp = sin( 0.5f*theta );
        wpr = -2.0f*wtemp*wtemp;
        wpi = sin( theta );
        wr = 1.0f;
        wi = 0.0f;

        for( UINT m=0; m < mmax; m++ )
        {
            //Inner loop is handled on the GPU
            {
                g_pWR->AsScalar()->SetFloat(wr);
                g_pWI->AsScalar()->SetFloat(wi);
                g_pMMAX->AsScalar()->SetInt(mmax);
                g_pM->AsScalar()->SetInt(m);
                g_pISTEP->AsScalar()->SetInt(istep);

                if( 0 == iterations%2 )
                {
                    g_ptxSource->AsShaderResource()->SetResource( g_pDestTexRV );
                    RenderToTexture( pd3dDevice, g_pSourceRTV, false, g_pFFTInner );
                }
                else
                {
                    g_ptxSource->AsShaderResource()->SetResource( g_pSourceTexRV );
                    RenderToTexture( pd3dDevice, g_pDestRTV, false, g_pFFTInner );
                }
                pd3dDevice->OMSetRenderTargets( 1, apOldRTVs, pOldDS );

                iterations++;
            }

            wtemp = wr;
            wr = wtemp*wpr-wi*wpi+wr;
            wi = wi*wpr+wtemp*wpi+wi;
        }
        mmax = istep;
    }

Complexity Considerations

A look at the implementation of the FFT shows that the inner loop gets executed N times, where N is the size of the window. Because the pixel shader is run for every pixel in the row, and a row is N samples wide, the time complexity could be said to be O(N*N). This is no better than the general DFT. However, taking a closer look at the PSFFTInner pixel shader reveals that most of the work is only done when special cases are met. For each execution of the shader the following happens, texture load, modulus operation, and two if statements. However, if any if the if statements are true, which they are 2*Log(N) times out of N, you have many more operations. Because of this you can state that this implementation is actually an O( M*N*N + 2*L*N*Log(N) ) operation, where M < L. This is still not O( N*log(N) ), but does perform fewer operations than the O(N*N) DFT.


HDRFormats10 Sample

High dynamic range lighting effects require the ability to work with color values beyond the 0 to 255 range, usually by storing high range color data in textures. Floating point texture formats are the natural choice for HDR applications, but they may not be available on all target systems. This sample shows how high dynamic range data can be encoded into integer formats for compatibility across a wide range of devices.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\HDRFormats10
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\HDRFormats10.exe

Sample Overview

High dynamic range lighting techniques add realism to your application; furthermore, these techniques are fairly straightforward to implement, integrate well into an existing render pipeline, and require a modest amount of processing time; however, most HDR techniques rely in floating-point texture formats, which may not be available on the target system. One way to enable HDR techniques on devices without floating-point texture support is to encode high range floating-point data into an integer format, decoding on-the-fly as needed. This sample supports both Direct3D 9 and Direct3D 10 codepaths. Examples for Direct3D 10 codepath will be discussed.

Be aware that integer textures are not perfect replacements for floating-point textures; the disadvantages of integer encoding are a loss of precision and/or a loss a range from the floating-point source, plus a performance hit resulting from the encoding/decoding process. This encoding/decoding happens seemlessly within the pixel shaders, so it's not prohibitively expensive but it can cause a slight frame-rate drop. For static elements, such as a skyboxes, the encoding can be done once during initialization, saving some cycles during run-time.

Implementation

The application uses two high dynamic range techniques: tone mapping and blooming. If you are not familiar with how these techniques work or want more information about high dynamic range images in general, look at the HDR Lighting programming guide first, and view the HDRLighting and HDRCubeMap samples included with the DirectX Documentation.

For the techniques used in this sample, the ability to store HDR data in textures is critical. The scene must be rendered to an HDR render target, the environment map texture needs to be HDR, and the temporary textures used to measure scene luminance all need to store HDR data. A device which supports floating-point textures will offer the best performance and simplest implementation, but with a little extra work integer textures can be used to store HDR data. This sample implements three encoding schemes:

RGB16

Using a 16-bit per channel integer format, 65536 discrete values are available to store per-channel data. This encoding is a simple linear distribution of those 65536 values between 0.0f and an arbitrary maximum value (100.0f for this sample). The alpha channel is unused. Here is the formula for decoding the floating-point value from an encoded RGB16 color:

decoded.rgb = encoded.rgb dot max_value

RGB32

Using a 32-bit per channel integer format gives better range of color than using a16-bit per channel integer formats. 4294967296 discrete values are available to store per-channel data. This encoding is a simple linear distribution of those 4294967296 values between 0.0f and an arbitrary maximum value (10000.0f for this sample). The alpha channel is unused. The formula for decoding the value from an encoded RGB32 color is exactly the same as it is for an RGB16 color:

decoded.rgb = encoded.rgb dot max_value

R9G9B9E5

This encoding is more sophisticated than RGB16 and allows for a far greater range of color data by using a logarithmic distribution. Each channel stores the mantissa of the color component, and the alpha channel stores a shared exponent. The added flexibility of this encoding comes at the cost of extra computation. Here is the formula for decoding the floating-point value from an encoded R9G9B9E5 color:

decoded.rgb = encoded.rgb * pow( 2, encoded.a )

The images below show the textures used to render the scene in top-down order according to when they're used. Images with a blue border contain high dynamic range data, shown here with RGBE8 encoding.

Rendering with HDR

The process of rendering the scene is nearly identical between the native floating-point texture mode and the encoded integer texture modes. Pixel shaders which read from high dynamic range textures simply require an extra decoding step when reading from encoded integer textures and require a similar encoding step when writing HDR data to integer textures. By using uniform arguments to the shader, the same shader can be compiled differently and used by every encoding scheme. For example, here is the pixel shader that lights the model:

//-----------------------------------------------------------------------------
// Name: ScenePS
// Type: Pixel Shader
// Desc: Environment mapping and simplified hemispheric lighting
//-----------------------------------------------------------------------------
float4 ScenePS( SceneVS_Output Input,
                uniform bool RGB9E5,
                uniform bool RGB32,
                uniform bool RGB16 ) : SV_TARGET
{
    // Sample the normal map
    float3 bump = g_tNormal.Sample( LinearSampler, Input.Tex );
    bump *= 2.0;
    bump -= float3(1,1,1);

    //move bump into world space
    float3 binorm = normalize( cross( Input.Normal_World, Input.Tangent_World ) );
    float3x3 wtanMatrix = float3x3( binorm, Input.Tangent_World, Input.Normal_World );
    bump = mul( bump, wtanMatrix ); //world space bump

    // Sample the environment map
    float3 vReflect = reflect( Input.ViewVec_World, bump );
    float4 vEnvironment = g_tCube.Sample( LinearSampler, vReflect );

    if( RGB9E5 )
        vEnvironment.rgb = DecodeRGB9E5( vEnvironment );
    else if( RGB32 )
        vEnvironment.rgb = DecodeRGB32( vEnvironment );
    else if( RGB16 )
        vEnvironment.rgb = DecodeRGB16( vEnvironment );

    // Simple overhead lighting
    float3 vColor = saturate( MODEL_COLOR * bump.y );

    // Add in reflection
    vColor = lerp( vColor, vEnvironment.rgb, MODEL_REFLECTIVITY );

    if( RGB9E5 )
        return EncodeRGB9E5( vColor );
    else if( RGB32 )
        return EncodeRGB32( vColor );
    else if( RGB16 )
        return EncodeRGB16( vColor );
    else
        return float4( vColor, 1.0f );
}

Normal Map Formats

In the Direct3D 10 codepath, the sample renders the object with a normal map. There are various normal map formats to choose from.

R8G8B8A8

The one in use for most Direct3D 9 generation shaders is the R8G8B8A8 format. In R8G8B8A8 the x, y, and z components of the normal are stored in 8bit R, G, and B channels in the texture. The values are biased, meaning that for each channel, 128 represents the value 0. 0 represents -1, and 255 represents +1.

The Alpha channel remains unused for this sample, but can be used to store height information for effects such as displacement or parallax mapping. Please refer to the DisplacementMapping10 sample for more information.

Floating Point Formats

Floating point normal formats provide more precision than integer formats such as R8G8B8A8. In addition, since floating point textures can be signed, there is no need to bias the texture to represent negative values. However, in this sample, the source of the normal map is already a biased R8G8B8A8 texture, so we still unbias in the shader. The sample simply gains precision from the floating point normal map formats.

Compressed Formats

New additions to Direct3D 10 are the compressed formats for storing normal maps. These are DXGI_FORMAT_BC5_SNORM and DXGI_FORMAT_BC5_UNORM respectively. They store data in a 0 to 1 range, but offer compression of the normal map. Unlike the HDR formats discussed above, there is no need to decode these formats in the shader. It is already handled by the hardware.

BC5_UNORM textures are unsigned. They store data in the range from 0 to 1. As with the R8G8B8A8 format, the data must be unbiased in the shader to get negative values.

BC5_SNORM textures are signed, meaning that they can store values from -1 to 1. If the normal maps are authored with this in mind, no unbiased needs to be done inside the shader to get negative values. Since the source normal map for the sample is already biased, the sample does not use the BC5_SNORM format to it's fullest.


HLSLWithoutFX10 Sample

HLSLwithoutEffects demonstrates using HLSL to write vertex and pixel shaders without using the effect interfaces. HLSL is a language that closely resembles C syntax and constructs.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\HLSLWithoutFX10
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\HLSLWithoutFX10.exe

How the Sample Works

The scene that this sample renders consists of a square grid of triangles lying on the XZ plane. In each frame, the vertices of this grid will move up or down along the Y direction based on a function of their distance to the origin and time. The vertices are also lit using another function of the distance and time. The time is incremented for each frame. Because the Y coordinate and color of the vertices are generated in each frame, they do not need to be stored. Therefore, the vertex declaration only contains a D3DXVECTOR2 for the X and Z coordinates.

During initialization, the sample calls D3DX10CompileShaderFromFile to read the shader function from a file and compile it into binary shader. After this process, an ID3D10Blob contains the shader binary. Then, the sample calls CreateVertexShader or CreatePixelShader with the shader code to obtain a ID3D10Device object that can be passed to the device.

In FrameMove, the sample uses the ID3D10Buffer interface to set the shader's global variables mViewProj and fTime in order to update the view + projection transformation and time parameter for the shader. At render time, the sample calls VSSetShader and PSSetShader to set the vertex and pixel shaders to be used for any subsequent rendering calls. GSSetShader is used to set the geometry shader to NULL, or unused. When DrawIndexed is called after that, the vertex shader will be invoked once for every vertex processed. The pixel shader will be invoked for every pixel rasterized.

To ensure that the structure defining the shader constants in the application code (VS_CONSTANT_BUFFER) lines up with the constant buffer in the shader (cbuffer cb0), manual packing of constants is used. By default Direct3D 10 attempts to pack as many variables into float4s as possible. This is similar to using #pragma pack(16) in Visual Studio, except that the HLSL compiler will actually pack multiple variables into a single float4. For example, two float2 variables would, by default, take up 4 float positions in HLSL, but 8 positions in Visual Studio. To ensure that variables are packed a certain way, the packoffset keyword can be used to manually discern where each variables is placed in the constant buffer. In the shader, the usage of the packoffset keyword is as follows.

//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------
cbuffer cb0
{
    row_major float4x4 mWorldViewProj : packoffset(c0);     // World * View * Projection transformation
    float fTime :                       packoffset(c5.y);   // Time parameter. This keeps increasing
                                                            // Notice, that this parameter is placed in c5.y.
                                                            // If it were packed by the default packing rules,
                                                            // it would be placed in c4.x
};

packoffset(c0) places the first entry of the mWorldViewProj matrix at c0. This ensures that the elements of the matrix cover constants c0, c1, c2, and c3. fTime is placed in c5.y. The default packing rules would place the fTime variable in c4.x. This methodology can be used to arrange variables in the constant buffer into very specific patterns. For example, putting the fTime variable at c4.z, would leave a space of 2 floats between the mWorldViewProj and fTime. Likewise, the application would have to change where it puts fTime in the constant buffer to ensure that the fTime variable is in the place that the shader expects.

In the sample, the vertex shader is written in a text file called HLSLwithoutEffects10.vsh. In this file, there are two global variables and a shader function called Ripple. Ripple takes a float2 as input (for X and Z of the vertex) and outputs two float4 representing the screen-space position and vertex color. The Y coordinate is generated using this formula:

Y = 0.1 * sin( 15 * L * sin(T) );

L is the distance between the vertex and the origin before the Y adjustment, so it has the value of sqrt(X2 + Z2), because the vertices are lying on the XZ plane. T is the fTime global variable.

The color of the vertex will be some shade of gray based on this formula:

C = 0.5 - 0.5 * cos( 15 * L * sin(T) );

C will be the value used for all red, green, blue, and alpha and will range from 0 to 1, giving the vertex a color of black to white, respectively. The result looks like ripples with width changing back and forth between narrow and wide and with proper shading based on the slope.


Instancing10 Sample

This sample demonstrates the use of the Instancing and Texture Arrays to reduce the number of draw calls required to render a complex scene. In addition, it uses AlphaToCoverage to avoid sorting semi-transparent primitives.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\Instancing10
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\Instancing10.exe

How the Sample Works

Reducing the number of draw calls made in any given frame is one way to improve graphics performance for a 3D application. The need for multiple draw calls in a scene arises from the different states required by different parts of the scene. These states often include matrices and material properties. One way to combat these issues is to use Instancing and Texture Arrays. In this sample, instancing enables the application to draw the same object multiple times in multiple places without the need for the CPU to update the world matrix for each object. Texture arrays allow multiple textures to be loaded into same resource and to be indexed by an extra texture coordinate, thus eliminating the need to change texture resources when a new object is drawn.

The Instancing sample draws several trees, each with many leaves, and several blades of grass using 3 draw calls. To achieve this, the sample uses one tree mesh, one leaf mesh, and one blade mesh instanced many time throughout the scene and drawn with DrawIndexedInstanced. To achieve variation in the leaf and grass appearance, texture arrays are used to hold different textures for both the leaf and grass instances. AlphaToCoverage allows the sample to further unburden the CPU and draw the leaves and blades of grass in no particular order. The rest of the environment is drawn in 6 draw calls.

Instancing the Tree

In order to replicate a tree the sample needs two pieces of information. The first is the mesh information. In this case, the mesh is loaded from tree_super.x. The second piece of information is a buffer containing a list of matrices that describe the locations of all tree instances. The sample uses IASetVertexBuffers to bind the mesh information to vertex stream 0 and the matrices to stream 1. To get this information into the shader correctly, the following InputLayout is used:

const D3D10_INPUT_ELEMENT_DESC instlayout[] =
{
    { L"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    { L"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    { L"TEXTURE0", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    { L"mTransform", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, D3D10_INPUT_PER_INSTANCE_DATA, 1 },
    { L"mTransform", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 16, D3D10_INPUT_PER_INSTANCE_DATA, 1 },
    { L"mTransform", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 32, D3D10_INPUT_PER_INSTANCE_DATA, 1 },
    { L"mTransform", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 48, D3D10_INPUT_PER_INSTANCE_DATA, 1 },
};

The vertex shader will be called (number of vertices in mesh)*(number of instance matrices) times. Because the matrix is a shader input, the shader can position the vertex at the correct location according to which instance it happens to be processing.

Instancing the Leaves

Because one leaf is instanced over an entire tree and one tree is instanced several times throughout the sample, the leaves must be handled differently than the tree and grass meshes. The matrices for the trees are loaded into a constant buffer. The InputLayout is setup to make sure the shader sees the leaf mesh data m_iNumTreeInstances time before stepping to the next leaf matrix. The last element, fOcc, is a baked occlusion term used to shade the leaves.

const D3D10_INPUT_ELEMENT_DESC leaflayout[] =
{
    { L"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    { L"TEXTURE0", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    { L"mTransform", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, D3D10_INPUT_PER_INSTANCE_DATA, m_iNumTreeInstances },
    { L"mTransform", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 16, D3D10_INPUT_PER_INSTANCE_DATA, m_iNumTreeInstances },
    { L"mTransform", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 32, D3D10_INPUT_PER_INSTANCE_DATA, m_iNumTreeInstances },
    { L"mTransform", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 48, D3D10_INPUT_PER_INSTANCE_DATA, m_iNumTreeInstances },
    { L"fOcc", 0, DXGI_FORMAT_R32_FLOAT, 1, 64, D3D10_INPUT_PER_INSTANCE_DATA, m_iNumTreeInstances },
};

The Input Assembler automatically generates an InstanceID which can be passed into the shader. The following snippet of shader code demonstrates how the leaves are positioned.

    int iTree = input.InstanceId%g_iNumTrees;
    float4 vInstancePos = mul( float4(input.pos, 1), input.mTransform  );
    float4 InstancePosition = mul(vInstancePos, g_mTreeMatrices[iTree] );

If there were 3 trees in the scene, the leaves would be drawn in the following order: Tree1, leaf1; Tree2, leaf1; Tree3, leaf1; Tree1, leaf2; Tree2, leaf2; etc...

Instancing the Grass

Grass rendering is handled differently than the Tree and Leaves. Instead of using the input assembler to instance the grass using a separate stream of matrices, the grass is dynamically generated in the geometry shader. The top of the island mesh is passed to the vertex shader, which passes this information directly to the GSGrassmain geometry shader. Depending on the grass density specified, the GSGrassmain calculates psuedo-random positions on the current triangle that correspond to grass positions. These positions are then passed to a helper function that creates a blade of grass at the point. An 1D texture of random floating point values is used to provide the psuedo-random numbers. It is indexed by vertex ids of the input mesh. This ensures that the random distribution doesn't change from frame to frame.

Alternatively, the grass can be rendered in the same way as the tree by placing the vertices of a quad into the first vertex stream and the matrices for each blade of grass in the second vertex stream. The fOcc element of the second stream can be used to place precalculated shadows on the blades of grass (just as it is used to precalculate shadows on the leaves). However, the storage space for a stream of several hundred thousand matrices is a concern even on modern graphics hardware. The grass generation method of using the geometry shader, while lacking built-in shadows, uses far less storage.

Changing Leaves with Texture Arrays

Texture arrays are just what the name implies. They are arrays of textures, each with full mipmaps. For a texture2D array, the array is indexed by the z coordinate. Because the InstanceID is passed into the shader, the sample uses InstanceID%numArrayIndices to determine which texture in the array to use for rendering that specific leaf or blade of grass.

Drawing Transparent Objects with Alpha To Coverage

The number of transparent leave and blades of grass in the sample makes sorting these objects on the CPU expensive. Alpha to coverage helps solve this problem by allowing the Instancing sample to produce convincing results without the need to sort leaves and grass back to front. Alpha to coverage must be used with multisample anti-aliasing (MSAA). MSAA is a method to get edge anti-aliasing by evaluating triangle coverage at a higher-frequency on a higher resolution z-buffer. With alpha to coverage, the MSAA mechanism can be tricked into creating psuedo order independant transparency. Alpha to coverage generates a MSAA coverage mask for a pixel based upon the pixel shader output alpha. That result gets AND'ed with the coverage mask for the triangle. This process is similar to screen-door transparency, but at the MSAA level.

Alpha to coverage is not designed for true order independent transparency like windows, but works great for cases where alpha is being used to represent coverage, like in a mipmapped leaf texture.


MotionBlur10 Sample

This sample implements motion blur using the geometry shader to extrude fins from the original mesh.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\MotionBlur10
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\MotionBlur10.exe

Sample_Overview

The MotionBlur10 sample implements motion blur using a geometric approach combined with order independent transparency through the use of AlphaToCoverage and with anisotropic texture filtering.

Extruding Geometry

Geometry is extruded along the path of motion. A triangle strip is extruded backwards and forwards in time such that the middle triangle is always at the current time. This is done by passing in an array of matrices each containing the transformation information for specific points in time. Namely, N equally spaced points of time ahead and N equally spaced points of time behind. The sample handles this in the application code by calculating the current time and then determining how far to go backwards in time based upon the length of time that the fictional "shutter" will stay open. The middle time in this array of matrices is where the object will look most "solid". This method allows the motion blur effect to be independent of frame rate. The only dependency is that the application must track or guess the locations of the objects at times in the past. Normally this is just a few fractions of a second into the past, but for dramatic effect, applications could blur over several seconds.

Alpha Blending

As each section of the triangle strip is extruded, it is given an alpha value based upon how much time has elapsed between the time represented by this section of the strip and the current time (the triangle in the middle of the forwards and backwards strip). Because this information is not transmitted back to the CPU, we do not have the option of using the CPU to sort the triangles for accurate alpha blending. Therefore, the sample uses AlphaToCoverage to fake order independent transparency. Please see the Instancing10 sample for a more detailed description of transparency using AlphaToCoverage.

Texture Space Motion Blur

The final trick to achieving the motion blur illusion is to blur the texture in the direction of motion when sampling. This is achieved by enabling anisotropic filtering and carefully controlling the ddx and ddy parameters to SampleGrad. These can be found by transforming the vector indicating the direction of motion into the texture space for that particular triangle.

    // Find the projection of our motion into our tangent/texture space
    Output.Aniso.y = max( 0.0001, abs( g_fTextureSmear*dot( clipTangent, clipMotionDir ) ) );
    Output.Aniso.x = max( 0.0001, abs( g_fTextureSmear*dot( clipBiTangent, clipMotionDir ) ) );

Note that the g_fTextureSmear variable can be used to control how much the texture will stretch along the direction of motion. Setting this value too high can result in the anisotropic filter accessing part of the texture completely unrelated to the current texture coordinate.


MultiMon10 Sample

This sample demonstrates how to use multiple monitors with Direct3D 10.

Path

Source: | SDK root\Samples\C++\Direct3D10\MultiMon10
Executable: | SDK root\Samples\C++\Direct3D10\Bin\platform\MultiMon10.exe

How the Sample Works

The sample works by enumerationg all Direct3D 10 adapters and outputs on the system. In Direct3D 10 an adapter refers to the physical display hardware in the machine. An output refers to an output device connected to that physical display hardware. The output device is most often a monitor. Many display adapters will have more than one output attached. For example, if your video card has two DVI connectors on the back, Direct3D 10 will most likely enumerate this as on adapter with two outputs attached.

To render to multiple monitors, the sample creates one Direct3D 10 device per adapter, and one swapchain per output. On a system like the one described above, this would be one Direct3D 10 device with two swapchains attached to it.

Enumerating Adapters and Outputs

The EnumerateAdapters functions enumerates both the display adapters in the machine and the outputs connected to those display adapters. IDXGIFactory::EnumAdapters functions in much the same as the GDI enumeration functions. You keep passing in a higher and higher adapter number into the function until it returns DXGI_ERROR_NOT_FOUND, which is the clue that there are no more adapters. Each adapter has number of outputs that can be attached to it. These too, must be enumerated.

Setting Up MultiMon

Once the adapters and outputs have been enumerated, the sample setups a typical multi-monitor scenario. Each monitor will have one window on it. Each adapter will have one Direct3D 10 device. Each output attached to that adapter will have one swapchain. It is important to note that unless sharing is used, resources created on one device cannot be accessed from another device. To illustrate this, each device that is created will create and draw a different shape.

Rendering to Multiple Monitors

Once a swapchain has been assocated with each window/output, rendering can begin. RenderToAllMonitors renders to each window/output sequentially. In order to render to a specific output, the render target and viewport must be set to those specific to that swapchain.

    // set the render target
    pWindowObj->pDeviceObj->pDevice->OMSetRenderTargets( 1, &pWindowObj->pRenderTargetView, pWindowObj->pDepthStencilView );
    // set the viewport
    D3D10_VIEWPORT Viewport;
    Viewport.TopLeftX = 0;
    Viewport.TopLeftY = 0;
    Viewport.Width = pWindowObj->Width;
    Viewport.Height = pWindowObj->Height;
    Viewport.MinDepth = 0.0f;
    Viewport.MaxDepth = 1.0f;
    pWindowObj->pDeviceObj->pDevice->RSSetViewports( 1, &Viewport );

After this, the window specific render function can be called. PresentToAllMonitors presents to each swapchain assocated with a window to get the final image on the screen.

Toggling Fullscreen

This sample uses DXGI's Alt+Enter handling to toggle between full-screen and windowed mode. When DXGI handles Alt+Enter, the application only needs to handle WM_SIZE messages to realize that the window size has changed, and therefore, the backbuffer needs to be resized. When a WM_SIZE message is received, the sample first finds the WINDOW_OBJECT that corresponds to the window handle that received the message. Once this is found, the render target view, depth stencil view, and depth stencil surface are released. The swapchain is resized based upon the dimensions of the window's client rect. Finally, the render target view, depth stencil surface, and depth stencil view are recreated to match the new swapchain.

    DXGI_SWAP_CHAIN_DESC Desc;
    pObj->pSwapChain->GetDesc( &Desc );

    pObj->pSwapChain->ResizeBuffers( Desc.BufferCount,
                                     (UINT)rcCurrentClient.right,
                                     (UINT)rcCurrentClient.bottom,
                                     Desc.BufferDesc.Format,
                                     0 );

    pObj->Width = (UINT)rcCurrentClient.right;
    pObj->Height = (UINT)rcCurrentClient.bottom;

    // recreate the views
    CreateViewsForWindowObject( pObj );


MultiStreamRendering Sample

Path

Source: | (SDK root)\Samples\C++\Direct3D10\MultiStreamRendering
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\MultiStreamRendering.exe

Sample Overview

This sample explains how to perform multi-stream rendering on Direct3D 9 and Direct3D 10 platforms. Multi-stream rendering allows vertex attributes to be split between different vertex streams. Multiple streams are referenced using a single index buffer. In addition, Direct3D 10 allows multi-stream and multi-index rendering, where multiple indices are used to access vertex data that is stored at frequencies. In this sample, the Direct3D 10 codepath references positions that are stored once per vertex and, in the same shader, references normals that are only stored once per triangle.

Multi-Stream Single-Index Rendering in Direct3D 9

Multi-Stream Single-Index rendering renders geometry using multiple vertex streams that are indexed by the same index buffer. This means that all data must be stored at the same frequency (namely, data is stored per-vertex). For mult-stream single-index rendering, 4 input vertex buffers are created. They store position, normal, textures coordinates, and alternative texture coordinates respectively.

The first step is to create a vertex declaration that incorporates all of these individual vertex streams. The goal of this vertex declaration is to make the multiple individual streams look like one unified stream to the vertex shader.

    // Create a Vertex Decl for the MultiStream data.
    // Notice that the first parameter is the stream index.  This indicates the
    // VB that the particular data comes from.  In this case, position data
    // comes from stream 0.  Normal data comes from stream 1.  Texture coordinate
    // data comes from stream 2.
    D3DVERTEXELEMENT9 declDesc[] =
    {
        {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
        {1, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,  D3DDECLUSAGE_NORMAL, 0},
        {2, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,  D3DDECLUSAGE_TEXCOORD, 0},
        {0xFF,0,D3DDECLTYPE_UNUSED, 0,0,0}// D3DDECL_END
    };
    pd3dDevice->CreateVertexDeclaration( declDesc, &g_pDecl );

Before rendering the sample must make sure that all streams are bound, that the index buffer is bound, and that the correct vertex declaration is set. Notice that the third vertex stream ( stream number 2 ) can be switched between the original set of texture coordinates and the alternate set of texture coordinates without affecting the other streams.

    // Setup our multiple streams
    pd3dDevice->SetStreamSource( 0, g_pVBs[ST_VERTEX_POSITION], 0, sizeof(D3DXVECTOR3) );
    pd3dDevice->SetStreamSource( 1, g_pVBs[ST_VERTEX_NORMAL], 0, sizeof(D3DXVECTOR3) );
    if(g_bUseAltUV)
        pd3dDevice->SetStreamSource( 2, g_pVBs[ST_VERTEX_TEXTUREUV2], 0, sizeof(D3DXVECTOR2) );
    else
        pd3dDevice->SetStreamSource( 2, g_pVBs[ST_VERTEX_TEXTUREUV], 0, sizeof(D3DXVECTOR2) );

    // Set our index buffer as well
    pd3dDevice->SetIndices( g_pIB );

    // Set A Multistream Vertex Decl insted of FVF
    pd3dDevice->SetVertexDeclaration( g_pDecl );

This is all of the work necessary to facilitate multi-stream single-index rendering on Direct3D 9. The vertex shader is written as if all of the input came in from a single stream.

Multi-Stream Single-Index Rendering in Direct3D 10

The setup is similar for performing multi-stream single-index rendering in Direct3D 10. The same vertex buffers are created (position, normal, texture coordinates, alternate texture coordinates). The sample then creates and input layout incorporating the separate vertex streams. Again, the purpose is to make the multiple vertex streams look like one stream to the vertex shader.

    // Create a Input Layout for the MultiStream data.
    // Notice that the 4th parameter is the stream index.  This indicates the
    // VB that the particular data comes from.  In this case, position data
    // comes from stream 0.  Normal data comes from stream 1.  Texture coordinate
    // data comes from stream 2.
    const D3D10_INPUT_ELEMENT_DESC vertlayout_singleindex[] =
    {
        { "SV_POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "NORMAL",      0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD0",   0, DXGI_FORMAT_R32G32_FLOAT,    2, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    };
    UINT iNumElements = sizeof(vertlayout_singleindex)/sizeof(D3D10_INPUT_ELEMENT_DESC);
    D3D10_PASS_DESC PassDesc;
    g_pRenderScene_SI->GetPassByIndex( 0 )->GetDesc( &PassDesc );
    V_RETURN( pd3dDevice->CreateInputLayout( vertlayout_singleindex, iNumElements, PassDesc.pIAInputSignature, &g_pVertexLayout_SI ) );

Before rendering the sample must make sure that all streams are bound, that the index buffer is bound, and that the correct input layout is set. Notice that the third vertex stream ( stream number 2 ) can be switched between the original set of texture coordinates and the alternate set of texture coordinates without affecting the other streams.

    UINT strides[3];
    UINT offsets[3] = {0, 0, 0};

    // Set the parameters for MultiIndex or SingleIndex
    ID3D10Buffer* pBuffers[3];

    ...

        pd3dDevice->IASetInputLayout( g_pVertexLayout_SI );

        pBuffers[0] = g_pVBs[ST_VERTEX_POSITION];
        pBuffers[1] = g_pVBs[ST_VERTEX_NORMAL];

        if( g_bUseAltUV )
            pBuffers[2] = g_pVBs[ST_VERTEX_TEXTUREUV2];
        else
            pBuffers[2] = g_pVBs[ST_VERTEX_TEXTUREUV];

        strides[0] = sizeof(D3DXVECTOR3);
        strides[1] = sizeof(D3DXVECTOR3);
        strides[2] = sizeof(D3DXVECTOR2);

        numVBsSet = 3;

    ...

    pd3dDevice->IASetVertexBuffers( 0, numVBsSet, pBuffers, strides, offsets );
    pd3dDevice->IASetIndexBuffer( g_pIB, DXGI_FORMAT_R32_UINT, 0 );
    pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

Multi-Stream Multi-Index Rendering

The Direct3D 10 codepath also allows the use of vertex streams that are stored at different frequencies. In order to access this vertex data stored at different frequencies, multiple index buffers are needed. Note that there is no API to allow users of Direct3D 10 to set more than one index buffer at a time. To perform this multi-stream multi-index rendering, some fancy shader work must be done.

First the buffers are created. In this scenario, 5 streams are created. They are described as follows:

  • FewVertexPositions: Stores NumVertices unique positions.
  • PositionIndices: Stores NumFaces*3 indices into the position buffer.
  • VertexTextureUV: Stores NumFaces*3 texture coordinates.
  • VertexTextureUV2: Stores NumFaces*3 texture coordinates.
  • FaceNormals: Stores NumFaces vertex normals.

Note that FewVertexPosition holds NumVertices positions, while PositionIndices, VertexTextureUV, and VertexTextureUV2 hold NumFaces*3 values. In addition, FaceNormals only contains NumFaces values. This shows a large difference in data frequencies since NumVertices != NumFaces*3 in this scenario.

Since the position indices and texture coordinates share the same frequency, they can be added to the input layout.

    // Create a Input Layout for the MultiStream MultiIndex data.
    //
    const D3D10_INPUT_ELEMENT_DESC vertlayout_multiindex[] =
    {
        { "POSINDEX",    0, DXGI_FORMAT_R32_UINT,		 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD0",   0, DXGI_FORMAT_R32G32_FLOAT,    1, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
    };
    iNumElements = sizeof(vertlayout_multiindex)/sizeof(D3D10_INPUT_ELEMENT_DESC);
    g_pRenderScene_MI->GetPassByIndex( 0 )->GetDesc( &PassDesc );
    V_RETURN( pd3dDevice->CreateInputLayout( vertlayout_multiindex, iNumElements, PassDesc.pIAInputSignature, &g_pVertexLayout_MI ) );

They are also bound as vertex buffers similarly to the way it is handled for multi-stream single-index rendering.

        pd3dDevice->IASetInputLayout( g_pVertexLayout_MI );

        pBuffers[0] = g_pVBs[ST_POSITION_INDEX];
        if( g_bUseAltUV )
            pBuffers[1] = g_pVBs[ST_VERTEX_TEXTUREUV2];
        else
            pBuffers[1] = g_pVBs[ST_VERTEX_TEXTUREUV];

        strides[0] = sizeof(UINT);
        strides[1] = sizeof(D3DXVECTOR2);

However, the data stored at different frequencies must be passed in as buffers.

        g_pPosBuffer->SetResource( g_pFewVertexPosRV );
        g_pNormBuffer->SetResource( g_pFaceNormalRV );

The rest of the magic happens in the vertex shader. The vertex position is loaded from the position buffer based upon the input position index. The face normal is loaded from the normal buffer using the vertexID/3. SV_VertexID is automatically generated by the input assembler. The sample could also use SV_PrimitiveID (not divided by 3) to accomplish the same task.

    float4 Pos = g_posBuffer.Load( input.PositionIndex );
    float4 Norm = g_normBuffer.Load( input.vertID/3 );


ParticlesGS Sample

This sample implements a complete particle system on the GPU using the Direct3D 10 Geometry Shader, Stream Output, and DrawAuto.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\ParticlesGS
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\ParticlesGS.exe

How the Sample Works

Particle system computation has traditionally been performed on the CPU with the GPU rendering the particles as point sprites for visualization. With Geometry Shaders, the ability to output arbitrary amounts of data to a stream allows the GPU to create new geometry and to store the result of computations on existing geometry.

This sample uses the stream out capabilities of the geometry shader to store the results of particles calculations into a buffer. Additionally, the Geometry Shader controls particle birth and death by either outputting new geometry to the stream or by avoiding writing existing geometry to the stream. A Geometry Shader that streams output to a buffer must be constructed differently from a normal Geometry Shader.

When used inside an FX file

//--------------------------------------------------------------------------------------
// Construct StreamOut Geometry Shader
//--------------------------------------------------------------------------------------
geometryshader gsStreamOut = ConstructGSWithSO(compile gs_4_0 GSAdvanceParticlesMain(),
                                                "POSITION.xyz;
                                                NORMAL.xyz;
                                                TIMER.x;
                                                TYPE.x" );

When used without FX

//--------------------------------------------------------------------------------------
// Construct StreamOut Geometry Shader
//--------------------------------------------------------------------------------------
D3D10_STREAM_OUTPUT_DECLARATION_ENTRY pDecl[] =
{
    // semantic name, semantic index, start component, component count, output slot
    { L"POSITION", 0, 0, 3, 0 }, // output first 3 components of "POSITION"
    { L"NORMAL", 0, 0, 3, 0 }, // output the first 3 components of "NORMAL"
    { L"TIMER", 0, 0, 1, 0 }, //  output the first component of "TIMER"
    { L"TYPE", 0, 0, 1, 0 }, //  output the first component of "TYPE"
};

CreateGeometryShaderWithStreamOut( pShaderData, pDecl, 4, sizeof(PARTICLE_VERTEX), &pGS );

Particle Types

This particle system is composed of 5 different particle types with varying properties. Each particle type has its own velocity and behavior and may or may not emit other particles.

Launcher Particles

Launcher particles do not move and do not die. They simply count down until they can emit a Shell particle. Once they have emitted a Shell particle, they reset their timer.

Shell Particles

Shell particles are single particles that are given random velocities and launched into the air by Launcher particles. They are meant to represent fireworks shells before they explode. When a Shell particle reaches the end of it's lifespan it does not re-emit itself into the system. Instead, it emits several Ember1 and Ember2 type particles.

Ember1 Particles

Ember1 particles are emitted from Shell particles when they explode. Ember1 particles have short lifespans and fade out as their timer counts down. When their timer reaches zero, these particles do not re-emit themselves into the system and effectively "die."

Ember2 Particles

Ember2 particles are also emitted from Shell particles when they explode. Unlike Ember1 particles, when Ember2 particles reach the end of their lifespans they emit Ember3 particles. These are the source of the secondary explosions in the system.

Ember3 Particles

Ember3 particles are similar to Ember1 particles except that they are of a different color and have a shorter lifespan.

Handling Particles in the Geometry Shader

Particles are handled entirely on the GPU by the Geometry Shader. Instead of going to the rasterizer, the vertex data passed into the geometry shader is output to another vertex buffer. After an initial seeding of the vertex buffer with LAUNCHER type particles, the system can sustain itself on the GPU with only per-frame timing information coming from the CPU.

The sample uses 3 buffers consisting of vertex data to facilitate a fireworks particle system. The first stream contains the initial particles needed to "seed" the system. It is used only once during the first frame that the particle system is active. The second and third buffers are ping-pong buffers and trade off being streamed to and rendered from every other frame.

The particle system works in the following manner:

1. The seed buffer is filled with an initial launcher particle

2. The first time through the GS, the GS sees that the LAUNCHER is at 0 and emits a SHELL at the launcher position. NOTE: Because the particle system is rebuilt every pass through the GS, any particles that are necessary for the next frame need to be emitted, not just new particles.

3. The second time through the GS, the LAUNCHER and SHELL timers are decremented and the SHELL is moved to a new position.

4. The SHELL timer is decremented to 0, which means that this is the last frame for this SHELL.

5. Because its timer is at 0, the SHELL is not emitted again. In its place, 4 EMBER particles are emitted.

6. The LAUNCHER is at zero, and therefore must emit another SHELL particle. The EMBER particles are moved to a new position and have their timers decremented as well. The LAUNCHER timer is reset.

Knowing How Many Particles Were Output

Geometry Shaders can emit a variable amount of data each frame. Because of this, the sample has no way of knowing how many particles are in the buffer at any given time. Using standard Draw calls, the sample would have to guess at the number of particles to tell the GPU to draw. Fortunately, DrawAuto is designed to handle this situation. DrawAuto allows the dynamic amount of data written to streamout buffer to be used as the input amount of data for the draw call. Because this happens on the GPU, the CPU can advance and draw the particle system with no knowledge of how many particles actually comprise the system.

Rendering Particles

After the particles are advanced by the gsStreamOut Geometry Shader, the buffer that just received the output is used in a second pass for rendering the particles as point sprites. The VSSceneMain Vertex Shader takes care of assigning size and color to the particles based upon their type and age. GSSceneMain constructs point sprites from the points by emitting a 2 triangle strip for every point that is passed in. In this pass, the Geometry Shader output is passed to the rasterizer and does not stream out to any buffer.


PipesGS Sample

This sample implements two vine generation algorithms on the GPU using the StreamOut capabilities of the Geometry Shader and DrawAuto.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\PipesGS
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\PipesGS.exe

How the Sample Works

The vines for VinesGS are generated using two algorithms. The first algorithm starts the vines at the face centers of random mesh faces and grows the vines away from the normal of the face. The second starts the vines at the face centers of random mesh faces, but then grows the vines along the tangent of the face in the direction of one of the nearest face centers. The details of the algorithms can be found by looking through the geometry shader code for both types of vine generation.

The focus of the sample is geometry amplification and deamplification using the Geometry Shader. As with ParticlesGS, the geometry is handled in two passes. The first pass grows the pipes, while the second renders them.

Growing Pipes

For more details on geometry amplification in the Geometry Shader, see ParticlesGS.

For this sample, the pipes segments are tracked by a line list. Each point in the line list represents one pipe segment. The end of the pipe segment is the only area where a new pipe segment can grow from. This is labeled as a Grow point. All other points are either labeled as Start points (the start of a new vine) or Static points. Start points differentiate where one pipe stops and another pipe begins. Static points can only age and die when their timer is up. When the Geometry Shader encounters a Grow point, it coverts it to a Static point. It then outputs another Grow point a short distance away from the current point in a direction defined by the generation algorithm. For Static points, the shader keeps track of the time it's been alive as well as the total time that the vine it belongs to has been alive. When a Static point's timer runs out, it is not output to the stream-out buffer. This effectively kills the point.

Growing Leaves

PipesGS also grows leaves along the length of the pipe. Leaves are handled with a separate variable in the point structure calls leaves. For each point that is added the line list, a random number in the range of [0..1] is selected inside the shader. If the number is below the leaf generation rate as defined by the application, the Leaves member of that point structure is set to a random number. Otherwise, Leaves is 0 for this point. During the rendering pass, the Geometry Shader renders a leaf with a random texture at that point if Leaves is non-zero.

Drawing the Pipes and Leaves

This particle system is composed of 5 different particle types with varying properties. Each particle type has it's own velocity and behavior and may or may not emit other particles.

Additionally points at each end of the cylinder are scaled according to the timing information of the closest point. Segments will go through the following life cycle. Young segments will grow until they reach their maximum radius. They will continue to age until they reach a time where they start to whither. During withering, the radius will be scaled down to zero. Once the radius is scaled to zero, the segment may die.

For each pair of points, the shader checks to see whether the first point's Leaves field is non-zero. If it is, a leaf is draw at this point. The leaf is made from a two-triangle strip that represents a quad oriented with the pipe at that point. The Z texture coordinate for the leaf quad is selected from the range of [1..5] based upon the value of Leaves. In the pixel shader, any leaves will fetch a texel from the indices [1..5] of the texture array, which have been preloaded as leaf textures. All pipe sections will use index 0 of the texture array, which is a bark texture.

Knowing How Many Pipe Segements are in the Buffer

Geometry Shaders can emit a variable amount of data each frame. Because of this, the sample has no way of knowing how many pipe segments are in the buffer at any given time. Using standard Draw calls, the sample would have to guess at the number of pipe segments to tell the GPU to draw. Fortunately, DrawAuto is designed to handle this situation. DrawAuto allows the dynamic amount of data written to streamout buffer to be used as the input amount of data for the draw call. Because this happens on the GPU, the CPU can advance and draw the pipes with no knowledge of how much geometry is actually in any of the buffers.


ShadowVolume10 Sample

Path

Source: | (SDK root)\Samples\C++\Direct3D10\ShadowVolume10
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\ShadowVolume10.exe

How the Sample Works

A shadow volume of an object is the region in the scene that is covered by the shadow of the object caused by a particular light source. When rendering the scene, all geometry that lies within the shadow volume should not be lit by the particular light source. A closed shadow volume consists of three parts: a front cap, a back cap, and the side. The front and back caps can be created from the shadow-casting geometry: the front cap from light-facing faces and the back cap from faces facing away from light. In addition, the back cap is formed by translating the front facing faces a large distance away from the light, to make the shadow volume long enough to cover enough geometry in the scene. The side is usually created by first determining the silhouette edges of the shadow-casting geometry then generating faces that represent the silhouette edges extruded for a large distance away from the light direction. Figure 1 shows different parts of a shadow volume.

Figure 1: Creation of a shadow volume.

The front cap (blue) and back cap (red) are created from the occluder's geometry. The back cap is translated to prolong the shadow volume, and the side faces (purple) are generated to enclose the shadow volume.

This sample demonstrates a specific implementation of shadow volumes. Many traditional shadow volume approaches determine the silhouette and generate the shadow volume geometry on the CPU. This sample determines the silhouette in the geometry shader and uses the fact that the geometry shader can send a variable amount of data to the rasterizer to create new shadow volume geometry on the fly. The underlying idea is that for triangles that face the light, we can use them as-is for the front cap of the shadow volume. The back cap is generated from the front facing triangles translated a large distance along the light direction at each vertex, then they can be used as the back cap. However, a problem occurs at silhouette edges where one triangle faces the light and its neighbor faces away from the light. In this situation, the geometry shader extrudes two new triangles to create a quad to match up between the front cap of the shadow volume and the back cap.

In order for the geometry shader to find silhouette edges it must know which faces are adjacent to each other. Fortunately, the geometry shader has support for a new type of input primitive, triangleadj. Triangleadj assumes that every other vertex is an adjacent vertex. The index buffer of the geometry must be modified to reflect the adjacency information of the mesh. The CDXUTMesh10::ConvertToAdjacencyIndices handles this by creating an index buffer in which every other value is the index of the adjacent vertex of the triangle that shares an edge with the current triangle. The index buffer will double in size due to the extra information being stored. The figure below demonstrates the ordering of the adjacency information.

Rendering Shadows

At the top level, the rendering steps look like the following:

  • If ambient lighting is enabled, render the entire scene with ambient only.
  • For each light in the scene, do the following:
    • Disable depth-buffer and frame-buffer writing.
    • Prepare the stencil buffer render states for rendering the shadow volume.
    • Render the shadow volume mesh with a vertex extruding shader. This sets up the stencil buffer according to whether or not the pixels are in the shadow volume.
    • Prepare the stencil buffer render states for lighting.
    • Prepare the additive blending mode.
    • Render the scene for lighting with only the light being processed.

The lights in the scene must be processed separately because different light positions require different shadow volumes, and thus different stencil bits get updated. Here is how the code processes each light in the scene in details. First, it renders the shadow volume mesh without writing to the depth buffer and frame buffer. These buffers need to be disabled because the purpose of rendering the shadow volume is merely setting the stencil bits for pixels covered by the shadow, and the shadow volume mesh itself should not be visible in the scene. The shadow mesh is rendered using the depth-fail stencil shadow technique and a vertex extruding shader. In the shader, the vertex's normal is examined. If the normal points toward the light, the vertex is left where it is. However, if the normal points away from the light, the vertex is extruded to infinity. This is done by making the vertex's world coordinates the same as the light-to-vertex vector with a W value of 0. The effect of this operation is that all faces facing away from the light get projected to infinity along the light direction. Since faces are connected by quads, when one face gets projected and its neighbor does not, the quad between them is no longer degenerate. It is stretched to become the side of the shadow volume. Figure 6 shows this.

Figure 4: The faces of the shadow volume that face away from light (left, shown in red) have their vertices extruded by the vertex shader to create a volume that encloses area covered by shadows (right).

When rendering the shadow mesh with the depth-fail technique, the code first renders all back-facing triangles of the shadow mesh. If a pixel's depth value fails the depth comparison (usually this means the pixel's depth is greater than the value in the depth buffer), the stencil value is incremented for that pixel. Next, the code renders all front-facing triangles, and if a pixel's depth fails the depth comparison, the stencil value for the pixel is decremented. When the entire shadow volume mesh has been rendered in this fashion, the pixels in the scene that are covered by the shadow volume have a non-zero stencil value while all other pixels have a zero stencil. Lighting for the light being processed can then be done by rendering the entire scene and writing out pixels only if their stencil values are zero.

Figure 5: The depth-fail technique.

Figure 5 illustrates the depth-fail technique. The orange block represents the shadow receiver geometry. Regions A, B, C, D and E are five areas in the frame buffer where the shadow volume is rendered. The numbers indicate the stencil value changes as the front and back faces of the shadow volume are rendered. In region A and E, both the front and back faces of the shadow volume fail the depth test, and therefore both cause the stencil value to change. For region A, the orange shadow receiver is causing the depth test to fail, and for region E, the cube's geometry is failing the test. The net result is that stencil values in this region stay at 0 after all faces are rendered. In region B and D, the front faces pass the depth test while the back faces fail, so the stencil values are not changed with the front faces, and the net stencil changes are 1. In region C, both the front and back faces pass the depth test, and so neither causes the stencil values to change, and the stencil values stay at 0 in this region. When the shadow volume is completely rendered, only the stencil values in regions B and D are non-zero, which correctly indicates that regions B and D are the only shadowed areas for this particular light.

"Performance Considerations

The current sample performs normal rendering and shadow rendering using the same mesh. Because the mesh class tracks only one index buffer at a time, adjacency information is sent to the shader even when it is not needed for shadow calculations. The shader must do extra work to remove this adjacency information in the geometry shader. To improve performance the application could keep two index buffers for each mesh. One would be the standard index buffer and would be used for non-shadow rendering. The second would contain adjacency information and only be used when extruding shadow volumes.

Finally, there is another area that could call for some performance optimization. As shown earlier, the rendering algorithm with shadow volumes requires that the scene be rendered in multiple passes (one plus the number of lights in the scene, to be precise). Every time the scene is rendered, the same vertices get sent to the device and processed by the vertex shaders. This can be avoided if the application employs deferred lighting with multiple rendertargets. With this technique, the application renders the scene once and outputs a color map, a normal map, and a position map. Then, in subsequent passes, it can retrieve the values in these maps in the pixel shader and apply lighting based on the color, normal and position data it reads. The benefit of doing this is tremendous. Each vertex in the scene only has to be processed once (during the first pass), and each pixel is processed exactly once in subsequent passes, thus ensuring that no overdraw happens in these passes.

"Shadow Volume Artifacts

It is worth noting that a shadow volume is not a flawless shadow technique. Aside from the high fill-rate requirement and silhouette determination, the image rendered by the technique can sometimes contain artifacts near the silhouette edges, as shown in figure 9. The prime source of this artifact lies in the fact that when a geometry is rendered to cast shadow onto itself, its faces are usually entirely in shadow or entirely lit, depending on whether the face's normal points toward the light. Lighting computation, however, uses vertex normals instead of face normals. Therefore, for a face that is near-parallel to the light direction, it will either be all lit or all shadowed, when in truth, only part of it might really be in shadow. This is an inherent flaw of stencil shadow volume technique, and should be a consideration when implementing shadow support. The artifact can be reduced by increasing mesh details, at the cost of higher rendering time for the mesh. The closer to the face normal that the vertex normals get, the less apparent the artifact will be. If the application cannot reduce the artifact down to an acceptable level, it should also consider using other types of shadow technique, such as shadow mapping or pre-computed radiance transfer.

Figure 6: Shadow volume artifact near the silhouette edges.

Figure 7: Displaying the shadow volume reveals that the jagged edge is caused by faces that are treated as being entirely in shadow when they are actually only partially shadowed.


SimpleSample10 Sample

Path

Source: | (SDK root)\Samples\C++\Direct3D10\SimpleSample10
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\SimpleSample10.exe

Sample Overview

This sample can be used as a basic starting point for creating a Direct3D sample.

How the Sample Works

This sample follows the typical use of DXUT such as device initialization, resetting devices, the render loop etc. Use this sample as a starting point for your samples.


Skinning10 Sample

This sample demonstrates multiple ways to perform skinning on Direct3D 10 hardware.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\Skinning10
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\Skinning10.exe

How the Sample Works

This sample focuses on different methodlogies of indexing transformation matrices via bone indices defined within the mesh vertex stream. It does not cover skeletal animation or hierarchial transformations.

The Skinning10 sample demonstrates 4 different methods of indexing bone transformation matrices for GPU skinning. In addition, it demonstrates how stream out without a Geometry Shader can be used to cut down vertex processing cost when skinned model will used for mutiple rendering passes.

Constant Buffer Skinning

Of all 4 methods described here, Constant Buffer Skinning is most like the traditional Direct3D 9 style GPU based skinning. Transformation matrices are loaded into shader constants, and the vertex shader indexes these based upon the bone index in the vertex stream. Like most Direct3D 9 implementations, the number of bone indices per vertex is limted to 4. Unlike most Direct3D 9 implementations the skinning method used in this sample does not create a palette of matrices nor does it section up the mesh by vertices that share like indices. This is because Direct3D 10 allows constant buffers to be much larger than Direct3D 9 constant buffers. Only for meshes with several hundred bones would splitting the bone matrices into palettes be a necessity. The code for indexing the bones in the shader is as follows:

    mret = g_mConstBoneWorld[ iBone ];

Texture Buffer Skinning

Texture Buffer (or TBuffer) skinning looks basically the same as Constant Buffer skinning. In fact the bones are referenced the same way in HLSL.

    mret = g_mTexBoneWorld[ iBone ];

The only difference is that the constant buffer that holds the transformation matrices is declared as a texture buffer (tbuffer) instead of a normal constant buffer. Declaring a buffer as a tbuffer allows it to be accessed like a texture which may increase performance for applications that require a more random access of the texture.

Texture Skinning

A logical extension of tbuffer based skinning is to just store the transformation matrices for the bones in a floating point texture. Depending on the texture fetch performance of the video hardware as well as whether the shader is ALU or texture fetch bound, this method could give a surprising increase in skinning speed.

        iBone *= 4;
        float4 row1 = g_txTexBoneWorld.Load( float2(iBone,     0) );
        float4 row2 = g_txTexBoneWorld.Load( float2(iBone + 1, 0) );
        float4 row3 = g_txTexBoneWorld.Load( float2(iBone + 2, 0) );
        float4 row4 = g_txTexBoneWorld.Load( float2(iBone + 3, 0) );

        mret = float4x4( row1, row2, row3, row4 );

As can be seen here, the act of fetching transformations via 4 texture fetches may be faster than fetching the same transformation from a constant buffer depending on the hardware.

Buffer Skinning

The final method of indexing transformation matrices is through Buffer Skinning. In buffer skinning, the matrices are loaded into an ID3D10Buffer object which is then bound as a shader resource. The matrix data is loaded from the buffer using the Load command.

    iBone *= 4;
        float4 row1 = g_BufferBoneWorld.Load( iBone );
        float4 row2 = g_BufferBoneWorld.Load( iBone + 1 );
        float4 row3 = g_BufferBoneWorld.Load( iBone + 2 );
        float4 row4 = g_BufferBoneWorld.Load( iBone + 3 );

        mret = float4x4( row1, row2, row3, row4 );

Speeding up Multiple Passes with Stream Out

One traditional problem with GPU skinning was that if multiple passes needed to be performed on an object, the object needed to be skinned once for each pass. Take, for example, a scene with 3 shadow mapped light sources and a skinned character. To generate shadows for each of the lights the character needs to be drawn 3 times, once from the point of view of each light. (NOTE: Amplifying and streaming geometry to multiple render targets using the GS could also help aleviate this problem.) This would require that the Vertex Shader skin the character 3 times. The unfortunate reality is that this is two times too many. We really want to skin the character once and save this transformed character to use for the remainder of the frame. That way, if we had a scene that required 10 passes, the character wouldn't need to be skinned 10 times.

Fortunately, Stream Out allows us to do just that. Direct3D 10 allows the sample to skin the character once and stream the results out to a buffer in video memory. Then, for the remainder of the passes, the application just uses the pre-skinned vertices. For a character that may take 10 passes to render, this is 9-fold savings in vertex processing.

This sample does not render multiple passes, but instead renders the character multiple times. It's the same problem, just stated differently. When Stream Out is disabled, the application skins the character each time it renders it. However, when Stream Out is enabled, the skins the character once, saves the results via Stream Out, and renders the multiple characters using the pre-skinned geometry.


SoftParticles Sample

Path

Source: | SDK root\Samples\C++\Direct3D10\SoftParticles
Executable: | SDK root\Samples\C++\Direct3D10\Bin\platform\SoftParticles.exe

Sample Overview

Particle systems are a common method for creating volumetric effects in games. They can be used to simulate such things as fire, cloudes, smoke, dust, glowing projectiles, magic spells, and so on. A common technique is to use 2D camera-aligned quads centered at each particle to represent the volume that the particle represents. Because the quads follow the camera, they give the illusion of a substance filling a 3D volume. However, this illusion often breaks down when the 2D sprites used to visualize the particles intersect with the world geometry. The intersection of the 2D quad with the 3D world geometry creates a hard, straight line — on one side of the line is particle, and on the other is world geometry. Figure 1 shows an example of this.

Figure 1. Hard, Flat Particles

2D Particles with Depth

The first approach to dealing with this is to perturb the depth being output from the pixel shader by a depth stored in the particle texture. This makes the intersections with the world geometry follow the contour of the particle. Figure 2 shows an example of this.

Figure 2. Depth Particles

2D Soft Particles

In the basic flat particle system, the line where the particle quad intersects the geometry is a giveaway that the particles are not actually 3D. To avoid this, the sample can read back the depth buffer as a texture. In the shader, this depth value is sampled and tested against the depth value being rendered for the current pixel in the particle. The alpha value increases as the difference between the depth value in the buffer, and then depth being written out from the pixel shader decreases. Therefore, the particle becomes more transparent as it approaches intersection with the scene geometry.

Figure 3. 2D Soft Particles

Depth Soft Particles

The same approach can be used with particles that output depth. The only difference is that the depth compared with the depth buffer is not the depth from the quad, but the depth from the quad augmented by the depth stored in the particle texture.

Figure 4. Depth Soft Particles, example

Figure 5. Depth Soft Particles, explanation

Animating the 2D Particles

To animate the 2D particles, the sample uses a series of animated particle texture frames stored in a volume texture. The first slice of the volume texture stores the first frame of the animation; the last slice stores the last. As the particle ages, the shader uses the age (in this case a float in the range of [0..1]) to look up a color in a 1D texture. This color modulates the color of the entire particle and makes the particle appear dark near its birth and lighter just before death.

Volumetric Particles

The volumetric techniques in the sample give the particles the appearance of true 3D volume instead of the flat look of 2D particles. To achieve this, the sample traces rays through an imaginary 3D primitive circumscribed by the camera-aligned particle quad. In this case, the sample uses a sphere as the imaginary primitive. There are three main reasons for choosing a sphere. First, it is always possible to circumscribe a sphere in a camera-aligned quad. Second, a sphere is a very symmetrical shape. It looks the same no matter how you orient it. Third, the intersection between a ray and a sphere is easy to compute.

The main process is as follows. The particles are handled in the same manner as in the 2D technique until they reach the pixel shader. The pixel shader computes a ray from the eye to the pixel being drawn on the quad.

Figure 6. Volumetric Particles, Main Process

It then calculates the intersections of this ray and the imaginary sphere circumscribed by the particle quad. If no intersections occur, the ray is discarded.

Figure 7. Volumetric Particles, Calculate the Intersection

Using a fixed step-size, the shader determines the number of steps needed to march from one intersection point to the other. Along the way, several octaves of noise are sampled. These are stored in a 4-channel volume texture. The RGB channels contain the inverse density gradient. The alpha channel contains the density. Lighting is computed at the point using a combination of the normal from the center of the sphere at the point and the density gradient. Each step is summed with the previous step, and the final result is the opacity and color value for the ray traced through the volume. This result is modified slightly by some overall opacity values to get a specific look.

Figure 8. March Between the Two Intersection Points

If the ray intersects the depth buffer before it exits the sphere, the shader changes the rear exit point to be the depth buffer intersection. Optionally, to achieve the soft intersection with world geometry, the alpha can be attenuated based upon the distance between the sample and the depth buffer.

Figure 9. Ray Intersecting the Depth Buffer

Figure 10. Hard Volume Particles

Figure 11. Soft Volume Particles

Animating the Volume Particles

Although the particles are animating (moving away from the source), added detail is gained by animating the texture coordinates used to calculate the lookup in the the noise volume texture. By moving the texture coordinates in one direction, the smoke is made to look like it is moving in the opposite direction.


SparseMorphTargets Sample

This sample implements mesh animation using morph targets.

Path

Source: | (SDK root)\Samples\C++\Direct3D10\SparseMorphTargets
Executable: | (SDK root)\Samples\C++\Direct3D10\Bin\x86 or x64\SparseMorphTargets.exe

Morph Targets

The SparseMorphTargets sample demonstrates facial animation by combining multiple morph targets on top of a base mesh to create different facial expressions.

Morph targets are different poses of the same mesh. Each of the minor variations below is a deformation of the base mesh located in the upper left. By combining different poses together at different intensities, the sample can effectively create many different facial poses.

How the Sample Works

Preprocessing

In a preprocessing step, the vertex data for the base pose is stored into three 2D textures. These textures store position, normal, and tangent information respectively.

This base texture is stored into the .mt file along with index buffer data and vertex buffer data that contains only texture coordinates. Then, for each additional morph target, the mesh is converted to three 2D textures. The base mesh textures are subtracted from the three morph target textures. The smallest subrect that can fully contain all of the differences between the two textures is then stored into the .mt file. By only storing the smallest texture subrect that can hold all of the differences between the two meshes, the sample cuts down on the storage requirements for the morph targets.

Applying Morph Targets at Runtime

Morph targets are handled in the MorphTarget.cpp and MorphTarget.h files. These contain classes that help with the application of the morph targets. To apply the different morph targets to the mesh, the sample sets up a texture2Darray render target with three array indices. The first holds position data, while the second and third hold normal and tangent information respectively.

The first part of the process involves filling the render targets with the position, normal, and tangent information from the base pose. Then for any morph targets that need to be added, the following occurs:

  • The alpha blending mode is set to additive blending
  • The viewport is set to the exact size of the pos, norm, and tangent render targets
  • A quad covering only the pixels in the render target that will change for the given morph target is drawn
  • This quad is drawn with the morph target position, normal, and tangent texture bound as a textured2darray
  • A special Geometry Shader replicates the quad three times and sends one to each render target
  • The Pixel Shader sets the output alpha to the blend amount. The blend amount is the amount of influence this morph target should have in the final image.

Effectively, the above uses the alpha blending hardware of the GPU to add up a series of sparse morph targets to a base mesh. The position, normal, and tangent render targets now contain the vertex data of the final deformed mesh. These are bound as inputs to the technique that renders the final morphed mesh onscreen.

Rendering

The input vertex stream contains a vertex reference that tells the VSRefScenemain shader which texel in the position, normal, and tangent maps contains our vertex data. In the shader, the uiVertexRef is converted to a 2D texture coordinate. The position, normal, and tangent data is then loaded from textures and transformed as they would be as if they had been passed in via the vertex stream.

    //find out which texel holds our data
    uint iYCoord = input.uiVertexRef / g_DataTexSize;
    //workaround for modulus
    uint iXCoord = input.uiVertexRef - (input.uiVertexRef/g_DataTexSize)*g_DataTexSize;
    float4 dataTexcoord = float4( iXCoord, iYCoord, 0, 0 );
    dataTexcoord += float4(0.5,0.5,0,0);
    dataTexcoord.x /= (float)g_DataTexSize;
    dataTexcoord.y /= (float)g_DataTexSize;

    ...

    //find our position, normal, and tangent
    float3 pos = tex2Darraylod( g_samPointClamp, g_txVertData, dataTexcoord ).xyz;
    dataTexcoord.z = 1.0f;
    float3 norm = tex2Darraylod( g_samPointClamp, g_txVertData, dataTexcoord ).xyz;
    dataTexcoord.z = 2.0f;
    float3 tangent = tex2Darraylod( g_samPointClamp, g_txVertData, dataTexcoord ).xyz;

    //output our final positions in clipspace
    output.pos = mul( float4( pos, 1 ), g_mWorldViewProj );

Adding a Simple Wrinkle Model

To add a bit of realism the sample uses a simple wrinkle model to modulate the influence of the normal map in the final rendered image. When rendering the final morphed image, the Geometry Shader calculates the difference between the triangle areas of the base mesh and the triangle areas of the current morphed mesh. These differences are used to determine whether the triangle grew or shrank during the deformation. If it shrank, the influence of the normal map increases. If it grew, the influence of the normal map decreases.

Adding Illumination Using LDPRT

Local Deformable Precomputed Radiance Transfer is used to light the head. The PRT simulation is done on the base mesh and the 4th order LDPRT coefficients are saves to a .ldprt file. The sample loads this file into memory and merges it with the vertex buffer at load time. The bulk of the LDPRT lighting calculations are handled by GetLDPRTColor. The current implementation only uses 4th order coefficients. However, uncommenting the last half of GetLDPRTColor, re-running the PRT simulation to generate 6th order coefficients, and changing dwOrder to 6 in UpdateLightingEnvironment may give a better lighting approximation for less convex meshes.

For a more detailed explanation of Local Deformable Precomputed Radiance Transfer, refer to the Direct3D 9 LocalDeformablePRT sample or the PRTDemo sample.


Direct3D 10 Reference

The Direct3D 10 API is described in the following sections:

Direct3D reference
D3DX reference
HLSL reference
DXGI reference
DXUT reference


Direct3D Reference

This section contains the following sections:

  • Core Reference
  • Resource Reference
  • Shader Reference
  • Effect Reference
  • Direct3D 10 Return Codes


Core Reference

The Direct3D API defines several core API elements.

  • Core Interfaces
  • Core Functions
  • Core Structures
  • Core Enumerations

See Also

Direct3D Reference


Core Interfaces

This section contains information about the following core interfaces:

Figure 1. D3D10 Core State Interface Inheritance Tree

Interfaces | Description
ID3D10BlendState Interface |
ID3D10DepthStencilState Interface |
ID3D10GeometryShader Interface |
ID3D10InputLayout Interface |
ID3D10PixelShader Interface |
ID3D10RasterizerState Interface |
ID3D10SamplerState Interface |
ID3D10VertexShader Interface |

Figure 2. D3D10 Core Other Interfaces Inheritance Tree

Interfaces | Description
ID3D10Asynchronous Interface |
ID3D10Blob Interface |
ID3D10Counter Interface |
ID3D10Debug Interface |
ID3D10Device Interface |
ID3D10DeviceChild Interface |
ID3D10Include Interface |
ID3D10InfoQueue Interface |
ID3D10Multithread Interface |
ID3D10Predicate Interface |
ID3D10Query Interface |
ID3D10StateBlock Interface |
ID3D10SwitchToRef Interface |

See Also

Core Reference


ID3D10Asynchronous Interface

This interface encapsulates methods for retrieving data from the GPU asynchronously.

Methods | Description
ID3D10Asynchronous::Begin | Mark the beginning of a series of commands.
ID3D10Asynchronous::End | Mark the end of a series of commands.
ID3D10Asynchronous::GetData | Get data from the GPU asynchronously.
ID3D10Asynchronous::GetDataSize | Get the size of the data (in bytes) that is output when calling ID3D10Asynchronous::GetData.

There are three types of asynchronous interfaces, all of which inherit this interface:

  • ID3D10Query Interface - Queries information from the GPU.
  • ID3D10Predicate Interface - Determines whether a piece of geometry should be processed or not depending on the results of a previous draw call.
  • ID3D10Counter Interface - Measures GPU performance.

See Also

Core Interfaces


ID3D10Asynchronous::Begin

Mark the beginning of a series of commands.

void Begin();

Parameters

None.

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Asynchronous Interface


ID3D10Asynchronous::End

Mark the end of a series of commands.

void End();

Parameters

None.

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Asynchronous Interface


ID3D10Asynchronous::GetData

Get data from the GPU asynchronously.

HRESULT GetData(
  void *pData,
  UINT DataSize,
  UINT GetDataFlags
);

Parameters

pData
[out] Address of memory that will receive the data. If NULL, GetData will be used only to check status, see remarks. The type of data output will depend on the type of asynchronous interface. See remarks.
DataSize
[in] Size of the data to retrieve or 0. This value can be obtained with ID3D10Asynchronous::GetDataSize. Must be 0 when pData is NULL.
GetDataFlags
[in] Optional flags. Can be 0 or any combination of D3D10_ASYNC_GETDATA_ flags.

Return Values

If this function succeeds, it will return S_OK. Otherwise, possible return values are: S_FALSE, DXGI_ERROR_DEVICE_REMOVED, or DXGI_ERROR_INVALID_CALL.

Remarks

If DataSize is 0, GetData will only be used to check status where a return value of S_OK indicates that data is available to give to an application, and a return value of S_FALSE indicates data is not yet available.

It is invalid to invoke this API on a predicate created with the D3D10_QUERY_MISCFLAG_PREDICATEHINT flag.

If the asynchronous interface that calls this API is an ID3D10Query Interface, then the following applies:

Query Type | Output Data Type | Supports Begin Method
EVENT | BOOL | NO
OCCLUSION | UINT64 | YES
TIMESTAMP | UINT64 | NO
TIMESTAMP_DISJOINT | QUERYDATA_TIMESTAMP_DISJOINT | YES
PIPELINE_STATISTICS | QUERYDATA_PIPELINE_STATISTICS | YES
OCCLUSION_PREDICATE | BOOL | YES
SO_STATISTICS | QUERYDATA_SO_STATISTICS | YES
SO_OVERFLOW_PREDICATE | BOOL | YES

If the asynchronous interface that calls this API is an ID3D10Counter Interface, then the following applies:

Counter Type | Output Data Type | Units
GPU_IDLE | FLOAT32 | fraction of time
VERTEX_PROCESSING | FLOAT32 | fraction of time
GEOMETRY_PROCESSING | FLOAT32 | fraction of time
PIXEL_PROCESSING | FLOAT32 | fraction of time
OTHER_GPU_PROCESSING | FLOAT32 | fraction of time
HOST_ADAPTER_BANDWIDTH_UTILIZATION | FLOAT32 | fraction of theoretical maximum
LOCAL_VIDMEM_BANDWIDTH_UTILIZATION | FLOAT32 | fraction of theoretical maximum
VERTEX_THROUGHPUT_UTILIZATION | FLOAT32 | fraction of theoretical maximum
TRISETUP_THROUGHPUT_UTILIZATION | FLOAT32 | fraction of theoretical maximum
FILLRATE_THROUGHPUT_UTILIZATION | FLOAT32 | fraction of theoretical maximum
VERTEXSHADER_MEMORY_LIMITED | FLOAT32 | fraction of time
VERTEXSHADER_COMPUTATION_LIMITED | FLOAT32 | fraction of time
GEOMETRYSHADER_MEMORY_LIMITED | FLOAT32 | fraction of time
GEOMETRYSHADER_COMPUTATION_LIMITED | FLOAT32 | fraction of time
PIXELSHADER_MEMORY_LIMITED | FLOAT32 | fraction of time
PIXELSHADER_COMPUTATION_LIMITED | FLOAT32 | fraction of time
POST_TRANSFORM_CACHE_HIT_RATE | FLOAT32 | fraction
TEXTURE_CACHE_HIT_RATE | FLOAT32 | fraction

The value returned by a GPU_IDLE, VERTEX_PROCESSING, GEOMETRY_PROCESSING, PIXEL_PROCESSING, or OTHER_GPU_PROCESSING counter may be different depending on the number of parallel counters that exist on a video card, and those values can be interpreted with the following equation:

The value of NumDetectableParallelUnits can be retrieved with ID3D10Device::CheckCounterInfo.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Asynchronous Interface


ID3D10Asynchronous::GetDataSize

Get the size of the data (in bytes) that is output when calling ID3D10Asynchronous::GetData.

UINT GetDataSize();

Parameters

None.

Return Values

Size of the data (in bytes) that is output when calling GetData.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Asynchronous Interface


ID3D10BlendState Interface

A blend-state interface manages the blend state for the output-merger stage. This interface contains the methods shown in the following table.

Methods | Description
ID3D10BlendState::GetDesc | Get the blend state.

Blending combines two pixel values. You have control over how the pixels are blended by using a predefined set of blending operations, as well as preblending operations. The Blending Block Diagram shows conceptually how blending works.

To create a blend-state interface, call ID3D10Device::CreateBlendState. To initialize the blend state, call ID3D10Device::OMSetBlendState.

See Also

Core Interfaces


ID3D10BlendState::GetDesc

Get the blend state.

void GetDesc(
  D3D10_BLEND_DESC *pDesc
);

Parameters

pDesc
[out] A pointer to the blend state (see D3D10_BLEND_DESC).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10BlendState Interface


ID3D10Blob Interface

Used to return arbitrary length data.

ID3D10Blob Members

Method | Description
ID3D10Blob::GetBufferPointer | Gets a pointer to the data.
ID3D10Blob::GetBufferSize | Gets the size.

Remarks

An ID3D10Blob Interface is obtained by calling D3D10CreateBlob.

Blobs can be used as a data buffer, storing vertex, adjacency, and material information during mesh optimization and loading operations. Also, these objects are used to return object code and error messages in APIs that compile vertex, geometry and pixel shaders.

Requirements

Header: Declared in D3D10Shader.h.

Library: Use D3D10shader.lib.

See Also

Core Interfaces


ID3D10Blob::GetBufferPointer

Get a pointer to the data.

LPVOID GetBufferPointer();

Parameters

None.

Return Values

Returns a pointer.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10Blob Interface


ID3D10Blob::GetBufferSize

Get the size.

SIZE_T GetBufferSize();

Parameters

None.

Return Values

The size of the data, in bytes.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10Blob Interface


ID3D10Counter Interface

This interface encapsulates methods for measuring GPU performance.

Methods | Description
ID3D10Counter::GetDesc | Get a counter description.

A counter can be created with ID3D10Device::CreateCounter.

This is a derived class of ID3D10Asynchronous Interface.

Counter data is gathered by issuing an ID3D10Asynchronous::Begin command, issuing some graphics commands, issuing an ID3D10Asynchronous::End command, and then calling ID3D10Asynchronous::GetData to get data about what happened in between the Begin and End calls. The data returned by GetData will be different depending on the type of counter. The call to End causes the data returned by GetData to be accurate up until the last call to End.

Counters are best suited for profiling.

For a list of the types of performance counters, see D3D10_COUNTER.

See Also

Core Interfaces


ID3D10Counter::GetDesc

Get a counter description.

void GetDesc(
  D3D10_COUNTER_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a counter description (see D3D10_COUNTER_DESC).

Return Values

Returns nothing.

Requirements

Header: Declared in D3d10core.

See Also

ID3D10Counter Interface


ID3D10Debug Interface

A debug interface controls debug settings, validates pipeline state and can only be used if the debug layer is turned on. This interface contains methods shown in the following table.

Methods | Description
ID3D10Debug::GetFeatureMask | Get a bitfield of flags that indicates which debug features are on or off.
ID3D10Debug::GetPresentPerRenderOpDelay | Get the number of milliseconds to sleep after IDXGISwapChain::Present is called.
ID3D10Debug::GetSwapChain | Get the swap chain that the runtime will use for automatically calling IDXGISwapChain::Present.
ID3D10Debug::SetFeatureMask | Set a bitfield of flags that will turn debug features on and off.
ID3D10Debug::SetPresentPerRenderOpDelay | Set the number of milliseconds to sleep after IDXGISwapChain::Present is called.
ID3D10Debug::SetSwapChain | Set a swap chain that the runtime will use for automatically calling IDXGISwapChain::Present.
ID3D10Debug::Validate | Check the validity of pipeline state.

Remarks

This interface is obtained by querying it from the ID3D10Device Interface using IUnknown::QueryInterface.

See Also

Core Interfaces


ID3D10Debug::GetFeatureMask

Get a bitfield of flags that indicates which debug features are on or off.

UINT GetFeatureMask();

Parameters

None.

Return Values

Mask of feature-mask flags bitwise ORed together. If a flag is present, then that feature will be set to on, otherwise the feature will be set to off. See ID3D10Debug::SetFeatureMask for a list of possible feature-mask flags.

Requirements

Header: Declared in D3D10SDKLayers.h.

See Also

ID3D10Debug Interface


ID3D10Debug::GetPresentPerRenderOpDelay

Get the number of milliseconds to sleep after IDXGISwapChain::Present is called.

UINT GetPresentPerRenderOpDelay();

Parameters

None.

Return Values

Number of milliseconds to sleep after Present is called.

Remarks

Value is set with ID3D10Debug::SetPresentPerRenderOpDelay.

Requirements

Header: Declared in D3D10SDKLayers.h.

See Also

ID3D10Debug Interface


ID3D10Debug::GetSwapChain

Get the swap chain that the runtime will use for automatically calling IDXGISwapChain::Present.

HRESULT GetSwapChain(
  IDXGISwapChain **ppSwapChain
);

Parameters

ppSwapChain
[out] Swap chain that the runtime will use for automatically calling IDXGISwapChain::Present.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

The swap chain retrieved by this method will only be used if D3D10_DEBUG_FEATURE_PRESENT_PER_RENDER_OP is set in the feature mask.

Requirements

Header: Declared in D3D10SDKLayers.h.

See Also

ID3D10Debug Interface


ID3D10Debug::SetFeatureMask

Set a bitfield of flags that will turn debug features on and off.

HRESULT SetFeatureMask(
  UINT Mask
);

Parameters

Mask
[in] Feature-mask flags bitwise ORed together. If a flag is present, then that feature will be set to on, otherwise the feature will be set to off. See remarks for a list of flags.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

Setting a feature-mask flag will cause a rendering-operation method (listed below) to do some extra task when called. The possible feature flags are:

D3D10_DEBUG_FEATURE_FINISH_PER_RENDER_OP | Application will wait for the GPU to finish processing the rendering operation before continuing.
D3D10_DEBUG_FEATURE_FLUSH_PER_RENDER_OP | Runtime will additionally call ID3D10Device::Flush.
D3D10_DEBUG_FEATURE_PRESENT_PER_RENDER_OP | Runtime will call IDXGISwapChain::Present. Setting this feature also enables the ID3D10Debug::SetSwapChain and ID3D10Debug::SetPresentPerRenderOpDelay functionality.

These feature-mask flags apply to the following rendering-operation methods:

  • ID3D10Device::Draw
  • ID3D10Device::DrawIndexed
  • ID3D10Device::DrawInstanced
  • ID3D10Device::DrawIndexedInstanced
  • ID3D10Device::DrawAuto
  • ID3D10Device::ClearRenderTargetView
  • ID3D10Device::ClearDepthStencilView
  • ID3D10Device::CopySubresourceRegion
  • ID3D10Device::CopyResource
  • ID3D10Device::UpdateSubresource
  • ID3D10Device::GenerateMips
  • ID3D10Device::ResolveSubresource

Requirements

Header: Declared in D3D10SDKLayers.h.

See Also

ID3D10Debug Interface


ID3D10Debug::SetPresentPerRenderOpDelay

Set the number of milliseconds to sleep after IDXGISwapChain::Present is called.

HRESULT SetPresentPerRenderOpDelay(
  UINT Milliseconds
);

Parameters

Milliseconds
[in] Number of milliseconds to sleep after Present is called.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

The application will only sleep if D3D10_DEBUG_FEATURE_PRESENT_PER_RENDER_OP is a set in the feature mask. If that flag is not set the number of milliseconds is set but ignored and the application does not sleep. 10ms is used as a default value if this method is never called.

Requirements

Header: Declared in D3D10SDKLayers.h.

See Also

ID3D10Debug Interface


ID3D10Debug::SetSwapChain

Set a swap chain that the runtime will use for automatically calling IDXGISwapChain::Present.

HRESULT SetSwapChain(
  IDXGISwapChain *pSwapChain
);

Parameters

pSwapChain
[in] Swap chain that the runtime will use for automatically calling IDXGISwapChain::Present; must have been created with the DXGI_SWAP_EFFECT_SEQUENTIAL swap-effect flag.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

The swap chain set by this method will only be used if D3D10_DEBUG_FEATURE_PRESENT_PER_RENDER_OP is set in the feature mask.

Requirements

Header: Declared in D3D10SDKLayers.h.

See Also

ID3D10Debug Interface


ID3D10Debug::Validate

Check the validity of pipeline state.

HRESULT Validate();

Parameters

None.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

When the debug layer is turned on all draw functions will do this operation.

Requirements

Header: Declared in D3D10SDKLayers.h.

See Also

ID3D10Debug Interface


ID3D10DepthStencilState Interface

A depth-stencil-state interface manages the state which sets up the depth-stencil test for the output-merger stage. This interface contains methods shown in the following table.

Methods | Description
ID3D10DepthStencilState::GetDesc | Get the depth-stencil state.

Create a depth-stencil state object by calling ID3D10Device::CreateDepthStencilState.

To initialize depth-stencil state, bind the depth-stencil-state object to the pipeline by calling ID3D10Device::OMSetDepthStencilState.

See Also

Core Interfaces


ID3D10DepthStencilState::GetDesc

Get the depth-stencil state.

void GetDesc(
  D3D10_DEPTH_STENCIL_DESC *pDesc
);

Parameters

pDesc
[out] A pointer to the depth-stencil state (see D3D10_DEPTH_STENCIL_DESC).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10DepthStencilState Interface


ID3D10Device Interface

Used to perform DrawPrimitive-based rendering, create resources, work with system-level variables, and create shaders.

ID3D10Device Members

Method | Description
ID3D10Device::CheckCounter | Get the type, name, units of measure, and a description of an existing counter.
ID3D10Device::CheckCounterInfo | Get the counter's information.
ID3D10Device::CheckFormatSupport | Get the capabilities of a given format on the installed video device.
ID3D10Device::CheckMultisampleQualityLevels | Get the quality level of a particular multisample.
ID3D10Device::ClearDepthStencilView | Clears the depth stencil.
ID3D10Device::ClearRenderTargetView | Make a rendertarget all one color.
ID3D10Device::ClearState |
ID3D10Device::CopyResource | Copy the contents of one resource to another using the GPU.
ID3D10Device::CopySubresourceRegion | Copy a subresource to a region of another subresource using the GPU.
ID3D10Device::CreateBlendState | Create a blend state interface.
ID3D10Device::CreateBuffer | Create a buffer for storing data.
ID3D10Device::CreateCounter | Create a counter interface.
ID3D10Device::CreateDepthStencilState | Create a depth stencil state interface.
ID3D10Device::CreateDepthStencilView | Create a depth stencil view.
ID3D10Device::CreateGeometryShader | Create a geometry shader.
ID3D10Device::CreateGeometryShaderWithStreamOutput | Create a geometry shader with streaming output buffers.
ID3D10Device::CreateInputLayout | Create an input layout.
ID3D10Device::CreatePixelShader | Create a pixel shader.
ID3D10Device::CreatePredicate | Creates a predicate interface.
ID3D10Device::CreateQuery | Creates a query interface.
ID3D10Device::CreateRasterizerState | Create a rasterizer state object.
ID3D10Device::CreateRenderTargetView | Create a rendertarget view.
ID3D10Device::CreateSamplerState | Create a sampler state.
ID3D10Device::CreateShaderResourceView | Create a shader resource view.
ID3D10Device::CreateTexture1D | Create a 1D texture.
ID3D10Device::CreateTexture2D | Create a 2D texture.
ID3D10Device::CreateTexture3D | Create a 3D texture.
ID3D10Device::CreateVertexShader | Create a vertex shader.
ID3D10Device::Draw | Draw to screen using the vertex buffers currently set to the device.
ID3D10Device::DrawAuto | Draw to an input buffer using streaming output.
ID3D10Device::DrawIndexed | Draw to screen using the index and vertex buffers currently set to the device.
ID3D10Device::DrawIndexedInstanced | Draw several instances of the same object defined by index buffers.
ID3D10Device::DrawInstanced | Draw several instances of the same object defined by vertex buffers.
ID3D10Device::Flush | Send the commands in the command buffer to the GPU.
ID3D10Device::GenerateMips | Generates mipmaps for the given shader resource.
ID3D10Device::GetCreationFlags | Get the device's creation flags.
ID3D10Device::GetDeviceRemovedReason | Get the reason why the device was removed.
ID3D10Device::GetExceptionMode | Gets the exception mode.
ID3D10Device::GetPredication | Get the device's primitive rendering predicate.
ID3D10DeviceChild::GetPrivateData | Get the data set by ID3D10DeviceChild::SetPrivateData. Similar to IDXGIObject::GetPrivateData.
ID3D10Device::GetTextFilterSize | TBD
ID3D10Device::GSGetConstantBuffers | Get the geometry shader's constant buffers.
ID3D10Device::GSGetSamplers | Get the geometry shader's samplers.
ID3D10Device::GSGetShader | Get the geometry shader currently set on the device.
ID3D10Device::GSGetShaderResources | Get the geometry shader resources.
ID3D10Device::GSSetConstantBuffers | Set the geometry shader constant buffers.
ID3D10Device::GSSetSamplers | Set the geometry shader's samplers.
ID3D10Device::GSSetShader | Set the geometry shader to the device.
ID3D10Device::GSSetShaderResources | Set the geometry shader's resources.
ID3D10Device::IAGetIndexBuffer | Get an index buffer currently set to the device.
ID3D10Device::IAGetInputLayout | Get the input layout currently set on the device.
ID3D10Device::IAGetPrimitiveTopology | Get the primitive topology currently set on the device.
ID3D10Device::IAGetVertexBuffers | Get the vertex buffer currently set on the device.
ID3D10Device::IASetIndexBuffer | Set an index buffer to the device.
ID3D10Device::IASetInputLayout | Set the input layout onto the device.
ID3D10Device::IASetPrimitiveTopology | Set the primitive topology to the device.
ID3D10Device::IASetVertexBuffers | Set vertex buffers to the device.
ID3D10Device::OMGetBlendState | Get the blend state currently set on the device.
ID3D10Device::OMGetDepthStencilState | Get the depth stencil state currently set on the device.
ID3D10Device::OMGetRenderTargets | Get the rendertargets.
ID3D10Device::OMSetBlendState | Set the blend state on the device.
ID3D10Device::OMSetDepthStencilState | Set the depth stencil state on the device.
ID3D10Device::OMSetRenderTargets | Set the rendertargets.
ID3D10Device::OpenSharedResource |
ID3D10Device::PSGetConstantBuffers | Get the pixel shader's constant buffers.
ID3D10Device::PSGetSamplers | Get the pixel shader's samplers.
ID3D10Device::PSGetShader | Get the pixel shader currently set on the device.
ID3D10Device::PSGetShaderResources | Get the pixel shader resources.
ID3D10Device::PSSetConstantBuffers | Set the pixel shader constant buffers.
ID3D10Device::PSSetSamplers | Set the pixel shader's samplers.
ID3D10Device::PSSetShader | Sets the pixel shader to the device.
ID3D10Device::PSSetShaderResources | Set the pixel shader's resources.
ID3D10Device::ResolveSubresource |
ID3D10Device::RSGetScissorRects | Get the scissor rects currently set to the rasterizer.
ID3D10Device::RSGetState | Get the rasterizer state currently set on the device.
ID3D10Device::RSGetViewports | Get the viewports.
ID3D10Device::RSSetScissorRects | Set the scissor rects.
ID3D10Device::RSSetState | Set the rasterizer state to the device.
ID3D10Device::RSSetViewports | Set the viewports to the rasterizer.
ID3D10Device::SetExceptionMode | Set the exception mode.
ID3D10Device::SetPredication | Set a rendering predicate to the device.
ID3D10Device::SetPrivateData | Copy data and associate the copy with a guid. Similar to IDXGIObject::SetPrivateData.
ID3D10DeviceChild::SetPrivateDataInterface | Copy data from an IUnknown to the device and associate the copy with a guid. Similar to IDXGIObject::SetPrivateDataInterface.
ID3D10Device::SetTextFilterSize | TBD
ID3D10Device::SOGetTargets | Get the target output buffers.
ID3D10Device::SOSetTargets | Set the target output buffers.
ID3D10Device::UpdateSubresource | Update the data inside a resource's subresource.
ID3D10Device::VSGetConstantBuffers | Get the vertex shader's constant buffers.
ID3D10Device::VSGetSamplers | Get the vertex shader's samplers.
ID3D10Device::VSGetShader | Get the vertex shader currently set on the device.
ID3D10Device::VSGetShaderResources | Get the vertex shader resources.
ID3D10Device::VSSetConstantBuffers | Set the vertex shader constant buffers.
ID3D10Device::VSSetSamplers | Set the vertex shader's samplers.
ID3D10Device::VSSetShader | Set the vertex shader to the device.
ID3D10Device::VSSetShaderResources | Set the vertex shader's resources.

Remarks

A device is created using D3D10CreateDevice.

See Also

Core Interfaces


ID3D10Device::CheckCounter

Get the type, name, units of measure, and a description of an existing counter.

HRESULT CheckCounter(
  const D3D10_COUNTER_DESC *pDesc,
  D3D10_COUNTER_TYPE *pType,
  UINT *pActiveCounters,
  LPSTR szName,
  UINT *pNameLength,
  LPSTR szUnits,
  UINT *pUnitsLength,
  LPSTR szDescription,
  UINT *pDescriptionLength
);

Parameters

pDesc
[in] Pointer to a counter description (see D3D10_COUNTER_DESC). Specifies which counter information is to be retrieved about.
pType
[out] Pointer to the data type of a counter (see D3D10_COUNTER_TYPE). Specifies the data type of the counter being retrieved.
pActiveCounters
[out] Pointer to the number of hardware counters that are needed for this counter type to be created. All instances of the same counter type use the same hardware counters.
szName
[out] String to be filled with a brief name for the counter. May be NULL if the application is not interested in the name of the counter.
pNameLength
[in, out] Length of the string returned to szName. Can be NULL.
szUnits
[out] Name of the units a counter measures, provided the memory the pointer points to has enough room to hold the string. Can be NULL. The returned string will always be in English.
pUnitsLength
[in, out] Length of the string returned to szUnits. Can be NULL.
szDescription
[out] A description of the counter, provided the memory the pointer points to has enough room to hold the string. Can be NULL. The returned string will always be in English.
pDescriptionLength
[in, out] Length of the string returned to szDescription. Can be NULL.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

Length parameters can be NULL, which indicates the application is not interested in the length nor the corresponding string value. When a length parameter is non-NULL and the corresponding string is NULL, the input value of the length parameter is ignored, and the length of the corresponding string (including terminating NULL) will be returned through the length parameter. When length and the corresponding parameter are both non-NULL, the input value of length is checked to ensure there is enough room, and then the length of the string (including terminating NULL character) is passed out through the length parameter.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CheckCounterInfo

Get a counter's information.

void CheckCounterInfo(
  D3D10_COUNTER_INFO *pCounterInfo
);

Parameters

pCounterInfo
[out] Pointer to counter information (see D3D10_COUNTER_INFO).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CheckFormatSupport

Get the support of a given format on the installed video device.

HRESULT CheckFormatSupport(
  DXGI_FORMAT Format,
  UINT *pFormatSupport
);

Parameters

Format
[in] The format we are checking support for.
pFormatSupport
[out] A bitfield describing the support of Format on the installed device. See D3D10_FORMAT_SUPPORT. The enum values are ORed together.

Return Values

If this function succeeds, it will return S_OK. If it fails, possible return values are: E_INVALIDARG if Format is NULL or E_FAIL if Format does not exist.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CheckMultisampleQualityLevels

Get the number of quality levels available during multisampling.

HRESULT CheckMultisampleQualityLevels(
  DXGI_FORMAT Format,
  UINT SampleCount,
  UINT *pNumQualityLevels
);

Parameters

Format
[in] The texture format. See DXGI_FORMAT.
SampleCount
[in] The number of samples during multisampling.
pNumQualityLevels
[out] Number of quality levels supported by the adapter. See remarks.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

When multisampling a texture, the number of quality levels available for an adapter is dependent on the texture format used and the number of samples requested. The maximum number of quality levels is defined by D3D10_MAX_MULTISAMPLE_SAMPLE_COUNT in d3d10.h. If this method returns 0, the format and sample count combination is not supported for the installed adapter.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::ClearDepthStencilView

Clears the depth-stencil resource.

void ClearDepthStencilView(
  ID3D10DepthStencilView *pDepthStencilView,
  UINT ClearFlags,
  FLOAT Depth,
  UINT8 Stencil
);

Parameters

pDepthStencilView
[in] Pointer to the depth stencil to be cleared.
ClearFlags
[in] Which parts of the buffer to clear. See D3D10_CLEAR_FLAG.
Depth
[in] Clear the depth buffer with this value. This value will be clamped between 0 and 1.
Stencil
[in] Clear the stencil buffer with this value.

Return Values

Returns nothing.

Remarks

Differences between Direct3D 9 and Direct3D 10:

Unlike Direct3D 9, the full extent of the resource view is always cleared. Viewport and scissor settings are not applied.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::ClearRenderTargetView

Set all the elements in a render target to one value.

void ClearRenderTargetView(
  ID3D10RenderTargetView *pRenderTargetView,
  const FLOAT ColorRGBA[4]
);

Parameters

pRenderTargetView
[in] Pointer to the rendertarget.
ColorRGBA
[in] A 4-component array that represents the color to fill the render target with.

Return Values

Returns nothing.

Remarks

Applications that wish to clear a render target to a specific integer value bit pattern should render a screen-aligned quad instead of using this method. The reason for this is because this method accepts as input a floating point value, which may not have the same bit pattern as the original integer.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::ClearState

Restore all default device settings; return the device to the state it was in when it was created. This will set all set all input/output resource slots, shaders, input layouts, predications, scissor rectangles, depth-stencil state, rasterizer state, blend state, sampler state, and viewports to NULL. The primitive topology will be set to UNDEFINED.

void ClearState();

Parameters

None.

Return Values

Returns nothing.

Requirements

Header: Declared in D3d10core.

See Also

ID3D10Device Interface


ID3D10Device::CopyResource

Copy the entire contents of the source resource to the destination resource using the GPU.

void CopyResource(
  ID3D10Resource *pDstResource,
  ID3D10Resource *pSrcResource
);

Parameters

pDstResource
[in] A pointer to the destination resource (see ID3D10Resource).
pSrcResource
[in] A pointer to the source resource (see ID3D10Resource).

Return Values

Returns nothing

Remarks

This method is unusual in that it causes the GPU to perform the copy operation (similar to a memcpy by the CPU). As a result, it has a few restrictions designed for improving performance. For instance, the source and destination resources:

  • Must be different resources.
  • Must be the same type.
  • Must have identical dimensions (including width, height, depth, and size as appropriate).
  • Will only be copied. CopyResource does not support any stretch, color key, blend, or format conversions.
  • Must have compatible formats, which means the formats must be identical or at least from the same type group. For example, a DXGI_FORMAT_R32G32B32_FLOAT texture can be copied to an DXGI_FORMAT_R32G32B32_UINT texture since both of these formats are in the DXGI_FORMAT_R32G32B32_TYPELESS group.
  • May not be currently mapped.

Depth-stencil, and immutable resources cannot be used as a destination. Resources created with multisampling capability cannot be used as either a source or destination.

The method is an asynchronous call which may be added to the command-buffer queue. This attempts to remove pipeline stalls that may occur when copying data. See performance considerations for more details.

An application that only needs to copy a portion of the data in a resource should use ID3D10Device::CopySubresourceRegion instead.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Resource Interface


ID3D10Device::CopySubresourceRegion

Copy a portion of a source subresource to a destination subresource. The source is specified by a rectangular region.

void CopySubresourceRegion(
  ID3D10Resource *pDstResource,
  UINT DstSubresource,
  UINT DstX,
  UINT DstY,
  UINT DstZ,
  ID3D10Resource *pSrcResource,
  UINT SrcSubresource,
  const D3D10_BOX *pSrcBox
);

Parameters

pDstResource
[in] A pointer to the destination resource (see ID3D10Resource).
DstSubresource
[in] A zero-based index, that identifies the destination subresource. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.
DstX
[in] The offset (x coordinate) for the placement of the source box in the destination resource. See remarks.
DstY
[in] The offset (y coordinate) for the placement of the source box in the destination resource. See remarks. For 1D subresources, this must be zero.
DstZ
[in] The offset (z coordinate) for the placement of the source box in the destination resource. See remarks. For 1D or 2D subresources, this must be zero.
pSrcResource
[in] A pointer to the source resource (see ID3D10Resource).
SrcSubresource
[in] Index of the source subresource.
pSrcBox
[in] The region of the source subresource to copy. If NULL, the entire source subresource is copied. The dimensions of box must fit within the source subresource (see D3D10_BOX).

Return Values

Returns nothing

Remarks

The source box dimensions must be less than or equal to the dimensions of the source subresource. The destination offset, (x, y, z) allows the source data to be offset into the destination resource; however, the dimensions of the source box (with offset) must be less than or equal to the dimensions of the destination subresource.

If the source and destination resources are buffers, all coordinates are in bytes, however, if the source and destination resources are textures, all coordinates are in texels. For example, the following code snippet shows how to copy a region in a 2D texture to a different location in another 2D texture. Assume the source and destination textures are both 512x512 textures and the operation will copy the data in [(120,100)..(200,220)] from the source texture to location (10,20) in the destination texture. Front and back are set to 0 and 1 respectively, because by having front equal to back, the box is technically empty.

D3D10_BOX sourceRegion;
box.left = 120;
box.right = 200;
box.top = 100;
box.bottom = 220;
box.front = 0;
box.back = 1;

pd3dDevice->CopySubresourceRegion( pDestTexture, 0, 10, 20, 0, pSourceTexture, 0, &sourceRegion );

This method is unusual in that it causes the GPU to perform the copy operation (similar to a memcpy by the CPU). As a result, it has a few restrictions designed for improving performance. For instance, the source and destination resources:

  • Must be different subresources (note that the subresources can come from the same resource).
  • Must be the same type.
  • Need not be of equal size; however, the source and destination regions must fit entirely within the subresources..
  • Will only be copied. CopyResource does not support any stretch, color key, blend, or format conversions.
  • Must have compatible formats, which means the formats must be identical or at least from the same type group. For example, a DXGI_FORMAT_R32G32B32_FLOAT texture can be copied to an DXGI_FORMAT_R32G32B32_UINT texture since both of these formats are in the DXGI_FORMAT_R32G32B32_TYPELESS group.
  • May not be currently mapped.

Depth-stencil, and immutable resources cannot be used as a destination. Resources created with multisampling capability cannot be used as either a source or destination.

The method is an asynchronous call which may be added to the command-buffer queue. This attempts to remove pipeline stalls that may occur when copying data. See performance considerations for more details.

An application that needs to copy an entire resource should use ID3D10Device::CopyResource instead.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Resource Interface


ID3D10Device::CreateBlendState

Create a blend-state object that encapsules blend state for the output-merger stage.

HRESULT CreateBlendState(
  const D3D10_BLEND_DESC *pBlendStateDesc,
  ID3D10BlendState **ppBlendState
);

Parameters

pBlendStateDesc
[in] Pointer to a blend-state description (see D3D10_BLEND_DESC).
ppBlendState
[out] Address of a pointer to the blend-state object created (see ID3D10BlendState Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

An application can create up to 4096 unique blend-state objects. For each object created, the runtime checks to see if a previous object has the same state. If such a previous object exists, the runtime will return a pointer to previous instance instead of creating a duplicate object.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateBuffer

Create a buffer resource.

HRESULT CreateBuffer(
  const D3D10_BUFFER_DESC *pDesc,
  const D3D10_SUBRESOURCE_DATA *pInitialData,
  ID3D10Buffer **ppBuffer
);

Parameters

pDesc
[in] Pointer to a buffer description (see D3D10_BUFFER_DESC).
pInitialData
[in] Pointer to a buffer subresource description (see D3D10_SUBRESOURCE_DATA). Among other information, the subresource description contains a pointer to the initial resource data. This parameter may be NULL if you are allocating space for a resource that will have data stored in it later (perhaps the data does not exist yet). See remarks.
ppBuffer
[out] Address of a pointer to the buffer created (see ID3D10Buffer Interface). Set this parameter to NULL to validate the other input parameters (the method will return S_FALSE if the other input parameters pass validation).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

All Direct3D resources are derived from the buffer or the texture resource types; this API creates a buffer resource. Examples of buffer resources used by the pipeline include: vertex buffers, index buffers, and constant buffers.

Using Index Buffers with Line Strips or Triangle Strips

Multiple line or triangle strips can be defined in a single index buffer. Setting an index to the maximum possible value (0xffff for a 16-bit index, 0xffffffff for a 32-bit index) indicates the end of one strip and the beginning of another strip.

Figure 1. Index Buffer Defining Two Triangle Strips

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateCounter

Create a counter object for measuring GPU performance.

HRESULT CreateCounter(
  const D3D10_COUNTER_DESC *pCounterDesc,
  ID3D10Counter **ppCounter
);

Parameters

pCounterDesc
[in] Pointer to a counter description (see D3D10_COUNTER_DESC).
ppCounter
[out] Address of a pointer to a counter (see ID3D10Counter Interface).

Return Values

If this function succeeds, it will return S_OK. If it fails, possible return values are: S_FALSE, E_OUTOFMEMORY, DXGI_ERROR_UNSUPPORTED, DXGI_ERROR_NONEXCLUSIVE, or E_INVALIDARG.

DXGI_ERROR_UNSUPPORTED is returned whenever the application requests to create a well-known counter, but the current device does not support it.

DXGI_ERROR_NONEXCLUSIVE indicates that another device object is currently using the counters, so they cannot be used by this device at the moment.

E_INVALIDARG is returned whenever an out-of-range well-known or device-dependent counter is requested, or when the simulataneously active counters have been exhausted.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateDepthStencilState

Create a depth-stencil state object that encapsulates depth-stencil test information for the output-merger stage.

HRESULT CreateDepthStencilState(
  const D3D10_DEPTH_STENCIL_DESC *pDepthStencilDesc,
  ID3D10DepthStencilState **ppDepthStencilState
);

Parameters

pDepthStencilDesc
[in] Pointer to a depth-stencil state description (see D3D10_DEPTH_STENCIL_DESC).
ppDepthStencilState
[out] Address of a pointer to the depth-stencil state object created (see ID3D10DepthStencilState Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

4096 unique depth-stencil state objects can be created on a device at a time.

If an application attempts to create a depth-stencil state with the same description as an already existing depth-stencil state, then the same interface with an incremented reference count will be returned and the total number of unique depth-stencil state objects will stay the same.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateDepthStencilView

Create a depth-stencil view for accessing resource data.

HRESULT CreateDepthStencilView(
  ID3D10Resource *pResource,
  const D3D10_DEPTH_STENCIL_VIEW_DESC *pDesc,
  ID3D10DepthStencilView **ppDepthStencilView
);

Parameters

pResource
[in] Pointer to the resource that will serve as the depth-stencil surface. This resource must have been created with the D3D10_BIND_DEPTH_STENCIL flag.
pDesc
[in] Pointer to a depth-stencil-view description (see D3D10_DEPTH_STENCIL_VIEW_DESC). Set this parameter to NULL to create a view that accesses mipmap level 0 of the entire resource (using the format the resource was created with).
ppDepthStencilView
[out] Address of a pointer to an ID3D10DepthStencilView. Set this parameter to NULL to validate the other input parameters (the method will return S_FALSE if the other input parameters pass validation).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

A depth-stencil view can be bound to the output-merger stage by calling ID3D10Device::OMSetRenderTargets.

For more background information, see the programming guide page about depth stencils.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateGeometryShader

Create a geometry shader.

HRESULT CreateGeometryShader(
  const void *pShaderBytecode,
  SIZE_T BytecodeLength,
  ID3D10GeometryShader **ppGeometryShader
);

Parameters

pShaderBytecode
[in] A pointer to the compiled shader. To get this pointer see Getting a Pointer to a Compiled Shader.
BytecodeLength
[in] Size of the compiled geometry shader.
ppGeometryShader
[out] Address of a pointer to an ID3D10GeometryShader Interface. If this is NULL, all other parameters will be validated, and if all parameters pass validation this API will return S_FALSE instead of S_OK.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

Once created, the shader can be set to the device by calling ID3D10Device::GSSetShader.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateGeometryShaderWithStreamOutput

Create a geometry shader that can write to streaming output buffers.

HRESULT CreateGeometryShaderWithStreamOutput(
  const void *pShaderBytecode,
  SIZE_T BytecodeLength,
  const D3D10_SO_DECLARATION_ENTRY *pSODeclaration,
  UINT NumEntries,
  UINT OutputStreamStride,
  ID3D10GeometryShader **ppGeometryShader
);

Parameters

pShaderBytecode
[in] A pointer to the compiled shader. To get this pointer see Getting a Pointer to a Compiled Shader.
BytecodeLength
[in] Size of the compiled geometry shader.
pSODeclaration
[in] Pointer to a D3D10_SO_DECLARATION_ENTRY array. Cannot be NULL if NumEntries > 0.
NumEntries
[in] The number of entries in pStreamOutputDecl. Minimum 0, maximum 64.
OutputStreamStride
[in] The size of pStreamOutputDecl. This parameter is only used when the output slot is 0 for all entries in pStreamOutputDecl.
ppGeometryShader
[out] Address of a pointer to an ID3D10GeometryShader Interface. If this is NULL, all other parameters will be validated, and if all parameters pass validation this API will return S_FALSE instead of S_OK.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateInputLayout

Create an input-layout object to describe the input-buffer data for the input-assembler stage.

HRESULT CreateInputLayout(
  const D3D10_INPUT_ELEMENT_DESC *pInputElementDescs,
  UINT NumElements,
  const void *pShaderBytecodeWithInputSignature,
  SIZE_T BytecodeLength,
  ID3D10InputLayout **ppInputLayout
);

Parameters

pInputElementDescs
[in] An array of the input-assembler stage input data types; each type is described by an element description (see D3D10_INPUT_ELEMENT_DESC).
NumElements
[in] The number of input-data types in the array of input-elements.
pShaderBytecodeWithInputSignature
[in] A pointer to the compiled shader. To get this pointer see Getting a Pointer to a Compiled Shader. The compiled shader code contains a input signature which is validated against the array of elements. See remarks.
BytecodeLength
[in] Size of the compiled shader.
ppInputLayout
[out] A pointer to the input-layout object created (see ID3D10InputLayout Interface). To validate the other input parameters, set this pointer to be NULL and verify that the method returns S_FALSE.

Return Values

If the method succeeds, the return code is S_OK. See Direct3D 10 Return Codes for failing error codes.

Remarks

After creating an input layout object, it must be bound to the input-assembler stage before calling a draw API. See Getting Started with the Input-Assembler Stage (Direct3D 10) for example code.

Once an input-layout object is created from a shader signature, the input-layout object can be reused with any other shader that has an identical input signature (semantics included). This can simplify the creation of input-layout objects when you are working with many shaders with identical inputs.

Differences between Direct3D 9 and Direct3D 10:

Mapping the vertex data to the shader inputs with an input layout is a new way of doing things in Direct3D 10 that improves performance.

In Direct3D 10 the vertex data is mapped to the shader inputs when the input layout object is created, whereas in Direct3D 9 this mapping was done at Draw time based on the currently bound vertex declarations, vertex buffers, and vertex shaders. Doing this mapping when the input layout object is created reduces or eliminates extra linkage work for drivers at Draw time because this re-mapping is no longer necessary.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreatePixelShader

Create a pixel shader.

HRESULT CreatePixelShader(
  const void *pShaderBytecode,
  SIZE_T BytecodeLength,
  ID3D10PixelShader **ppPixelShader
);

Parameters

pShaderBytecode
[in] A pointer to the compiled shader. To get this pointer see Getting a Pointer to a Compiled Shader.
BytecodeLength
[in] Size of the compiled pixel shader.
ppPixelShader
[out] Address of a pointer to an ID3D10PixelShader Interface. If this is NULL, all other parameters will be validated, and if all parameters pass validation this API will return S_FALSE instead of S_OK.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

After creating the pixel shader, you can set it to the device using ID3D10Device::PSSetShader.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreatePredicate

Creates a predicate.

HRESULT CreatePredicate(
  const D3D10_QUERY_DESC *pPredicateDesc,
  ID3D10Predicate **ppPredicate
);

Parameters

pPredicateDesc
[in] Pointer to a query description where the type of query must be a D3D10_QUERY_SO_OVERFLOW_PREDICATE or D3D10_QUERY_OCCLUSION_PREDICATE (see D3D10_QUERY_DESC).
ppPredicate
[out] Address of a pointer to a predicate (see ID3D10Predicate Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateQuery

This interface encapsulates methods for querying information from the GPU.

HRESULT CreateQuery(
  const D3D10_QUERY_DESC *pQueryDesc,
  ID3D10Query **ppQuery
);

Parameters

pQueryDesc
[in] Pointer to a query description (see D3D10_QUERY_DESC).
ppQuery
[out] Address of a pointer to the query object created (see ID3D10Query Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateRasterizerState

Create a rasterizer state object that tells the rasterizer stage how to behave.

HRESULT CreateRasterizerState(
  const D3D10_RASTERIZER_DESC *pRasterizerDesc,
  ID3D10RasterizerState **ppRasterizerState
);

Parameters

pRasterizerDesc
[in] Pointer to a rasterizer state description (see D3D10_RASTERIZER_DESC).
ppRasterizerState
[out] Address of a pointer to the rasterizer state object created (see ID3D10RasterizerState Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

4096 unique rasterizer state objects can be created on a device at a time.

If an application attempts to create a rasterizer state with the same description as an already existing rasterizer state, then the same interface with an incremented reference count will be returned and the total number of unique rasterizer state objects will stay the same.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateRenderTargetView

Create a render-target view for accessing resource data.

HRESULT CreateRenderTargetView(
  ID3D10Resource *pResource,
  const D3D10_RENDER_TARGET_VIEW_DESC *pDesc,
  ID3D10RenderTargetView **ppRTView
);

Parameters

pResource
[in] Pointer to the resource that will serve as the render target. This resource must have been created with the D3D10_BIND_RENDER_TARGET flag.
pDesc
[in] Pointer to a depth-stencil-view description (see D3D10_RENDER_TARGET_VIEW_DESC). Set this parameter to NULL to create a view that accesses mipmap level 0 of the entire resource (using the format the resource was created with).
ppRTView
[out] Address of a pointer to an ID3D10RenderTargetView. Set this parameter to NULL to validate the other input parameters (the method will return S_FALSE if the other input parameters pass validation).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

A rendertarget view can be bound to the output merger stage by calling ID3D10Device::OMSetRenderTargets.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateSamplerState

Create a sampler-state object that encapsulates sampling information for a texture.

HRESULT CreateSamplerState(
  const D3D10_SAMPLER_DESC *pSamplerDesc,
  ID3D10SamplerState **ppSamplerState
);

Parameters

pSamplerDesc
[in] Pointer to a sampler state description (see D3D10_SAMPLER_DESC).
ppSamplerState
[out] Address of a pointer to the sampler state object created (see ID3D10SamplerState Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

4096 unique sampler state objects can be created on a device at a time.

If an application attempts to create a sampler state with the same description as an already existing sampler state, then the same interface with an incremented reference count will be returned and the total number of unique sampler state objects will stay the same.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateShaderResourceView

Create a shader-resource view for accessing data in a resource.

HRESULT CreateShaderResourceView(
  ID3D10Resource *pResource,
  const D3D10_SHADER_RESOURCE_VIEW_DESC *pDesc,
  ID3D10ShaderResourceView **ppSRView
);

Parameters

pResource
[in] Pointer to the resource that will serve as input to a shader. This resource must have been created with the D3D10_BIND_SHADER_RESOURCE flag.
pDesc
[in] Pointer to a shader-resource-view description (see D3D10_SHADER_RESOURCE_VIEW_DESC). Set this parameter to NULL to create a view that accesses the entire resource (using the format the resource was created with).
ppSRView
[out] Address of a pointer to an ID3D10ShaderResourceView. Set this parameter to NULL to validate the other input parameters (the method will return S_FALSE if the other input parameters pass validation).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

A resource is made up of one or more subresources, a view identifies which subresources to allow the pipeline to access. In addition, each resource is bound to the pipeline using a view. A shader-resource view is designed to bind any buffer or texture resource to the shader stages using the following API methods: VSSetShaderResources, GSSetShaderResources and PSSetShaderResources.

Since a view is fully typed, this means that typeless resources become fully typed when bound to the pipeline.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateTexture1D

Create an array of 1D textures (see Texture1D).

HRESULT CreateTexture1D(
  const D3D10_TEXTURE1D_DESC *pDesc,
  const D3D10_SUBRESOURCE_DATA *pInitialData,
  ID3D10Texture1D **ppTexture1D
);

Parameters

pDesc
[in] Pointer to a 1D texture description (see D3D10_TEXTURE1D_DESC). To create a typeless resource that can be interpreted at runtime into different, compatible formats, specify a typeless format in the texture description. To generate mipmap levels automatically, set the number of mipmap levels to 0.
pInitialData
[in] Pointer to an array of subresource descriptions (see D3D10_SUBRESOURCE_DATA); one for each subresource. Applications may not specify NULL for pInitialData when creating IMMUTABLE resources (see D3D10_USAGE). If the resource is multisampled, pInitialData must be NULL because multisampled resources cannot be initialized with data when they are created.
ppTexture1D
[out] Address of a pointer to the created texture (see ID3D10Texture1D Interface). Set this parameter to NULL to validate the other input parameters (the method will return S_FALSE if the other input parameters pass validation).

Return Values

If the method succeeds, the return code is S_OK. See Direct3D 10 Return Codes for failing error codes.

Remarks

CreateTexture1D creates a 1D texture resource, which contains an array of 1D textures. The number of textures is specified in the texture description. All textures in a resource must have the same format, size, and number of mipmap levels.

All resources are made up of one or more subresources. To load data into the texture, applications may supply the data initially as part of D3D10_SUBRESOURCE_DATA structure pointed to by pInitialData, or it may use one of the Texturing Functions supplied by the SDK.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateTexture2D

Create an array of 2D textures (see Texture2D).

HRESULT CreateTexture2D(
  const D3D10_TEXTURE2D_DESC *pDesc,
  const D3D10_SUBRESOURCE_DATA *pInitialData,
  ID3D10Texture2D **ppTexture2D
);

Parameters

pDesc
[in] Pointer to a 2D texture description (see D3D10_TEXTURE2D_DESC). To create a typeless resource that can be interpreted at runtime into different, compatible formats, specify a typeless format in the texture description. To generate mipmap levels automatically, set the number of mipmap levels to 0.
pInitialData
[in] Pointer to an array of subresource descriptions (see D3D10_SUBRESOURCE_DATA); one for each subresource. Applications may not specify NULL for pInitialData when creating IMMUTABLE resources (see D3D10_USAGE). If the resource is multisampled, pInitialData must be NULL because multisampled resources cannot be initialized with data when they are created.
ppTexture2D
[out] Address of a pointer to the created texture (see ID3D10Texture2D Interface). Set this parameter to NULL to validate the other input parameters (the method will return S_FALSE if the other input parameters pass validation).

Return Values

If the method succeeds, the return code is S_OK. See Direct3D 10 Return Codes for failing error codes.

Remarks

CreateTexture2D creates a 2D texture resource, which contains an array of 1D textures. The number of textures is specified in the texture description. All textures in a resource must have the same format, size, and number of mipmap levels.

All resources are made up of one or more subresources. To load data into the texture, applications may supply the data initially as part of D3D10_SUBRESOURCE_DATA structure pointed to by pInitialData, or it may use one of the Texturing Functions supplied by the SDK.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateTexture3D

Create a single 3D texture (see Texture3D).

HRESULT CreateTexture3D(
  const D3D10_TEXTURE3D_DESC *pDesc,
  const D3D10_SUBRESOURCE_DATA *pInitialData,
  ID3D10Texture3D **ppTexture3D
);

Parameters

pDesc
[in] Pointer to a 3D texture description (see D3D10_TEXTURE3D_DESC). To create a typeless resource that can be interpreted at runtime into different, compatible formats, specify a typeless format in the texture description. To generate mipmap levels automatically, set the number of mipmap levels to 0.
pInitialData
[in] Pointer to an array of subresource descriptions (see D3D10_SUBRESOURCE_DATA); one for each subresource. Applications may not specify NULL for pInitialData when creating IMMUTABLE resources (see D3D10_USAGE). If the resource is multisampled, pInitialData must be NULL because multisampled resources cannot be initialized with data when they are created.
ppTexture3D
[out] Address of a pointer to the created texture (see ID3D10Texture3D Interface). Set this parameter to NULL to validate the other input parameters (the method will return S_FALSE if the other input parameters pass validation).

Return Values

If the method succeeds, the return code is S_OK. See Direct3D 10 Return Codes for failing error codes.

Remarks

CreateTexture3D creates a 3D texture resource, which contains an array of 1D textures. The number of textures is specified in the texture description. All textures in a resource must have the same format, size, and number of mipmap levels.

All resources are made up of one or more subresources. To load data into the texture, applications may supply the data initially as part of D3D10_SUBRESOURCE_DATA structure pointed to by pInitialData, or it may use one of the Texturing Functions supplied by the SDK.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::CreateVertexShader

Create a vertex-shader object from a compiled shader.

HRESULT CreateVertexShader(
  const void *pShaderBytecode,
  SIZE_T BytecodeLength,
  ID3D10VertexShader **ppVertexShader
);

Parameters

pShaderBytecode
[in] A pointer to the compiled shader. To get this pointer see Getting a Pointer to a Compiled Shader.
BytecodeLength
[in] Size of the compiled vertex shader.
ppVertexShader
[out] Address of a pointer to an ID3D10VertexShader Interface. If this is NULL, all other parameters will be validated, and if all parameters pass validation this API will return S_FALSE instead of S_OK.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::Draw

Draw non-indexed, non-instanced primitives.

void Draw(
  UINT VertexCount,
  UINT StartVertexLocation
);

Parameters

VertexCount
[in] Number of vertices to draw.
StartVertexLocation
[in] Index of the first vertex.

Return Values

Returns nothing.

Remarks

Draw APIs submit work to the rendering pipeline; this API draws using vertex data.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::DrawAuto

Draw geometry of an unknown size that was created by the geometry shader stage. See remarks.

void DrawAuto();

Parameters

None.

Return Values

Returns nothing.

Remarks

After data has been streamed out to SO stage buffers, those buffers can be again bound to the Input Assembler stage at input slot 0 and DrawAuto will draw them without the application needing to know the amount of data that was written to the buffers. A measurement of the amount of data written to the SO stage buffers is maintained internally when the data is streamed out. This means that the CPU does not need to fetch the measurement before re-binding the data that was streamed as input data. Although this amount is tracked internally, it is still the responsibility of applications to use input layouts to describe the format of the data in the SO stage buffers so that the layouts are available when the buffers are again bound to the input assembler.

Figure 1. Conceptual Diagram of DrawAuto

Calling DrawAuto does not change the state of the streaming-output buffers that were bound again as inputs.

DrawAuto only works when drawing with one input buffer bound as an input to the IA stage at slot 0. Applications must create the SO buffer resource with both binding flags, D3D10_BIND_VERTEX_BUFFER and D3D10_BIND_STREAM_OUTPUT.

This API does not support indexing or instancing.

If an application needs to retrieve the size of the streaming-output buffer, it can query for statistics on streaming output by using D3D10_QUERY_SO_STATISTICS.

Example of using DrawAuto can be found in the ParticlesGS Sample and PipesGS Sample.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::DrawIndexed

Draw indexed, non-instanced primitives.

void DrawIndexed(
  UINT IndexCount,
  UINT StartIndexLocation,
  INT BaseVertexLocation
);

Parameters

IndexCount
[in] Number of indices to draw.
StartIndexLocation
[in] Index of the first index.
BaseVertexLocation
[in] Index of the first vertex (which can be negative).

Return Values

Returns nothing.

Remarks

Draw APIs submit work to the rendering pipeline; this API draws using vertex data and index data.

If the sum of both indices is negative, the result of the function call is undefined.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::DrawIndexedInstanced

Draw indexed, instanced primitives.

void DrawIndexedInstanced(
  UINT IndexCountPerInstance,
  UINT InstanceCount,
  UINT StartIndexLocation,
  INT BaseVertexLocation,
  UINT StartInstanceLocation
);

Parameters

IndexCountPerInstance
[in] Size of the index buffer used in each instance.
InstanceCount
[in] Number of instances to draw.
StartIndexLocation
[in] Index of the first index.
BaseVertexLocation
[in] Index of the first vertex. The index is signed, which allows a negative index. If the negative index plus the index value from the index buffer are less than 0, the result is undefined.
StartInstanceLocation
[in] Index of the first instance.

Return Values

Returns nothing.

Remarks

Instancing may extend performance by reusing the same geometry to draw multiple objects in a scene. One example of instancing could be to draw the same object with different positions and colors. Indexing requires multiple vertex buffers: at least one for per-vertex data and a second buffer for per-instance data. For an example of instancing, see the Instancing10 Sample.

Draw APIs submit work to the rendering pipeline; this API draws using vertex data, index data and instance data.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::DrawInstanced

Draw non-indexed, instanced primitives.

void DrawInstanced(
  UINT VertexCountPerInstance,
  UINT InstanceCount,
  UINT StartVertexLocation,
  UINT StartInstanceLocation
);

Parameters

VertexCountPerInstance
[in] Number of vertices to draw.
InstanceCount
[in] Number of instances to draw.
StartVertexLocation
[in] Index of the first vertex.
StartInstanceLocation
[in] Index of the first instance.

Return Values

Returns nothing.

Remarks

Instancing may extend performance by reusing the same geometry to draw multiple objects in a scene. One example of instancing could be to draw the same object with different positions and colors. For an example of instancing, see the Instancing10 Sample.

Draw APIs submit work to the rendering pipeline; this API draws using vertex data and instance data.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::Flush

Send queued-up commands in the command buffer to the GPU.

void Flush();

Parameters

None.

Return Values

Returns nothing.

Remarks

Most applications will not need to call this method. Calling this method when not necessary will incur a performance penalty. Each call to Flush incurs a significant amount of overhead.

When Direct3D state-setting, present, or draw commands are called by an application, those commands are queued into an internal command buffer. Flush sends those commands to the GPU for processing. Normally, these commands are sent to the GPU automatically whenever Direct3D determines that they need to be, such as when the command buffer is full or when mapping a resource. Flush will send the commands manually.

Flush should be used when applications deal with shared resources or when the CPU waits for an arbitrary amount of time (such as when calling Sleep, ID3DX10ThreadPump::WaitForAllItems, or IDXGIOutput::WaitForVBlank.

For more information about how flushing works, see Accurately Profiling Direct3D API Calls (Direct3D 9).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GSGetConstantBuffers

Get the constant buffers used by the geometry shader pipeline stage.

void GSGetConstantBuffers(
  UINT StartSlot,
  UINT NumBuffers,
  ID3D10Buffer **ppConstantBuffers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin retrieving constant buffers from.
NumBuffers
[in] Number of buffers to retrieve.
ppConstantBuffers
[out] Array of constant buffer interface pointers (see ID3D10Buffer) to be returned by the method.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GSGetSamplers

Get an array of sampler states from the geometry shader pipeline stage.

void GSGetSamplers(
  UINT StartSlot,
  UINT NumSamplers,
  ID3D10SamplerState **ppSamplers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin getting samplers from.
NumSamplers
[in] Number of samplers to get from the device. Each pipeline stage has a total of 16 sampler slots available.
ppSamplers
[out] Arry of sampler-state pointers (see ID3D10SamplerState) to be returned by the device.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GSGetShader

Get the geometry shader currently set on the device.

void GSGetShader(
  ID3D10GeometryShader **ppGeometryShader
);

Parameters

ppGeometryShader
[out] Address of a pointer to a geometry shader (see ID3D10GeometryShader) to be returned by the method.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GSGetShaderResources

Get the geometry shader resources.

void GSGetShaderResources(
  UINT StartSlot,
  UINT NumViews,
  ID3D10ShaderResourceView **ppShaderResourceViews
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin getting shader resources from.
NumViews
[in] The number of resources to get from the device. Up to a maximum of 128 slots are available for shader resources.
ppShaderResourceViews
[out] Array of shader resource view interfaces to be returned by the device.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GSSetConstantBuffers

Set the constant buffers used by the geometry shader pipeline stage.

void GSSetConstantBuffers(
  UINT StartSlot,
  UINT NumBuffers,
  ID3D10Buffer *const *ppConstantBuffers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin setting constant buffers to.
NumBuffers
[in] Number of buffers to set.
ppConstantBuffers
[in] Array of constant buffers (see ID3D10Buffer.xml) being given to the device.

Return Values

Returns nothing.

Remarks

The method will not hold references to the interfaces passed in. For that reason, applications should be careful not to release interfaces currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GSSetSamplers

Set an array of sampler states to the geometry shader pipeline stage.

void GSSetSamplers(
  UINT StartSlot,
  UINT NumSamplers,
  ID3D10SamplerState *const *ppSamplers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin setting samplers to.
NumSamplers
[in] Number of samplers in the array. Each pipeline stage has a total of 16 sampler slots available.
ppSamplers
[in] Pointer to an array of sampler-state interfaces (see ID3D10SamplerState). See Remarks.

Return Values

Returns nothing.

Remarks

Any sampler may be set to NULL; this invokes the default state, which is defined to be the following.

//Default sampler state:
D3D10_SAMPLER_DESC SamplerDesc;
SamplerDesc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
SamplerDesc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
SamplerDesc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
SamplerDesc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
SamplerDesc.MipLODBias = 0;
SamplerDesc.MaxAnisotropy = 1;
SamplerDesc.ComparisonFunc = D3D10_COMPARISON_NEVER;
SamplerDesc.BorderColor[0] = 1.0f;
SamplerDesc.BorderColor[1] = 1.0f;
SamplerDesc.BorderColor[2] = 1.0f;
SamplerDesc.BorderColor[3] = 1.0f;
SamplerDesc.MinLOD = -FLT_MAX;
SamplerDesc.MaxLOD = FLT_MAX;

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GSSetShader

Set a geometry shader to the device.

void GSSetShader(
  ID3D10GeometryShader *pShader
);

Parameters

pShader
[in] Pointer to a geometry shader (see ID3D10GeometryShader). Passing in NULL disables the shader for this pipeline stage.

Return Values

Returns nothing.

Remarks

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GSSetShaderResources

Bind an array of shader resources to the geometry shader stage.

void GSSetShaderResources(
  UINT StartSlot,
  UINT NumViews,
  ID3D10ShaderResourceView * const *ppShaderResourceViews
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin setting shader resources to.
NumViews
[in] Number of shader resources to set. Up to a maximum of 128 slots are available for shader resources.
ppShaderResourceViews
[in] Array of shader resource view interfaces to set to the device.

Return Values

Returns nothing.

Remarks

If an overlapping resource view is already bound to an output slot, such as a render target, then the method will fill the destination shader resource slot with NULL.

For information about creating shader-resource views, see ID3D10Device::CreateShaderResourceView.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GenerateMips

Generate mipmaps for the given shader resource.

void GenerateMips(
  ID3D10ShaderResourceView *pShaderResourceView
);

Parameters

pShaderResourceView
[in] Pointer to an ID3D10ShaderResourceView Interface. The mipmaps will be generated for this shader resource.

Return Values

Returns nothing.

Remarks

GenerateMips may be called on any ID3D10ShaderResourceView in order to generate the lower mipmap levels. GenerateMips uses the largest mipmap level of the view to recursively generate the lower levels of the mip, stopping with the smallest level specified by the view. If the base resource was not created with D3D10_BIND_RENDERTARGET and D3D10_RESOURCE_MISC_GENERATE_MIPS, this call has no effect.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GetCreationFlags

Get the flags used during the call to create the device with D3D10CreateDevice.

UINT GetCreationFlags();

Parameters

None.

Return Values

A bitfield containing the flags used to create the device. See D3D10_CREATE_DEVICE_FLAG.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GetDeviceRemovedReason

Get the reason why the device was removed.

HRESULT GetDeviceRemovedReason();

Parameters

None.

Return Values

Possible return values:

  • S_OK - The device has not been removed
  • DXGI_ERROR_DEVICE_REMOVED - Plug-and-play stop has been exercised on this adapter. Odds are good that the adapter might no longer be available.
  • DXGI_ERROR_DEVICE_HUNG - The device took an unreasonable amount of time to execute its comands, or the hardware crashed/hung. As a result, the TDR (Timeout Detection and Recovery) components of the OS have been exercised. The current device context was exeucting commands when the hang occured. The application may want to respawn and fallback to less aggressive use of the display hardware.
  • DXGI_ERROR_DEVICE_RESET - The hardware took an unreasonable amount of time to execute a different device context comands, or the hardware crashed/hung. As a result, the TDR (Timeout Detection and Recovery) components of the OS have been exercised. The current device context was NOT exeucting commands when the hang occured. However, the current video memory and device context could not be completely recovered. The application may want to just respawn itself, as the other application may no longer be around to cause this again.
  • DXGI_ERROR_DRIVER_INTERNAL_ERROR - there is strong evidence that the driver has performed an undefined operation. Depending on the current ExceptionMode, an exception may also be raised, meaning an application will typically never see this error code
  • E_OUTOFMEMORY - The graphics accelerator could make forward progress, because the graphics system architecture could not make all the required resources accessable to the accelerator. This is generally due to the condition where an application has many large resorces bound to the graphics pipeline, during a single draw call. There is not enough physical or virtual video memory address space to satisfy the single draw call. The application needs to make less aggressive use of the display memory, perhaps by leveraging ID3D10Device::ClearState to ensure large Resources do not stay bound to the pipeline, or by leveraging information, such as the DedicatedVideoMemory member of the DXGI_ADAPTER_DESC structure.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GetExceptionMode

Get the exception mode of the device. When the driver encounters an internal error, an exception meant to terminate the application will be raised.

UINT GetExceptionMode();

Parameters

None.

Return Values

Specifies the conditions which will cause an exception to be raised. The application will not be able to continue and must terminate. See D3D10_RAISE_FLAG.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GetPredication

Get the rendering predicate state.

void GetPredication(
  ID3D10Predicate **ppPredicate,
  BOOL *pPredicateValue
);

Parameters

ppPredicate
[out] Address of a pointer to a predicate (see ID3D10Predicate). Value stored here will be NULL upon device creation.
pPredicateValue
[out] Address of a boolean to fill with the predicate comparison value. FALSE upon device creation.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10DeviceChild::GetPrivateData

Get data from a device that is associated with a guid.

HRESULT GetPrivateData(
  REFGUID guid,
  UINT *pDataSize,
  void *pData
);

Parameters

guid
[in] Guid associated with the data.
pDataSize
[in, out] Size of the data.
pData
[out] Pointer to the data stored with the device. If pData is NULL, DataSize must also be 0, and any data previously associated with the guid will be destroyed.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

The data stored in the device is set with ID3D10DeviceChild::SetPrivateData.

The data retrieved and the guid will typically be application-defined.

This method can be used to get the device type by specifying GUID_DeviceType as the guid. In this case pData will point to a driver-type-enumeration value (see D3D10_DRIVER_TYPE).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::GetTextFilterSize

TBD

void GetTextFilterSize(
  UINT *Width,
  UINT *Height
);

Parameters

Width
Pointer to store the width.
Height
Pointer to store the height.

Return Values

This method returns nothing.

Remarks

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::IAGetIndexBuffer

Get a pointer to the index buffer that is bound to the input-assembler stage.

void IAGetIndexBuffer(
  ID3D10Buffer **pIndexBuffer,
  DXGI_FORMAT *Format,
  UINT *Offset
);

Parameters

pIndexBuffer
[out] A pointer to an index buffer returned by the method (see ID3D10Buffer).
Format
[out] Specifies format of the data in the index buffer (see DXGI_FORMAT). These formats provide the size and type of the data in the buffer. The only formats allowed for index buffer data are 16-bit (DXGI_FORMAT_R16_UINT) and 32-bit (DXGI_FORMAT_R32_UINT) integers.
Offset
[out] Offset (in bytes) from the start of the index buffer, to the first index to use.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::IAGetInputLayout

Get a pointer to the input-layout object that is bound to the input-assembler stage.

void IAGetInputLayout(
  ID3D10InputLayout **ppInputLayout
);

Parameters

ppInputLayout
[out] A pointer to the input-layout object (see ID3D10InputLayout), which describes the input buffers that will be read by the IA stage.

Return Values

Returns nothing.

Remarks

For information about creating an input-layout object, see Creating the Input-Layout Object.

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::IAGetPrimitiveTopology

Get information about the primitive type, and data order that describes input data for the input assembler stage.

void IAGetPrimitiveTopology(
  D3D10_PRIMITIVE_TOPOLOGY *pTopology
);

Parameters

pTopology
[out] A pointer to the type of primitive, and ordering of the primitive data (see D3D10_PRIMITIVE_TOPOLOGY).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::IAGetVertexBuffers

Get the vertex buffers bound to the input-assembler stage.

void IAGetVertexBuffers(
  UINT StartSlot,
  UINT NumBuffers,
  ID3D10Buffer **ppVertexBuffers,
  UINT *pStrides,
  UINT *pOffsets
);

Parameters

StartSlot
[in] The input slot of the first vertex buffer to get. The first vertex buffer is explicitly bound to the start slot; this causes each additional vertex buffer in the array to be implicitly bound to each subsequent input slot. There are 16 input slots.
NumBuffers
[in] The number of vertex buffers to get starting at the offset. The number of buffers (plus the starting slot) cannot exceed the total number of IA-stage input slots.
ppVertexBuffers
[out] A pointer to an array of vertex buffers returned by the method (see ID3D10Buffer).
pStrides
[out] Pointer to an array of stride values returned by the method; one stride value for each buffer in the vertex-buffer array. Each stride value is the size (in bytes) of the elements that are to be used from that vertex buffer.
pOffsets
[out] Pointer to an array of offset values returned by the method; one offset value for each buffer in the vertex-buffer array. Each offset is the number of bytes between the first element of a vertex buffer and the first element that will be used.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::IASetIndexBuffer

Bind an index buffer to the input-assembler stage.

void IASetIndexBuffer(
  ID3D10Buffer *pIndexBuffer,
  DXGI_FORMAT Format,
  UINT Offset
);

Parameters

pIndexBuffer
[in] A pointer to a buffer (see ID3D10Buffer) that contains indices. The index buffer must have been created with the D3D10_BIND_INDEX_BUFFER flag.
Format
[in] Specifies format of the data in the index buffer. The only formats allowed for index buffer data are 16-bit (DXGI_FORMAT_R16_UINT) and 32-bit (DXGI_FORMAT_R32_UINT) integers.
Offset
[in] Offset (in bytes) from the start of the index buffer to the first index to use.

Return Values

Returns nothing.

Remarks

For information about creating index buffers, see Create an Index Buffer.

Calling this method using a buffer that is currently bound for writing (i.e. bound to the stream output pipeline stage) will effectively bind NULL instead because a buffer cannot be bound as both an input and an output at the same time.

The Debug Layer will generate a warning whenever a resource is prevented from being bound simultaneously as an input and an output, but this will not prevent invalid data from being used by the runtime.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::IASetInputLayout

Bind an input-layout object to the input-assembler stage.

void IASetInputLayout(
  ID3D10InputLayout *pInputLayout
);

Parameters

pInputLayout
[in] A pointer to the input-layout object (see ID3D10InputLayout), which describes the input buffers that will be read by the IA stage.

Return Values

Returns nothing.

Remarks

Input-layout objects describe how vertex buffer data is streamed into the IA pipeline stage. To create an input-layout object, call ID3D10Device::CreateInputLayout.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::IASetPrimitiveTopology

Bind information about the primitive type, and data order that describes input data for the input assembler stage.

void IASetPrimitiveTopology(
  D3D10_PRIMITIVE_TOPOLOGY Topology
);

Parameters

Topology
[in] The type of primitive and ordering of the primitive data (see D3D10_PRIMITIVE_TOPOLOGY).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::IASetVertexBuffers

Bind an array of vertex buffers to the input-assembler stage.

void IASetVertexBuffers(
  UINT StartSlot,
  UINT NumBuffers,
  ID3D10Buffer *const *ppVertexBuffers,
  const UINT *pStrides,
  const UINT *pOffsets
);

Parameters

StartSlot
[in] The first input slot for binding. The first vertex buffer is explicitly bound to the start slot; this causes each additional vertex buffer in the array to be implicitly bound to each subsequent input slot. There are 16 input slots.
NumBuffers
[in] The number of vertex buffers in the array. The number of buffers (plus the starting slot) cannot exceed the total number of IA-stage input slots.
ppVertexBuffers
[in] A pointer to an array of vertex buffers (see ID3D10Buffer). The vertex buffers must have been created with the D3D10_BIND_VERTEX_BUFFER flag.
pStrides
[in] Pointer to an array of stride values; one stride value for each buffer in the vertex-buffer array. Each stride is the size (in bytes) of the elements that are to be used from that vertex buffer.
pOffsets
[in] Pointer to an array of offset values; one offset value for each buffer in the vertex-buffer array. Each offset is the number of bytes between the first element of a vertex buffer and the first element that will be used.

Return Values

Returns nothing.

Remarks

For information about creating vertex buffers, see Create a Vertex Buffer.

Calling this method using a buffer that is currently bound for writing (i.e. bound to the stream output pipeline stage) will effectively bind NULL instead because a buffer cannot be bound as both an input and an output at the same time.

The Debug Layer will generate a warning whenever a resource is prevented from being bound simultaneously as an input and an output, but this will not prevent invalid data from being used by the runtime.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::OMGetBlendState

Get the blend state of the output-merger stage.

void OMGetBlendState(
  ID3D10BlendState **ppBlendState,
  FLOAT BlendFactor[4],
  UINT *pSampleMask
);

Parameters

ppBlendState
[out] Address of a pointer to a blend-state interface (see ID3D10BlendState).
BlendFactor
[out] Array of blend factors, one for each RGBA component.
pSampleMask
[out] Pointer to a sample mask.

Return Values

Returns nothing.

Remarks

The reference count of the returned interface will be incremented by one when the blend state is retrieved. Applications must release returned pointer(s) when they are no longer needed, or else there will be a memory leak.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::OMGetDepthStencilState

Gets the depth-stencil state of the output-merger stage.

void OMGetDepthStencilState(
  ID3D10DepthStencilState **ppDepthStencilState,
  UINT *pStencilRef
);

Parameters

ppDepthStencilState
[out] Address of a pointer to a depth-stencil state interface (see ID3D10DepthStencilState) to be filled with information from the device.
pStencilRef
[out] Pointer to the stencil reference value used in the depth-stencil test.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::OMGetRenderTargets

Get pointers to the render targets and the depth-stencil buffer that are available to the output-merger stage.

void OMGetRenderTargets(
  UINT NumViews,
  ID3D10RenderTargetView **ppRenderTargetViews,
  ID3D10DepthStencilView **ppDepthStencilView
);

Parameters

NumViews
[in] Number of render targets to retrieve.
ppRenderTargetViews
[out] Pointer to an array of render targets views (see ID3D10RenderTargetView) to be filled with the render targets from the device. Specify NULL for this parameter when retrieval of a render target is not needed.
ppDepthStencilView
[out] Pointer to a depth-stencil view (see ID3D10DepthStencilView) to be filled with the depth-stencil information from the device. Specify NULL for this parameter when retrieval of the depth-stencil view is not needed.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::OMSetBlendState

Set the blend state of the output-merger stage.

void OMSetBlendState(
  ID3D10BlendState *pBlendState,
  const FLOAT BlendFactor[4],
  UINT SampleMask
);

Parameters

pBlendState
[in] Pointer to a blend-state interface (see ID3D10BlendState). Passing in NULL implies a default blend state. See remarks for further details.
BlendFactor
[in] Array of blend factors, one for each RGBA component. This requires a blend state object that specifies the D3D10_BLEND_BLEND_FACTOR option.
SampleMask
[in] 32-bit sample coverage. The default value is 0xffffffff. See remarks.

Return Values

Returns nothing.

Remarks

Blend state is used by the output-merger stage to determine how to blend together two pixel values. The two values are commonly the current pixel value and the pixel value already in the output render target. Use the blend operation to control where the two pixel values come from and how they are mathematically combined.

To create a blend-state interface, call ID3D10Device::CreateBlendState.

Passing in NULL for the blend-state interface indicates to the runtime to set a default blending state. The following table indicates the default blending parameters.

State | Default Value
AlphaToCoverageEnable | FALSE
BlendEnable | FALSE[8]
SrcBlend | D3D10_BLEND_ONE
DstBlend | D3D10_BLEND_ZERO
BlendOp | D3D10_BLEND_OP_ADD
SrcBlendAlpha | D3D10_BLEND_ONE
DstBlendAlpha | D3D10_BLEND_ZERO
BlendOpAlpha | D3D10_BLEND_OP_ADD
RenderTargetWriteMask[8] | D3D10_COLOR_WRITE_ENABLE_ALL[8]

A sample mask determines which samples get updated in all the active render targets. The mapping of bits in a sample mask to samples in a multisample render target is the responsibility of an individual application. A sample mask is always applied; it is independent of whether multisampling is enabled, and does not depend on whether an application uses multisample render targets.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::OMSetDepthStencilState

Sets the depth-stencil state of the output-merger stage.

void OMSetDepthStencilState(
  ID3D10DepthStencilState *pDepthStencilState,
  UINT StencilRef
);

Parameters

pDepthStencilState
[in] Pointer to a depth-stencil state interface (see ID3D10DepthStencilState) to bind to the device.
StencilRef
[in] Reference value to perform against when doing a depth-stencil test. See remarks.

Return Values

Returns nothing.

Remarks

To create a depth-stencil state interface, call ID3D10Device::CreateDepthStencilState.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::OMSetRenderTargets

Bind one or more render targets and the depth-stencil buffer to the output-merger stage.

void OMSetRenderTargets(
  UINT NumViews,
  ID3D10RenderTargetView *const *ppRenderTargetViews,
  ID3D10DepthStencilView *pDepthStencilView
);

Parameters

NumViews
[in] Number of render targets to bind.
ppRenderTargetViews
[in] Pointer to an array of render targets (see ID3D10RenderTargetView) to bind to the device. If this parameter is NULL, no render targets are bound. See Remarks.
pDepthStencilView
[in] Pointer to a depth-stencil view (see ID3D10DepthStencilView) to bind to the device. If this parameter is NULL, the depth-stencil state is not bound.

Return Values

Returns nothing.

Remarks

The maximum number of active render targets a device can have active at any given time is set by a #define in D3D10.h called D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT. It is invalid to try to set the same subresource to multiple render target slots.

If any subresources are also currently bound for reading in a different or writing (perhaps in a different part of the pipeline), those bind points will be NULL'ed out to prevent the same subresource from being read and written simultaneously in a single rendering operation.

The method will not hold references to the interfaces passed in. For that reason, applications should be careful not to release interfaces currently in use by the device.

See Binding Resources and Pipeline stages for more information on binding resources.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::OpenSharedResource

Give a device access to a shared resource created on a different device..

HRESULT OpenSharedResource(
  HANDLE hResource,
  REFIID ReturnedInterface,
  void **ppResource
);

Parameters

hResource
[in] A resource handle. See remarks.
ReturnedInterface
[in] The globally unique identifier (GUID) for the resource interface. See remarks.
ppResource
[out] Address of a pointer to the resource we are gaining access to.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

The resource must have been created with the D3D10_RESOURCE_MISC_SHARED flag, if it were created from a Direct3D 10 device. If it was created from a DXGI device, then the resource is always shared.

The REFIID, or GUID, of the interface to the resource can be obtained by using the __uuidof() macro. For example, __uuidof(ID3D10Buffer) will get the GUID of the interface to a buffer resource.

The unique handle of the resource is obtained differently depending on the type of device that originally created the resource.

  • D3D10 device - call ID3D10Device::QueryInterface to get the IDXGIResource and then call IDXGIResource::GetSharedHandle... doesn't work because QI will not know which resource on the device to query.
  • DXGI device - call IDXGIResource::GetSharedHandle.
  • D3D9L device - can't figure this one out.

Requirements

Header: Declared in D3d10core.

See Also

ID3D10Device Interface


ID3D10Device::PSGetConstantBuffers

Get the constant buffers used by the pixel shader pipeline stage.

void PSGetConstantBuffers(
  UINT StartSlot,
  UINT NumBuffers,
  ID3D10Buffer **ppConstantBuffers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin retrieving constant buffers from.
NumBuffers
[in] Number of buffers to retrieve.
ppConstantBuffers
[out] Array of constant buffer interface pointers (see ID3D10Buffer) to be returned by the method.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::PSGetSamplers

Get an array of sampler states from the pixel shader pipeline stage.

void PSGetSamplers(
  UINT StartSlot,
  UINT NumSamplers,
  ID3D10SamplerState **ppSamplers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin getting samplers from.
NumSamplers
[in] Number of samplers to get from the device. Each pipeline stage has a total of 16 sampler slots available.
ppSamplers
[out] Arry of sampler-state interface pointers (see ID3D10SamplerState) to be returned by the device.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::PSGetShader

Get the pixel shader currently set on the device.

void PSGetShader(
  ID3D10PixelShader **ppPixelShader
);

Parameters

ppPixelShader
[out] Address of a pointer to a pixel shader (see ID3D10PixelShader) to be returned by the method.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::PSGetShaderResources

Get the pixel shader resources.

void PSGetShaderResources(
  UINT StartSlot,
  UINT NumViews,
  ID3D10ShaderResourceView **ppShaderResourceViews
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin getting shader resources from.
NumViews
[in] The number of resources to get from the device. Up to a maximum of 128 slots are available for shader resources.
ppShaderResourceViews
[out] Array of shader resource view interfaces to be returned by the device.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::PSSetConstantBuffers

Set the constant buffers used by the pixel shader pipeline stage.

void PSSetConstantBuffers(
  UINT StartSlot,
  UINT NumBuffers,
  ID3D10Buffer *const *ppConstantBuffers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin setting constant buffers to.
NumBuffers
[in] Number of buffers to set.
ppConstantBuffers
[in] Array of constant buffers (see ID3D10Buffer) being given to the device.

Return Values

Returns nothing.

Remarks

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::PSSetSamplers

Set an array of sampler states to the pixel shader pipeline stage.

void PSSetSamplers(
  UINT StartSlot,
  UINT NumSamplers,
  ID3D10SamplerState *const *ppSamplers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin setting samplers to.
NumSamplers
[in] Number of samplers in the array. Each pipeline stage has a total of 16 sampler slots available.
ppSamplers
[in] Pointer to an array of sampler-state interfaces (see ID3D10SamplerState). See Remarks.

Return Values

Returns nothing.

Remarks

Any sampler may be set to NULL; this invokes the default state, which is defined to be the following.

State | Default Value
Filter | D3D10_FILTER_MIN_MAG_MIP_LINEAR
AddressU | D3D10_TEXTURE_ADDRESS_CLAMP
AddressV | D3D10_TEXTURE_ADDRESS_CLAMP
AddressW | D3D10_TEXTURE_ADDRESS_CLAMP
MipLODBias | 0
MaxAnisotropy | 1
ComparisonFunc | D3D10_COMPARISON_NEVER
BorderColor[0] | 1.0f
BorderColor[1] | 1.0f
BorderColor[2] | 1.0f
BorderColor[3] | 1.0f
MinLOD | -FLT_MAX
MaxLOD | FLT_MAX

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::PSSetShader

Sets a pixel shader to the device.

void PSSetShader(
  ID3D10PixelShader *pPixelShader
);

Parameters

pPixelShader
[in] Pointer to a pixel shader (see ID3D10PixelShader). Passing in NULL disables the shader for this pipeline stage.

Return Values

Returns nothing.

Remarks

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::PSSetShaderResources

Bind an array of shader resources to the pixel shader stage.

void PSSetShaderResources(
  UINT StartSlot,
  UINT NumViews,
  ID3D10ShaderResourceView *const *ppShaderResourceViews
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin setting shader resources to.
NumViews
[in] Number of shader resources to set. Up to a maximum of 128 slots are available for shader resources.
ppShaderResourceViews
[in] Array of shader resource view interfaces to set to the device.

Return Values

Returns nothing.

Remarks

If an overlapping resource view is already bound to an output slot, such as a rendertarget, then this API will fill the destination shader resource slot with NULL.

For information about creating shader-resource views, see ID3D10Device::CreateShaderResourceView.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::ResolveSubresource

Copy a multisampled resource into a non-multisampled resource. This API is most useful when re-using the resulting rendertarget of one render pass as an input to a second render pass.

void ResolveSubresource(
  ID3D10Resource *pDstResource,
  UINT DstSubresource,
  ID3D10Resource *pSrcResource,
  UINT SrcSubresource,
  DXGI_FORMAT Format
);

Parameters

pDstResource
[in] Destination resource. Must be a created with the D3D10_USAGE_DEFAULT flag and be single-sampled. See ID3D10Resource.
DstSubresource
[in] A zero-based index, that identifies the destination subresource. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.
pSrcResource
[in] Source resource. Must be multisampled.
SrcSubresource
[in] The source subresource of the source resource.
Format
[in] DXGI_FORMAT that indicates how the multisampled resource will be resolved to a single-sampled resource. See remarks.

Return Values

Returns nothing.

Remarks

Both the source and destination resources must be the same resource type and have the same dimensions.

The source and destination must have compatible formats. There are three scenarios for this:

Scenario | Requirements
Source and destination are prestructured and typed | Both the source and destination must have identical formats and that format must be specified in the Format parameter.
One resouce is prestructured and typed and the other is prestructured and typeless | The typed resource must have a format that is compatible with the typeless resource (i.e. the typed resource is DXGI_FORMAT_R32_FLOAT and the typeless resource is DXGI_FORMAT_R32_TYPELESS). The format of the typed resource must be specified in the Format parameter.
Source and destination are prestructured and typeless | Both the source and desintation must have the same typeless format (i.e. both must have DXGI_FORMAT_R32_TYPELESS), and the Format parameter must specify a format that is compatible with the source and destination (i.e. if both are DXGI_FORMAT_R32_TYPELESS then DXGI_FORMAT_R32_FLOAT or DXGI_FORMAT_R32_UINT could be specified in the Format parameter).

Requirements

Header: Declared in D3d10core.

See Also

ID3D10Device Interface


ID3D10Device::RSGetScissorRects

Get the array of scissor rectangles bound to the rasterizer stage.

void RSGetScissorRects(
  UINT *NumRects,
  D3D10_RECT *pRects
);

Parameters

NumRects
[in, out] Number of scissor rectangles to get. If pRects is NULL, this will be filled with the number of scissor rectangles currently bound.
pRects
[out] An array of scissor rectangles (see D3D10_RECT). If NumRects is greater than the number of scissor rects currently bound, then unused members of the array will contain 0.

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::RSGetState

Get the rasterizer state from the rasterizer stage of the pipeline.

void RSGetState(
  ID3D10RasterizerState **ppRasterizerState
);

Parameters

ppRasterizerState
[out] Address of a pointer to a rasterizer-state interface (see ID3D10RasterizerState) to fill with information from the device.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::RSGetViewports

Get the array of viewports bound to the rasterizer stage

void RSGetViewports(
  UINT *NumViewports,
  D3D10_VIEWPORT *pViewports
);

Parameters

NumViewports
[in, out] Number of viewports in pViewports.
pViewports
[out] An array of viewports (see D3D10_VIEWPORT) to be filled with information from the device. If NumViewports is greater than the actual number of viewports currently bound, then unused members of the array will contain 0.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::RSSetScissorRects

Bind an array of scissor rectangles to the rasterizer stage.

void RSSetScissorRects(
  UINT NumRects,
  const D3D10_RECT *pRects
);

Parameters

NumRects
[in] Number of scissor rectangles to bind.
pRects
[in] An array of scissor rectangles (see D3D10_RECT).

Return Values

Returns nothing.

Remarks

The scissor rectangles will only be used if ScissorEnable is set to true in the rasterizer state (see D3D10_RASTERIZER_DESC).

Which scissor rectangle to use is determined by the SV_ViewportArrayIndex semantic output by a geometry shader (see shader semantic syntax). If a geometry shader does not make use of the SV_ViewportArrayIndex semantic then Direct3D will use the first scissor rectangle in the array.

Each scissor rectangle in the array corresponds to a viewport in an array of viewports (see ID3D10Device::RSSetViewports).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::RSSetState

Set the rasterizer state for the rasterizer stage of the pipeline.

void RSSetState(
  ID3D10RasterizerState *pRasterizerState
);

Parameters

pRasterizerState
[in] Pointer to a rasterizer-state interface (see ID3D10RasterizerState) to bind to the pipeline.

Return Values

Returns nothing.

Remarks

To create the rasterizer state interface, call ID3D10Device::CreateRasterizerState.

For more details on setting up the rasterizer state, see Set Rasterizer State.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::RSSetViewports

Bind an array of viewports to the rasterizer stage of the pipeline.

void RSSetViewports(
  UINT NumViewports,
  const D3D10_VIEWPORT *pViewports
);

Parameters

NumViewports
[in] Number of viewports to bind.
pViewports
[in] An array of viewports (see D3D10_VIEWPORT) to bind to the device. Each viewport must have it's extents within the allowed ranges: D3D10_VIEWPORT_BOUNDS_MIN, D3D10_VIEWPORT_BOUNDS_MAX, D3D10_MIN_DEPTH, and D3D10_MAX_DEPTH.

Return Values

Returns nothing.

Remarks

All viewports must be set atomically as one operation. Any viewports not defined by the call are disabled.

Which viewport to use is determined by the SV_ViewportArrayIndex semantic output by a geometry shader (see shader semantic syntax). If a geometry shader does not make use of the SV_ViewportArrayIndex semantic then Direct3D will use the first viewport in the array.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::SetTextFilterSize

TBD

void SetTextFilterSize(
  UINT Width,
  UINT Height
);

Parameters

Width
[in] Width of the text filter.
Height
[in] Height of the text filter.

Return Values

This method returns nothing.

Remarks

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::SOGetTargets

Get the target output buffers for the StreamOutput stage of the pipeline.

void SOGetTargets(
  UINT NumBuffers,
  ID3D10Buffer **ppSOTargets,
  UINT *pOffsets
);

Parameters

NumBuffers
[in] Number of buffers to get. A maximum of four output buffers can be retrieved.
ppSOTargets
[out] An array of output buffers (see ID3D10Buffer) to be retrieved from the device.
pOffsets
[out] Array of offsets to the output buffers from ppBuffers, one offset for each buffer. The offset values are in bytes.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::SOSetTargets

Set the target output buffers for the StreamOutput stage of the pipeline.

void SOSetTargets(
  UINT NumBuffers,
  ID3D10Buffer *const *ppSOTargets,
  const UINT *pOffsets
);

Parameters

NumBuffers
[in] The number of buffer to bind to the device. A maximum of four output buffers can be set. If less than four are defined by the call, the remaining buffer slots are set to NULL. See Remarks.
ppSOTargets
[in] The array of output buffers (see ID3D10Buffer) to bind to the device. The buffers must have been created with the D3D10_BIND_STREAM_OUTPUT flag.
pOffsets
[in] Array of offsets to the output buffers from ppBuffers, one offset for each buffer. The offset values must be in bytes.

Return Values

Returns nothing.

Remarks

An offset of -1 will cause the stream output buffer to be appended, continuing after the last location written to the buffer in a previous stream output pass.

Calling this method using a buffer that is currently bound for writing will effectively bind NULL instead because a buffer cannot be bound as both an input and an output at the same time.

The Debug Layer will generate a warning whenever a resource is prevented from being bound simultaneously as an input and an output, but this will not prevent invalid data from being used by the runtime.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::SetExceptionMode

Set the exception mode of the device. When the driver encounters an internal error, an exception meant to terminate the application will be raised.

HRESULT SetExceptionMode(
  UINT RaiseFlags
);

Parameters

RaiseFlags
[in] Specifies conditions which will cause an exception. Values are expected to be bit-wise OR'ed together. 0 is also valid and indicates to never raise exceptions. See D3D10_RAISE_FLAG.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::SetPredication

Set a rendering predicate.

void SetPredication(
  ID3D10Predicate *pPredicate,
  BOOL PredicateValue
);

Parameters

pPredicate
[in] Pointer to a predicate (see ID3D10Predicate). A NULL value indicates "no" predication; in this case, the value of PredicateValue is irrelevent but will be preserved for ID3D10Device::GetPredication.
PredicateValue
[in] If TRUE, rendering will be affected by when the predicate's conditions are met. If FALSE, rendering will be affected when the conditions are not met.

Return Values

Returns nothing.

Remarks

The predicate must be in the "issued" or "signaled" state to be used for predication. While the predicate is set for predication, calls to ID3D10Asynchronous::Begin and ID3D10Asynchronous::End are invalid.

This method is used to denote that subsequent rendering and resource manipulation commands are not actually performed if the resulting Predicate data of the Predicate is equal to the PredicateValue. However, some Predicates are only hints, so they may not actually prevent operations from being performed.

The primary usefulness of Predication is to allow an application to issue graphics commands without taking the performance hit of spinning, waiting for ID3D10Asynchronous::GetData to return. So, Predication can occur while ID3D10Asynchronous::GetData returns S_FALSE. Another way to think of it: an application can also use Predication as a fallback, if it is possible that ID3D10Asynchronous::GetData returns S_FALSE. If ID3D10Asynchronous::GetData returns S_OK, the application can skip calling the graphics commands manually with it's own application logic.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::SetPrivateData

Set data to a device and associate that data with a guid.

HRESULT SetPrivateData(
  REFGUID guid,
  UINT DataSize,
  const void *pData
);

Parameters

guid
[in] Guid associated with the data.
DataSize
[in] Size of the data.
pData
[in] Pointer to the data to be stored with this device. If pData is NULL, DataSize must also be 0, and any data previously associated with the guid will be destroyed.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

The data stored in the device with this method can be retrieved with ID3D10DeviceChild::GetPrivateData.

The data and guid set with this method will typically be application-defined.

If an application uses this method to change the device type using GUID_DeviceType, results are undefined. However, GUID_DeviceType can be used to retrieve the device type using ID3D10DeviceChild::GetPrivateData.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10DeviceChild::SetPrivateDataInterface

Associate an IUnknown-derived interface with this device and associate that interface with an application-defined guid.

HRESULT SetPrivateDataInterface(
  REFGUID guid,
  const IUnknown *pData
);

Parameters

guid
[in] Guid associated with the interface.
pData
[in] Pointer to an IUnknown-derived interface to be associated with the device.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

When this method is called ::addref() will be called on the IUnknown-derived interface, and when the device is detroyed ::release() will be called on the IUnknown-derived interface.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::UpdateSubresource

The CPU copies data from memory to a subresource created in non-mappable memory. See remarks.

void UpdateSubresource(
  ID3D10Resource *pDstResource,
  UINT DstSubresource,
  const D3D10_BOX *pDstBox,
  const void *pSrcData,
  UINT SrcRowPitch,
  UINT SrcDepthPitch
);

Parameters

pDstResource
[in] A pointer to the destination resource (see ID3D10Resource Interface).
DstSubresource
[in] A zero-based index, that identifies the destination subresource. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.
pDstBox
[in] A box that defines the portion of the destination subresource to copy the resource data into. Coordinates are in bytes for buffers and in texels for textures. If NULL, the data is written to the destination subresource with no offset. The dimensions of the source must fit the destination (see D3D10_BOX).
pSrcData
[in] A pointer to the source data in memory.
SrcRowPitch
[in] The size of one row of the source data.
SrcDepthPitch
[in] The size of one depth slice of source data.

Return Values

Returns nothing

Remarks

A resource cannot be used as a destination if:

  • the resource is created with immutable usage.
  • the resource is created as a depth-stencil resource.
  • the resource is created with multisampling capability (see DXGI_SAMPLE_DESC).

When UpdateSubresource returns, the application is free to change or even free the data pointed to by pSrcData because the method has already copied/snapped away the original contents.

The performance of UpdateSubresource depends on whether or not there is contention for the destination resource. For example, contention for a vertex buffer resource occurs when the application executes a Draw call and later calls UpdateSubresource on the same vertex buffer before the Draw call is actually executed by the GPU.

  • When there is contention for the resource, UpdateSubresource will perform 2 copies of the source data. First, the data is copied by the CPU to a temporary storage space accessible by the command buffer. This copy happens before the method returns. A second copy is then performed by the GPU to copy the source data into non-mappable memory. This second copy happens asynchronously because it is executed by GPU when the command buffer is flushed.
  • When there is no resource contention, the behavior of UpdateSubresource is dependent on which is faster (from the CPU's perspective): copying the data to the command buffer and then having a second copy execute when the command buffer is flushed, or having the CPU copy the data to the final resource location. This is dependent on the architecture of the underlying system.

To better understand the source row pitch and source depth pitch parameters, consider this conceptual representation of a 3D volume texture.

Figure 1. A visual conception of a 3D volume texture

Each block in this visual represents an element of data, and the size of each element is dependant on the resource's format. For example, if the resource format is DXGI_FORMAT_R32G32B32A32_FLOAT, then the size of each element would be 128 bits, or 16 bytes. This 3D volume texture has a width of two, a height of three, and a depth of four.

To calculate the source row pitch and source depth pitch for a given resource, use the following formulas:

  • Source Row Pitch = [size of one element in bytes] * [number of elements in one row]
  • Source Depth Pitch = [Source Row Pitch] * [number of rows (height)]

In the case of this example 3D volume texture where the size of each element is 16 bytes, the formulas are as follows:

  • Source Row Pitch = 16 * 2 = 32
  • Source Depth Pitch = 16 * 2 * 3 = 96

Below is a visual conception of the resource as it is laid out in memory:

Figure 2. Visual conception of a the 3D volume texture laid out in memory

For example, the following code snippet shows how to specify a destination region in a 2D texture. Assume the destination texture is 512x512 and the operation will copy the data pointed to by pData to [(120,100)..(200,220)] in the destination texture. Also assume that rowPitch has been initialized with the proper value (as explained above). Front and back are set to 0 and 1 respectively, because by having front equal to back, the box is technically empty.

D3D10_BOX destRegion;
box.left = 120;
box.right = 200;
box.top = 100;
box.bottom = 220;
box.front = 0;
box.back = 1;

pd3dDevice->UpdateSubresource( pDestTexture, 0, &destRegion, pData, rowPitch, 0 );

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Resource Interface


ID3D10Device::VSGetConstantBuffers

Get the constant buffers used by the vertex shader pipeline stage.

void VSGetConstantBuffers(
  UINT StartSlot,
  UINT NumBuffers,
  ID3D10Buffer **ppConstantBuffers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin retrieving constant buffers from.
NumBuffers
[in] Number of buffers to retrieve.
ppConstantBuffers
[out] Array of constant buffer interface pointers (see ID3D10Buffer) to be returned by the method.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::VSGetSamplers

Get an array of sampler states from the vertex shader pipeline stage.

void VSGetSamplers(
  UINT StartSlot,
  UINT NumSamplers,
  ID3D10SamplerState **ppSamplers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin getting samplers from.
NumSamplers
[in] Number of samplers to get from the device. Each pipeline stage has a total of 16 sampler slots available.
ppSamplers
[out] Arry of sampler-state interface pointers (see ID3D10SamplerState) to be returned by the device.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::VSGetShader

Get the vertex shader currently set on the device.

void VSGetShader(
  ID3D10VertexShader **ppVertexShader
);

Parameters

ppVertexShader
[out] Address of a pointer to a vertex shader (see ID3D10VertexShader) to be returned by the method.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::VSGetShaderResources

Get the vertex shader resources.

void VSGetShaderResources(
  UINT StartSlot,
  UINT NumViews,
  ID3D10ShaderResourceView **ppShaderResourceViews
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin getting shader resources from.
NumViews
[in] The number of resources to get from the device. Up to a maximum of 128 slots are available for shader resources.
ppShaderResourceViews
[out] Array of shader resource view interfaces to be returned by the device.

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one. Applications should call IUnknown::Release on the returned interfaces when they are no longer needed to avoid memory leaks.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::VSSetConstantBuffers

Set the constant buffers used by the vertex shader pipeline stage.

void VSSetConstantBuffers(
  UINT StartSlot,
  UINT NumBuffers,
  ID3D10Buffer *const *ppConstantBuffers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin setting constant buffers to.
NumBuffers
[in] Number of buffers to set.
ppConstantBuffers
[in] Array of constant buffers (see ID3D10Buffer) being given to the device.

Return Values

Returns nothing.

Remarks

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::VSSetSamplers

Set an array of sampler states to the vertex shader pipeline stage.

void VSSetSamplers(
  UINT StartSlot,
  UINT NumSamplers,
  ID3D10SamplerState *const *ppSamplers
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin setting samplers to.
NumSamplers
[in] Number of samplers in the array. Each pipeline stage has a total of 16 sampler slots available.
ppSamplers
[in] Pointer to an array of sampler-state interfaces (see ID3D10SamplerState). See Remarks.

Return Values

Returns nothing.

Remarks

Any sampler may be set to NULL; this invokes the default state, which is defined to be the following.

//Default sampler state:
D3D10_SAMPLER_DESC SamplerDesc;
SamplerDesc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
SamplerDesc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
SamplerDesc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
SamplerDesc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
SamplerDesc.MipLODBias = 0;
SamplerDesc.MaxAnisotropy = 1;
SamplerDesc.ComparisonFunc = D3D10_COMPARISON_NEVER;
SamplerDesc.BorderColor[0] = 1.0f;
SamplerDesc.BorderColor[1] = 1.0f;
SamplerDesc.BorderColor[2] = 1.0f;
SamplerDesc.BorderColor[3] = 1.0f;
SamplerDesc.MinLOD = -FLT_MAX;
SamplerDesc.MaxLOD = FLT_MAX;

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::VSSetShader

Set a vertex shader to the device.

void VSSetShader(
  ID3D10VertexShader *pVertexShader
);

Parameters

pVertexShader
[in] Pointer to a vertex shader (see ID3D10VertexShader). Passing in NULL disables the shader for this pipeline stage.

Return Values

Returns nothing.

Remarks

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Device::VSSetShaderResources

Bind an array of shader resources to the vertex shader stage.

void VSSetShaderResources(
  UINT StartSlot,
  UINT NumViews,
  ID3D10ShaderResourceView *const *ppShaderResourceViews
);

Parameters

StartSlot
[in] Index into the device's zero-based array to begin setting shader resources to.
NumViews
[in] Number of shader resources to set. Up to a maximum of 128 slots are available for shader resources.
ppShaderResourceViews
[in] Array of shader resource view interfaces to set to the device.

Return Values

Returns nothing.

Remarks

If an overlapping resource view is already bound to an output slot, such as a rendertarget, then this API will fill the destination shader resource slot with NULL.

For information about creating shader-resource views, see ID3D10Device::CreateShaderResourceView.

The method will not hold a reference to the interfaces passed in. For that reason, applications should be careful not to release an interface currently in use by the device.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10DeviceChild Interface

A device child interface contains data used by a device. This interface contains methods shown in the following table.

Methods | Description
ID3D10DeviceChild::GetDevice | Get a pointer to the device that created this interface.
ID3D10DeviceChild::GetPrivateData | Get application-defined data from a device child.
ID3D10DeviceChild::SetPrivateData | Set application-defined data to a device child and associate that data with an application-defined guid.
ID3D10DeviceChild::SetPrivateDataInterface | Associate an IUnknown-derived interface with this device child and associate that interface with an application-defined guid.

There are several types of device child interfaces, all of which inherit this interface. They include shaders, state objects, and input layouts.

See Also

Core Interfaces


ID3D10DeviceChild::GetDevice

Get a pointer to the device that created this interface.

void GetDevice(
  ID3D10Device **ppDevice
);

Parameters

ppDevice
[out] Address of a pointer to a device (see ID3D10Device Interface).

Return Values

Returns nothing.

Remarks

Any returned interfaces will have their reference count incremented by one, so be sure to call ::release() on the returned pointer(s) before they are freed or else you will have a memory leak.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10DeviceChild Interface


ID3D10DeviceChild::GetPrivateData

Get application-defined data from a device child.

HRESULT GetPrivateData(
  REFGUID guid,
  UINT *pDataSize,
  void *pData
);

Parameters

guid
[in] Guid associated with the data.
pDataSize
[in, out] Size of the data.
pData
[out] Pointer to the data stored with the device child. If pData is NULL, DataSize must also be 0, and any data previously associated with the guid will be destroyed.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

The data stored in the device child is set with ID3D10DeviceChild::SetPrivateData.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10DeviceChild Interface


ID3D10DeviceChild::SetPrivateData

Set application-defined data to a device child and associate that data with an application-defined guid.

HRESULT SetPrivateData(
  REFGUID guid,
  UINT DataSize,
  const void *pData
);

Parameters

guid
[in] Guid associated with the data.
DataSize
[in] Size of the data.
pData
[in] Pointer to the data to be stored with this device child. If pData is NULL, DataSize must also be 0, and any data previously associated with the specified guid will be destroyed.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

The data stored in the device child with this method can be retrieved with ID3D10DeviceChild::GetPrivateData.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10DeviceChild Interface


ID3D10DeviceChild::SetPrivateDataInterface

Associate an IUnknown-derived interface with this device child and associate that interface with an application-defined guid.

HRESULT SetPrivateDataInterface(
  REFGUID guid,
  const IUnknown *pData
);

Parameters

guid
[in] Guid associated with the interface.
pData
[in] Pointer to an IUnknown-derived interface to be associated with the device child.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

When this method is called ::addref() will be called on the IUnknown-derived interface, and when the device child is detroyed ::release() will be called on the IUnknown-derived interface.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10DeviceChild Interface


ID3D10Include Interface

Applications can derive code from ID3D10Include to provide user-implemented methods of opening and closing included files when loading an effect from memory.

ID3D10Include Members

Method | Description
ID3D10Include::Close | A user-implemented method for closing a shader #include file.
ID3D10Include::Open | A user-implemented method for opening and reading the contents of a shader #include file.

Remarks

This objects of this interface are not created by Direct3D. Applications inherit this interface and then implement its two methods. These methods could then open and close any files the application needed.

See Also

Core Interfaces


ID3D10Include::Close

A user-implemented method for closing a shader #include file.

HRESULT Close(
  LPCVOID pData
);

Parameters

pData
[in] Pointer to the returned buffer that contains the include directives. This is the pointer that was returned by the corresponding ID3D10Include::Open call.

Return Values

The user-implemented method should return S_OK. If the callback fails when reading the #include file, the application programming interface (API) that caused the callback to be called will fail. This is one of the following:

  • The high-level shader language (HLSL) shader will fail one of the D3D10CompileShader*** functions.
  • The effect will fail one of the D3D10CreateEffect*** functions.

Remarks

If ID3D10Include::Open was successful, ID3D10Include::Close is guaranteed to be called before the API using this interface returns.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Include Interface


ID3D10Include::Open

A user-implemented method for opening and reading the contents of a shader #include file.

HRESULT Open(
  D3D10_INCLUDE_TYPE IncludeType,
  LPCSTR pFileName,
  LPCVOID pParentData,
  LPCVOID *ppData,
  UINT *pBytes
);

Parameters

IncludeType
[in] The location of the #include file. See D3D10_INCLUDE_TYPE.
pFileName
[in] Name of the #include file.
pParentData
[in] Pointer to the container that includes the #include file.
ppData
[out] Pointer to the returned buffer that contains the include directives. This pointer remains valid until ID3D10Include::Close is called.
pBytes
[in] Number of bytes returned in ppData.

Return Values

The user-implemented method should return S_OK. If the callback fails when reading the #include file, the application programming interface (API) that caused the callback to be called will fail. This is one of the following:

  • The high-level shader language (HLSL) shader will fail one of the D3D10CompileShader*** functions.
  • The effect will fail one of the D3D10CreateEffect*** functions.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Include Interface


ID3D10InfoQueue Interface

The information queue stores, retrieves, and filters debug messages. The queue consists of: a message queue, an optional storage filter stack, and a optional retrieval filter stack.

Method | Description
ID3D10InfoQueue::AddApplicationMessage | Add a user-defined message to the message queue; also send the message to debug output.
ID3D10InfoQueue::AddMessage | Add a debug message to the message queue; also send the message to debug output.
ID3D10InfoQueue::AddRetrievalFilterEntries | Add storage filters to the top of the retrieval-filter stack.
ID3D10InfoQueue::ClearRetrievalFilter | Remove a retrieval filter from the top of the retrieval-filter stack.
ID3D10InfoQueue::ClearStoredMessages | Clear all messages from the message queue.
ID3D10InfoQueue::GetBreakOnCategory | Get a message category to break on when a message with that category passes through the storage filter.
ID3D10InfoQueue::GetBreakOnID | Get a message identifier to break on when a message with that identifier passes through the storage filter.
ID3D10InfoQueue::GetBreakOnSeverity | Get a message severity level to break on when a message with that severity level passes through the storage filter.
ID3D10InfoQueue::GetMessage | Get a message from the message queue.
ID3D10InfoQueue::GetMessageCountLimit | Get the maximum number of messages that can be added to the message queue.
ID3D10InfoQueue::GetMuteDebugOutput | Get a boolean that turns the debug output on or off.
ID3D10InfoQueue::GetNumMessagesDiscardedByMessageCountLimit | Get the number of messages discarded by the message count limit.
ID3D10InfoQueue::GetNumStoredMessages | Get the number of messages in the message queue.
ID3D10InfoQueue::GetNumStoredMessagesAllowedByRetrievalFilter | Get the number of messages that are able to pass through a retrieval filter.
ID3D10InfoQueue::GetRetrievalFilter | Get the retrieval filter.
ID3D10InfoQueue::GetRetrievalFilterStackSize | Get the size of the retrieval-filter stack in bytes.
ID3D10InfoQueue::PopRetrievalFilter | Pop a retrieval filter.
ID3D10InfoQueue::PushCopyOfRetrievalFilter | Push a copy of retrieval filter currently on the top of the retrieval-filter stack onto the retrieval-filter stack.
ID3D10InfoQueue::PushEmptyRetrievalFilter | Push an empty retrieval filter onto the retrieval-filter stack.
ID3D10InfoQueue::PushRetrievalFilter | Push a retrieval filter onto the retrieval-filter stack.
ID3D10InfoQueue::SetBreakOnCategory | Set a message category to break on.
ID3D10InfoQueue::SetBreakOnID | Set an ID to break on.
ID3D10InfoQueue::SetBreakOnSeverity | Set the message severity level.
ID3D10InfoQueue::SetMessageCountLimit | Set the maximum number of messages.
ID3D10InfoQueue::SetMuteDebugOutput | Set a boolean that turns the debug output on or off.

This interface is obtained by turning on the debug layer and querying it from the ID3D10Device Interface using IUnknown::QueryInterface.

See Also

Core Interfaces


ID3D10InfoQueue::AddApplicationMessage

Add a user-defined message to the message queue and send that message to debug output.

HRESULT AddApplicationMessage(
  D3D10_MESSAGE_SEVERITY Severity,
  LPCSTR pDescription
);

Parameters

Severity
[in] Severity of a message (see D3D10_MESSAGE_SEVERITY).
pDescription
[in] Message string.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::AddMessage

Add a Direct3D 10 debug message to the message queue and send that message to debug output.

HRESULT AddMessage(
  D3D10_MESSAGE_CATEGORY Category,
  D3D10_MESSAGE_SEVERITY Severity,
  D3D10_MESSAGE_ID ID,
  LPCSTR pDescription
);

Parameters

Category
[in] Category of a message (see D3D10_MESSAGE_CATEGORY).
Severity
[in] Severity of a message (see D3D10_MESSAGE_SEVERITY).
ID
[in] Unique identifier of a message (see D3D10_MESSAGE_ID).
pDescription
[in] User-defined message.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

This method is used by the runtime's internal mechanisms to add Direct3D 10 debug messages to the message queue and send them to debug output. For applications to add their own custom messages to the message queue and send them to debug output, call ID3D10InfoQueue::AddApplicationMessage.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::AddRetrievalFilterEntries

Add storage filters to the top of the retrieval-filter stack.

HRESULT AddRetrievalFilterEntries(
  D3D10_INFO_QUEUE_FILTER *pFilter
);

Parameters

pFilter
[in] Array of retrieval filters (see D3D10_INFO_QUEUE_FILTER).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::AddStorageFilterEntries

Add storage filters to the top of the storage-filter stack.

HRESULT AddStorageFilterEntries(
  D3D10_INFO_QUEUE_FILTER *pFilter
);

Parameters

pFilter
[in] Array of storage filters (see D3D10_INFO_QUEUE_FILTER).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::ClearRetrievalFilter

Remove a retrieval filter from the top of the retrieval-filter stack.

void ClearRetrievalFilter();

Parameters

None.

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::ClearStorageFilter

Remove a storage filter from the top of the storage-filter stack.

void ClearStorageFilter();

Parameters

None.

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::ClearStoredMessages

Clear all messages from the message queue.

void ClearStoredMessages();

Parameters

None.

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetBreakOnCategory

Get a message category to break on when a message with that category passes through the storage filter.

BOOL GetBreakOnCategory(
  D3D10_MESSAGE_CATEGORY Category
);

Parameters

Category
[in] Message category to break on (see D3D10_MESSAGE_CATEGORY).

Return Values

Whether this breaking condition is turned on or off (true for on, false for off).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetBreakOnID

Get a message identifier to break on when a message with that identifier passes through the storage filter.

BOOL GetBreakOnID(
  D3D10_MESSAGE_ID ID
);

Parameters

ID
[in] Message identifier to break on (see D3D10_MESSAGE_ID).

Return Values

Whether this breaking condition is turned on or off (true for on, false for off).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetBreakOnSeverity

Get a message severity level to break on when a message with that severity level passes through the storage filter.

BOOL GetBreakOnSeverity(
  D3D10_MESSAGE_SEVERITY Severity
);

Parameters

Severity
[in] Message severity level to break on (see D3D10_MESSAGE_SEVERITY).

Return Values

Whether this breaking condition is turned on or off (true for on, false for off).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetMessage

Get a message from the message queue.

HRESULT GetMessage(
  UINT64 MessageIndex,
  D3D10_MESSAGE *pMessage,
  SIZE_T *pMessageByteLength
);

Parameters

MessageIndex
[in] Index into message queue after an optional retrieval filter has been applied. This can be between 0 and the number of messages in the message queue that pass through the retrieval filter (which can be obtained with ID3D10InfoQueue::GetNumStoredMessagesAllowedByRetrievalFilter). 0 is the message at the front of the message queue.
pMessage
[out] Returned message (see D3D10_MESSAGE).
pMessageByteLength
[in, out] Size of pMessage in bytes, including the size of the message string that the pMessage points to.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

This method does not remove any messages from the message queue.

This method gets messages from the message queue after an optional retrieval filter has been applied.

Applications should call this method twice to retrieve a message - first to obtain the size of the message and second to get the message. Here is a typical example:

// Get the size of the message
SIZE_T messageLength = 0;
HRESULT hr = pInfoQueue->GetMessage(0, NULL, &messageLength);

// Allocate space and get the message
D3D10_MESSAGE * pMessage = (D3D10_MESSAGE*)malloc(messageLength);
hr = pInfoQueue->GetMessage(0, pMessage, &messageLength);

For an overview see Information Queue Overview.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetMessageCountLimit

Get the maximum number of messages that can be added to the message queue.

UINT64 GetMessageCountLimit();

Parameters

None.

Return Values

Maximum number of messages that can be added to the queue. -1 means no limit.

Remarks

When the number of messages in the message queue has reached the maximum limit, new messages coming in will push old messages out.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetMuteDebugOutput

Get a boolean that turns the debug output on or off.

BOOL GetMuteDebugOutput();

Parameters

None.

Return Values

Whether the debug output is on or off (true for on, false for off).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetNumMessagesAllowedByStorageFilter

Get the number of messages that were allowed to pass through a storage filter.

UINT64 GetNumMessagesAllowedByStorageFilter();

Parameters

None.

Return Values

Number of messages allowed by a storage filter.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetNumMessagesDeniedByStorageFilter

Get the number of messages that were denied passage through a storage filter.

UINT64 GetNumMessagesDeniedByStorageFilter();

Parameters

None.

Return Values

Number of messages denied by a storage filter.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetNumMessagesDiscardedByMessageCountLimit

Get the number of messages that were discarded due to the message count limit.

UINT64 GetNumMessagesDiscardedByMessageCountLimit();

Parameters

None.

Return Values

Number of messages discarded.

Remarks

Get and set the message count limit with ID3D10InfoQueue::GetMessageCountLimit and ID3D10InfoQueue::SetMessageCountLimit, respectively.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetNumStoredMessages

Get the number of messages currently stored in the message queue.

UINT64 GetNumStoredMessages();

Parameters

None.

Return Values

Number of messages currently stored in the message queue.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetNumStoredMessagesAllowedByRetrievalFilter

Get the number of messages that are able to pass through a retrieval filter.

UINT64 GetNumStoredMessagesAllowedByRetrievalFilter();

Parameters

None.

Return Values

Number of messages allowed by a retrieval filter.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetRetrievalFilter

Get the retrieval filter at the top of the retrieval-filter stack.

HRESULT GetRetrievalFilter(
  D3D10_INFO_QUEUE_FILTER *pFilter,
  SIZE_T *pFilterByteLength
);

Parameters

pFilter
[out] Retrieval filter at the top of the retrieval-filter stack.
pFilterByteLength
[in, out] Size of the retrieval filter in bytes. If pFilter is NULL, the size of the retrieval filter will be output to this parameter.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetRetrievalFilterStackSize

Get the size of the retrieval-filter stack in bytes.

UINT GetRetrievalFilterStackSize();

Parameters

None.

Return Values

Size of the retrieval-filter stack in bytes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetStorageFilter

Get the storage filter at the top of the storage-filter stack.

HRESULT GetStorageFilter(
  D3D10_INFO_QUEUE_FILTER *pFilter,
  SIZE_T *pFilterByteLength
);

Parameters

pFilter
[out] Storage filter at the top of the storage-filter stack.
pFilterByteLength
[in, out] Size of the storage filter in bytes. If pFilter is NULL, the size of the storage filter will be output to this parameter.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::GetStorageFilterStackSize

Get the size of the storage-filter stack in bytes.

UINT GetStorageFilterStackSize();

Parameters

None.

Return Values

Size of the storage-filter stack in bytes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::PopRetrievalFilter

Pop a retrieval filter from the top of the retrieval-filter stack.

void PopRetrievalFilter();

Parameters

None.

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::PopStorageFilter

Pop a storage filter from the top of the storage-filter stack.

void PopStorageFilter();

Parameters

None.

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::PushCopyOfRetrievalFilter

Push a copy of retrieval filter currently on the top of the retrieval-filter stack onto the retrieval-filter stack.

HRESULT PushCopyOfRetrievalFilter();

Parameters

None.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::PushCopyOfStorageFilter

Push a copy of storage filter currently on the top of the storage-filter stack onto the storage-filter stack.

HRESULT PushCopyOfStorageFilter();

Parameters

None.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::PushEmptyRetrievalFilter

Push an empty retrieval filter onto the retrieval-filter stack.

HRESULT PushEmptyRetrievalFilter();

Parameters

None.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

An empty retrieval filter allows all messages to pass through.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::PushEmptyStorageFilter

Push an empty storage filter onto the storage-filter stack.

HRESULT PushEmptyStorageFilter();

Parameters

None.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

An empty storage filter allows all messages to pass through.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::PushRetrievalFilter

Push a retrieval filter onto the retrieval-filter stack.

HRESULT PushRetrievalFilter(
  D3D10_INFO_QUEUE_FILTER *pFilter
);

Parameters

pFilter
[in] Pointer to a retrieval filter (see D3D10_INFO_QUEUE_FILTER).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::PushStorageFilter

Push a storage filter onto the storage-filter stack.

HRESULT PushStorageFilter(
  D3D10_INFO_QUEUE_FILTER *pFilter
);

Parameters

pFilter
[in] Pointer to a storage filter (see D3D10_INFO_QUEUE_FILTER).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::SetBreakOnCategory

Set a message category to break on when a message with that category passes through the storage filter.

HRESULT SetBreakOnCategory(
  D3D10_MESSAGE_CATEGORY Category,
  BOOL bEnable
);

Parameters

Category
[in] Message category to break on (see D3D10_MESSAGE_CATEGORY).
bEnable
[in] Turns this breaking condition on or off (true for on, false for off).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::SetBreakOnID

Set a message identifier to break on when a message with that identifier passes through the storage filter.

HRESULT SetBreakOnID(
  D3D10_MESSAGE_ID ID,
  BOOL bEnable
);

Parameters

ID
[in] Message identifier to break on (see D3D10_MESSAGE_ID).
bEnable
[in] Turns this breaking condition on or off (true for on, false for off).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::SetBreakOnSeverity

Set a message severity level to break on when a message with that severity level passes through the storage filter.

HRESULT SetBreakOnSeverity(
  D3D10_MESSAGE_SEVERITY Severity,
  BOOL bEnable
);

Parameters

Severity
[in] Message severity level to break on (see D3D10_MESSAGE_SEVERITY).
bEnable
[in] Turns this breaking condition on or off (true for on, false for off).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::SetMessageCountLimit

Set the maximum number of messages that can be added to the message queue.

HRESULT SetMessageCountLimit(
  UINT64 MessageCountLimit
);

Parameters

MessageCountLimit
[in] Maximum number of messages that can be added to the message queue. -1 means no limit.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

When the number of messages in the message queue has reached the maximum limit, new messages coming in will push old messages out.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InfoQueue::SetMuteDebugOutput

Set a boolean that turns the debug output on or off.

void SetMuteDebugOutput(
  BOOL bMute
);

Parameters

bMute
[in] Turns the debug output on or off (true for on, false for off).

Return Values

Returns nothing.

Remarks

This will stop messages that pass the storage filter from being printed out in the debug output, however those messages will still be added to the message queue.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10InfoQueue Interface


ID3D10InputLayout Interface

Interface for an input-layout object, which describes the input data for the input-assembler stage.

Remarks

This interface is created by calling ID3D10Device::CreateInputLayout; use ID3D10Device::IASetInputLayout to bind it to the graphics pipeline.

See Also

Core Interfaces


ID3D10Multithread Interface

A multithread interface controls multithread settings and can only be used if the thread-safe layer is turned on. This interface contains methods shown in the following table.

Methods | Description
ID3D10Multithread::Enter | Enter a device's critical section.
ID3D10Multithread::GetMultithreadProtected | Find out if multithreading is turned on or not.
ID3D10Multithread::Leave | Leave a device's critical section.
ID3D10Multithread::SetMultithreadProtected | Turn multithreading on or off.

Remarks

This interface is obtained by querying it from the ID3D10Device Interface using IUnknown::QueryInterface.

See Also

Core Interfaces


ID3D10Multithread::Enter

Enter a device's critical section.

void Enter();

Parameters

None.

Return Values

Returns nothing.

Remarks

Entering a device's critical section prevents other threads from simultaneously calling that device's methods (if multithread protection is set to true), calling DXGI methods, and calling the methods of all resource, view, shader, state, and asynchronous interfaces.

This function should be used in multithreaded applications when there is a series of graphics commands that must happen in order. This function is typically called at the beginning of the series of graphics commands, and ID3D10Multithread::Leave is typically called after those graphics commands.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Multithread::GetMultithreadProtected

Find out if multithreading is turned on or not.

BOOL GetMultithreadProtected();

Parameters

None.

Return Values

Whether or not multithreading is turned on. True means on, false means off.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Multithread Interface


ID3D10Multithread::Leave

Leave a device's critical section.

void Leave();

Parameters

None.

Return Values

Returns nothing.

Remarks

This function is typically used in multithreaded applications when there is a series of graphics commands that must happen in order. ID3D10Multithread::Enter is typically called at the beginning of a series of graphics commands, and this function is typically called after those graphics commands.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Device Interface


ID3D10Multithread::SetMultithreadProtected

Turn multithreading on or off.

BOOL SetMultithreadProtected(
  BOOL bMTProtect
);

Parameters

bMTProtect
[in] True to turn multithreading on, false to turn it off.

Return Values

True if multithreading was turned on prior to calling this method, false otherwise.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Multithread Interface


ID3D10Predicate Interface

This interface encapsulates methods for determining whether a piece of geometry should be processed or not depending on the results of a previous draw call.

A predicate can be created with ID3D10Device::CreatePredicate.

There are two types of predicates in Direct3D 10: stream-output-overflow predicates and occlusion predicates. Stream-output-overflow predicates will cause any geometry residing in stream-output buffers that were overflowed to not be processed. Occlusion predicates will cause any geometry that did not have a single sample pass the depth/stencil tests to not be processed.

For an example of occlusion-predicated rendering, see Draw Predicated Sample.

Once created, this interface may be used with ID3D10Device::SetPredication.

See Also

Core Interfaces


ID3D10Query Interface

This interface encapsulates methods for querying information from the GPU. This interface contains methods shown in the following table.

Methods | Description
ID3D10Query::GetDesc | Get the properties of a query.

A query can be created with ID3D10Device::CreateQuery.

This interface inherits the functionality of an ID3D10Asynchronous Interface.

Query data is typically gathered by issuing an ID3D10Asynchronous::Begin command, issuing some graphics commands, issuing an ID3D10Asynchronous::End command, and then calling ID3D10Asynchronous::GetData to get data about what happened in between the Begin and End calls. The data returned by GetData will be different depending on the type of query.

There are, however, some queries that do not require calls to Begin. For a list of possible queries see D3D10_QUERY.

A query is typically executed in the following steps:

D3D10_QUERY_DESC queryDesc;

... // Fill out queryDesc structure

ID3D10Query * pQuery;
pDevice->CreateQuery(&queryDesc, &pQuery);

pQuery->Begin();

... // Issue graphis commands, do whatever

pQuery->End();

UINT64 queryData; // This data type is different depending on the query type

while( S_OK != pQuery->GetData(&queryData, sizeof(UINT64), 0) )
{
}

When using a query that does not require a call to Begin, it still requires a call to End. The call to End causes the data returned by GetData to be accurate up until the last call to End.

See Also

Core Interfaces


ID3D10Query::GetDesc

Get a query description.

void GetDesc(
  D3D10_QUERY_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a query description (see D3D10_QUERY_DESC).

Return Values

Returns nothing.

Requirements

Header: Declared in D3d10core.

See Also

ID3D10Query Interface


ID3D10RasterizerState Interface

Contains information about the behavior of the rasterizer stage.

This interface contains the following methods:

Method | Description
ID3D10RasterizerState::GetDesc | Get the properties of a rasterizer-state object.

Remarks

A rasterizer-state object is created with ID3D10Device::CreateRasterizerState and bound to the pipeline with ID3D10Device::RSSetState.

See Also

Core Interfaces


ID3D10RasterizerState::GetDesc

Get the properties of a rasterizer-state object.

void GetDesc(
  D3D10_RASTERIZER_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a rasterizer-state description (see D3D10_RASTERIZER_DESC).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10RasterizerState Interface


ID3D10SamplerState Interface

A sampler-state interface manages the state which sets up sampling information for a texture.

This interface contains the following methods:

Methods | Description
ID3D10SamplerState::GetDesc | Get the sampler state.

Create a sampler-state object by calling ID3D10Device::CreateSamplerState.

To initialize sampler state, bind the sampler-state object to the pipeline by calling ID3D10Device::VSSetSamplers, ID3D10Device::GSSetSamplers, or ID3D10Device::PSSetSamplers.

See Also

Core Reference


ID3D10SamplerState::GetDesc

Get the sampler state.

void GetDesc(
  D3D10_SAMPLER_DESC *pDesc
);

Parameters

pDesc
[out] A pointer to the sampler state (see D3D10_SAMPLER_DESC).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10SamplerState Interface


ID3D10StateBlock Interface

Encapsulates render states.

ID3D10StateBlock Members

Method | Description
ID3D10StateBlock::Apply | Apply the state block to the current device state.
ID3D10StateBlock::Capture | Capture the current value of states that are included in a stateblock.
ID3D10StateBlock::GetDevice | Gets the device.

Remarks

To create a state-block interface, call D3D10CreateStateBlock.

This interface can be used to save and restore pipeline state. It can also be used to capture the current state.

See Also

Core Interfaces


ID3D10StateBlock::Apply

Apply the state block to the current device state.

HRESULT Apply();

Parameters

None.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10StateBlock Interface


ID3D10StateBlock::Capture

Capture the current value of states that are included in a stateblock.

HRESULT Capture();

Parameters

None.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Capture captures current values for states within an existing state block. It does not capture the entire state of the device. Creating an empty stateblock and calling Capture does nothing if no states have been set.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10StateBlock Interface


ID3D10StateBlock::GetDevice

Get the device.

HRESULT GetDevice(
  ID3D10Device **ppDevice
);

Parameters

ppDevice
[out] Pointer to the ID3D10Device interface that is returned.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10StateBlock Interface


ID3D10SwitchToRef Interface

The ID3D10SwitchToRef Interface manages the switch-to-reference layer, which enables an application to switch between a hardware and software device. The interface contains the following methods.

Method | Description
ID3D10SwitchToRef::GetUseRef | Get a boolean value that indicates the type of device being used.
ID3D10SwitchToRef::SetUseRef | Switch between a hardware and software device.

This interface is obtained by calling IUnknown::QueryInterface on a ID3D10Device Interface created with the D3D10_CREATE_DEVICE_SWITCH_TO_REF flag.

See Also

Core Interfaces


ID3D10SwitchToRef::GetUseRef

Get a boolean value that indicates the type of device being used.

BOOL GetUseRef();

Parameters

None.

Return Values

TRUE if the device is a software device, FALSE if the device is a hardware device. See remarks.

Remarks

A hardware device is commonly refered to as a HAL device, which stands for a hardware accelerated device. This means that the pipeline is rendering all of the pipeline commands in hardware, using the GPU. Operating the pipeline with a HAL device gives the best performance generally, but it can be more difficult to debug since resources exist on the GPU instead of the CPU.

A software device implements rendering in software using the CPU with no hardware acceleration. A software device is commonly refered to as a reference device or REF device. Because a REF device implements rendering on the CPU, it is generally slower, but is easier to debug since it allows access to resources.

Requirements

Header: Declared in D3D10SDKLayers.h.

See Also

ID3D10SwitchToRef Interface


ID3D10SwitchToRef::SetUseRef

Switch between a hardware and a software device.

BOOL SetUseRef(
  BOOL UseRef
);

Parameters

UseRef
[in] A boolean value. Set this to TRUE to change to a software device, set this to FALSE to change to a hardware device.

Return Values

The previous value of UseRef.

Remarks

This API will fail if the device is not switchable; you must have created a device that is switchable by specifying the D3D10_CREATE_DEVICE_SWITCH_TO_REF flag during device creation (when calling D3D10CreateDevice).

Switching from a software device to a hardware device clears all cached objects from system memory. Switching from a hardware device to a software device causes resources to be downloaded to system memory.

Requirements

Header: Declared in D3D10SDKLayers.h.

See Also

ID3D10SwitchToRef Interface


Core Functions

This section contains information about the following core functions:

Functions | Description
D3D10CreateBlob | Create a buffer.
D3D10CreateDevice | Create a Direct3D device.
D3D10CreateDeviceAndSwapChain | Create a Direct3D device and a swap chain.

See Also

Core Reference


D3D10CreateBlob

Create a buffer.

HRESULT D3D10CreateBlob(
  SIZE_T NumBytes,
  LPD3D10BLOB *ppBuffer
);

Parameters

NumBytes
[in] Number of bytes in the blob.
ppBuffer
[out] The address of a pointer to the buffer (see ID3D10Blob Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Misc.h.

See Also

Core Functions


D3D10CreateDevice

Create a Direct3D device that represents the display adapter.

HRESULT D3D10CreateDevice(
  IDXGIAdapter *pAdapter,
  D3D10_DRIVER_TYPE DriverType,
  HMODULE Software,
  UINT Flags,
  UINT SDKVersion,
  ID3D10Device **ppDevice
);

Parameters

pAdapter
[in] Pointer to the display adapter (see IDXGIAdapter Interface) when creating a hardware device; otherwise set this parameter to NULL. If NULL is specified when creating a hardware device, Direct3D will use the first adapter enumerated by IDXGIFactory Interface.
DriverType
[in] The device-driver type (see D3D10_DRIVER_TYPE). The driver type determines the type of device you will create.
Software
[in] Reserved. Set to NULL.
Flags
[in] Optional. Device creation flags (see D3D10_CREATE_DEVICE_FLAG) that enable API layers. These flags can be bitwise OR'd together.
SDKVersion
[in] Bit flag that indicates the version of the SDK. Should always be D3D10_SDK_VERSION.
ppDevice
[out] Address of a pointer to the device created (see ID3D10Device Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

This example creates a NULL reference device.

ID3D10Device* g_pd3dDevice = NULL;
D3D10CreateDevice( NULL, D3D10_DRIVER_TYPE_REFERENCE, NULL, 0,
    D3D10_SDK_VERSION, &g_pd3dDevice );

To create a device and a swap chain at the same time, see D3D10CreateDeviceAndSwapChain.

Requirements

Header: Declared in D3D10Misc.h.

See Also

Core Functions


D3D10CreateDeviceAndSwapChain

Create a Direct3D device and a swap chain.

HRESULT D3D10CreateDeviceAndSwapChain(
  IDXGIAdapter *pAdapter,
  D3D10_DRIVER_TYPE DriverType,
  HMODULE Software,
  UINT Flags,
  UINT SDKVersion,
  DXGI_SWAP_CHAIN_DESC *pSwapChainDesc,
  IDXGISwapChain **ppSwapChain,
  ID3D10Device **ppDevice
);

Parameters

pAdapter
[in] Pointer to a IDXGIAdapter Interface.
DriverType
[in] The type of driver for the device. See D3D10_DRIVER_TYPE.
Software
[in] A handle to the DLL that implements a software rasterizer. Must be NULL if DriverType is non-software. The HMODULE of a DLL can be obtained with LoadLibrary, LoadLibraryEx, or GetModuleHandle.
Flags
[in] Optional. Device creation flags (see D3D10_CREATE_DEVICE_FLAG) that enable API layers. These flags can be bitwise OR'd together.
SDKVersion
[in] Bit flag that indicates the version of the SDK. Should be D3D_SDK_VERSION, defined in d3d10.h.
pSwapChainDesc
[in] Description of the swap chain. See DXGI_SWAP_CHAIN_DESC.
ppSwapChain
[out] Address of a pointer to an IDXGISwapChain Interface.
ppDevice
[out] Address of a pointer to an ID3D10Device Interface that will receive the newly created device.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

To create a device without creating a swap chain, see D3D10CreateDevice.

Requirements

Header: Declared in D3D10Misc.h.

See Also

Core Functions


Core Structures

This section contains information about the following core structures:

Structures | Description
D3D10_BLEND_DESC | Description of a blend operation.
D3D10_BOX | Defines a region, usually an area of a texture.
D3D10_COUNTER_DESC | Description of a performance counter.
D3D10_COUNTER_INFO | Information about the video card's performance counter capabilities.
D3D10_DEPTH_STENCIL_DESC | Description of a depth stencil resource.
D3D10_DEPTH_STENCILOP_DESC | Description of a depth stencil operation.
D3D10_INFO_QUEUE_FILTER | Debug message filter.
D3D10_INFO_QUEUE_FILTER_DESC | Allow or deny certain types of messages. See D3D10_INFO_QUEUE_FILTER_DESC.
D3D10_INPUT_ELEMENT_DESC | Description of a vertex element in a vertex buffer in an input slot.
D3D10_QUERY_DATA_PIPELINE_STATISTICS | Query information about graphics pipeline activity.
D3D10_QUERY_DATA_SO_STATISTICS | Query information about the amount of data streamed out to the output buffers.
D3D10_QUERY_DATA_TIMESTAMP_DISJOINT | Query information about the reliability of a timestamp query.
D3D10_QUERY_DESC | Description of a Query.
D3D10_MESSAGE | A debug message in the Information Queue.
D3D10_RASTERIZER_DESC | Description of the rasterizer stage of the pipeline.
D3D10_RECT | A 2D rectangle used as a scissors rectangle.
D3D10_SAMPLER_DESC | Description of a sampler.
D3D10_SIGNATURE_PARAMETER_DESC | Describes a parameter of a signature.
D3D10_STATE_BLOCK_MASK | Indicates the device state.
D3D10_SO_DECLARATION_ENTRY | Description of a vertex element in a vertex buffer in an output slot.
D3D10_VIEWPORT | Defines the dimensions of a viewport.

Remarks

In addition, there is a 2D rectangle structure defined in d3d10.h.

typedef RECT D3D10_RECT;

For documentation, see RECT.

See Also

Core Reference


D3D10_BLEND_DESC

Describes the blend state.

typedef struct D3D10_BLEND_DESC {
    BOOL AlphaToCoverageEnable;
    BOOL BlendEnable[8];
    D3D10_BLEND SrcBlend;
    D3D10_BLEND DestBlend;
    D3D10_BLEND_OP BlendOp;
    D3D10_BLEND SrcBlendAlpha;
    D3D10_BLEND DestBlendAlpha;
    D3D10_BLEND_OP BlendOpAlpha;
    UINT8 RenderTargetWriteMask[8];
} D3D10_BLEND_DESC;

Members

AlphaToCoverageEnable
Determines whether or not to use alpha-to-coverage as a multisampling technique when setting a pixel to a rendertarget.
BlendEnable
Enable (or disable) blending. There are eight elements in this array; these correspond to the eight rendertargets that can be set to output-merger stage at one time.
SrcBlend
This blend option specifies the first RGB data source and includes an optional pre-blend operation.
DestBlend
This blend option specifies the second RGB data source and includes an optional pre-blend operation.
BlendOp
This blend operation defines how to combine the RGB data sources.
SrcBlendAlpha
This blend option specifies the first alpha data source and includes an optional pre-blend operation. Blend options that end in _COLOR are not allowed.
DestBlendAlpha
This blend option specifies the second alpha data source and includes an optional pre-blend operation. Blend options that end in _COLOR are not allowed.
BlendOpAlpha
This blend operation defines how to combine the alpha data sources.
RenderTargetWriteMask
A per-pixel write mask that allows control over which components can be written (see D3D10_COLOR_WRITE_ENABLE).

Remarks

To see how blending is done, see Output-Merger Stage (Direct3D 10).

These are the default values for blend state.

State | Default Value
AlphaToCoverageEnable | FALSE
BlendEnable[8] | FALSE (for all 8)
SrcBlend | D3D10_BLEND_ONE
DestBlend | D3D10_BLEND_ZERO
BlendOp | D3D10_BLEND_OP_ADD
SrcBlendAlpha | D3D10_BLEND_ONE
DestBlendAlpha | D3D10_BLEND_ZERO
BlendOpAlpha | D3D10_BLEND_OP_ADD
RenderTargetWriteMask[8] | D3D10_COLOR_WRITE_ENABLE_ALL (for all 8)

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_BOX

Defines a 3D box.

typedef struct D3D10_BOX {
    UINT left;
    UINT top;
    UINT front;
    UINT right;
    UINT bottom;
    UINT back;
} D3D10_BOX;

Members

left
The x position of the left hand side of the box.
top
The y position of the top of the box.
front
The z position of the front of the box.
right
The x position of the right hand side of the box.
bottom
The y position of the bottom of the box.
back
The z position of the back of the box.

Remarks

Figure 1. 3D Box - Origin is left, front, top

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_COUNTER_DESC

Describes a counter.

typedef struct D3D10_COUNTER_DESC {
    D3D10_COUNTER Counter;
    UINT MiscFlags;
} D3D10_COUNTER_DESC;

Members

Counter
Type of counter (see D3D10_COUNTER).
MiscFlags
Reserved.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_COUNTER_INFO

Information about the video card's performance counter capabilities.

typedef struct D3D10_COUNTER_INFO {
    D3D10_COUNTER LastDeviceDependentCounter;
    UINT NumSimultaneousCounters;
    UINT8 NumDetectableParallelUnits;
} D3D10_COUNTER_INFO;

Members

LastDeviceDependentCounter
Largest device-dependent counter ID that the device supports. If none are supported, this value will be 0. Otherwise it will be greater than or equal to D3D10_COUNTER_DEVICE_DEPENDENT_0. See D3D10_COUNTER.
NumSimultaneousCounters
Number of counters that can be simultaneously supported.
NumDetectableParallelUnits
Number of detectable parallel units that the counter is able to discern. Values are 1 ~ 4. Use NumDetectableParallelUnits to interpret the values of the VERTEX_PROCESSING, GEOMETRY_PROCESSING, PIXEL_PROCESSING, and OTHER_GPU_PROCESSING counters. See ID3D10Asynchronous::GetData for an equation.

Remarks

This structure is returned by ID3D10Device::CheckCounterInfo.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_DEPTH_STENCILOP_DESC

Stencil operations that can be performed based on the results of stencil test.

typedef struct D3D10_DEPTH_STENCILOP_DESC {
    D3D10_STENCIL_OP StencilFailOp;
    D3D10_STENCIL_OP StencilDepthFailOp;
    D3D10_STENCIL_OP StencilPassOp;
    D3D10_COMPARISON_FUNC StencilFunc;
} D3D10_DEPTH_STENCILOP_DESC;

Members

StencilFailOp
The stencil operation to perform when stencil testing fails.
StencilDepthFailOp
The stencil operation to perform when stencil testing passes and depth testing fails.
StencilPassOp
The stencil operation to perform when stencil testing and depth testing both pass.
StencilFunc
A function that compares stencil data against existing stencil data. The function options are listed in D3D10_COMPARISON_FUNC.

Remarks

All stencil operations are specified as a D3D10_STENCIL_OP. The stencil operation can be set differently based on the outcome of the stencil test (which is referred to as StencilFunc in the stencil test portion of depth-stencil testing.

This structure is a member of a depth-stencil description.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_DEPTH_STENCIL_DESC

Describes depth-stencil state.

typedef struct D3D10_DEPTH_STENCIL_DESC {
    BOOL DepthEnable;
    D3D10_DEPTH_WRITE_MASK DepthWriteMask;
    D3D10_COMPARISON_FUNC DepthFunc;
    BOOL StencilEnable;
    UINT8 StencilReadMask;
    UINT8 StencilWriteMask;
    D3D10_DEPTH_STENCILOP_DESC FrontFace;
    D3D10_DEPTH_STENCILOP_DESC BackFace;
} D3D10_DEPTH_STENCIL_DESC;

Members

DepthEnable
Enable depth testing.
DepthWriteMask
Identify a portion of the depth-stencil buffer that can be modified by depth data (see D3D10_DEPTH_WRITE_MASK).
DepthFunc
A function that compares depth data against existing depth data. The function options are listed in D3D10_COMPARISON_FUNC.
StencilEnable
Enable stencil testing.
StencilReadMask
Identify a portion of the depth-stencil buffer for reading stencil data.
StencilWriteMask
Identify a portion of the depth-stencil buffer for writing stencil data.
FrontFace
Identify how to use the results of the depth test and the stencil test for pixels whose surface normal is facing towards the camera (see D3D10_DEPTH_STENCILOP_DESC).
BackFace
Identify how to use the results of the depth test and the stencil test for pixels whose surface normal is facing away from the camera (see D3D10_DEPTH_STENCILOP_DESC).

Remarks

Depth-stencil state controls how depth-stencil testing is performed by the output-merger stage.

The following table shows the default values of depth-stencil states.

State | Default Value
DepthEnable | TRUE
DepthWriteMask | D3D10_DEPTH_WRITE_MASK_ALL
DepthFunc | D3D10_COMPARISON_LESS
StencilEnable | FALSE
StencilReadMask | D3D10_DEFAULT_STENCIL_READ_MASK
StencilWriteMask | D3D10_DEFAULT_STENCIL_WRITE_MASK
StencilFunc | D3D10_STENCIL_OP_KEEP
StencilDepthFailOp | D3D10_STENCIL_OP_KEEP
StencilPassOp | D3D10_STENCIL_OP_KEEP
StencilFailOp | D3D10_COMPARISON_ALWAYS

The formats that support stenciling are DXGI_FORMAT_D24_UNORM_S8_UINT and DXGI_FORMAT_D32_FLOAT_S8X24_UINT.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_INFO_QUEUE_FILTER

Debug message filter; contains a lists of message types to allow or deny.

typedef struct D3D10_INFO_QUEUE_FILTER {
    D3D10_INFO_QUEUE_FILTER_DESC AllowList;
    D3D10_INFO_QUEUE_FILTER_DESC DenyList;
} D3D10_INFO_QUEUE_FILTER;

Members

AllowList
Types of messages that you want to allow. See D3D10_INFO_QUEUE_FILTER_DESC.
DenyList
Types of messages that you want to deny.

Remarks

For use with an ID3D10InfoQueue Interface.

Requirements

Header: Declared in D3d10.h.

See Also

Core Structures


D3D10_INFO_QUEUE_FILTER_DESC

Allow or deny certain types of messages to pass through a filter.

typedef struct D3D10_INFO_QUEUE_FILTER_DESC {
    UINT NumCategories;
    D3D10_MESSAGE_CATEGORY *pCategoryList;
    UINT NumSeverities;
    D3D10_MESSAGE_SEVERITY *pSeverityList;
    UINT NumIDs;
    D3D10_MESSAGE_ID *pIDList;
} D3D10_INFO_QUEUE_FILTER_DESC;

Members

NumCategories
Number of message categories to allow or deny.
pCategoryList
Array of message categories to allow or deny. Array must have at least NumCategories members (see D3D10_MESSAGE_CATEGORY).
NumSeverities
Number of message severity levels to allow or deny.
pSeverityList
Array of message severity levels to allow or deny. Array must have at least NumSeverities members (see D3D10_MESSAGE_SEVERITY).
NumIDs
Number of message IDs to allow or deny.
pIDList
Array of message IDs to allow or deny. Array must have at least NumIDs members (see D3D10_MESSAGE_ID).

Requirements

Header: Declared in D3d10.h.

See Also

Core Structures


D3D10_INPUT_ELEMENT_DESC

A description of a single element for the input-assembler stage.

typedef struct D3D10_INPUT_ELEMENT_DESC {
    LPCSTR SemanticName;
    UINT SemanticIndex;
    DXGI_FORMAT Format;
    UINT InputSlot;
    UINT AlignedByteOffset;
    D3D10_INPUT_CLASSIFICATION InputSlotClass;
    UINT InstanceDataStepRate;
} D3D10_INPUT_ELEMENT_DESC;

Members

SemanticName
The HLSL semantic associated with this element in a shader input-signature.
SemanticIndex
The semantic index for the element. A semantic index modifies a semantic, with an integer index number. A semantic index is only needed in a case where there is more than one element with the same semantic. For example, a 4x4 matrix would have four components each with the semantic name matrix, however each of the four component would have different semantic indices (0, 1, 2, and 3).
Format
The data type of the element data. See DXGI_FORMAT.
InputSlot
An integer value that identifies the input-assembler (see input slot). Valid values are between 0 and 15, defined in D3D10.h.
AlignedByteOffset
Optional. Offset (in bytes) between each element. Use D3D10_APPEND_ALIGNED_ELEMENT for convenience to define the current element directly after the previous one, including any packing if necessary.
InputSlotClass
Identifies the input data class for a single input slot (see D3D10_INPUT_CLASSIFICATION).
InstanceDataStepRate
The number of instances to draw using the same per-instance data before advancing in the buffer by one element. This value must be 0 for an element that contains per-vertex data (the slot class is set to D3D10_INPUT_PER_VERTEX_DATA).

Remarks

An input-layout object contains an array of structures, each structure defines one element being read from an input slot. Create an input-layout object by calling ID3D10Device::CreateInputLayout. For an example, see Create an input-layout object.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_MESSAGE

A debug message in the Information Queue.

typedef struct D3D10_MESSAGE {
    D3D10_MESSAGE_CATEGORY Category;
    D3D10_MESSAGE_SEVERITY Severity;
    D3D10_MESSAGE_ID ID;
    const char *pDescription;
    SIZE_T DescriptionByteLength;
} D3D10_MESSAGE;

Members

Category
The category of the message. See D3D10_MESSAGE_CATEGORY.
Severity
The severity of the message. See D3D10_MESSAGE_SEVERITY.
ID
The ID of the message. See D3D10_MESSAGE_ID.
pDescription
The message string.
DescriptionByteLength
The length of pDescription in bytes.

Remarks

This structure is returned from ID3D10InfoQueue::GetMessage as part of the Information Queue feature (see ID3D10InfoQueue Interface).

Requirements

Header: Declared in D3d10.h.

See Also

Core Structures


D3D10_QUERY_DATA_PIPELINE_STATISTICS

Query information about graphics-pipeline activity in between calls to ID3D10Asynchronous::Begin and ID3D10Asynchronous::End.

typedef struct D3D10_QUERY_DATA_PIPELINE_STATISTICS {
    UINT64 IAVertices;
    UINT64 IAPrimitives;
    UINT64 VSInvocations;
    UINT64 GSInvocations;
    UINT64 GSPrimitives;
    UINT64 CInvocations;
    UINT64 CPrimitives;
    UINT64 PSInvocations;
} D3D10_QUERY_DATA_PIPELINE_STATISTICS;

Members

IAVertices
Number of vertices read by input assembler.
IAPrimitives
Number of primitives read by the input assembler. This number can be different depending on the primitive topology used. For example, a triangle strip with 6 vertices will produce 4 triangles, however a triangle list with 6 vertices will produce 2 triangles.
VSInvocations
Number of times a vertex shader was invoked. Direct3D invokes the vertex shader once per vertex.
GSInvocations
Number of times a geometry shader was invoked. When the geometry shader is set to NULL, this statistic may or may not increment depending on the hardware manufacturer.
GSPrimitives
Number of primitives output by a geometry shader.
CInvocations
Number of primitives that were sent to the rasterizer. When the rasterizer is disabled, this will not increment.
CPrimitives
Number of primitives that were rendered. This may be larger or smaller than CInvocations because after a primitive is clipped sometimes it is either broken up into more than one primitive or completely culled.
PSInvocations
Number of times a pixel shader was invoked.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_QUERY_DATA_SO_STATISTICS

Query information about the amount of data streamed out to the stream-output buffers in between ID3D10Asynchronous::Begin and ID3D10Asynchronous::End.

typedef struct D3D10_QUERY_DATA_SO_STATISTICS {
    UINT64 NumPrimitivesWritten;
    UINT64 PrimitivesStorageNeeded;
} D3D10_QUERY_DATA_SO_STATISTICS;

Members

NumPrimitivesWritten
Number of primitives (that is, points, lines, and triangles) written to the stream-output buffers.
PrimitivesStorageNeeded
Number of primitives that would have been written to the stream-output buffers if there had been enough space for them all.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_QUERY_DATA_TIMESTAMP_DISJOINT

Query information about the reliability of a timestamp query.

typedef struct D3D10_QUERY_DATA_TIMESTAMP_DISJOINT {
    UINT64 Frequency;
    BOOL Disjoint;
} D3D10_QUERY_DATA_TIMESTAMP_DISJOINT;

Members

Frequency
How frequently the GPU counter increments in Hz.
Disjoint
If this is TRUE, something occurred in between the query's ID3D10Asynchronous::Begin and ID3D10Asynchronous::End calls that caused the timestamp counter to become discontinuous or disjoint, such as unplugging the AC chord on a laptop, overheating, or throttling up/down due to laptop savings events. The timestamp returned by ID3D10Asynchronous::GetData for a timestamp query is only reliable if Disjoint is FALSE.

Remarks

For a list of query types see D3D10_QUERY.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_QUERY_DESC

Describes a query.

typedef struct D3D10_QUERY_DESC {
    D3D10_QUERY Query;
    UINT MiscFlags;
} D3D10_QUERY_DESC;

Members

Query
Type of query (see D3D10_QUERY).
MiscFlags
Miscellaneous flags (see D3D10_QUERY_MISC_FLAG).

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_RASTERIZER_DESC

Contains information about the behavior of the rasterizer stage.

typedef struct D3D10_RASTERIZER_DESC {
    D3D10_FILL_MODE FillMode;
    D3D10_CULL_MODE CullMode;
    BOOL FrontCounterClockwise;
    INT DepthBias;
    FLOAT DepthBiasClamp;
    FLOAT SlopeScaledDepthBias;
    BOOL DepthClipEnable;
    BOOL ScissorEnable;
    BOOL MultisampleEnable;
    BOOL AntialiasedLineEnable;
} D3D10_RASTERIZER_DESC;

Members

FillMode
Determines the fill mode to use when rendering (see D3D10_FILL_MODE).
CullMode
Indicates triangles facing the specified direction are not drawn (see D3D10_CULL_MODE).
FrontCounterClockwise
Determines if a triangle is front- or back-facing. If this parameter is true, then a triangle will be considered front-facing if its vertices are counter-clockwise on the render target and considered back-facing if they are clockwise. If this parameter is false then the opposite is true.
DepthBias
Depth value added to a given pixel (see Depth Bias).
DepthBiasClamp
Maximum depth bias of a pixel (see Depth Bias).
SlopeScaledDepthBias
Scalar on a given pixel's slope (see Depth Bias).
DepthClipEnable
Enable clipping based on distance.
ScissorEnable
Enable scissor-rectangle culling. All pixels ouside an active scissor rectangle are culled (see Set the Scissor Rectangle).
MultisampleEnable
Enable multisample antialiasing.
AntialiasedLineEnable
Enable line antialiasing; only applies if doing line drawing and MultisampleEnable is false.

Remarks

Depth Bias

Polygons that are coplanar in 3D space can be made to appear as if they are not coplanar by adding a z-bias (or depth bias) to each one. This is a technique commonly used to ensure that shadows in a scene are displayed properly. For instance, a shadow on a wall will likely have the same depth value as the wall. If an application renders a wall first and then a shadow, the shadow might not be visible, or depth artifacts might be visible.

An application can help ensure that coplanar polygons are rendered properly by adding a bias to the z-values that the system uses when rendering the sets of coplanar polygons. The depth bias can be specified in the DepthBias member of this structure.

The DepthBias, DepthBiasClamp, and SlopeScaledDepthBias members of this structure are all part of the pixel depth calculation, which is done in a three-step process that Direct3D will do.

Direct3D will first calculate the bias in one of two ways.

If the depth buffer currently bound to the output-merger stage has a UNORM format or no depth buffer is bound the calculation will be:

Bias = (float)DepthBias * r + SlopeScaledDepthBias * MaxDepthSlope;

Where r is the minimum representable value > 0 in the depth buffer format, converted to float32. If a floating-point depth buffer is bound to the output-merger stage, then the bias calculation will be:

Bias = (float)DepthBias * 2^(exponent(max z in primitive) - r) +
            SlopeScaledDepthBias * MaxDepthSlope;

Where r is the number of mantissa bits in the floating point representation (excluding the hidden bit); for example, 23 for float32.

In the second step of bias calculation, Direct3D will clamp the bias value like so:

if(DepthBiasClamp > 0)
    Bias = min(DepthBiasClamp, Bias)
else if(DepthBiasClamp < 0)
    Bias = max(DepthBiasClamp, Bias)

In the third and final step, Direct3D will calculate the pixel depth (z):

if ( (DepthBias != 0) || (SlopeScaledDepthBias != 0) )
    z = z + Bias

Polygons with a larger PixelDepth will be drawn in front of polygons with a smaller PixelDepth.

SlopeScaledDepthBias provides a method of scaling up the PixelDepth when the polygon is being viewed at an angle.

The SlopeScaledDepthBias equation can return an unreasonably large PixelDepth for extremely steep polygons which can result in visual artifacts. DepthBiasClamp solves this problem by providing a way of indicating the largest possible bias amount.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_RECT

D3D10_RECT is declared as follows:

typedef RECT D3D10_RECT;

For more information about this GDI rectangle structure, see RECT.

Remarks

This structure is used for scissor rectangles by ID3D10Device::RSGetScissorRects and ID3D10Device::RSSetScissorRects.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_SAMPLER_DESC

Describes a sampler state.

typedef struct D3D10_SAMPLER_DESC {
    D3D10_FILTER Filter;
    D3D10_TEXTURE_ADDRESS_MODE AddressU;
    D3D10_TEXTURE_ADDRESS_MODE AddressV;
    D3D10_TEXTURE_ADDRESS_MODE AddressW;
    FLOAT MipLODBias;
    UINT MaxAnisotropy;
    D3D10_COMPARISON_FUNC ComparisonFunc;
    FLOAT BorderColor[4];
    FLOAT MinLOD;
    FLOAT MaxLOD;
} D3D10_SAMPLER_DESC;

Members

Filter
Filtering method to use when sampling a texture (see D3D10_FILTER).
AddressU
Method to use for resolving a u texture coordinate that is outside the 0 to 1 range (see D3D10_TEXTURE_ADDRESS_MODE).
AddressV
Method to use for resolving a v texture coordinate that is outside the 0 to 1 range.
AddressW
Method to use for resolving a w texture coordinate that is outside the 0 to 1 range.
MipLODBias
Offset from the calculated mipmap level. For example, if Direct3D calculates that a texture should be sampled at mipmap level 3 and MipLODBias is 2, then the texture will be sampled at mipmap level 5.
MaxAnisotropy
Clamping value used if D3D10_FILTER_ANISOTROPIC or D3D10_FILTER_COMPARISON_ANISOTROPIC is specified in Filter. Valid values are between 1 and 16.
ComparisonFunc
A function that compares sampled data against existing sampled data. The function options are listed in D3D10_COMPARISON_FUNC.
BorderColor
Border color to use if D3D10_TEXTURE_ADDRESS_BORDER is specified for AddressU, AddressV, or AddressW. Range must be between 0.0 and 1.0 inclusive.
MinLOD
Lower end of the mipmap range to clamp access to, where 0 is the largest and most detailed mipmap level and any level higher than that is less detailed.
MaxLOD
Upper end of the mipmap range to clamp access to, where 0 is the largest and most detailed mipmap level and any level higher than that is less detailed. This value must be greater than or equal to MinLOD. To have no upper limit on LOD set this to a large value such as D3D10_FLOAT32_MAX.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_STATE_BLOCK_MASK

Indicates the device state.

typedef struct D3D10_STATE_BLOCK_MASK {
    BYTE VS;
    BYTE VSSamplers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT)];
    BYTE VSShaderResources[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)];
    BYTE VSConstantBuffers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_CONSTANT_BUFFER_SLOT_COUNT)];
    BYTE GS;
    BYTE GSSamplers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT)];
    BYTE GSShaderResources[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)];
    BYTE GSConstantBuffers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_CONSTANT_BUFFER_SLOT_COUNT)];
    BYTE PS;
    BYTE PSSamplers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT)];
    BYTE PSShaderResources[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)];
    BYTE PSConstantBuffers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_CONSTANT_BUFFER_SLOT_COUNT)];
    BYTE IAVertexBuffers[D3D10_BYTES_FROM_BITS(D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT)];
    BYTE IAIndexBuffer;
    BYTE IAInputLayout;
    BYTE IAPrimitiveTopology;
    BYTE OMRenderTargets;
    BYTE OMDepthStencilState;
    BYTE OMBlendState;
    BYTE RSViewports;
    BYTE RSScissorRects;
    BYTE RSRasterizerState;
    BYTE SOBuffers;
    BYTE Predication;
} D3D10_STATE_BLOCK_MASK;

Members

VS
Vertex shader.
VSSamplers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT)]
Array of vertex-shader samplers.
VSShaderResources[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]
Array of vertex-shader resources.
VSConstantBuffers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_CONSTANT_BUFFER_SLOT_COUNT)]
Array of vertex-shader constant buffers.
GS
Geometry shader.
GSSamplers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT)]
Array of geometry-shader samplers.
GSShaderResources[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]
Array of geometry-shader resources.
GSConstantBuffers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_CONSTANT_BUFFER_SLOT_COUNT)]
Array of geometry-shader constant buffers.
PS
Pixel shader.
PSSamplers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT)]
Array of pixel-shader samplers.
PSShaderResources[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]
Array of pixel-shader resources.
PSConstantBuffers[D3D10_BYTES_FROM_BITS(D3D10_COMMONSHADER_CONSTANT_BUFFER_SLOT_COUNT)]
Array of pixel-shader constant buffers.
IAVertexBuffers[D3D10_BYTES_FROM_BITS(D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT)]
Array of vertex buffers.
IAIndexBuffer
Index buffer.
IAInputLayout
Input layout.
IAPrimitiveTopology
Primitive topology.
OMRenderTargets
Render targets.
OMDepthStencilState
Depth-stencil state.
OMBlendState
Blend state.
RSViewports
Viewports.
RSScissorRects
Scissor rectangles.
RSRasterizerState
Rasterizer state.
SOBuffers
Stream-out buffers.
Predication
Predication.

Remarks

A state-block mask indicates the device states that a pass or a technique changes.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_SO_DECLARATION_ENTRY

Description of a vertex element in a vertex buffer in an output slot.

typedef struct D3D10_SO_DECLARATION_ENTRY {
    LPCSTR SemanticName;
    UINT SemanticIndex;
    BYTE StartComponent;
    BYTE ComponentCount;
    BYTE OutputSlot;
} D3D10_SO_DECLARATION_ENTRY;

Members

SemanticName
Type of output element. Possible values: L"POSITION", L"NORMAL", or L"TEXCOORD0".
SemanticIndex
Output element's zero-based index. Should be used if, for example, you have more than one texture coordinate stored in each vertex.
StartComponent
Which component of the entry to begin writing out to. Valid values are 0 ~ 3. For example, if you only wish to output to the y and z components of a position, then StartComponent should be 1 and ComponentCount should be 2.
ComponentCount
The number of components of the entry to write out to. Valid values are 1 ~ 4. For example, if you only wish to output to the y and z components of a position, then StartComponent should be 1 and ComponentCount should be 2.
OutputSlot
The output slot that contains the vertex buffer that contains this output entry.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


D3D10_VIEWPORT

Defines the dimensions of a viewport.

typedef struct D3D10_VIEWPORT {
    INT TopLeftX;
    INT TopLeftY;
    UINT Width;
    UINT Height;
    FLOAT MinDepth;
    FLOAT MaxDepth;
} D3D10_VIEWPORT;

Members

TopLeftX
X position of the left hand side of the viewport. Must be between -16384 and 16383.
TopLeftY
Y position of the top of the viewport. Must be between -16384 and 16383.
Width
Width of the viewport. Must be between -16384 and 16383.
Height
Height of the viewport. Must be between -16384 and 16383.
MinDepth
Minimum depth of the viewport. Must be between 0 and 1.
MaxDepth
Maximum depth of the viewport. Must be between 0 and 1.

Requirements

Header: Declared in D3D10.h.

See Also

Core Structures


Core Enumerations

This section contains information about the following core enumerations:

Enumeration | Description
D3D10_ASYNC_GETDATA_FLAG | Optional flags that control what happens when data is retrieved by calling ID3D10Asynchronous::GetData.
D3D10_BLEND | Types of blend colors usually used to define the source and destination colors of a blend operation.
D3D10_BLEND_OP | Blending operations between source and destination pixels.
D3D10_CLEAR_FLAG | Specifies which parts of the depth stencil to clear.
D3D10_COLOR_WRITE_ENABLE | Color writing masks.
D3D10_COMPARISON_FUNC | Comparison functions.
D3D10_COUNTER | Types of performance counters.
D3D10_COUNTER_TYPE | Data type of a counter.
D3D10_CREATE_DEVICE_FLAG | Device creation flags.
D3D10_CULL_MODE | Rasterizer cull modes.
D3D10_DEPTH_WRITE_MASK | Determines which portion of the depth stencil is writable.
D3D10_DEVICE_STATE_TYPES | Used in ID3D10StateBlockMask function calls.
D3D10_DRIVER_TYPE | Type of device driver.
D3D10_FILL_MODE | Rasterizer fill modes.
D3D10_FILTER | Types of sampler filters.
D3D10_FILTER_TYPE | Types of magnification or minification sampler filters.
D3D10_FORMAT_SUPPORT | Which resources are supported for a given format and given device. See ID3D10Device::CheckFormatSupport.
D3D10_INPUT_CLASSIFICATION | Types of input data.
D3D10_MESSAGE_CATEGORY | Categories of debug messages.
D3D10_MESSAGE_ID | A debug message's unique ID.
D3D10_MESSAGE_SEVERITY | Severity of a debug message.
D3D10_PRIMITIVE_TOPOLOGY | Types of primitive topology or the way a primitive's data is arranged.
D3D10_QUERY | Types of queries.
D3D10_QUERY_MISC_FLAG | Flags that describe miscellaneous query behavior.
D3D10_RAISE_FLAG | Flags that indicate how to handle internal driver errors.
D3D10_REGISTER_COMPONENT_TYPE | The register component types, usually used in D3D10_SIGNATURE_PARAMETER_DESC.
D3D10_RESOURCE_RETURN_TYPE | The return type of a resource. See D3D10_SHADER_INPUT_BIND_DESC.
D3D10_STENCIL_OP | Stencil operations.
D3D10_TEXTURE_ADDRESS_MODE | Actions to perform when a texture coordinate is outside of the boundaries of a texture.
D3D10_TEXTURECUBE_FACE | The different faces of a cube texture.

See Also

Core Reference


D3D10_ASYNC_GETDATA_FLAG

Optional flags that control the behavior of ID3D10Asynchronous::GetData.

typedef enum D3D10_ASYNC_GETDATA_FLAG
{
    D3D10_ASYNC_GETDATA_DONOTFLUSH = 0x1,
} D3D10_ASYNC_GETDATA_FLAG;

Constants

D3D10_ASYNC_GETDATA_DONOTFLUSH
Do not flush the command buffer. This can potentially cause an infinite loop if GetData is continually called until it returns S_OK as there may still be commands in the command buffer that need to be processed in order for GetData to return S_OK. Since the commands in the command buffer are not flushed they will not be processed and therefore GetData will never return S_OK.

Requirements

Header: Declared in D3d10core.h.

See Also

Core Enumerations


D3D10_BLEND

Blend options. A blend option identifies the data source and an optional pre-blend operation.

typedef enum D3D10_BLEND
{
    D3D10_BLEND_ZERO = 1,
    D3D10_BLEND_ONE = 2,
    D3D10_BLEND_SRC_COLOR = 3,
    D3D10_BLEND_INV_SRC_COLOR = 4,
    D3D10_BLEND_SRC_ALPHA = 5,
    D3D10_BLEND_INV_SRC_ALPHA = 6,
    D3D10_BLEND_DEST_ALPHA = 7,
    D3D10_BLEND_INV_DEST_ALPHA = 8,
    D3D10_BLEND_DEST_COLOR = 9,
    D3D10_BLEND_INV_DEST_COLOR = 10,
    D3D10_BLEND_SRC_ALPHA_SAT = 11,
    D3D10_BLEND_BLEND_FACTOR = 14,
    D3D10_BLEND_INV_BLEND_FACTOR = 15,
    D3D10_BLEND_SRC1_COLOR = 16,
    D3D10_BLEND_INV_SRC1_COLOR = 17,
    D3D10_BLEND_SRC1_ALPHA = 18,
    D3D10_BLEND_INV_SRC1_ALPHA = 19,
} D3D10_BLEND;

Constants

D3D10_BLEND_ZERO
The data source is the color black (0, 0, 0, 0). No pre-blend operation.
D3D10_BLEND_ONE
The data source is the color white (1, 1, 1, 1). No pre-blend operation.
D3D10_BLEND_SRC_COLOR
The data source is color data (RGB) from a pixel shader. No pre-blend operation.
D3D10_BLEND_INV_SRC_COLOR
The data source is color data (RGB) from a pixel shader. The pre-blend operation inverts the data, generating 1 - RGB.
D3D10_BLEND_SRC_ALPHA
The data source is alpha data (A) from a pixel shader. No pre-blend operation.
D3D10_BLEND_INV_SRC_ALPHA
The data source is alpha data (A) from a pixel shader. The pre-blend operation inverts the data, generating 1 - A.
D3D10_BLEND_DEST_ALPHA
The data source is alpha data from a rendertarget. No pre-blend operation.
D3D10_BLEND_INV_DEST_ALPHA
The data source is alpha data from a rendertarget. The pre-blend operation inverts the data, generating 1 - A.
D3D10_BLEND_DEST_COLOR
The data source is color data from a rendertarget. No pre-blend operation.
D3D10_BLEND_INV_DEST_COLOR
The data source is color data from a rendertarget. The pre-blend operation inverts the data, generating 1 - RGB.
D3D10_BLEND_SRC_ALPHA_SAT
The data source is alpha data from a pixel shader. The pre-blend operation clamps the data to 1 or less.
D3D10_BLEND_BLEND_FACTOR
The data source is the blend factor set with ID3D10Device::OMSetBlendState. No pre-blend operation.
D3D10_BLEND_INV_BLEND_FACTOR
The data source is the blend factor set with ID3D10Device::OMSetBlendState. The pre-blend operation inverts the blend factor, generating 1 - blend_factor.
D3D10_BLEND_SRC1_COLOR
The data sources are both color data output by a pixel shader. There is no pre-blend operation. This options supports dual-source color blending.
D3D10_BLEND_INV_SRC1_COLOR
The data sources are both color data output by a pixel shader. The pre-blend operation inverts the data, generating 1 - RGB. This options supports dual-source color blending.
D3D10_BLEND_SRC1_ALPHA
The data sources are alpha data output by a pixel shader. There is no pre-blend operation. This options supports dual-source color blending.
D3D10_BLEND_INV_SRC1_ALPHA
The data sources are alpha data output by a pixel shader. The pre-blend operation inverts the data, generating 1 - A. This options supports dual-source color blending.

Remarks

Blend operations are specified in a blend description.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_BLEND_OP

RGB or alpha blending operation.

typedef enum D3D10_BLEND_OP
{
    D3D10_BLEND_OP_ADD = 1,
    D3D10_BLEND_OP_SUBTRACT = 2,
    D3D10_BLEND_OP_REV_SUBTRACT = 3,
    D3D10_BLEND_OP_MIN = 4,
    D3D10_BLEND_OP_MAX = 5,
} D3D10_BLEND_OP;

Constants

D3D10_BLEND_OP_ADD
Add source 1 and source 2.
D3D10_BLEND_OP_SUBTRACT
Subtract source 1 from source 2.
D3D10_BLEND_OP_REV_SUBTRACT
Subtract source 2 from source 1.
D3D10_BLEND_OP_MIN
Find the minimum of source 1 and source 2.
D3D10_BLEND_OP_MAX
Find the maximum of source 1 and source 2.

Remarks

The runtime implements RGB blending and alpha blending separately. Therefore, blend state requires separate blend operations for RGB data and alpha data. These blend operations are specified in a blend description. The two sources — Source 1, called SrcBlend and SrcBlendAlpha, and Source 2, called DestBlend and DestBlendAlpha — are shown in the blending block diagram.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_CLEAR_FLAG

Specifies the parts of the depth stencil to clear. Usually used with ID3D10Device::ClearDepthStencilView.

typedef enum D3D10_CLEAR_FLAG
{
    D3D10_CLEAR_DEPTH = 0x1L,
    D3D10_CLEAR_STENCIL = 0x2L,
} D3D10_CLEAR_FLAG;

Constants

D3D10_CLEAR_DEPTH
Clear the depth buffer.
D3D10_CLEAR_STENCIL
Clear the stencil buffer.

Remarks

These flags can be bitwise ORed together.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_COLOR_WRITE_ENABLE

Identify which components of each pixel of a render target are writable during blending.

typedef enum D3D10_COLOR_WRITE_ENABLE
{
    D3D10_COLOR_WRITE_ENABLE_RED = 1,
    D3D10_COLOR_WRITE_ENABLE_GREEN = 2,
    D3D10_COLOR_WRITE_ENABLE_BLUE = 4,
    D3D10_COLOR_WRITE_ENABLE_ALPHA = 8,
    D3D10_COLOR_WRITE_ENABLE_ALL =
      ( D3D10_COLOR_WRITE_ENABLE_RED | D3D10_COLOR_WRITE_ENABLE_GREEN |
        D3D10_COLOR_WRITE_ENABLE_BLUE | D3D10_COLOR_WRITE_ENABLE_ALPHA ),
} D3D10_COLOR_WRITE_ENABLE;

Constants

D3D10_COLOR_WRITE_ENABLE_RED
Allow data to be stored in the red component.
D3D10_COLOR_WRITE_ENABLE_GREEN
Allow data to be stored in the green component.
D3D10_COLOR_WRITE_ENABLE_BLUE
Allow data to be stored in the blue component.
D3D10_COLOR_WRITE_ENABLE_ALPHA
Allow data to be stored in the alpha component.
D3D10_COLOR_WRITE_ENABLE_ALL
Allow data to be stored in all components.

Remarks

These flags can be combined with a bitwise OR.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_COMPARISON_FUNC

Comparison options.

typedef enum D3D10_COMPARISON_FUNC
{
    D3D10_COMPARISON_NEVER = 1,
    D3D10_COMPARISON_LESS = 2,
    D3D10_COMPARISON_EQUAL = 3,
    D3D10_COMPARISON_LESS_EQUAL = 4,
    D3D10_COMPARISON_GREATER = 5,
    D3D10_COMPARISON_NOT_EQUAL = 6,
    D3D10_COMPARISON_GREATER_EQUAL = 7,
    D3D10_COMPARISON_ALWAYS = 8,
} D3D10_COMPARISON_FUNC;

Constants

D3D10_COMPARISON_NEVER
Never pass the comparison.
D3D10_COMPARISON_LESS
If the source data is less than the destination data, the comparison passes.
D3D10_COMPARISON_EQUAL
If the source data is equal to the destination data, the comparison passes.
D3D10_COMPARISON_LESS_EQUAL
If the source data is less than or equal to the destination data, the comparison passes.
D3D10_COMPARISON_GREATER
If the source data is greater than the destination data, the comparison passes.
D3D10_COMPARISON_NOT_EQUAL
If the source data is not equal to the destination data, the comparison passes.
D3D10_COMPARISON_GREATER_EQUAL
If the source data is greater than or equal to the destination data, the comparison passes.
D3D10_COMPARISON_ALWAYS
Always pass the comparison.

Remarks

A comparison option determines whether how the runtime compares source (new) data against destination (existing) data before storing the new data. The comparison option is declared in a decription before an object is created. The API allows you to set a comparison option for a depth-stencil buffer (see D3D10_DEPTH_STENCIL_DESC), depth-stencil operations (see D3D10_DEPTH_STENCILOP_DESC), or sampler state (see D3D10_SAMPLER_DESC).

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_COUNTER

Performance counter types.

typedef enum D3D10_COUNTER
{
    D3D10_COUNTER_GPU_IDLE = 0,
    D3D10_COUNTER_VERTEX_PROCESSING = ( D3D10_COUNTER_GPU_IDLE + 1 ),
    D3D10_COUNTER_GEOMETRY_PROCESSING = ( D3D10_COUNTER_VERTEX_PROCESSING + 1 ),
    D3D10_COUNTER_PIXEL_PROCESSING = ( D3D10_COUNTER_GEOMETRY_PROCESSING + 1 ),
    D3D10_COUNTER_OTHER_GPU_PROCESSING = ( D3D10_COUNTER_PIXEL_PROCESSING + 1 ),
    D3D10_COUNTER_HOST_ADAPTER_BANDWIDTH_UTILIZATION = ( D3D10_COUNTER_OTHER_GPU_PROCESSING + 1 ),
    D3D10_COUNTER_LOCAL_VIDMEM_BANDWIDTH_UTILIZATION = ( D3D10_COUNTER_HOST_ADAPTER_BANDWIDTH_UTILIZATION + 1 ),
    D3D10_COUNTER_VERTEX_THROUGHPUT_UTILIZATION = ( D3D10_COUNTER_LOCAL_VIDMEM_BANDWIDTH_UTILIZATION + 1 ),
    D3D10_COUNTER_TRIANGLE_SETUP_THROUGHPUT_UTILIZATION = ( D3D10_COUNTER_VERTEX_THROUGHPUT_UTILIZATION + 1 ),
    D3D10_COUNTER_FILLRATE_THROUGHPUT_UTILIZATION = ( D3D10_COUNTER_TRIANGLE_SETUP_THROUGHPUT_UTILIZATION + 1 ),
    D3D10_COUNTER_VS_MEMORY_LIMITED = ( D3D10_COUNTER_FILLRATE_THROUGHPUT_UTILIZATION + 1 ),
    D3D10_COUNTER_VS_COMPUTATION_LIMITED = ( D3D10_COUNTER_VS_MEMORY_LIMITED + 1 ),
    D3D10_COUNTER_GS_MEMORY_LIMITED = ( D3D10_COUNTER_VS_COMPUTATION_LIMITED + 1 )),
    D3D10_COUNTER_GS_COMPUTATION_LIMITED = ( D3D10_COUNTER_GS_MEMORY_LIMITED + 1 ),
    D3D10_COUNTER_PS_MEMORY_LIMITED = ( D3D10_COUNTER_GS_COMPUTATION_LIMITED + 1 ),
    D3D10_COUNTER_PS_COMPUTATION_LIMITED = ( D3D10_COUNTER_PS_MEMORY_LIMITED + 1 ),
    D3D10_COUNTER_POST_TRANSFORM_CACHE_HIT_RATE = ( D3D10_COUNTER_PS_COMPUTATION_LIMITED + 1 ),
    D3D10_COUNTER_TEXTURE_CACHE_HIT_RATE = ( D3D10_COUNTER_POST_TRANSFORM_CACHE_HIT_RATE + 1 ),
    D3D10_COUNTER_DEVICE_DEPENDENT_0 = 0x40000000,
} D3D10_COUNTER;

Constants

D3D10_COUNTER_GPU_IDLE
Percentage of the time that the GPU is idle.
D3D10_COUNTER_VERTEX_PROCESSING
Percentage of the time that the GPU does vertex processing.
D3D10_COUNTER_GEOMETRY_PROCESSING
Percentage of the time that the GPU does geometry processing.
D3D10_COUNTER_PIXEL_PROCESSING
Percentage of the time that the GPU does pixel processing.
D3D10_COUNTER_OTHER_GPU_PROCESSING
Percentage of the time that the GPU does other processing (not vertex, geometry, or pixel processing).
D3D10_COUNTER_HOST_ADAPTER_BANDWIDTH_UTILIZATION
Percentage of bandwidth used on a host adapter. Value returned by ID3D10Asynchronous::GetData between 0.0 and 1.0 when using this counter.
D3D10_COUNTER_LOCAL_VIDMEM_BANDWIDTH_UTILIZATION
Percentage of bandwidth used by the local video memory. Value returned by ID3D10Asynchronous::GetData between 0.0 and 1.0 when using this counter
D3D10_COUNTER_VERTEX_THROUGHPUT_UTILIZATION
Percentage of throughput used for vertices. Value returned by ID3D10Asynchronous::GetData between 0.0 and 1.0 when using this counter
D3D10_COUNTER_TRIANGLE_SETUP_THROUGHPUT_UTILIZATION
Percentage of throughput used for triangle setup. Value returned by ID3D10Asynchronous::GetData between 0.0 and 1.0 when using this counter
D3D10_COUNTER_FILLRATE_THROUGHPUT_UTILIZATION
Percentage of throughput used for the fillrate. Value returned by ID3D10Asynchronous::GetData between 0.0 and 1.0 when using this counter.
D3D10_COUNTER_VS_MEMORY_LIMITED
Percentage of time that a vertex shader spends sampling resources.
D3D10_COUNTER_VS_COMPUTATION_LIMITED
Percentage of time that a vertex shader spends doing computations.
D3D10_COUNTER_GS_MEMORY_LIMITED
Percentage of time that a geometry shader spends sampling resources.
D3D10_COUNTER_GS_COMPUTATION_LIMITED
Percentage of time that a geometry shader spends doing computations.
D3D10_COUNTER_PS_MEMORY_LIMITED
Percentage of time that a pixel shader spends sampling resources.
D3D10_COUNTER_PS_COMPUTATION_LIMITED
Percentage of time that a pixel shader spends doing computations.
D3D10_COUNTER_POST_TRANSFORM_CACHE_HIT_RATE
Percentage of vertex data that was read from the vertex cache. For example, if 6 vertices were added to the cache and 3 of them were read from the cache, then the hit rate would be 0.5.
D3D10_COUNTER_TEXTURE_CACHE_HIT_RATE
Percentage of texel data that was read from the vertex cache. For example, if 6 texels were added to the cache and 3 of them were read from the cache, then the hit rate would be 0.5.
D3D10_COUNTER_DEVICE_DEPENDENT_0
Start of the device-dependent counters. See remarks.

Remarks

In addition to these performance counters, independent hardware vendors may define their own set of performance counters for their devices. The enum values for these counters would start after D3D10_COUNTER_DEVICE_DEPENDENT_0 and would be defined by those hardware vendors.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_COUNTER_TYPE

Data type of a performance counter.

typedef enum D3D10_COUNTER_TYPE
{
    D3D10_COUNTER_TYPE_FLOAT32 = 0,
    D3D10_COUNTER_TYPE_UINT16 = ( D3D10_COUNTER_TYPE_FLOAT32 + 1 ),
    D3D10_COUNTER_TYPE_UINT32 = ( D3D10_COUNTER_TYPE_UINT16 + 1 ),
    D3D10_COUNTER_TYPE_UINT64 = ( D3D10_COUNTER_TYPE_UINT32 + 1 ),
} D3D10_COUNTER_TYPE;

Constants

D3D10_COUNTER_TYPE_FLOAT32
32-bit floating point.
D3D10_COUNTER_TYPE_UINT16
16-bit unsigned integer.
D3D10_COUNTER_TYPE_UINT32
32-bit unsigned integer.
D3D10_COUNTER_TYPE_UINT64
64-bit unsigned integer.

Remarks

These flags are an output parameter in ID3D10Device::CheckCounter.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_CREATE_DEVICE_FLAG

Device creation flags.

typedef enum D3D10_CREATE_DEVICE_FLAG
{
    D3D10_CREATE_DEVICE_SINGLETHREADED = 0x1,
    D3D10_CREATE_DEVICE_DEBUG = 0x2,
    D3D10_CREATE_DEVICE_SWITCH_TO_REF = 0x4,
    D3D10_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS = 0x8,
} D3D10_CREATE_DEVICE_FLAG;

Constants

D3D10_CREATE_DEVICE_SINGLETHREADED
Create a single-threaded device. See remarks.
D3D10_CREATE_DEVICE_DEBUG
Create a device that supports the debug layer.
D3D10_CREATE_DEVICE_SWITCH_TO_REF
Create both a software (REF) and hardware (HAL) version of the device simultaneously, which allows an application to switch to a reference device to enable debugging. See ID3D10SwitchToRef Interface for more information.
D3D10_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS
Reserved.

Remarks

Device creation flags are used by D3D10CreateDevice and D3D10CreateDeviceAndSwapChain.

By default, all Direct3D 10 calls are handled in a thread-safe way. By creating a single-threaded device, you disable thread-safe calling.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_CULL_MODE

Indicates triangles facing a particular direction are not drawn.

typedef enum D3D10_CULL_MODE
{
    D3D10_CULL_NONE = 1,
    D3D10_CULL_FRONT = 2,
    D3D10_CULL_BACK = 3,
} D3D10_CULL_MODE;

Constants

D3D10_CULL_NONE
Always draw all triangles.
D3D10_CULL_FRONT
Do not draw triangles that are front-facing.
D3D10_CULL_BACK
Do not draw triangles that are back-facing.

Remarks

This enumeration is part of a rasterizer-state object description (see D3D10_RASTERIZER_DESC).

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_DEPTH_WRITE_MASK

Identify the portion of a depth-stencil buffer for writing depth data.

typedef enum D3D10_DEPTH_WRITE_MASK
{
    D3D10_DEPTH_WRITE_MASK_ZERO = 0,
    D3D10_DEPTH_WRITE_MASK_ALL = 1,
} D3D10_DEPTH_WRITE_MASK;

Constants

D3D10_DEPTH_WRITE_MASK_ZERO
Turn off writes to the depth-stencil buffer.
D3D10_DEPTH_WRITE_MASK_ALL
Turn on writes to the depth-stencil buffer.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_DEVICE_STATE_TYPES

Used to specify device state.

typedef enum D3D10_DEVICE_STATE_TYPES
{
    D3D10_DST_SO_BUFFERS = 1,
    D3D10_DST_OM_RENDER_TARGETS = ,
    D3D10_DST_OM_DEPTH_STENCIL_STATE = ,
    D3D10_DST_OM_BLEND_STATE = ,
    D3D10_DST_VS = ,
    D3D10_DST_VS_SAMPLERS = ,
    D3D10_DST_VS_SHADER_RESOURCES = ,
    D3D10_DST_VS_CONSTANT_BUFFERS = ,
    D3D10_DST_GS = ,
    D3D10_DST_GS_SAMPLERS = ,
    D3D10_DST_GS_SHADER_RESOURCES = ,
    D3D10_DST_GS_CONSTANT_BUFFERS = ,
    D3D10_DST_PS = ,
    D3D10_DST_PS_SAMPLERS = ,
    D3D10_DST_PS_SHADER_RESOURCES = ,
    D3D10_DST_PS_CONSTANT_BUFFERS = ,
    D3D10_DST_IA_VERTEX_BUFFERS = ,
    D3D10_DST_IA_INDEX_BUFFER = ,
    D3D10_DST_IA_INPUT_LAYOUT = ,
    D3D10_DST_IA_PRIMITIVE_TOPOLOGY = ,
    D3D10_DST_RS_VIEWPORTS = ,
    D3D10_DST_RS_SCISSOR_RECTS = ,
    D3D10_DST_RS_RASTERIZER_STATE = ,
    D3D10_DST_PREDICATION = ,
} D3D10_DEVICE_STATE_TYPES;

Constants

D3D10_DST_SO_BUFFERS
D3D10_DST_OM_RENDER_TARGETS
D3D10_DST_OM_DEPTH_STENCIL_STATE
D3D10_DST_OM_BLEND_STATE
D3D10_DST_VS
D3D10_DST_VS_SAMPLERS
D3D10_DST_VS_SHADER_RESOURCES
D3D10_DST_VS_CONSTANT_BUFFERS
D3D10_DST_GS
D3D10_DST_GS_SAMPLERS
D3D10_DST_GS_SHADER_RESOURCES
D3D10_DST_GS_CONSTANT_BUFFERS
D3D10_DST_PS
D3D10_DST_PS_SAMPLERS
D3D10_DST_PS_SHADER_RESOURCES
D3D10_DST_PS_CONSTANT_BUFFERS
D3D10_DST_IA_VERTEX_BUFFERS
D3D10_DST_IA_INDEX_BUFFER
D3D10_DST_IA_INPUT_LAYOUT
D3D10_DST_IA_PRIMITIVE_TOPOLOGY
D3D10_DST_RS_VIEWPORTS
D3D10_DST_RS_SCISSOR_RECTS
D3D10_DST_RS_RASTERIZER_STATE
D3D10_DST_PREDICATION

Remarks

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_DRIVER_TYPE

The device-driver type.

typedef enum D3D10_DRIVER_TYPE
{
    D3D10_DRIVER_TYPE_HARDWARE = 0,
    D3D10_DRIVER_TYPE_REFERENCE = 1,
    D3D10_DRIVER_TYPE_NULL = 2,
    D3D10_DRIVER_TYPE_SOFTWARE = 3,
} D3D10_DRIVER_TYPE;

Constants

D3D10_DRIVER_TYPE_HARDWARE
A hardware device; commonly called a HAL device.
D3D10_DRIVER_TYPE_REFERENCE
A reference device; commonly called a REF device.
D3D10_DRIVER_TYPE_NULL
A NULL device; which is a reference device without render capability.
D3D10_DRIVER_TYPE_SOFTWARE
Reserved for later use.

Remarks

The device-driver type needs to be specified when the device is created (using D3D10CreateDevice or D3D10CreateDeviceAndSwapChain).

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_FILL_MODE

Determines the fill mode to use when rendering triangles.

typedef enum D3D10_FILL_MODE
{
    D3D10_FILL_WIREFRAME = 2,
    D3D10_FILL_SOLID = 3,
} D3D10_FILL_MODE;

Constants

D3D10_FILL_WIREFRAME
Draw lines connecting the vertices. Adjacent vertices are not drawn.
D3D10_FILL_SOLID
Fill the triangles formed by the vertices. Adjacent vertices are not drawn.

Remarks

This enumeration is part of a rasterizer-state object description (see D3D10_RASTERIZER_DESC).

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_FILTER

Filtering options during texture sampling.

typedef enum D3D10_FILTER
{
    D3D10_FILTER_MIN_MAG_MIP_POINT = 0,
    D3D10_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1,
    D3D10_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4,
    D3D10_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5,
    D3D10_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10,
    D3D10_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11,
    D3D10_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14,
    D3D10_FILTER_MIN_MAG_MIP_LINEAR = 0x15,
    D3D10_FILTER_ANISOTROPIC = 0x55,
    D3D10_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80,
    D3D10_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81,
    D3D10_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84,
    D3D10_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85,
    D3D10_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90,
    D3D10_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91,
    D3D10_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94,
    D3D10_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95,
    D3D10_FILTER_COMPARISON_ANISOTROPIC = 0xd5,
    D3D10_FILTER_TEXT_1BIT = 0x80000000,
} D3D10_FILTER;

Constants

D3D10_FILTER_MIN_MAG_MIP_POINT
Use point sampling for minification, magnification, and mip-level sampling.
D3D10_FILTER_MIN_MAG_POINT_MIP_LINEAR
Use point sampling for minification and magnification; use linear interpolation for mip-level sampling.
D3D10_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT
Use point sampling for minification; use linear interpolation for magnification; use point sampling for mip-level sampling.
D3D10_FILTER_MIN_POINT_MAG_MIP_LINEAR
Use point sampling for minification; use linear interpolation for magnification and mip-level sampling.
D3D10_FILTER_MIN_LINEAR_MAG_MIP_POINT
Use linear interpolation for minification; use point sampling for magnification and mip-level sampling.
D3D10_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR
Use linear interpolation for minification; use point sampling for magnification; use linear interpolation for mip-level sampling.
D3D10_FILTER_MIN_MAG_LINEAR_MIP_POINT
Use linear interpolation for minification and magnification; use point sampling for mip-level sampling.
D3D10_FILTER_MIN_MAG_MIP_LINEAR
Use linear interpolation for minification, magnification, and mip-level sampling.
D3D10_FILTER_ANISOTROPIC
Use anisotropic interpolation for minification, magnification, and mip-level sampling.
D3D10_FILTER_COMPARISON_MIN_MAG_MIP_POINT
Use point sampling for minification, magnification, and mip-level sampling. Compare the result to the comparison value.
D3D10_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR
Use point sampling for minification and magnification; use linear interpolation for mip-level sampling. Compare the result to the comparison value.
D3D10_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT
Use point sampling for minification; use linear interpolation for magnification; use point sampling for mip-level sampling. Compare the result to the comparison value.
D3D10_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR
Use point sampling for minification; use linear interpolation for magnification and mip-level sampling. Compare the result to the comparison value.
D3D10_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT
Use linear interpolation for minification; use point sampling for magnification and mip-level sampling. Compare the result to the comparison value.
D3D10_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR
Use linear interpolation for minification; use point sampling for magnification; use linear interpolation for mip-level sampling. Compare the result to the comparison value.
D3D10_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT
Use linear interpolation for minification and magnification; use point sampling for mip-level sampling. Compare the result to the comparison value.
D3D10_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR
Use linear interpolation for minification, magnification, and mip-level sampling. Compare the result to the comparison value.
D3D10_FILTER_COMPARISON_ANISOTROPIC
Use anisotropic interpolation for minification, magnification, and mip-level sampling. Compare the result to the comparison value.
D3D10_FILTER_TEXT_1BIT
For use in pixel shaders with textures that have the R1_UNORM format.

Remarks

During texture sampling, one or more texels are read and combined (this is calling filtering) to produce a single value. Point sampling reads a single texel while linear sampling reads two texels (endpoints) and linearly interpolates a third value between the endpoints.

HLSL texture-sampling functions also support comparison filtering during texture sampling. Comparison filtering compares each sampled texel against a comparison value. The boolean result is blended the same way that normal texture filtering is blended.

You can use HLSL intrinsic texture-sampling functions that implement texture filtering only or companion functions that use texture filtering with comparison filtering.

Texture Sampling Function | Texture Sampling Function with Comparison Filtering
sample | samplecmp or samplecmplevelzero

Comparison filters only work with textures that have the following formats: R32_FLOAT_X8X24_TYPELESS, R32_FLOAT, R24_UNORM_X8_TYPELESS, R16_UNORM.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_FILTER_TYPE

Types of magnification or minification sampler filters.

typedef enum D3D10_FILTER_TYPE
{
    D3D10_FILTER_TYPE_POINT = 0,
    D3D10_FILTER_TYPE_LINEAR = 1,
} D3D10_FILTER_TYPE;

Constants

D3D10_FILTER_TYPE_POINT
Point filtering used as a texture magnification or minification filter. The texel with coordinates nearest to the desired pixel value is used. The texture filter to be used between mipmap levels is nearest-point mipmap filtering. The rasterizer uses the color from the texel of the nearest mipmap texture.
D3D10_FILTER_TYPE_LINEAR
Bilinear interpolation filtering used as a texture magnification or minification filter. A weighted average of a 2 x 2 area of texels surrounding the desired pixel is used. The texture filter to use between mipmap levels is trilinear mipmap interpolation. The rasterizer linearly interpolates pixel color, using the texels of the two nearest mipmap textures.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_FORMAT_SUPPORT

Which resources are supported for a given format and given device. See ID3D10Device::CheckFormatSupport.

typedef enum D3D10_FORMAT_SUPPORT
{
    D3D10_FORMAT_SUPPORT_BUFFER = 0x1,
    D3D10_FORMAT_SUPPORT_IA_VERTEX_BUFFER = 0x2,
    D3D10_FORMAT_SUPPORT_IA_INDEX_BUFFER = 0x4,
    D3D10_FORMAT_SUPPORT_SO_BUFFER = 0x8,
    D3D10_FORMAT_SUPPORT_TEXTURE1D = 0x10,
    D3D10_FORMAT_SUPPORT_TEXTURE2D = 0x20,
    D3D10_FORMAT_SUPPORT_TEXTURE3D = 0x40,
    D3D10_FORMAT_SUPPORT_TEXTURECUBE = 0x80,
    D3D10_FORMAT_SUPPORT_SHADER_LOAD = 0x100,
    D3D10_FORMAT_SUPPORT_SHADER_SAMPLE = 0x200,
    D3D10_FORMAT_SUPPORT_SHADER_SAMPLE_COMPARISON = 0x400,
    D3D10_FORMAT_SUPPORT_SHADER_SAMPLE_MONO_TEXT = 0x800,
    D3D10_FORMAT_SUPPORT_MIP = 0x1000,
    D3D10_FORMAT_SUPPORT_MIP_AUTOGEN = 0x2000,
    D3D10_FORMAT_SUPPORT_RENDER_TARGET = 0x4000,
    D3D10_FORMAT_SUPPORT_BLENDABLE = 0x8000,
    D3D10_FORMAT_SUPPORT_DEPTH_STENCIL = 0x10000,
    D3D10_FORMAT_SUPPORT_CPU_LOCKABLE = 0x20000,
    D3D10_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE = 0x40000,
    D3D10_FORMAT_SUPPORT_DISPLAY = 0x80000,
    D3D10_FORMAT_SUPPORT_CAST_WITHIN_BIT_LAYOUT = 0x100000,
    D3D10_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET = 0x200000,
    D3D10_FORMAT_SUPPORT_MULTISAMPLE_LOAD = 0x400000,
} D3D10_FORMAT_SUPPORT;

Constants

D3D10_FORMAT_SUPPORT_BUFFER
Buffer resources supported.
D3D10_FORMAT_SUPPORT_IA_VERTEX_BUFFER
Vertex buffers supported.
D3D10_FORMAT_SUPPORT_IA_INDEX_BUFFER
Index buffers supported.
D3D10_FORMAT_SUPPORT_SO_BUFFER
Streaming output buffers supported.
D3D10_FORMAT_SUPPORT_TEXTURE1D
1D texture resources supported.
D3D10_FORMAT_SUPPORT_TEXTURE2D
2D texture resources supported.
D3D10_FORMAT_SUPPORT_TEXTURE3D
3D texture resources supported.
D3D10_FORMAT_SUPPORT_TEXTURECUBE
Cube texture resources supported.
D3D10_FORMAT_SUPPORT_SHADER_LOAD
The intrinsic HLSL function Load supported.
D3D10_FORMAT_SUPPORT_SHADER_SAMPLE
The intrinsic HLSL functions Sample supported.
D3D10_FORMAT_SUPPORT_SHADER_SAMPLE_COMPARISON
The intrinsic HLSL functions SampleCmp and SampleCmpLevelZero supported.
D3D10_FORMAT_SUPPORT_SHADER_SAMPLE_MONO_TEXT
Reserved.
D3D10_FORMAT_SUPPORT_MIP
Mipmaps supported.
D3D10_FORMAT_SUPPORT_MIP_AUTOGEN
Automatic generation of mipmaps supported.
D3D10_FORMAT_SUPPORT_RENDER_TARGET
Rendertargets supported.
D3D10_FORMAT_SUPPORT_BLENDABLE
Blend operations supported.
D3D10_FORMAT_SUPPORT_DEPTH_STENCIL
Depth stencils supported.
D3D10_FORMAT_SUPPORT_CPU_LOCKABLE
CPU locking supported.
D3D10_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE
Multisampling resolution supported.
D3D10_FORMAT_SUPPORT_DISPLAY
Format can be displayed on screen.
D3D10_FORMAT_SUPPORT_CAST_WITHIN_BIT_LAYOUT
Format cannot be cast to another format.
D3D10_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET
Format can be used as a multisampled rendertarget.
D3D10_FORMAT_SUPPORT_MULTISAMPLE_LOAD
Format can be used as a multisampled texture and read into a shader with the intrinsic HLSL Load function.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_INPUT_CLASSIFICATION

Type of data contained in an input slot.

typedef enum D3D10_INPUT_CLASSIFICATION
{
    D3D10_INPUT_PER_VERTEX_DATA = 0,
    D3D10_INPUT_PER_INSTANCE_DATA = 1,
} D3D10_INPUT_CLASSIFICATION;

Constants

D3D10_INPUT_PER_VERTEX_DATA
Input data is per-vertex data.
D3D10_INPUT_PER_INSTANCE_DATA
Input data is per-instance data.

Remarks

Use these values to specify the type of data for a particular input element (see D3D10_INPUT_ELEMENT_DESC) of an input-layout object.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_MESSAGE_CATEGORY

Categories of debug messages. This will identify the category of a message when retrieving a message with ID3D10InfoQueue::GetMessage and when adding a message with ID3D10InfoQueue::AddMessage. When creating an info queue filter, these values can be used to allow or deny any categories of messages to pass through the storage and retrieval filters.

typedef enum D3D10_MESSAGE_CATEGORY
{
    D3D10_MESSAGE_CATEGORY_APPLICATION_DEFINED = 0,
    D3D10_MESSAGE_CATEGORY_MISCELLANEOUS = ( D3D10_MESSAGE_CATEGORY_APPLICATION_DEFINED + 1 ),
    D3D10_MESSAGE_CATEGORY_INITIALIZATION = ( D3D10_MESSAGE_CATEGORY_MISCELLANEOUS + 1 ),
    D3D10_MESSAGE_CATEGORY_CLEANUP = ( D3D10_MESSAGE_CATEGORY_INITIALIZATION + 1 ),
    D3D10_MESSAGE_CATEGORY_COMPILATION = ( D3D10_MESSAGE_CATEGORY_CLEANUP + 1 ),
    D3D10_MESSAGE_CATEGORY_STATE_CREATION = ( D3D10_MESSAGE_CATEGORY_COMPILATION + 1 ),
    D3D10_MESSAGE_CATEGORY_STATE_SETTING = ( D3D10_MESSAGE_CATEGORY_STATE_CREATION + 1 ),
    D3D10_MESSAGE_CATEGORY_STATE_GETTING = ( D3D10_MESSAGE_CATEGORY_STATE_SETTING + 1 ),
    D3D10_MESSAGE_CATEGORY_RESOURCE_MANIPULATION = ( D3D10_MESSAGE_CATEGORY_STATE_GETTING + 1 ),
    D3D10_MESSAGE_CATEGORY_EXECUTION = ( D3D10_MESSAGE_CATEGORY_RESOURCE_MANIPULATION + 1 ),
} D3D10_MESSAGE_CATEGORY;

Constants

D3D10_MESSAGE_CATEGORY_APPLICATION_DEFINED
User defined message. See ID3D10InfoQueue::AddMessage.
D3D10_MESSAGE_CATEGORY_MISCELLANEOUS
D3D10_MESSAGE_CATEGORY_INITIALIZATION
D3D10_MESSAGE_CATEGORY_CLEANUP
D3D10_MESSAGE_CATEGORY_COMPILATION
D3D10_MESSAGE_CATEGORY_STATE_CREATION
D3D10_MESSAGE_CATEGORY_STATE_SETTING
D3D10_MESSAGE_CATEGORY_STATE_GETTING
D3D10_MESSAGE_CATEGORY_RESOURCE_MANIPULATION
D3D10_MESSAGE_CATEGORY_EXECUTION

Remarks

This is part of the Information Queue feature. See ID3D10InfoQueue Interface.

Requirements

Header: Declared in D3d10.h.

See Also

Core Enumerations


D3D10_MESSAGE_ID

A debug message's unique ID. Each message ID is associated with a particular debug text string. These IDs are used to identify a debug message when retrieving one with ID3D10InfoQueue::GetMessage and when adding a message with ID3D10InfoQueue::AddMessage. When creating an info queue filter, these values can be used to allow or deny any categories of messages to pass through the storage and retrieval filters.

typedef enum D3D10_MESSAGE_ID
{
    D3D10_MESSAGE_ID_UNKNOWN = 0,
    D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_HAZARD = ( D3D10_MESSAGE_ID_UNKNOWN + 1 ),
    D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_HAZARD = ( D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_HAZARD + 1 ),
    D3D10_MESSAGE_ID_DEVICE_VSSETSHADERRESOURCES_HAZARD = ( D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_HAZARD + 1 ),
    D3D10_MESSAGE_ID_DEVICE_VSSETCONSTANTBUFFERS_HAZARD = ( D3D10_MESSAGE_ID_DEVICE_VSSETSHADERRESOURCES_HAZARD + 1 ),
    D3D10_MESSAGE_ID_DEVICE_GSSETSHADERRESOURCES_HAZARD = ( D3D10_MESSAGE_ID_DEVICE_VSSETCONSTANTBUFFERS_HAZARD + 1 ),
    D3D10_MESSAGE_ID_DEVICE_GSSETCONSTANTBUFFERS_HAZARD = ( D3D10_MESSAGE_ID_DEVICE_GSSETSHADERRESOURCES_HAZARD + 1 ),
    D3D10_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_HAZARD = ( D3D10_MESSAGE_ID_DEVICE_GSSETCONSTANTBUFFERS_HAZARD + 1 ),
    D3D10_MESSAGE_ID_DEVICE_PSSETCONSTANTBUFFERS_HAZARD = ( D3D10_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_HAZARD + 1 ),
    D3D10_MESSAGE_ID_DEVICE_OMSETRENDERTARGETS_HAZARD = ( D3D10_MESSAGE_ID_DEVICE_PSSETCONSTANTBUFFERS_HAZARD + 1 ),
    D3D10_MESSAGE_ID_DEVICE_SOSETTARGETS_HAZARD = ( D3D10_MESSAGE_ID_DEVICE_OMSETRENDERTARGETS_HAZARD + 1 ),
    D3D10_MESSAGE_ID_STRING_FROM_APPLICATION = ( D3D10_MESSAGE_ID_DEVICE_SOSETTARGETS_HAZARD + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_THIS = ( D3D10_MESSAGE_ID_STRING_FROM_APPLICATION + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER1 = ( D3D10_MESSAGE_ID_CORRUPTED_THIS + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER2 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER1 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER3 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER2 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER4 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER3 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER5 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER4 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER6 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER5 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER7 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER6 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER8 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER7 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER9 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER8 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER10 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER9 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER11 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER10 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER12 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER11 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER13 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER12 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER14 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER13 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_PARAMETER15 = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER14 + 1 ),
    D3D10_MESSAGE_ID_CORRUPTED_MULTITHREADING = ( D3D10_MESSAGE_ID_CORRUPTED_PARAMETER15 + 1 ),
    D3D10_MESSAGE_ID_MESSAGE_REPORTING_OUTOFMEMORY = ( D3D10_MESSAGE_ID_CORRUPTED_MULTITHREADING + 1 ),
    D3D10_MESSAGE_ID_IASETINPUTLAYOUT_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_MESSAGE_REPORTING_OUTOFMEMORY + 1 ),
    D3D10_MESSAGE_ID_IASETVERTEXBUFFERS_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_IASETINPUTLAYOUT_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_IASETINDEXBUFFER_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_IASETVERTEXBUFFERS_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_VSSETSHADER_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_IASETINDEXBUFFER_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_VSSETSHADERRESOURCES_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_VSSETSHADER_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_VSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_VSSETSHADERRESOURCES_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_VSSETSAMPLERS_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_VSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_GSSETSHADER_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_VSSETSAMPLERS_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_GSSETSHADERRESOURCES_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_GSSETSHADER_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_GSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_GSSETSHADERRESOURCES_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_GSSETSAMPLERS_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_GSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_SOSETTARGETS_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_GSSETSAMPLERS_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_PSSETSHADER_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_SOSETTARGETS_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_PSSETSHADERRESOURCES_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_PSSETSHADER_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_PSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_PSSETSHADERRESOURCES_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_PSSETSAMPLERS_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_PSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_RSSETSTATE_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_PSSETSAMPLERS_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_OMSETBLENDSTATE_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_RSSETSTATE_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_OMSETDEPTHSTENCILSTATE_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_OMSETBLENDSTATE_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_OMSETRENDERTARGETS_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_OMSETDEPTHSTENCILSTATE_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_SETPREDICATION_UNBINDDELETINGOBJECT = ( D3D10_MESSAGE_ID_OMSETRENDERTARGETS_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_GETPRIVATEDATA_MOREDATA = ( D3D10_MESSAGE_ID_SETPREDICATION_UNBINDDELETINGOBJECT + 1 ),
    D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDFREEDATA = ( D3D10_MESSAGE_ID_GETPRIVATEDATA_MOREDATA + 1 ),
    D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDIUNKNOWN = ( D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDFREEDATA + 1 ),
    D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDFLAGS = ( D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDIUNKNOWN + 1 ),
    D3D10_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS = ( D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDFLAGS + 1 ),
    D3D10_MESSAGE_ID_SETPRIVATEDATA_OUTOFMEMORY = ( D3D10_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDFORMAT = ( D3D10_MESSAGE_ID_SETPRIVATEDATA_OUTOFMEMORY + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDSAMPLES = ( D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDUSAGE = ( D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDSAMPLES + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDBINDFLAGS = ( D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDUSAGE + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDCPUACCESSFLAGS = ( D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDBINDFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDMISCFLAGS = ( D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDCPUACCESSFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDCPUACCESSFLAGS = ( D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDMISCFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDBINDFLAGS = ( D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDCPUACCESSFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDINITIALDATA = ( D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDBINDFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDDIMENSIONS = ( D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDINITIALDATA + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDMIPLEVELS = ( D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDDIMENSIONS + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDMISCFLAGS = ( D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDMIPLEVELS + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDARG_RETURN = ( D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDMISCFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_OUTOFMEMORY_RETURN = ( D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDARG_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_NULLDESC = ( D3D10_MESSAGE_ID_CREATEBUFFER_OUTOFMEMORY_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDCONSTANTBUFFERBINDINGS = ( D3D10_MESSAGE_ID_CREATEBUFFER_NULLDESC + 1 ),
    D3D10_MESSAGE_ID_CREATEBUFFER_LARGEALLOCATION = ( D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDCONSTANTBUFFERBINDINGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDFORMAT = ( D3D10_MESSAGE_ID_CREATEBUFFER_LARGEALLOCATION + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_UNSUPPORTEDFORMAT = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDSAMPLES = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_UNSUPPORTEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDUSAGE = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDSAMPLES + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDBINDFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDUSAGE + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDCPUACCESSFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDBINDFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDMISCFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDCPUACCESSFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDCPUACCESSFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDMISCFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDBINDFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDCPUACCESSFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDINITIALDATA = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDBINDFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDDIMENSIONS = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDINITIALDATA + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDMIPLEVELS = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDDIMENSIONS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDMISCFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDMIPLEVELS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDARG_RETURN = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDMISCFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_OUTOFMEMORY_RETURN = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDARG_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_NULLDESC = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_OUTOFMEMORY_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE1D_LARGEALLOCATION = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_NULLDESC + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDFORMAT = ( D3D10_MESSAGE_ID_CREATETEXTURE1D_LARGEALLOCATION + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_UNSUPPORTEDFORMAT = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDSAMPLES = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_UNSUPPORTEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDUSAGE = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDSAMPLES + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDBINDFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDUSAGE + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDCPUACCESSFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDBINDFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDMISCFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDCPUACCESSFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDCPUACCESSFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDMISCFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDBINDFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDCPUACCESSFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDINITIALDATA = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDBINDFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDDIMENSIONS = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDINITIALDATA + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDMIPLEVELS = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDDIMENSIONS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDMISCFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDMIPLEVELS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDARG_RETURN = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDMISCFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_OUTOFMEMORY_RETURN = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDARG_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_NULLDESC = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_OUTOFMEMORY_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE2D_LARGEALLOCATION = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_NULLDESC + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDFORMAT = ( D3D10_MESSAGE_ID_CREATETEXTURE2D_LARGEALLOCATION + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_UNSUPPORTEDFORMAT = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDSAMPLES = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_UNSUPPORTEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDUSAGE = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDSAMPLES + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDBINDFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDUSAGE + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDCPUACCESSFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDBINDFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDMISCFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDCPUACCESSFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDCPUACCESSFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDMISCFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDBINDFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDCPUACCESSFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDINITIALDATA = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDBINDFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDDIMENSIONS = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDINITIALDATA + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDMIPLEVELS = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDDIMENSIONS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDMISCFLAGS = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDMIPLEVELS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDARG_RETURN = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDMISCFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_OUTOFMEMORY_RETURN = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDARG_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_NULLDESC = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_OUTOFMEMORY_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATETEXTURE3D_LARGEALLOCATION = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_NULLDESC + 1 ),
    D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_UNRECOGNIZEDFORMAT = ( D3D10_MESSAGE_ID_CREATETEXTURE3D_LARGEALLOCATION + 1 ),
    D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDESC = ( D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_UNRECOGNIZEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDFORMAT = ( D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDESC + 1 ),
    D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDIMENSIONS = ( D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDRESOURCE = ( D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDIMENSIONS + 1 ),
    D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_TOOMANYOBJECTS = ( D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDRESOURCE + 1 ),
    D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDARG_RETURN = ( D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_TOOMANYOBJECTS + 1 ),
    D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_OUTOFMEMORY_RETURN = ( D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDARG_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_UNRECOGNIZEDFORMAT = ( D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_OUTOFMEMORY_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_UNSUPPORTEDFORMAT = ( D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_UNRECOGNIZEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDESC = ( D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_UNSUPPORTEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDFORMAT = ( D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDESC + 1 ),
    D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDIMENSIONS = ( D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDRESOURCE = ( D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDIMENSIONS + 1 ),
    D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_TOOMANYOBJECTS = ( D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDRESOURCE + 1 ),
    D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDARG_RETURN = ( D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_TOOMANYOBJECTS + 1 ),
    D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_OUTOFMEMORY_RETURN = ( D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDARG_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_UNRECOGNIZEDFORMAT = ( D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_OUTOFMEMORY_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDESC = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_UNRECOGNIZEDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDFORMAT = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDESC + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDIMENSIONS = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDRESOURCE = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDIMENSIONS + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_TOOMANYOBJECTS = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDRESOURCE + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDARG_RETURN = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_TOOMANYOBJECTS + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_OUTOFMEMORY_RETURN = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDARG_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_OUTOFMEMORY = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_OUTOFMEMORY_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TOOMANYELEMENTS = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_OUTOFMEMORY + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDFORMAT = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TOOMANYELEMENTS + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INCOMPATIBLEFORMAT = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOT = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INCOMPATIBLEFORMAT + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDINPUTSLOTCLASS = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOT + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_STEPRATESLOTCLASSMISMATCH = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDINPUTSLOTCLASS + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOTCLASSCHANGE = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_STEPRATESLOTCLASSMISMATCH + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSTEPRATECHANGE = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOTCLASSCHANGE + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDALIGNMENT = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSTEPRATECHANGE + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_DUPLICATESEMANTIC = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDALIGNMENT + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_DUPLICATESEMANTIC + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_NULLSEMANTIC = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_MISSINGELEMENT = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_NULLSEMANTIC + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_NULLDESC = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_MISSINGELEMENT + 1 ),
    D3D10_MESSAGE_ID_CREATEVERTEXSHADER_OUTOFMEMORY = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_NULLDESC + 1 ),
    D3D10_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE = ( D3D10_MESSAGE_ID_CREATEVERTEXSHADER_OUTOFMEMORY + 1 ),
    D3D10_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERTYPE = ( D3D10_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_OUTOFMEMORY = ( D3D10_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERTYPE + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERBYTECODE = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_OUTOFMEMORY + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERTYPE = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERBYTECODE + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTOFMEMORY = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERTYPE + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERBYTECODE = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTOFMEMORY + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERTYPE = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERBYTECODE + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMENTRIES = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERTYPE + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSTREAMSTRIDEUNUSED = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMENTRIES + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDDECL = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSTREAMSTRIDEUNUSED + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_EXPECTEDDECL = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDDECL + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSLOT0EXPECTED = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_EXPECTEDDECL + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSLOT = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSLOT0EXPECTED + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_ONLYONEELEMENTPERSLOT = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSLOT + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDCOMPONENTCOUNT = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_ONLYONEELEMENTPERSLOT + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTARTCOMPONENTANDCOMPONENTCOUNT = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDCOMPONENTCOUNT + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDGAPDEFINITION = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTARTCOMPONENTANDCOMPONENTCOUNT + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_REPEATEDOUTPUT = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDGAPDEFINITION + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSTREAMSTRIDE = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_REPEATEDOUTPUT + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGSEMANTIC = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSTREAMSTRIDE + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MASKMISMATCH = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGSEMANTIC + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_CANTHAVEONLYGAPS = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MASKMISMATCH + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DECLTOOCOMPLEX = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_CANTHAVEONLYGAPS + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGOUTPUTSIGNATURE = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DECLTOOCOMPLEX + 1 ),
    D3D10_MESSAGE_ID_CREATEPIXELSHADER_OUTOFMEMORY = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGOUTPUTSIGNATURE + 1 ),
    D3D10_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE = ( D3D10_MESSAGE_ID_CREATEPIXELSHADER_OUTOFMEMORY + 1 ),
    D3D10_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERTYPE = ( D3D10_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE + 1 ),
    D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDFILLMODE = ( D3D10_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERTYPE + 1 ),
    D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDCULLMODE = ( D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDFILLMODE + 1 ),
    D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDDEPTHBIASCLAMP = ( D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDCULLMODE + 1 ),
    D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDSLOPESCALEDDEPTHBIAS = ( D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDDEPTHBIASCLAMP + 1 ),
    D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_TOOMANYOBJECTS = ( D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDSLOPESCALEDDEPTHBIAS + 1 ),
    D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_NULLDESC = ( D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_TOOMANYOBJECTS + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHWRITEMASK = ( D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_NULLDESC + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHFUNC = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHWRITEMASK + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFAILOP = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHFUNC + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILZFAILOP = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFAILOP + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILPASSOP = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILZFAILOP + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFUNC = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILPASSOP + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFAILOP = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFUNC + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILZFAILOP = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFAILOP + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILPASSOP = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILZFAILOP + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFUNC = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILPASSOP + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_TOOMANYOBJECTS = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFUNC + 1 ),
    D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_NULLDESC = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_TOOMANYOBJECTS + 1 ),
    D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLEND = ( D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_NULLDESC + 1 ),
    D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLEND = ( D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLEND + 1 ),
    D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOP = ( D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLEND + 1 ),
    D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLENDALPHA = ( D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOP + 1 ),
    D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLENDALPHA = ( D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLENDALPHA + 1 ),
    D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOPALPHA = ( D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLENDALPHA + 1 ),
    D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDRENDERTARGETWRITEMASK = ( D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOPALPHA + 1 ),
    D3D10_MESSAGE_ID_CREATEBLENDSTATE_TOOMANYOBJECTS = ( D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDRENDERTARGETWRITEMASK + 1 ),
    D3D10_MESSAGE_ID_CREATEBLENDSTATE_NULLDESC = ( D3D10_MESSAGE_ID_CREATEBLENDSTATE_TOOMANYOBJECTS + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDFILTER = ( D3D10_MESSAGE_ID_CREATEBLENDSTATE_NULLDESC + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSU = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDFILTER + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSV = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSU + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSW = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSV + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMIPLODBIAS = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSW + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXANISOTROPY = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMIPLODBIAS + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDCOMPARISONFUNC = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXANISOTROPY + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMINLOD = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDCOMPARISONFUNC + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXLOD = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMINLOD + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_TOOMANYOBJECTS = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXLOD + 1 ),
    D3D10_MESSAGE_ID_CREATESAMPLERSTATE_NULLDESC = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_TOOMANYOBJECTS + 1 ),
    D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDQUERY = ( D3D10_MESSAGE_ID_CREATESAMPLERSTATE_NULLDESC + 1 ),
    D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDMISCFLAGS = ( D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDQUERY + 1 ),
    D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_UNEXPECTEDMISCFLAG = ( D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDMISCFLAGS + 1 ),
    D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_NULLDESC = ( D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_UNEXPECTEDMISCFLAG + 1 ),
    D3D10_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNRECOGNIZED = ( D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_NULLDESC + 1 ),
    D3D10_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNDEFINED = ( D3D10_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNRECOGNIZED + 1 ),
    D3D10_MESSAGE_ID_IASETVERTEXBUFFERS_INVALIDBUFFER = ( D3D10_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNDEFINED + 1 ),
    D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_OFFSET_TOO_LARGE = ( D3D10_MESSAGE_ID_IASETVERTEXBUFFERS_INVALIDBUFFER + 1 ),
    D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_BUFFERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_OFFSET_TOO_LARGE + 1 ),
    D3D10_MESSAGE_ID_IASETINDEXBUFFER_INVALIDBUFFER = ( D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_BUFFERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_FORMAT_INVALID = ( D3D10_MESSAGE_ID_IASETINDEXBUFFER_INVALIDBUFFER + 1 ),
    D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_OFFSET_TOO_LARGE = ( D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_FORMAT_INVALID + 1 ),
    D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_OFFSET_UNALIGNED = ( D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_OFFSET_TOO_LARGE + 1 ),
    D3D10_MESSAGE_ID_DEVICE_VSSETSHADERRESOURCES_VIEWS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_OFFSET_UNALIGNED + 1 ),
    D3D10_MESSAGE_ID_VSSETCONSTANTBUFFERS_INVALIDBUFFER = ( D3D10_MESSAGE_ID_DEVICE_VSSETSHADERRESOURCES_VIEWS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_VSSETCONSTANTBUFFERS_BUFFERS_EMPTY = ( D3D10_MESSAGE_ID_VSSETCONSTANTBUFFERS_INVALIDBUFFER + 1 ),
    D3D10_MESSAGE_ID_DEVICE_VSSETSAMPLERS_SAMPLERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_VSSETCONSTANTBUFFERS_BUFFERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_GSSETSHADERRESOURCES_VIEWS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_VSSETSAMPLERS_SAMPLERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_GSSETCONSTANTBUFFERS_INVALIDBUFFER = ( D3D10_MESSAGE_ID_DEVICE_GSSETSHADERRESOURCES_VIEWS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_GSSETCONSTANTBUFFERS_BUFFERS_EMPTY = ( D3D10_MESSAGE_ID_GSSETCONSTANTBUFFERS_INVALIDBUFFER + 1 ),
    D3D10_MESSAGE_ID_DEVICE_GSSETSAMPLERS_SAMPLERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_GSSETCONSTANTBUFFERS_BUFFERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_SOSETTARGETS_INVALIDBUFFER = ( D3D10_MESSAGE_ID_DEVICE_GSSETSAMPLERS_SAMPLERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_SOSETTARGETS_OFFSET_UNALIGNED = ( D3D10_MESSAGE_ID_SOSETTARGETS_INVALIDBUFFER + 1 ),
    D3D10_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_VIEWS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_SOSETTARGETS_OFFSET_UNALIGNED + 1 ),
    D3D10_MESSAGE_ID_PSSETCONSTANTBUFFERS_INVALIDBUFFER = ( D3D10_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_VIEWS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_PSSETCONSTANTBUFFERS_BUFFERS_EMPTY = ( D3D10_MESSAGE_ID_PSSETCONSTANTBUFFERS_INVALIDBUFFER + 1 ),
    D3D10_MESSAGE_ID_DEVICE_PSSETSAMPLERS_SAMPLERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_PSSETCONSTANTBUFFERS_BUFFERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_INVALIDVIEWPORT = ( D3D10_MESSAGE_ID_DEVICE_PSSETSAMPLERS_SAMPLERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_RSSETSCISSORRECTS_INVALIDSCISSOR = ( D3D10_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_INVALIDVIEWPORT + 1 ),
    D3D10_MESSAGE_ID_CLEARRENDERTARGETVIEW_DENORMFLUSH = ( D3D10_MESSAGE_ID_DEVICE_RSSETSCISSORRECTS_INVALIDSCISSOR + 1 ),
    D3D10_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_DENORMFLUSH = ( D3D10_MESSAGE_ID_CLEARRENDERTARGETVIEW_DENORMFLUSH + 1 ),
    D3D10_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_INVALID = ( D3D10_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_DENORMFLUSH + 1 ),
    D3D10_MESSAGE_ID_DEVICE_IAGETVERTEXBUFFERS_BUFFERS_EMPTY = ( D3D10_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_INVALID + 1 ),
    D3D10_MESSAGE_ID_DEVICE_VSGETSHADERRESOURCES_VIEWS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_IAGETVERTEXBUFFERS_BUFFERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_VSGETCONSTANTBUFFERS_BUFFERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_VSGETSHADERRESOURCES_VIEWS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_VSGETSAMPLERS_SAMPLERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_VSGETCONSTANTBUFFERS_BUFFERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_GSGETSHADERRESOURCES_VIEWS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_VSGETSAMPLERS_SAMPLERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_GSGETCONSTANTBUFFERS_BUFFERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_GSGETSHADERRESOURCES_VIEWS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_GSGETSAMPLERS_SAMPLERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_GSGETCONSTANTBUFFERS_BUFFERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_SOGETTARGETS_BUFFERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_GSGETSAMPLERS_SAMPLERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_PSGETSHADERRESOURCES_VIEWS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_SOGETTARGETS_BUFFERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_PSGETCONSTANTBUFFERS_BUFFERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_PSGETSHADERRESOURCES_VIEWS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_PSGETSAMPLERS_SAMPLERS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_PSGETCONSTANTBUFFERS_BUFFERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_RSGETVIEWPORTS_VIEWPORTS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_PSGETSAMPLERS_SAMPLERS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_RSGETSCISSORRECTS_RECTS_EMPTY = ( D3D10_MESSAGE_ID_DEVICE_RSGETVIEWPORTS_VIEWPORTS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_GENERATEMIPS_RESOURCE_INVALID = ( D3D10_MESSAGE_ID_DEVICE_RSGETSCISSORRECTS_RECTS_EMPTY + 1 ),
    D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDDESTINATIONSUBRESOURCE = ( D3D10_MESSAGE_ID_DEVICE_GENERATEMIPS_RESOURCE_INVALID + 1 ),
    D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCESUBRESOURCE = ( D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDDESTINATIONSUBRESOURCE + 1 ),
    D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCEBOX = ( D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCESUBRESOURCE + 1 ),
    D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCE = ( D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCEBOX + 1 ),
    D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDDESTINATIONSTATE = ( D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCE + 1 ),
    D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCESTATE = ( D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDDESTINATIONSTATE + 1 ),
    D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCE = ( D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCESTATE + 1 ),
    D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDDESTINATIONSTATE = ( D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCE + 1 ),
    D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCESTATE = ( D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDDESTINATIONSTATE + 1 ),
    D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSUBRESOURCE = ( D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCESTATE + 1 ),
    D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONBOX = ( D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSUBRESOURCE + 1 ),
    D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSTATE = ( D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONBOX + 1 ),
    D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_INVALID = ( D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSTATE + 1 ),
    D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_SUBRESOURCE_INVALID = ( D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_INVALID + 1 ),
    D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_INVALID = ( D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_SUBRESOURCE_INVALID + 1 ),
    D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_SUBRESOURCE_INVALID = ( D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_INVALID + 1 ),
    D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_FORMAT_INVALID = ( D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_SUBRESOURCE_INVALID + 1 ),
    D3D10_MESSAGE_ID_BUFFER_MAP_INVALIDMAPTYPE = ( D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_FORMAT_INVALID + 1 ),
    D3D10_MESSAGE_ID_BUFFER_MAP_INVALIDFLAGS = ( D3D10_MESSAGE_ID_BUFFER_MAP_INVALIDMAPTYPE + 1 ),
    D3D10_MESSAGE_ID_BUFFER_MAP_ALREADYMAPPED = ( D3D10_MESSAGE_ID_BUFFER_MAP_INVALIDFLAGS + 1 ),
    D3D10_MESSAGE_ID_BUFFER_MAP_DEVICEREMOVED_RETURN = ( D3D10_MESSAGE_ID_BUFFER_MAP_ALREADYMAPPED + 1 ),
    D3D10_MESSAGE_ID_BUFFER_UNMAP_NOTMAPPED = ( D3D10_MESSAGE_ID_BUFFER_MAP_DEVICEREMOVED_RETURN + 1 ),
    D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDMAPTYPE = ( D3D10_MESSAGE_ID_BUFFER_UNMAP_NOTMAPPED + 1 ),
    D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDSUBRESOURCE = ( D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDMAPTYPE + 1 ),
    D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDFLAGS = ( D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDSUBRESOURCE + 1 ),
    D3D10_MESSAGE_ID_TEXTURE1D_MAP_ALREADYMAPPED = ( D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDFLAGS + 1 ),
    D3D10_MESSAGE_ID_TEXTURE1D_MAP_DEVICEREMOVED_RETURN = ( D3D10_MESSAGE_ID_TEXTURE1D_MAP_ALREADYMAPPED + 1 ),
    D3D10_MESSAGE_ID_TEXTURE1D_UNMAP_INVALIDSUBRESOURCE = ( D3D10_MESSAGE_ID_TEXTURE1D_MAP_DEVICEREMOVED_RETURN + 1 ),
    D3D10_MESSAGE_ID_TEXTURE1D_UNMAP_NOTMAPPED = ( D3D10_MESSAGE_ID_TEXTURE1D_UNMAP_INVALIDSUBRESOURCE + 1 ),
    D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDMAPTYPE = ( D3D10_MESSAGE_ID_TEXTURE1D_UNMAP_NOTMAPPED + 1 ),
    D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDSUBRESOURCE = ( D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDMAPTYPE + 1 ),
    D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDFLAGS = ( D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDSUBRESOURCE + 1 ),
    D3D10_MESSAGE_ID_TEXTURE2D_MAP_ALREADYMAPPED = ( D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDFLAGS + 1 ),
    D3D10_MESSAGE_ID_TEXTURE2D_MAP_DEVICEREMOVED_RETURN = ( D3D10_MESSAGE_ID_TEXTURE2D_MAP_ALREADYMAPPED + 1 ),
    D3D10_MESSAGE_ID_TEXTURE2D_UNMAP_INVALIDSUBRESOURCE = ( D3D10_MESSAGE_ID_TEXTURE2D_MAP_DEVICEREMOVED_RETURN + 1 ),
    D3D10_MESSAGE_ID_TEXTURE2D_UNMAP_NOTMAPPED = ( D3D10_MESSAGE_ID_TEXTURE2D_UNMAP_INVALIDSUBRESOURCE + 1 ),
    D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDMAPTYPE = ( D3D10_MESSAGE_ID_TEXTURE2D_UNMAP_NOTMAPPED + 1 ),
    D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDSUBRESOURCE = ( D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDMAPTYPE + 1 ),
    D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDFLAGS = ( D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDSUBRESOURCE + 1 ),
    D3D10_MESSAGE_ID_TEXTURE3D_MAP_ALREADYMAPPED = ( D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDFLAGS + 1 ),
    D3D10_MESSAGE_ID_TEXTURE3D_MAP_DEVICEREMOVED_RETURN = ( D3D10_MESSAGE_ID_TEXTURE3D_MAP_ALREADYMAPPED + 1 ),
    D3D10_MESSAGE_ID_TEXTURE3D_UNMAP_INVALIDSUBRESOURCE = ( D3D10_MESSAGE_ID_TEXTURE3D_MAP_DEVICEREMOVED_RETURN + 1 ),
    D3D10_MESSAGE_ID_TEXTURE3D_UNMAP_NOTMAPPED = ( D3D10_MESSAGE_ID_TEXTURE3D_UNMAP_INVALIDSUBRESOURCE + 1 ),
    D3D10_MESSAGE_ID_CHECKFORMATSUPPORT_FORMAT_DEPRECATED = ( D3D10_MESSAGE_ID_TEXTURE3D_UNMAP_NOTMAPPED + 1 ),
    D3D10_MESSAGE_ID_CHECKMULTISAMPLEQUALITYLEVELS_FORMAT_DEPRECATED = ( D3D10_MESSAGE_ID_CHECKFORMATSUPPORT_FORMAT_DEPRECATED + 1 ),
    D3D10_MESSAGE_ID_SETEXCEPTIONMODE_UNRECOGNIZEDFLAGS = ( D3D10_MESSAGE_ID_CHECKMULTISAMPLEQUALITYLEVELS_FORMAT_DEPRECATED + 1 ),
    D3D10_MESSAGE_ID_SETEXCEPTIONMODE_INVALIDARG_RETURN = ( D3D10_MESSAGE_ID_SETEXCEPTIONMODE_UNRECOGNIZEDFLAGS + 1 ),
    D3D10_MESSAGE_ID_SETEXCEPTIONMODE_DEVICEREMOVED_RETURN = ( D3D10_MESSAGE_ID_SETEXCEPTIONMODE_INVALIDARG_RETURN + 1 ),
    D3D10_MESSAGE_ID_REF_SIMULATING_INFINITELY_FAST_HARDWARE = ( D3D10_MESSAGE_ID_SETEXCEPTIONMODE_DEVICEREMOVED_RETURN + 1 ),
    D3D10_MESSAGE_ID_REF_THREADING_MODE = ( D3D10_MESSAGE_ID_REF_SIMULATING_INFINITELY_FAST_HARDWARE + 1 ),
    D3D10_MESSAGE_ID_REF_UMDRIVER_EXCEPTION = ( D3D10_MESSAGE_ID_REF_THREADING_MODE + 1 ),
    D3D10_MESSAGE_ID_REF_KMDRIVER_EXCEPTION = ( D3D10_MESSAGE_ID_REF_UMDRIVER_EXCEPTION + 1 ),
    D3D10_MESSAGE_ID_REF_HARDWARE_EXCEPTION = ( D3D10_MESSAGE_ID_REF_KMDRIVER_EXCEPTION + 1 ),
    D3D10_MESSAGE_ID_REF_ACCESSING_INDEXABLE_TEMP_OUT_OF_RANGE = ( D3D10_MESSAGE_ID_REF_HARDWARE_EXCEPTION + 1 ),
    D3D10_MESSAGE_ID_REF_PROBLEM_PARSING_SHADER = ( D3D10_MESSAGE_ID_REF_ACCESSING_INDEXABLE_TEMP_OUT_OF_RANGE + 1 ),
    D3D10_MESSAGE_ID_REF_OUT_OF_MEMORY = ( D3D10_MESSAGE_ID_REF_PROBLEM_PARSING_SHADER + 1 ),
    D3D10_MESSAGE_ID_REF_INFO = ( D3D10_MESSAGE_ID_REF_OUT_OF_MEMORY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEXPOS_OVERFLOW = ( D3D10_MESSAGE_ID_REF_INFO + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAWINDEXED_INDEXPOS_OVERFLOW = ( D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEXPOS_OVERFLOW + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAWINSTANCED_VERTEXPOS_OVERFLOW = ( D3D10_MESSAGE_ID_DEVICE_DRAWINDEXED_INDEXPOS_OVERFLOW + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAWINSTANCED_INSTANCEPOS_OVERFLOW = ( D3D10_MESSAGE_ID_DEVICE_DRAWINSTANCED_VERTEXPOS_OVERFLOW + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INSTANCEPOS_OVERFLOW = ( D3D10_MESSAGE_ID_DEVICE_DRAWINSTANCED_INSTANCEPOS_OVERFLOW + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INDEXPOS_OVERFLOW = ( D3D10_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INSTANCEPOS_OVERFLOW + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_SHADER_NOT_SET = ( D3D10_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INDEXPOS_OVERFLOW + 1 ),
    D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND = ( D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_SHADER_NOT_SET + 1 ),
    D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERINDEX = ( D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND + 1 ),
    D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_COMPONENTTYPE = ( D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERINDEX + 1 ),
    D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERMASK = ( D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_COMPONENTTYPE + 1 ),
    D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SYSTEMVALUE = ( D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERMASK + 1 ),
    D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_NEVERWRITTEN_ALWAYSREADS = ( D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SYSTEMVALUE + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_NOT_SET = ( D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_NEVERWRITTEN_ALWAYSREADS + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_INPUTLAYOUT_NOT_SET = ( D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_NOT_SET + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_CONSTANT_BUFFER_NOT_SET = ( D3D10_MESSAGE_ID_DEVICE_DRAW_INPUTLAYOUT_NOT_SET + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_CONSTANT_BUFFER_TOO_SMALL = ( D3D10_MESSAGE_ID_DEVICE_DRAW_CONSTANT_BUFFER_NOT_SET + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_SAMPLER_NOT_SET = ( D3D10_MESSAGE_ID_DEVICE_DRAW_CONSTANT_BUFFER_TOO_SMALL + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_SHADERRESOURCEVIEW_NOT_SET = ( D3D10_MESSAGE_ID_DEVICE_DRAW_SAMPLER_NOT_SET + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_VIEW_DIMENSION_MISMATCH = ( D3D10_MESSAGE_ID_DEVICE_DRAW_SHADERRESOURCEVIEW_NOT_SET + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_STRIDE_TOO_SMALL = ( D3D10_MESSAGE_ID_DEVICE_DRAW_VIEW_DIMENSION_MISMATCH + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_TOO_SMALL = ( D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_STRIDE_TOO_SMALL + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_NOT_SET = ( D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_TOO_SMALL + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_FORMAT_INVALID = ( D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_NOT_SET + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_TOO_SMALL = ( D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_FORMAT_INVALID + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_GS_INPUT_PRIMITIVE_MISMATCH = ( D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_TOO_SMALL + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_RETURN_TYPE_MISMATCH = ( D3D10_MESSAGE_ID_DEVICE_DRAW_GS_INPUT_PRIMITIVE_MISMATCH + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_POSITION_NOT_PRESENT = ( D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_RETURN_TYPE_MISMATCH + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_OUTPUT_STREAM_NOT_SET = ( D3D10_MESSAGE_ID_DEVICE_DRAW_POSITION_NOT_PRESENT + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_BOUND_RESOURCE_MAPPED = ( D3D10_MESSAGE_ID_DEVICE_DRAW_OUTPUT_STREAM_NOT_SET + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_INVALID_PRIMITIVETOPOLOGY = ( D3D10_MESSAGE_ID_DEVICE_DRAW_BOUND_RESOURCE_MAPPED + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_OFFSET_UNALIGNED = ( D3D10_MESSAGE_ID_DEVICE_DRAW_INVALID_PRIMITIVETOPOLOGY + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_STRIDE_UNALIGNED = ( D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_OFFSET_UNALIGNED + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_OFFSET_UNALIGNED = ( D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_STRIDE_UNALIGNED + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_OUTPUT_STREAM_OFFSET_UNALIGNED = ( D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_OFFSET_UNALIGNED + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_LD_UNSUPPORTED = ( D3D10_MESSAGE_ID_DEVICE_DRAW_OUTPUT_STREAM_OFFSET_UNALIGNED + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_SAMPLE_UNSUPPORTED = ( D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_LD_UNSUPPORTED + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_SAMPLE_C_UNSUPPORTED = ( D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_SAMPLE_UNSUPPORTED + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_MULTISAMPLE_UNSUPPORTED = ( D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_SAMPLE_C_UNSUPPORTED + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_SO_TARGETS_BOUND_WITHOUT_SOURCE = ( D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_MULTISAMPLE_UNSUPPORTED + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_SO_STRIDE_LARGER_THAN_BUFFER = ( D3D10_MESSAGE_ID_DEVICE_DRAW_SO_TARGETS_BOUND_WITHOUT_SOURCE + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_OM_RENDER_TARGET_DOES_NOT_SUPPORT_BLENDING = ( D3D10_MESSAGE_ID_DEVICE_DRAW_SO_STRIDE_LARGER_THAN_BUFFER + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_OM_DUAL_SOURCE_BLENDING_CAN_ONLY_HAVE_RENDER_TARGET_0 = ( D3D10_MESSAGE_ID_DEVICE_DRAW_OM_RENDER_TARGET_DOES_NOT_SUPPORT_BLENDING + 1 ),
    D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_AT_FAULT = ( D3D10_MESSAGE_ID_DEVICE_DRAW_OM_DUAL_SOURCE_BLENDING_CAN_ONLY_HAVE_RENDER_TARGET_0 + 1 ),
    D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_POSSIBLY_AT_FAULT = ( D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_AT_FAULT + 1 ),
    D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_NOT_AT_FAULT = ( D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_POSSIBLY_AT_FAULT + 1 ),
    D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_INVALIDARG_RETURN = ( D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_NOT_AT_FAULT + 1 ),
    D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_OUTOFMEMORY_RETURN = ( D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_INVALIDARG_RETURN + 1 ),
    D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_BADINTERFACE_RETURN = ( D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_OUTOFMEMORY_RETURN + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_VIEWPORT_NOT_SET = ( D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_BADINTERFACE_RETURN + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TRAILING_DIGIT_IN_SEMANTIC = ( D3D10_MESSAGE_ID_DEVICE_DRAW_VIEWPORT_NOT_SET + 1 ),
    D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_TRAILING_DIGIT_IN_SEMANTIC = ( D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TRAILING_DIGIT_IN_SEMANTIC + 1 ),
    D3D10_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_DENORMFLUSH = ( D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_TRAILING_DIGIT_IN_SEMANTIC + 1 ),
    D3D10_MESSAGE_ID_OMSETRENDERTARGETS_INVALIDVIEW = ( D3D10_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_DENORMFLUSH + 1 ),
    D3D10_MESSAGE_ID_DEVICE_SETTEXTFILTERSIZE_INVALIDDIMENSIONS = ( D3D10_MESSAGE_ID_OMSETRENDERTARGETS_INVALIDVIEW + 1 ),
    D3D10_MESSAGE_ID_DEVICE_DRAW_SAMPLER_MISMATCH = ( D3D10_MESSAGE_ID_DEVICE_SETTEXTFILTERSIZE_INVALIDDIMENSIONS + 1 ),
    D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TYPE_MISMATCH = ( D3D10_MESSAGE_ID_DEVICE_DRAW_SAMPLER_MISMATCH + 1 ),
} D3D10_MESSAGE_ID;

Constants

D3D10_MESSAGE_ID_UNKNOWN
D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_HAZARD
D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_HAZARD
D3D10_MESSAGE_ID_DEVICE_VSSETSHADERRESOURCES_HAZARD
D3D10_MESSAGE_ID_DEVICE_VSSETCONSTANTBUFFERS_HAZARD
D3D10_MESSAGE_ID_DEVICE_GSSETSHADERRESOURCES_HAZARD
D3D10_MESSAGE_ID_DEVICE_GSSETCONSTANTBUFFERS_HAZARD
D3D10_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_HAZARD
D3D10_MESSAGE_ID_DEVICE_PSSETCONSTANTBUFFERS_HAZARD
D3D10_MESSAGE_ID_DEVICE_OMSETRENDERTARGETS_HAZARD
D3D10_MESSAGE_ID_DEVICE_SOSETTARGETS_HAZARD
D3D10_MESSAGE_ID_STRING_FROM_APPLICATION
D3D10_MESSAGE_ID_CORRUPTED_THIS
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER1
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER2
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER3
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER4
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER5
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER6
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER7
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER8
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER9
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER10
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER11
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER12
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER13
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER14
D3D10_MESSAGE_ID_CORRUPTED_PARAMETER15
D3D10_MESSAGE_ID_CORRUPTED_MULTITHREADING
D3D10_MESSAGE_ID_MESSAGE_REPORTING_OUTOFMEMORY
D3D10_MESSAGE_ID_IASETINPUTLAYOUT_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_IASETVERTEXBUFFERS_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_IASETINDEXBUFFER_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_VSSETSHADER_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_VSSETSHADERRESOURCES_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_VSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_VSSETSAMPLERS_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_GSSETSHADER_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_GSSETSHADERRESOURCES_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_GSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_GSSETSAMPLERS_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_SOSETTARGETS_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_PSSETSHADER_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_PSSETSHADERRESOURCES_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_PSSETCONSTANTBUFFERS_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_PSSETSAMPLERS_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_RSSETSTATE_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_OMSETBLENDSTATE_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_OMSETDEPTHSTENCILSTATE_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_OMSETRENDERTARGETS_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_SETPREDICATION_UNBINDDELETINGOBJECT
D3D10_MESSAGE_ID_GETPRIVATEDATA_MOREDATA
D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDFREEDATA
D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDIUNKNOWN
D3D10_MESSAGE_ID_SETPRIVATEDATA_INVALIDFLAGS
D3D10_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS
D3D10_MESSAGE_ID_SETPRIVATEDATA_OUTOFMEMORY
D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDFORMAT
D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDSAMPLES
D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDUSAGE
D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDBINDFLAGS
D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDCPUACCESSFLAGS
D3D10_MESSAGE_ID_CREATEBUFFER_UNRECOGNIZEDMISCFLAGS
D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDCPUACCESSFLAGS
D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDBINDFLAGS
D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDINITIALDATA
D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDDIMENSIONS
D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDMIPLEVELS
D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDMISCFLAGS
D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDARG_RETURN
D3D10_MESSAGE_ID_CREATEBUFFER_OUTOFMEMORY_RETURN
D3D10_MESSAGE_ID_CREATEBUFFER_NULLDESC
D3D10_MESSAGE_ID_CREATEBUFFER_INVALIDCONSTANTBUFFERBINDINGS
D3D10_MESSAGE_ID_CREATEBUFFER_LARGEALLOCATION
D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDFORMAT
D3D10_MESSAGE_ID_CREATETEXTURE1D_UNSUPPORTEDFORMAT
D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDSAMPLES
D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDUSAGE
D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDBINDFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDCPUACCESSFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE1D_UNRECOGNIZEDMISCFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDCPUACCESSFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDBINDFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDINITIALDATA
D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDDIMENSIONS
D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDMIPLEVELS
D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDMISCFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE1D_INVALIDARG_RETURN
D3D10_MESSAGE_ID_CREATETEXTURE1D_OUTOFMEMORY_RETURN
D3D10_MESSAGE_ID_CREATETEXTURE1D_NULLDESC
D3D10_MESSAGE_ID_CREATETEXTURE1D_LARGEALLOCATION
D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDFORMAT
D3D10_MESSAGE_ID_CREATETEXTURE2D_UNSUPPORTEDFORMAT
D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDSAMPLES
D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDUSAGE
D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDBINDFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDCPUACCESSFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE2D_UNRECOGNIZEDMISCFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDCPUACCESSFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDBINDFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDINITIALDATA
D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDDIMENSIONS
D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDMIPLEVELS
D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDMISCFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE2D_INVALIDARG_RETURN
D3D10_MESSAGE_ID_CREATETEXTURE2D_OUTOFMEMORY_RETURN
D3D10_MESSAGE_ID_CREATETEXTURE2D_NULLDESC
D3D10_MESSAGE_ID_CREATETEXTURE2D_LARGEALLOCATION
D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDFORMAT
D3D10_MESSAGE_ID_CREATETEXTURE3D_UNSUPPORTEDFORMAT
D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDSAMPLES
D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDUSAGE
D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDBINDFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDCPUACCESSFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE3D_UNRECOGNIZEDMISCFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDCPUACCESSFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDBINDFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDINITIALDATA
D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDDIMENSIONS
D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDMIPLEVELS
D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDMISCFLAGS
D3D10_MESSAGE_ID_CREATETEXTURE3D_INVALIDARG_RETURN
D3D10_MESSAGE_ID_CREATETEXTURE3D_OUTOFMEMORY_RETURN
D3D10_MESSAGE_ID_CREATETEXTURE3D_NULLDESC
D3D10_MESSAGE_ID_CREATETEXTURE3D_LARGEALLOCATION
D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_UNRECOGNIZEDFORMAT
D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDESC
D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDFORMAT
D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDIMENSIONS
D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDRESOURCE
D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_TOOMANYOBJECTS
D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDARG_RETURN
D3D10_MESSAGE_ID_CREATESHADERRESOURCEVIEW_OUTOFMEMORY_RETURN
D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_UNRECOGNIZEDFORMAT
D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_UNSUPPORTEDFORMAT
D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDESC
D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDFORMAT
D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDIMENSIONS
D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDRESOURCE
D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_TOOMANYOBJECTS
D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDARG_RETURN
D3D10_MESSAGE_ID_CREATERENDERTARGETVIEW_OUTOFMEMORY_RETURN
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_UNRECOGNIZEDFORMAT
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDESC
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDFORMAT
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDIMENSIONS
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDRESOURCE
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_TOOMANYOBJECTS
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDARG_RETURN
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_OUTOFMEMORY_RETURN
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_OUTOFMEMORY
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TOOMANYELEMENTS
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDFORMAT
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INCOMPATIBLEFORMAT
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOT
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDINPUTSLOTCLASS
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_STEPRATESLOTCLASSMISMATCH
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOTCLASSCHANGE
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSTEPRATECHANGE
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDALIGNMENT
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_DUPLICATESEMANTIC
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_NULLSEMANTIC
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_MISSINGELEMENT
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_NULLDESC
D3D10_MESSAGE_ID_CREATEVERTEXSHADER_OUTOFMEMORY
D3D10_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE
D3D10_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERTYPE
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_OUTOFMEMORY
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERBYTECODE
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERTYPE
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTOFMEMORY
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERBYTECODE
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERTYPE
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMENTRIES
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSTREAMSTRIDEUNUSED
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDDECL
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_EXPECTEDDECL
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSLOT0EXPECTED
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSLOT
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_ONLYONEELEMENTPERSLOT
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDCOMPONENTCOUNT
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTARTCOMPONENTANDCOMPONENTCOUNT
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDGAPDEFINITION
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_REPEATEDOUTPUT
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSTREAMSTRIDE
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGSEMANTIC
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MASKMISMATCH
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_CANTHAVEONLYGAPS
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DECLTOOCOMPLEX
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGOUTPUTSIGNATURE
D3D10_MESSAGE_ID_CREATEPIXELSHADER_OUTOFMEMORY
D3D10_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE
D3D10_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERTYPE
D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDFILLMODE
D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDCULLMODE
D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDDEPTHBIASCLAMP
D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDSLOPESCALEDDEPTHBIAS
D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_TOOMANYOBJECTS
D3D10_MESSAGE_ID_CREATERASTERIZERSTATE_NULLDESC
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHWRITEMASK
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHFUNC
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFAILOP
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILZFAILOP
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILPASSOP
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFUNC
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFAILOP
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILZFAILOP
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILPASSOP
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFUNC
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_TOOMANYOBJECTS
D3D10_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_NULLDESC
D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLEND
D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLEND
D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOP
D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLENDALPHA
D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLENDALPHA
D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOPALPHA
D3D10_MESSAGE_ID_CREATEBLENDSTATE_INVALIDRENDERTARGETWRITEMASK
D3D10_MESSAGE_ID_CREATEBLENDSTATE_TOOMANYOBJECTS
D3D10_MESSAGE_ID_CREATEBLENDSTATE_NULLDESC
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDFILTER
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSU
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSV
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSW
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMIPLODBIAS
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXANISOTROPY
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDCOMPARISONFUNC
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMINLOD
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXLOD
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_TOOMANYOBJECTS
D3D10_MESSAGE_ID_CREATESAMPLERSTATE_NULLDESC
D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDQUERY
D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDMISCFLAGS
D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_UNEXPECTEDMISCFLAG
D3D10_MESSAGE_ID_CREATEQUERYORPREDICATE_NULLDESC
D3D10_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNRECOGNIZED
D3D10_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNDEFINED
D3D10_MESSAGE_ID_IASETVERTEXBUFFERS_INVALIDBUFFER
D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_OFFSET_TOO_LARGE
D3D10_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_BUFFERS_EMPTY
D3D10_MESSAGE_ID_IASETINDEXBUFFER_INVALIDBUFFER
D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_FORMAT_INVALID
D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_OFFSET_TOO_LARGE
D3D10_MESSAGE_ID_DEVICE_IASETINDEXBUFFER_OFFSET_UNALIGNED
D3D10_MESSAGE_ID_DEVICE_VSSETSHADERRESOURCES_VIEWS_EMPTY
D3D10_MESSAGE_ID_VSSETCONSTANTBUFFERS_INVALIDBUFFER
D3D10_MESSAGE_ID_DEVICE_VSSETCONSTANTBUFFERS_BUFFERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_VSSETSAMPLERS_SAMPLERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_GSSETSHADERRESOURCES_VIEWS_EMPTY
D3D10_MESSAGE_ID_GSSETCONSTANTBUFFERS_INVALIDBUFFER
D3D10_MESSAGE_ID_DEVICE_GSSETCONSTANTBUFFERS_BUFFERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_GSSETSAMPLERS_SAMPLERS_EMPTY
D3D10_MESSAGE_ID_SOSETTARGETS_INVALIDBUFFER
D3D10_MESSAGE_ID_DEVICE_SOSETTARGETS_OFFSET_UNALIGNED
D3D10_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_VIEWS_EMPTY
D3D10_MESSAGE_ID_PSSETCONSTANTBUFFERS_INVALIDBUFFER
D3D10_MESSAGE_ID_DEVICE_PSSETCONSTANTBUFFERS_BUFFERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_PSSETSAMPLERS_SAMPLERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_INVALIDVIEWPORT
D3D10_MESSAGE_ID_DEVICE_RSSETSCISSORRECTS_INVALIDSCISSOR
D3D10_MESSAGE_ID_CLEARRENDERTARGETVIEW_DENORMFLUSH
D3D10_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_DENORMFLUSH
D3D10_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_INVALID
D3D10_MESSAGE_ID_DEVICE_IAGETVERTEXBUFFERS_BUFFERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_VSGETSHADERRESOURCES_VIEWS_EMPTY
D3D10_MESSAGE_ID_DEVICE_VSGETCONSTANTBUFFERS_BUFFERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_VSGETSAMPLERS_SAMPLERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_GSGETSHADERRESOURCES_VIEWS_EMPTY
D3D10_MESSAGE_ID_DEVICE_GSGETCONSTANTBUFFERS_BUFFERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_GSGETSAMPLERS_SAMPLERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_SOGETTARGETS_BUFFERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_PSGETSHADERRESOURCES_VIEWS_EMPTY
D3D10_MESSAGE_ID_DEVICE_PSGETCONSTANTBUFFERS_BUFFERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_PSGETSAMPLERS_SAMPLERS_EMPTY
D3D10_MESSAGE_ID_DEVICE_RSGETVIEWPORTS_VIEWPORTS_EMPTY
D3D10_MESSAGE_ID_DEVICE_RSGETSCISSORRECTS_RECTS_EMPTY
D3D10_MESSAGE_ID_DEVICE_GENERATEMIPS_RESOURCE_INVALID
D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDDESTINATIONSUBRESOURCE
D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCESUBRESOURCE
D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCEBOX
D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCE
D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDDESTINATIONSTATE
D3D10_MESSAGE_ID_COPYSUBRESOURCEREGION_INVALIDSOURCESTATE
D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCE
D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDDESTINATIONSTATE
D3D10_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCESTATE
D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSUBRESOURCE
D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONBOX
D3D10_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSTATE
D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_INVALID
D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_SUBRESOURCE_INVALID
D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_INVALID
D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_SUBRESOURCE_INVALID
D3D10_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_FORMAT_INVALID
D3D10_MESSAGE_ID_BUFFER_MAP_INVALIDMAPTYPE
D3D10_MESSAGE_ID_BUFFER_MAP_INVALIDFLAGS
D3D10_MESSAGE_ID_BUFFER_MAP_ALREADYMAPPED
D3D10_MESSAGE_ID_BUFFER_MAP_DEVICEREMOVED_RETURN
D3D10_MESSAGE_ID_BUFFER_UNMAP_NOTMAPPED
D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDMAPTYPE
D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDSUBRESOURCE
D3D10_MESSAGE_ID_TEXTURE1D_MAP_INVALIDFLAGS
D3D10_MESSAGE_ID_TEXTURE1D_MAP_ALREADYMAPPED
D3D10_MESSAGE_ID_TEXTURE1D_MAP_DEVICEREMOVED_RETURN
D3D10_MESSAGE_ID_TEXTURE1D_UNMAP_INVALIDSUBRESOURCE
D3D10_MESSAGE_ID_TEXTURE1D_UNMAP_NOTMAPPED
D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDMAPTYPE
D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDSUBRESOURCE
D3D10_MESSAGE_ID_TEXTURE2D_MAP_INVALIDFLAGS
D3D10_MESSAGE_ID_TEXTURE2D_MAP_ALREADYMAPPED
D3D10_MESSAGE_ID_TEXTURE2D_MAP_DEVICEREMOVED_RETURN
D3D10_MESSAGE_ID_TEXTURE2D_UNMAP_INVALIDSUBRESOURCE
D3D10_MESSAGE_ID_TEXTURE2D_UNMAP_NOTMAPPED
D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDMAPTYPE
D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDSUBRESOURCE
D3D10_MESSAGE_ID_TEXTURE3D_MAP_INVALIDFLAGS
D3D10_MESSAGE_ID_TEXTURE3D_MAP_ALREADYMAPPED
D3D10_MESSAGE_ID_TEXTURE3D_MAP_DEVICEREMOVED_RETURN
D3D10_MESSAGE_ID_TEXTURE3D_UNMAP_INVALIDSUBRESOURCE
D3D10_MESSAGE_ID_TEXTURE3D_UNMAP_NOTMAPPED
D3D10_MESSAGE_ID_CHECKFORMATSUPPORT_FORMAT_DEPRECATED
D3D10_MESSAGE_ID_CHECKMULTISAMPLEQUALITYLEVELS_FORMAT_DEPRECATED
D3D10_MESSAGE_ID_SETEXCEPTIONMODE_UNRECOGNIZEDFLAGS
D3D10_MESSAGE_ID_SETEXCEPTIONMODE_INVALIDARG_RETURN
D3D10_MESSAGE_ID_SETEXCEPTIONMODE_DEVICEREMOVED_RETURN
D3D10_MESSAGE_ID_REF_SIMULATING_INFINITELY_FAST_HARDWARE
D3D10_MESSAGE_ID_REF_THREADING_MODE
D3D10_MESSAGE_ID_REF_UMDRIVER_EXCEPTION
D3D10_MESSAGE_ID_REF_KMDRIVER_EXCEPTION
D3D10_MESSAGE_ID_REF_HARDWARE_EXCEPTION
D3D10_MESSAGE_ID_REF_ACCESSING_INDEXABLE_TEMP_OUT_OF_RANGE
D3D10_MESSAGE_ID_REF_PROBLEM_PARSING_SHADER
D3D10_MESSAGE_ID_REF_OUT_OF_MEMORY
D3D10_MESSAGE_ID_REF_INFO
D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEXPOS_OVERFLOW
D3D10_MESSAGE_ID_DEVICE_DRAWINDEXED_INDEXPOS_OVERFLOW
D3D10_MESSAGE_ID_DEVICE_DRAWINSTANCED_VERTEXPOS_OVERFLOW
D3D10_MESSAGE_ID_DEVICE_DRAWINSTANCED_INSTANCEPOS_OVERFLOW
D3D10_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INSTANCEPOS_OVERFLOW
D3D10_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INDEXPOS_OVERFLOW
D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_SHADER_NOT_SET
D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND
D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERINDEX
D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_COMPONENTTYPE
D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERMASK
D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SYSTEMVALUE
D3D10_MESSAGE_ID_DEVICE_SHADER_LINKAGE_NEVERWRITTEN_ALWAYSREADS
D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_NOT_SET
D3D10_MESSAGE_ID_DEVICE_DRAW_INPUTLAYOUT_NOT_SET
D3D10_MESSAGE_ID_DEVICE_DRAW_CONSTANT_BUFFER_NOT_SET
D3D10_MESSAGE_ID_DEVICE_DRAW_CONSTANT_BUFFER_TOO_SMALL
D3D10_MESSAGE_ID_DEVICE_DRAW_SAMPLER_NOT_SET
D3D10_MESSAGE_ID_DEVICE_DRAW_SHADERRESOURCEVIEW_NOT_SET
D3D10_MESSAGE_ID_DEVICE_DRAW_VIEW_DIMENSION_MISMATCH
D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_STRIDE_TOO_SMALL
D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_TOO_SMALL
D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_NOT_SET
D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_FORMAT_INVALID
D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_BUFFER_TOO_SMALL
D3D10_MESSAGE_ID_DEVICE_DRAW_GS_INPUT_PRIMITIVE_MISMATCH
D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_RETURN_TYPE_MISMATCH
D3D10_MESSAGE_ID_DEVICE_DRAW_POSITION_NOT_PRESENT
D3D10_MESSAGE_ID_DEVICE_DRAW_OUTPUT_STREAM_NOT_SET
D3D10_MESSAGE_ID_DEVICE_DRAW_BOUND_RESOURCE_MAPPED
D3D10_MESSAGE_ID_DEVICE_DRAW_INVALID_PRIMITIVETOPOLOGY
D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_OFFSET_UNALIGNED
D3D10_MESSAGE_ID_DEVICE_DRAW_VERTEX_STRIDE_UNALIGNED
D3D10_MESSAGE_ID_DEVICE_DRAW_INDEX_OFFSET_UNALIGNED
D3D10_MESSAGE_ID_DEVICE_DRAW_OUTPUT_STREAM_OFFSET_UNALIGNED
D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_LD_UNSUPPORTED
D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_SAMPLE_UNSUPPORTED
D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_SAMPLE_C_UNSUPPORTED
D3D10_MESSAGE_ID_DEVICE_DRAW_RESOURCE_MULTISAMPLE_UNSUPPORTED
D3D10_MESSAGE_ID_DEVICE_DRAW_SO_TARGETS_BOUND_WITHOUT_SOURCE
D3D10_MESSAGE_ID_DEVICE_DRAW_SO_STRIDE_LARGER_THAN_BUFFER
D3D10_MESSAGE_ID_DEVICE_DRAW_OM_RENDER_TARGET_DOES_NOT_SUPPORT_BLENDING
D3D10_MESSAGE_ID_DEVICE_DRAW_OM_DUAL_SOURCE_BLENDING_CAN_ONLY_HAVE_RENDER_TARGET_0
D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_AT_FAULT
D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_POSSIBLY_AT_FAULT
D3D10_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_NOT_AT_FAULT
D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_INVALIDARG_RETURN
D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_OUTOFMEMORY_RETURN
D3D10_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_BADINTERFACE_RETURN
D3D10_MESSAGE_ID_DEVICE_DRAW_VIEWPORT_NOT_SET
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TRAILING_DIGIT_IN_SEMANTIC
D3D10_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_TRAILING_DIGIT_IN_SEMANTIC
D3D10_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_DENORMFLUSH
D3D10_MESSAGE_ID_OMSETRENDERTARGETS_INVALIDVIEW
D3D10_MESSAGE_ID_DEVICE_SETTEXTFILTERSIZE_INVALIDDIMENSIONS
D3D10_MESSAGE_ID_DEVICE_DRAW_SAMPLER_MISMATCH
D3D10_MESSAGE_ID_CREATEINPUTLAYOUT_TYPE_MISMATCH

Requirements

Header: Declared in D3d10sdklayers.h.

See Also

Core Enumerations


D3D10_MESSAGE_SEVERITY

Severity level of a debug message. This will identify the severity level of a debug message when retrieving one with ID3D10InfoQueue::GetMessage and when adding a message with ID3D10InfoQueue::AddMessage. When creating an info queue filter, these values can be used to allow or deny any categories of messages to pass through the storage and retrieval filters.

typedef enum D3D10_MESSAGE_SEVERITY
{
    D3D10_MESSAGE_SEVERITY_CORRUPTION = 0,
    D3D10_MESSAGE_SEVERITY_ERROR = ( D3D10_MESSAGE_SEVERITY_CORRUPTION + 1 ),
    D3D10_MESSAGE_SEVERITY_WARNING = ( D3D10_MESSAGE_SEVERITY_ERROR + 1 ),
    D3D10_MESSAGE_SEVERITY_INFO = ( D3D10_MESSAGE_SEVERITY_WARNING + 1 ),
} D3D10_MESSAGE_SEVERITY;

Constants

D3D10_MESSAGE_SEVERITY_CORRUPTION
D3D10_MESSAGE_SEVERITY_ERROR
D3D10_MESSAGE_SEVERITY_WARNING
D3D10_MESSAGE_SEVERITY_INFO

Remarks

This is part of the Information Queue feature. See ID3D10InfoQueue Interface.

Requirements

Header: Declared in D3d10.h.

See Also

Core Enumerations


D3D10_PRIMITIVE_TOPOLOGY

How the pipeline interprets vertex data that is bound to the input-assembler stage. These primitive types determine how the vertex data is rendered on screen.

typedef enum D3D10_PRIMITIVE_TOPOLOGY
{
    D3D10_PRIMITIVE_TOPOLOGY_UNDEFINED = 0,
    D3D10_PRIMITIVE_TOPOLOGY_POINTLIST = 1,
    D3D10_PRIMITIVE_TOPOLOGY_LINELIST = 2,
    D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP = 3,
    D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4,
    D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5,
    D3D10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 10,
    D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 11,
    D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 12,
    D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 13,
} D3D10_PRIMITIVE_TOPOLOGY;

Constants

D3D10_PRIMITIVE_TOPOLOGY_UNDEFINED
The IA stage has not been initialized with a primitive topology. The IA stage will not function properly unless a primitive topology is defined.
D3D10_PRIMITIVE_TOPOLOGY_POINTLIST
Interpret the vertex data as a list of points.
D3D10_PRIMITIVE_TOPOLOGY_LINELIST
Interpret the vertex data as a list of lines.
D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP
Interpret the vertex data as a line strip.
D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST
Interpret the vertex data as a list of triangles.
D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP
Interpret the vertex data as a triangle strip.
D3D10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ
Interpret the vertex data as list of lines with adjacency data.
D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ
Interpret the vertex data as line strip with adjacency data.
D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ
Interpret the vertex data as list of triangles with adjacency data.
D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ
Interpret the vertex data as triangle strip with adjacency data.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_QUERY

Query types.

typedef enum D3D10_QUERY
{
    D3D10_QUERY_EVENT = 0,
    D3D10_QUERY_OCCLUSION = ( D3D10_QUERY_EVENT + 1 ),
    D3D10_QUERY_TIMESTAMP = ( D3D10_QUERY_OCCLUSION + 1 ),
    D3D10_QUERY_TIMESTAMP_DISJOINT = ( D3D10_QUERY_TIMESTAMP + 1 ),
    D3D10_QUERY_PIPELINE_STATISTICS = ( D3D10_QUERY_TIMESTAMP_DISJOINT + 1 ),
    D3D10_QUERY_OCCLUSION_PREDICATE = ( D3D10_QUERY_PIPELINE_STATISTICS + 1 ),
    D3D10_QUERY_SO_STATISTICS = ( D3D10_QUERY_OCCLUSION_PREDICATE + 1 ),
    D3D10_QUERY_SO_OVERFLOW_PREDICATE = ( D3D10_QUERY_SO_STATISTICS + 1 ),
} D3D10_QUERY;

Constants

D3D10_QUERY_EVENT
Determines whether or not the GPU is finished processing commands. When the GPU is finished processing commands ID3D10Asynchronous::GetData will return S_OK, and pData will point to a BOOL with a value of TRUE. When using this type of query, ID3D10Asynchronous::Begin is disabled.
D3D10_QUERY_OCCLUSION
Get the number of samples that passed the depth and stencil tests in between ID3D10Asynchronous::Begin and ID3D10Asynchronous::End. ID3D10Asynchronous::GetData returns a UINT64. If a depth or stencil test is disabled, then each of those tests will be counted as a pass.
D3D10_QUERY_TIMESTAMP
Get a timestamp value where ID3D10Asynchronous::GetData returns a UINT64. This kind of query is only useful if two timestamp queries are done in the middle of a D3D10_QUERY_TIMESTAMP_DISJOINT query. The difference of two timestamps can be used to determine how many ticks have elapsed, and the D3D10_QUERY_TIMESTAMP_DISJOINT query will determine if that difference is a reliable value and also has a value that shows how to convert the number of ticks into seconds. See D3D10_QUERY_DATA_TIMESTAMP_DISJOINT. When using this type of query, ID3D10Asynchronous::Begin is disabled.
D3D10_QUERY_TIMESTAMP_DISJOINT
Determines whether or not a D3D10_QUERY_TIMESTAMP is returning reliable values, and also gives the frequency of the processor enabling you to convert the number of elapsed ticks into seconds. ID3D10Asynchronous::GetData will return a D3D10_QUERY_DATA_TIMESTAMP_DISJOINT. This type of query should only be invoked once per frame or less.
D3D10_QUERY_PIPELINE_STATISTICS
Get pipeline statistics, such as the number of pixel shader invocations in between ID3D10Asynchronous::Begin and ID3D10Asynchronous::End. ID3D10Asynchronous::GetData will return a D3D10_QUERY_DATA_PIPELINE_STATISTICS.
D3D10_QUERY_OCCLUSION_PREDICATE
Similar to D3D10_QUERY_OCCLUSION, except ID3D10Asynchronous::GetData returns a BOOL indicating whether or not any samples passed the depth and stencil tests - TRUE meaning at least one passed, FALSE meaning none passed.
D3D10_QUERY_SO_STATISTICS
Get streaming output statistics, such as the number of primitives streamed out in between ID3D10Asynchronous::Begin and ID3D10Asynchronous::End. ID3D10Asynchronous::GetData will return a D3D10_QUERY_DATA_SO_STATISTICS structure.
D3D10_QUERY_SO_OVERFLOW_PREDICATE
Determines whether or not any of the streaming output buffers overflowed in between ID3D10Asynchronous::Begin and ID3D10Asynchronous::End. ID3D10Asynchronous::GetData returns a BOOL - TRUE meaning there was an overflow, FALSE meaning there was not an overflow. If streaming output writes to multiple buffers, and one of the buffers overflows, then it will stop writing to all the output buffers. When an overflow is detected by Direct3D it is prevented from happening - no memory is corrupted. This predication may be used in conjunction with an SO_STATISTICS query so that when an overflow occurs the SO_STATISTIC query will let the application know how much memory was needed to prevent an overflow.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_QUERY_MISC_FLAG

Flags that describe miscellaneous query behavior.

typedef enum D3D10_QUERY_MISC_FLAG
{
    D3D10_QUERY_MISC_PREDICATEHINT = 0x1,
} D3D10_QUERY_MISC_FLAG;

Constants

D3D10_QUERY_MISC_PREDICATEHINT
Tell the hardware that if it is not yet sure if something is hidden or not to draw it anyway. This is only used with an occlusion predicate. Predication data cannot be returned to your application via ID3D10Asynchronous::GetData when using this flag.

Remarks

This flag is part of a query description (see D3D10_QUERY_DESC).

Requirements

Header: Declared in D3d10core.h.

See Also

Core Enumerations


D3D10_RAISE_FLAG

Flags that indicate how to handle internal driver errors, usually used in ID3D10Device::SetExceptionMode.

typedef enum D3D10_RAISE_FLAG
{
    D3D10_RAISE_FLAG_DRIVER_INTERNAL_ERROR = 0x1L,
} D3D10_RAISE_FLAG;

Constants

D3D10_RAISE_FLAG_DRIVER_INTERNAL_ERROR
Will kill the application and throw an exception when there is an internal driver error. See Structured Exception Handling.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_REGISTER_COMPONENT_TYPE

The register component types, usually used in D3D10_SIGNATURE_PARAMETER_DESC.

typedef enum D3D10_REGISTER_COMPONENT_TYPE
{
    D3D10_REGISTER_COMPONENT_UNKNOWN = 0,
    D3D10_REGISTER_COMPONENT_UINT32 = 1,
    D3D10_REGISTER_COMPONENT_SINT32 = 2,
    D3D10_REGISTER_COMPONENT_FLOAT32 = 3,
} D3D10_REGISTER_COMPONENT_TYPE;

Constants

D3D10_REGISTER_COMPONENT_UNKNOWN
Reserved.
D3D10_REGISTER_COMPONENT_UINT32
32-bit unsigned integer.
D3D10_REGISTER_COMPONENT_SINT32
32-bit signed integer.
D3D10_REGISTER_COMPONENT_FLOAT32
32-bit floating-point number.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_RESOURCE_RETURN_TYPE

The return type of a resource. See D3D10_SHADER_INPUT_BIND_DESC.

typedef enum D3D10_RESOURCE_RETURN_TYPE
{
    D3D10_RETURN_TYPE_UNORM = 1,
    D3D10_RETURN_TYPE_SNORM = 2,
    D3D10_RETURN_TYPE_SINT = 3,
    D3D10_RETURN_TYPE_UINT = 4,
    D3D10_RETURN_TYPE_FLOAT = 5,
    D3D10_RETURN_TYPE_MIXED = 6,
} D3D10_RESOURCE_RETURN_TYPE;

Constants

D3D10_RETURN_TYPE_UNORM
Unsigned integer value normalized to a value between 0 and 1.
D3D10_RETURN_TYPE_SNORM
Signed integer value normalized to a value between -1 and 1.
D3D10_RETURN_TYPE_SINT
Signed integer.
D3D10_RETURN_TYPE_UINT
Unsigned integer.
D3D10_RETURN_TYPE_FLOAT
Floating-point number.
D3D10_RETURN_TYPE_MIXED
Reserved.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_STENCIL_OP

The stencil operations that can be performed during depth-stencil testing.

typedef enum D3D10_STENCIL_OP
{
    D3D10_STENCIL_OP_KEEP = 1,
    D3D10_STENCIL_OP_ZERO = 2,
    D3D10_STENCIL_OP_REPLACE = 3,
    D3D10_STENCIL_OP_INCR_SAT = 4,
    D3D10_STENCIL_OP_DECR_SAT = 5,
    D3D10_STENCIL_OP_INVERT = 6,
    D3D10_STENCIL_OP_INCR = 7,
    D3D10_STENCIL_OP_DECR = 8,
} D3D10_STENCIL_OP;

Constants

D3D10_STENCIL_OP_KEEP
Keep the existing stencil data.
D3D10_STENCIL_OP_ZERO
Set the stencil data to 0.
D3D10_STENCIL_OP_REPLACE
Set the stencil data to the reference value set by calling ID3D10Device::OMSetDepthStencilState.
D3D10_STENCIL_OP_INCR_SAT
Increment the stencil value by 1, and clamp the result.
D3D10_STENCIL_OP_DECR_SAT
Decrement the stencil value by 1, and clamp the result.
D3D10_STENCIL_OP_INVERT
Invert the stencil data.
D3D10_STENCIL_OP_INCR
Increment the stencil value by 1, and wrap the result if necessary.
D3D10_STENCIL_OP_DECR
Increment the stencil value by 1, and wrap the result if necessary.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_TEXTURECUBE_FACE

The different faces of a cube texture.

typedef enum D3D10_TEXTURECUBE_FACE
{
    D3D10_TEXTURECUBE_FACE_POSITIVE_X = 0,
    D3D10_TEXTURECUBE_FACE_NEGATIVE_X = 1,
    D3D10_TEXTURECUBE_FACE_POSITIVE_Y = 2,
    D3D10_TEXTURECUBE_FACE_NEGATIVE_Y = 3,
    D3D10_TEXTURECUBE_FACE_POSITIVE_Z = 4,
    D3D10_TEXTURECUBE_FACE_NEGATIVE_Z = 5,
} D3D10_TEXTURECUBE_FACE;

Constants

D3D10_TEXTURECUBE_FACE_POSITIVE_X
Positive X face.
D3D10_TEXTURECUBE_FACE_NEGATIVE_X
Negative X face.
D3D10_TEXTURECUBE_FACE_POSITIVE_Y
Positive Y face.
D3D10_TEXTURECUBE_FACE_NEGATIVE_Y
Negative Y face.
D3D10_TEXTURECUBE_FACE_POSITIVE_Z
Positive Z face.
D3D10_TEXTURECUBE_FACE_NEGATIVE_Z
Negative Z face.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


D3D10_TEXTURE_ADDRESS_MODE

Identify a technique for resolving texture coordinates that are outside of the boundaries of a texture.

typedef enum D3D10_TEXTURE_ADDRESS_MODE
{
    D3D10_TEXTURE_ADDRESS_WRAP = 1,
    D3D10_TEXTURE_ADDRESS_MIRROR = 2,
    D3D10_TEXTURE_ADDRESS_CLAMP = 3,
    D3D10_TEXTURE_ADDRESS_BORDER = 4,
    D3D10_TEXTURE_ADDRESS_MIRROR_ONCE = 5,
} D3D10_TEXTURE_ADDRESS_MODE;

Constants

D3D10_TEXTURE_ADDRESS_WRAP
Tile the texture at every integer junction. For example, for u values between 0 and 3, the texture is repeated three times.
D3D10_TEXTURE_ADDRESS_MIRROR
Flip the texture at every integer junction. For u values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is flipped (mirrored); between 2 and 3, the texture is normal again; and so on.
D3D10_TEXTURE_ADDRESS_CLAMP
Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively.
D3D10_TEXTURE_ADDRESS_BORDER
Texture coordinates outside the range [0.0, 1.0] are set to the border color specified in D3D10_SAMPLER_DESC or HLSL code.
D3D10_TEXTURE_ADDRESS_MIRROR_ONCE
Similar to D3D10_TEXTURE_ADDRESS_MIRROR and D3D10_TEXTURE_ADDRESS_CLAMP. Takes the absolute value of the texture coordinate (thus, mirroring around 0), and then clamps to the maximum value.

Requirements

Header: Declared in D3D10.h.

See Also

Core Enumerations


Resource Reference

The Direct3D API defines several API elements to help you create and manage resources:

  • Resource Interfaces
  • Resource Structures
  • Resource Enumerations
  • Resource Constants

See Also

Direct3D Reference


Resource Interfaces

Direct3D 10 defines a number of interfaces to manage the two basic types of resources: buffers and textures.

Figure 1. Resource Interfaces

Interfaces | Description
ID3D10Buffer Interface | Interface for a buffer resource.
ID3D10Resource Interface | Base class for all resource interfaces.
ID3D10Texture1D Interface | Interface for a 1D texture or a 1D texture array.
ID3D10Texture2D Interface | Interface for a 2D texture or a 2D texture array
ID3D10Texture3D Interface | Interface for a 3D texture or a 3D texture array.

The API also defines the following interfaces to manage how the pipeline accesses resource data.

Figure 2. Resource-View Interfaces

Interfaces | Description
ID3D10DepthStencilView Interface | Interface for managing depth-stencil buffer is accessed.
ID3D10RenderTargetView Interface | Interface for managing how a render target is accessed.
ID3D10ShaderResourceView Interface | Interface for managing how a shader resource is accessed. A shader resource can be a constant buffer, a texture buffer, a texture or a sampler.
ID3D10View Interface | Base class for all view interfaces.

A view defines the portion of a resource to access during rendering and how to interpret the data. Instead of binding a resource directly to the pipeline, an application must create a resource view, and bind that view to the appropriate pipeline stage.

See Also

Resource Reference


ID3D10Buffer Interface

A buffer interface manages a buffer resource, which is a chunk of unstructured memory. Buffers typically store vertex and index data . The interface contains the following methods.

Methods | Description
ID3D10Buffer::GetDesc | Get a buffer description.
ID3D10Buffer::Map | Get a pointer to the buffer data.
ID3D10Buffer::Unmap | Invalidate the pointer retrieved by ID3D10Buffer::Map.

Three types of buffers can be created; vertex, index, and shader-constant buffers. To create a buffer resource, call ID3D10Device::CreateBuffer.

A buffer must be bound to the pipeline before it can be accessed. Buffers can be bound to the input-assembler stage by calls to ID3D10Device::IASetVertexBuffers and ID3D10Device::IASetIndexBuffer, and to the stream-output stage by a call to ID3D10Device::SOSetTargets.

Buffers can be bound to multiple pipeline stages simultaneously for reading. A buffer can also be bound to a single pipeline stage for writing; however, the same buffer cannot be bound for reading and writing simultaneously. For more information, see binding resources.

See Also

Resource Interfaces


ID3D10Buffer::GetDesc

Get the properties of a buffer resource.

void GetDesc(
  D3D10_BUFFER_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a resource description (see D3D10_BUFFER_DESC) filled in by the method. This pointer cannot be NULL.

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Buffer Interface


ID3D10Buffer::Map

Get a pointer to the data contained in the resource and deny GPU access to the resource.

HRESULT Map(
  D3D10_MAP MapType,
  UINT MapFlags,
  void **ppData
);

Parameters

MapType
[in] Flag that specifies the CPU's permissions for the reading and writing of a resource. For possible values, see D3D10_MAP.
MapFlags
[in] Flag that specifies what the CPU should do when the GPU is busy (see D3D10_MAP_FLAG). This flag is optional/
ppData
[out] Pointer to the buffer resource data.

Return Values

If this function succeeds, it returns S_OK. Some the reasons that Map can fail are:

  • If MapType specifies D3D10_MAP_FLAG_DO_NOT_WAIT and the GPU is not yet finished with the resource, Map returns E_WASSTILLRENDERING.
  • Map returns E_DEVICEREMOVED if MapType includes any flags that permit reading and the hardware device (that is, the video card) has been removed.

Remarks

For the CPU to write the contents of a resource, the resource must be created with the dynamic usage flag, D3D10_USAGE_DYNAMIC. To both read and write those contents, the resource must be created with the staging usage flag, D3D10_USAGE_STAGING. (For more information about these flags, see D3D10_USAGE.) ID3D10Buffer::Map will retrieve a pointer to the resource data. For a discussion on how to access resources efficiently, see Copying and Accessing Resource Data (Direct3D 10).

Call ID3D10Buffer::Unmap to signify that the application has finished accessing the resource.

Map has a few other restrictions. For example:

  • The same buffer cannot be mapped multiple times; in other words, do not call Map on a buffer that is already mapped.
  • Any buffer that is bound to the pipeline must be unmapped before any rendering operation (that is, ID3D10Device::Draw) can be executed.

Differences between Direct3D 9 and Direct3D 10:

Map in Direct3D 10 is analogous to resource Lock in Direct3D 9.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Buffer Interface


ID3D10Buffer::Unmap

Invalidate the pointer to the resource retrieved by ID3D10Buffer::Map and reenable GPU access to the resource.

void Unmap();

Parameters

None.

Return Values

Returns nothing

Remarks

Differences between Direct3D 9 and Direct3D 10:

Unmap() in Direct3D 10 is analogous to resource Unlock() in Direct3D 9.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Buffer Interface


ID3D10DepthStencilView Interface

A depth-stencil-view interface manages a texture resource is accessed during the depth-stencil test. The interface contains the following methods.

Methods | Description
ID3D10DepthStencilView::GetDesc | Get a depth-stencil-view description.

To create a depth-stencil view, call ID3D10Device::CreateDepthStencilView.

To bind a depth-stencil view to the pipeline, call ID3D10Device::OMSetRenderTargets.

See Also

Direct3D Reference


ID3D10DepthStencilView::GetDesc

Get the depth-stencil view.

void GetDesc(
  D3D10_DEPTH_STENCIL_VIEW_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a depth-stencil-view description (see D3D10_DEPTH_STENCIL_VIEW_DESC).

Return Values

Returns nothing

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10DepthStencilView Interface


ID3D10RenderTargetView Interface

A render-target-view interface manages how the pipeline outputs data during rendering. The interface contains the following methods.

Methods | Description
ID3D10RenderTargetView::GetDesc | Get a render-target-view description.

A render-target view indicates the subresources to be rendered to. More than one resource can be rendered to simultaneously.

To create a render-target view, call ID3D10Device::CreateRenderTargetView.

To bind a render-target view to the pipeline, call ID3D10Device::OMSetRenderTargets.

See Also

Direct3D Reference


ID3D10RenderTargetView::GetDesc

Get the properties of a render target view.

void GetDesc(
  D3D10_RENDER_TARGET_VIEW_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to the description of a render target view (see D3D10_RENDER_TARGET_VIEW_DESC).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10RenderTargetView Interface


ID3D10Resource Interface

Provides common actions on all resources.

Methods | Description
ID3D10Resource::GetEvictionPriority | Get the eviction priority.
ID3D10Resource::GetType | Get the resource type.
ID3D10Resource::SetEvictionPriority | Set the eviction priority.

An instance of the ID3D10Resource interface cannot be created directly; instead, interfaces that inherit from ID3D10Resource, such as buffers and textures, must be crated.

For information on creating buffers, see Creating Buffer Resources; for ceating textures, see Creating Texture Resources.

See Also

Direct3D Reference


ID3D10Resource::GetEvictionPriority

Get the eviction priority of a resource.

UINT GetEvictionPriority();

Parameters

None.

Return Values

One of the following values, which specifies the eviction priority for the resource:

  • DXGI_RESOURCE_PRIORITY_MINIMUM
  • DXGI_RESOURCE_PRIORITY_LOW
  • DXGI_RESOURCE_PRIORITY_NORMAL
  • DXGI_RESOURCE_PRIORITY_HIGH
  • DXGI_RESOURCE_PRIORITY_MAXIMUM

Remarks

This method is a wrapper for IDXGIResource::GetEvictionPriority and is provided in the ID3D10Resource Interface interface for convenience.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Resource Interface


ID3D10Resource::GetType

Get the type of the resource.

void GetType(
  D3D10_RESOURCE_DIMENSION *rType
);

Parameters

rType
[out] Pointer to the resource type (see D3D10_RESOURCE_DIMENSION).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Resource Interface


ID3D10Resource::SetEvictionPriority

Set the eviction priority of a resource.

void SetEvictionPriority(
  UINT EvictionPriority
);

Parameters

EvictionPriority
[in] Eviction priority for the resource, which is one of the following values:
  • DXGI_RESOURCE_PRIORITY_MINIMUM
  • DXGI_RESOURCE_PRIORITY_LOW
  • DXGI_RESOURCE_PRIORITY_NORMAL
  • DXGI_RESOURCE_PRIORITY_HIGH
  • DXGI_RESOURCE_PRIORITY_MAXIMUM

Return Values

Returns nothing.

Remarks

Resource priorities determine which resource to evict from video memory when the system has run out of video memory. The resource will not be lost; it will be removed from video memory and placed into system memory, or possibly placed onto the hard drive. The resource will be loaded back into video memory when it is required.

A resource that is set to the maximum priority, DXGI_RESOURCE_PRIORITY_MAXIMUM, is only evicted if there is no other way of resolving the incoming memory request. The Windows Display Driver Model (WDDM) tries to split an incoming memory request to its minimum size and evict lower-priority resources before evicting a resource with maximum priority.

Changing the priorities of resources should be done carefully. The wrong eviction priorities could be a detriment to performance rather than an improvement. See IDXGIDevice::QueryResourceResidency for additional information.

This method is a wrapper for IDXGIResource::SetEvictionPriority and is provided in the ID3D10Resource Interface interface for convenience.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Resource Interface


ID3D10ShaderResourceView Interface

A shader-resource-view interface manages how a shader accesses a resource.

Methods | Description
ID3D10ShaderResourceView::GetDesc | Get a shader-resource-view description.

A shader-resource view specifies the subresources the shader will access during rendering.

To create a shader-resource view, call ID3D10Device::CreateShaderResourceView. A resource that will be bound to the pipeline and read by a shader must be created with the shader-resource-bind flag.

To bind a shader-resource view to the pipeline, call ID3D10Device::GSSetShaderResources, ID3D10Device::VSSetShaderResources, and/or ID3D10Device::PSSetShaderResources.

To access a resource from a view interface, call ID3D10View::GetResource.

See Also

Shader Interfaces


ID3D10ShaderResourceView::GetDesc

Get the shader resource view's description.

void GetDesc(
  D3D10_SHADER_RESOURCE_VIEW_DESC *pDesc
);

Parameters

pDesc
[out] A pointer to a D3D10_SHADER_RESOURCE_VIEW_DESC structure to be filled with data about the shader resource view.

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderResourceView Interface


ID3D10Texture1D Interface

A 1D texture interface manages texel data, which is a chunk of structured memory. Textures can be read from and/or written to during rendering. The interface contains the following methods.

Methods | Description
ID3D10Texture1D::GetDesc | Get a texture description.
ID3D10Texture1D::Map | Get a pointer to the texture data.
ID3D10Texture1D::Unmap | Invalidate the pointer retrieved by ID3D10Texture1D::Map.

To create an empty Texture1D resource, call ID3D10Device::CreateTexture1D. For more details on creating and loading textures, see Creating Texture Resources.

Textures cannot be bound directly to the pipeline; instead, a view must be created and bound. To use the texture as a render target or depth-stencil resource, call ID3D10Device::CreateRenderTargetView, and ID3D10Device::CreateDepthStencilView, respectively. To use the texture as an input to a shader, create a shader-resource view by calling ID3D10Device::CreateShaderResourceView.

Using the view mechanisim, texture data can be interpreted at run time to fit the application's needs, within certain restrictions.

See Also

Resource Interfaces


ID3D10Texture1D::GetDesc

Get the properties of the texture resource.

void GetDesc(
  D3D10_TEXTURE1D_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a resource description (see D3D10_TEXTURE1D_DESC).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Texture1D Interface


ID3D10Texture1D::Map

Get a pointer to the data contained in a subresource, and deny the GPU access to that subresource.

HRESULT Map(
  UINT Subresource,
  D3D10_MAP MapType,
  UINT MapFlags,
  void **ppData
);

Parameters

Subresource
[in] Index number of the subresource. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.
MapType
[in] Specifies the CPU's read and write permissions for a resource. For possible values, see D3D10_MAP.
MapFlags
[in] Flag that specifies what the CPU should do when the GPU is busy. This flag is optional.
ppData
[out] Pointer to the texture resource data.

Return Values

If this function succeeds, it returns S_OK. For other restrictions, and a listing of error values that can be returned by any of the Map methods, see Remarks.

Remarks

Mapping a texture enables the CPU to directly access the underlying data in the subresource of a texture. For the method to succeed, the texture being mapped must be created with the appropriate flags (see D3D10_CPU_ACCESS_FLAG), and its specified usage (see D3D10_USAGE) must be either D3D10_USAGE_DYNAMIC or D3D10_USAGE_STAGING.

Common failures of Map methods are indicated by the following return values:

E_WASSTILLRENDERING
If MapType specifies D3D10_MAP_FLAG_DO_NOT_WAIT and the GPU is not yet finished with the resource, Map returns E_WASSTILLRENDERING.
E_DEVICEREMOVED
Map returns E_DEVICEREMOVED if MapType allows any CPU read access and the video card has been removed.

Map has the following restrictions:

  • A single subresource cannot be mapped multiple times; in other words, do not call Map on a subresource that is already mapped.
  • Any subresource that is bound to the pipeline must be unmapped before any render operation (that is, before ID3D10Device::Draw) can be executed.

Applications must cast the void pData pointer to the appropriate type to meaningfully access the underlying subresource data. For example, the following code demonstrates how to read each texel of a 1D subresource. It is assumed that the texture was created using DXGI_FORMAT_R32G32B32A32_FLOAT and that pData is the pointer to the texture resource data output from a successful call to this method.

FLOAT* pTexels = (FLOAT*)pData;
for( UINT col = 0; col < width; col++ )
{
  pTexels[col*4 + 0]; // Alpha
  pTexels[col*4 + 1]; // Blue
  pTexels[col*4 + 2]; // Green
  pTexels[col*4 + 3]; // Red
}

Differences between Direct3D 9 and Direct3D 10:

Map in Direct3D 10 is analogous to resource Lock in Direct3D 9.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Texture1D Interface


ID3D10Texture1D::Unmap

Invalidate the pointer to a resource that was retrieved by ID3D10Texture1D::Map, and re-enable the GPU's access to that resource.

void Unmap(
  UINT Subresource
);

Parameters

Subresource
[in] Subresource to be unmapped. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.

Return Values

Returns nothing.

Remarks

A subresource must be mapped before Unmap is called.

Differences between Direct3D 9 and Direct3D 10:

Unmap in Direct3D 10 is analogous to resource Unlock in Direct3D 9.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Texture1D Interface


ID3D10Texture2D Interface

A 2D texture interface manages texel data, which is a chunk of structured memory. Textures can be read from and/or written to during rendering. The interface contains the following methods.

Methods | Description
ID3D10Texture2D::GetDesc | Get a texture description.
ID3D10Texture2D::Map | Get a pointer to the texture data.
ID3D10Texture2D::Unmap | Invalidate the pointer retrieved by ID3D10Texture2D::Map.

To create an empty Texture2D resource, call ID3D10Device::CreateTexture2D. For more details on creating and loading textures, see Creating Texture Resources.

Textures cannot be bound directly to the pipeline; instead, a view must be created and bound. To use the texture as a render target or depth-stencil resource, call ID3D10Device::CreateRenderTargetView, and ID3D10Device::CreateDepthStencilView, respectively. To use the texture as an input to a shader, create a shader-resource view by calling ID3D10Device::CreateShaderResourceView.

Using the view mechanisim, texture data can be interpreted at run time to fit the application's needs, within certain restrictions.

See Also

Resource Interfaces


ID3D10Texture2D::GetDesc

Get the properties of the texture resource.

void GetDesc(
  D3D10_TEXTURE2D_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a resource description (see D3D10_TEXTURE2D_DESC).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Texture2D Interface


ID3D10Texture2D::Map

Get a pointer to the data contained in a subresource, and deny GPU access to that subresource.

HRESULT Map(
  UINT Subresource,
  D3D10_MAP MapType,
  UINT MapFlags,
  D3D10_MAPPED_TEXTURE2D *pMappedTex2D
);

Parameters

Subresource
[in] Index number of the subresource. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.
MapType
[in] Integer that specifies the CPU's read and write permissions for a resource. For possible values, see D3D10_MAP.
MapFlags
[in] Flag that specifies what the CPU should do when the GPU is busy. This flag is optional.
pMappedTex2D
[out] Pointer to a structure (D3D10_MAPPED_TEXTURE2D) that is filled in by the function and contains a pointer to the resource data.

Return Values

If this function succeeds, it returns S_OK.

All of the Map methods have identical return values and operating restrictions. These are listed in the remarks section of ID3D10Texture1D::Map.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Texture2D Interface


ID3D10Texture2D::Unmap

Invalidate the pointer to the resource that was retrieved by ID3D10Texture2D::Map, and re-enable GPU access to the resource.

void Unmap(
  UINT Subresource
);

Parameters

Subresource
[in] Subresource to be unmapped. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.

Return Values

Returns nothing.

Remarks

A subresource must be mapped before Unmap is called.

Differences between Direct3D 9 and Direct3D 10:

Unmap in Direct3D 10 is analogous to resource Unlock in Direct3D 9.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Texture2D Interface


ID3D10Texture3D Interface

A 3D texture interface manages texel data, which is a chunk of structured memory. Textures can be read from and/or written to during rendering. The interface contains the following methods.

Methods | Description
ID3D10Texture3D::GetDesc | Get a texture description.
ID3D10Texture3D::Map | Get a pointer to the texture data.
ID3D10Texture3D::Unmap | Invalidate the pointer retrieved by ID3D10Texture3D::Map.

To create an empty Texture3D resource, call ID3D10Device::CreateTexture3D. For more details on creating and loading textures, see Creating Texture Resources.

Textures cannot be bound directly to the pipeline; instead, a view must be created and bound. To use the texture as a render target or depth-stencil resource, call ID3D10Device::CreateRenderTargetView, and ID3D10Device::CreateDepthStencilView, respectively. To use the texture as an input to a shader, create a shader-resource view by calling ID3D10Device::CreateShaderResourceView.

Using the view mechanisim, texture data can be interpreted at run time to fit the application's needs, within certain restrictions.

See Also

Resource Interfaces


ID3D10Texture3D::GetDesc

Get the properties of the texture resource.

void GetDesc(
  D3D10_TEXTURE3D_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a resource description (see D3D10_TEXTURE3D_DESC).

Return Values

Returns nothing.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Texture3D Interface


ID3D10Texture3D::Map

Get a pointer to the data contained in a subresource, and deny GPU access to that subresource.

HRESULT Map(
  UINT Subresource,
  D3D10_MAP MapType,
  UINT MapFlags,
  D3D10_MAPPED_TEXTURE3D *pMappedTex3D
);

Parameters

Subresource
[in] Index number of the subresource. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.
MapType
[in] Specifies the CPU's read and write permissions for a resource. For possible values, see D3D10_MAP.
MapFlags
[in] Flag that specifies what the CPU should do when the GPU is busy. This flag is optional.
pMappedTex3D
[out] Pointer to a structure (D3D10_MAPPED_TEXTURE3D) that is filled in by the function and contains a pointer to the resource data.

Return Values

If this function succeeds, it returns S_OK. All of the Map methods have identical return values and operating restrictions. These are listed in the remarks section of ID3D10Texture1D::Map.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Texture3D Interface


ID3D10Texture3D::Unmap

Invalidate the pointer to the resource retrieved by ID3D10Texture3D::Map, and re-enable the GPU's access to the resource.

void Unmap(
  UINT Subresource
);

Parameters

Subresource
[in] Subresource to be unmapped. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.

Return Values

Returns nothing.

Remarks

A subresource must be mapped before Unmap is called.

Differences between Direct3D 9 and Direct3D 10:

Unmap() in Direct3D 10 is analogous to resource Unlock() in Direct3D 9.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Texture3D Interface


ID3D10View Interface

The ID3D10View interface implements a view, which specifies the parts of a resource the pipeline can access during rendering. The interface contains the following methods.

Methods | Description
ID3D10View::GetResource | Get the resource that is accessed through this view.

To create a render-target view, call ID3D10Device::CreateRenderTargetView, to create a depth-stencil view, call ID3D10Device::CreateDepthStencilView, and to create a shader-resource view, call ID3D10Device::CreateShaderResourceView.

The ID3D10View interface is the parent interface for all views. There are three types of views; a depth-stencil view, a render-target view, and a shader-resource view. A view can access a typeless resource which is created without an explicit type, but given an explicit type when it is bound to the pipeline.

All resources must be bound to the pipeline before they can be accessed. To bind a render-target view or a depth-stencil view, call ID3D10Device::OMSetRenderTargets; to bind a shader-resource view, call ID3D10Device::VSSetShaderResources.

See Also

Direct3D Reference


ID3D10View::GetResource

Get the resource that is accessed through this view.

void GetResource(
  ID3D10Resource **ppResource
);

Parameters

ppResource
[out] Address of a pointer to the resource that is accessed through this view. (See ID3D10Resource.)

Return Values

Returns nothing.

Remarks

This function increments the reference count of the resource by one, so it is necessary to call Release on the returned pointer when the application is done with it. Destroying (or losing) the returned pointer before Release is called will result in a memory leak.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10View Interface


Resource Structures

Structures used to create and use resources.

Structures | Description
D3D10_BUFFER_DESC | Description of a buffer resource.
D3D10_BUFFER_RTV | Describes the elements in a buffer to be used in a render-target view.
D3D10_BUFFER_SRV | Describes the elements in a buffer resource to use in a shader-resource view.
D3D10_DEPTH_STENCIL_VIEW_DESC | Describes how the pipeline will interpret a depth-stencil resource.
D3D10_MAPPED_TEXTURE2D | Provides access to underlying subresource data in a 2D texture.
D3D10_MAPPED_TEXTURE3D | Provides access to underlying subresource data in a 3D texture.
D3D10_RENDER_TARGET_VIEW_DESC | Describes how the pipeline will interpret a render-target resource.
D3D10_SUBRESOURCE_DATA | Specifies data for initializing a subresource.
D3D10_TEX1D_ARRAY_DSV | Specifies which mipmap level and textures in a 1D texture array to use in a depth-stencil view.
D3D10_TEX1D_ARRAY_RTV | Specifies which mipmap level and textures in a 1D texture array to use in a render-target view.
D3D10_TEX1D_ARRAY_SRV | Specifies the mipmap levels and textures in a 1D texture array to use in a shader-resource view.
D3D10_TEX1D_DSV | Specifies which mipmap level of a 1D texture to use in a depth-stencil view.
D3D10_TEX1D_RTV | Specifies which mipmap level of a 1D texture to use in a render-target view.
D3D10_TEX1D_SRV | Specifies which mipmap level of a 1D texture to use in a shader-resource view.
D3D10_TEX2D_ARRAY_DSV | Specifies which mipmap level and which textures in a 2D texture array to use in a depth-stencil view.
D3D10_TEX2D_ARRAY_RTV | Specifies which mipmap level and which textures in a 2D texture array to use in a render-target view.
D3D10_TEX2D_ARRAY_SRV | Specifies the mipmap levels and textures in a 2D texture array to use in a shader-resource view.
D3D10_TEX2D_DSV | Specifies which mipmap level of a 2D texture to use in a depth-stencil view.
D3D10_TEX2D_RTV | Specifies which mipmap level of a 2D texture to use in a render-target view.
D3D10_TEX2D_SRV | Specifies which mipmap level of a 2D texture to use in a shader-resource view.
D3D10_TEX2DMS_ARRAY_DSV | SSpecifies which textures in a 2D texture array to use in a multisampled depth-stencil view.
D3D10_TEX2DMS_ARRAY_RTV | Specifies which textures in a 2D texture array to use in a multisampled render-target view.
D3D10_TEX2DMS_ARRAY_SRV | Specifies which textures in a 2D texture array to use in a multisampled shader-resource view.
D3D10_TEX2DMS_DSV | Specifies a depth-stencil view for a multisampled 2D resource.
D3D10_TEX2DMS_RTV | Specifies a render-target view for a multisampled 2D resource.
D3D10_TEX2DMS_SRV | Specifies a shader-resource view for a multisampled 2D resource.
D3D10_TEX3D_RTV | Specifies which mipmap level and which depth levels of a 3D texture to use in a render-target view.
D3D10_TEX3D_SRV | Specifies which mipmap level and which depth levels of a 3D texture to use in a shader-resource view.
D3D10_TEXCUBE_SRV | Specifies which mipmap level of a cube map to use in a shader-resource view.
D3D10_TEXTURE1D_DESC | Describes a 1D texture resource.
D3D10_TEXTURE2D_DESC | Describes a 2D texture resource.
D3D10_TEXTURE3D_DESC | Describes a 3D texture resource.

See Also

Resource Reference


D3D10_BUFFER_DESC

Describes a buffer resource.

typedef struct D3D10_BUFFER_DESC {
    UINT ByteWidth;
    D3D10_USAGE Usage;
    UINT BindFlags;
    UINT CPUAccessFlags;
    UINT MiscFlags;
} D3D10_BUFFER_DESC;

Members

ByteWidth
Size of the buffer in bytes.
Usage
Identify how the buffer is expected to be read from and written to. Frequency of update is a key factor. The most common value used is typically D3D10_USAGE_DEFAULT. See D3D10_USAGE for all possible values.
BindFlags
Identify how the buffer is to be bound to the pipeline. Applications can logicaly OR flags together (see D3D10_BIND_FLAG) to indicate that the buffer can be accessed in different ways.
CPUAccessFlags
Kinds of CPU access allowed for the texture. Applications can logicaly OR flags together (see D3D10_CPU_ACCESS_FLAG). If CPU access is not required, set to 0.
MiscFlags
Miscellaneous flags that identify less common options. Applications can logically OR flags together (see D3D10_RESOURCE_MISC_FLAG). If none of these flags apply, set to 0.

Remarks

This structure is used by ID3D10Device::CreateBuffer to create buffer resources.

In addition to this structure, there is also a helpful derived structure, CD3D10_BUFFER_DESC, which behaves like an inherited class to help create a buffer description. See D3D10.h for the full implementation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_BUFFER_RTV

Describes the elements in a buffer resource to use in a render-target view.

typedef struct D3D10_BUFFER_RTV {
    UINT ElementOffset;
    UINT ElementWidth;
} D3D10_BUFFER_RTV;

Members

ElementOffset
Number of bytes from beginning of the buffer to the first element to access.
ElementWidth
Number of bytes in each element in the buffer.

Remarks

This structure is a member of the D3D10_RENDER_TARGET_VIEW_DESC structure, which is used during a call to ID3D10Device::CreateRenderTargetView.

The Format member of D3D10_RENDER_TARGET_VIEW_DESC is used to determine the byte offset and width of the buffer.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_BUFFER_SRV

Describes the elements in a buffer resource to use in a shader-resource view.

typedef struct D3D10_BUFFER_SRV {
    UINT ElementOffset;
    UINT ElementWidth;
} D3D10_BUFFER_SRV;

Members

ElementOffset
Number of bytes from beginning of the buffer to the first element to access.
ElementWidth
Number of bytes in each element in the buffer.

Remarks

This structure is a member of the D3D10_SHADER_RESOURCE_VIEW_DESC structure, which is used during a call to ID3D10Device::CreateShaderResourceView.

The Format member of D3D10_SHADER_RESOURCE_VIEW_DESC is used to determine the byte offset and width of the buffer.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_DEPTH_STENCIL_VIEW_DESC

Describes how the pipeline will interpret a depth-stencil resource. This interpretation happens by using the view mechanism.

typedef struct D3D10_DEPTH_STENCIL_VIEW_DESC {
    DXGI_FORMAT Format;
    D3D10_DSV_DIMENSION ViewDimension;
    union {
        D3D10_TEX1D_DSV Texture1D;
        D3D10_TEX1D_ARRAY_DSV Texture1DArray;
        D3D10_TEX2D_DSV Texture2D;
        D3D10_TEX2D_ARRAY_DSV Texture2DArray;
        D3D10_TEX2DMS_DSV Texture2DMS;
        D3D10_TEX2DMS_ARRAY_DSV Texture2DMSArray;
    };
} D3D10_DEPTH_STENCIL_VIEW_DESC;

Members

Format
Format in which to interpret the data in a resource. May not be a typeless format; see Remarks for valid formats. If Format is set to DXGI_FORMAT_UNKNOWN, then the format of the parent resource is used.
ViewDimension
Type of resource (see D3D10_DSV_DIMENSION). Specifies how a depth-stencil resource will be accessed; the value is stored in the union in this structure.
Texture1D
Specifies which subresource in a 1D texture to use as a depth-stencil. See D3D10_TEX1D_DSV.
Texture1DArray
Specifies which texture and which mipmap level of that texture to use as a depth-stencil in a 1D texture array. See D3D10_TEX1D_ARRAY_DSV.
Texture2D
Specifies which subresource in a 2D texture to use as a depth-stencil. See D3D10_TEX2D_DSV.
Texture2DArray
Specifies which texture and which subresource of that texture to use as a depth-stencil in a 2D texture array. See D3D10_TEX2D_ARRAY_DSV.
Texture2DMS
Specifies nothing, because a multisampled 2D texture always contains a single subresource. See D3D10_TEX2DMS_DSV.
Texture2DMSArray
Specifies which textures in a multisampled 2D texture array to use as a depth-stencil. See D3D10_TEX2DMS_ARRAY_DSV.

Remarks

This structure is used in a call to ID3D10Device::CreateDepthStencilView.

The depth-stencil-view format must be one of the following (see DXGI_FORMAT).

  • DXGI_FORMAT_D16_UNORM
  • DXGI_FORMAT_D24_UNORM_S8_UINT
  • DXGI_FORMAT_D32_FLOAT
  • DXGI_FORMAT_D32_FLOAT_S8X24_UINT
  • DXGI_FORMAT_UNKNOWN

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_MAPPED_TEXTURE2D

Provides access to underlying subresource data in a 2D texture.

typedef struct D3D10_MAPPED_TEXTURE2D {
    void *pData;
    UINT RowPitch;
} D3D10_MAPPED_TEXTURE2D;

Members

pData
Pointer to the underlying bits of the subresource.
RowPitch
Number of bytes in one row of the subresource.

Remarks

This structure is used in a call to ID3D10Texture2D::Map.

Applications must cast the pData pointer to the appropriate type to meaningfully access the underlying subresource data. For example, the following code demonstrates how to read each texel of a subresource. It is assumed that the texture was created using DXGI_FORMAT_R32G32B32A32_FLOAT.

D3D10_MAPPED_TEXTURE2D mappedTexture;
pTexture->Map( D3D10CalcSubresource(0, 0, 1), D3D10_MAP_WRITE_DISCARD, 0, &mappedTexture );

FLOAT* pTexels = (FLOAT*)mappedTexture.pData;
for( UINT row = 0; row < height; row++ )
{
  UINT rowStart = row * mappedTexture.RowPitch/4;
  for( UINT col = 0; col < width; col++ )
  {
    pTexels[rowStart + col*4 + 0]; // Red
    pTexels[rowStart + col*4 + 1]; // Green
    pTexels[rowStart + col*4 + 2]; // Blue
    pTexels[rowStart + col*4 + 3]; // Alpha
  }
}

pTexture->Unmap(D3D10CalcSubresource(0, 0, 1));

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_MAPPED_TEXTURE3D

Provides access to underlying subresource data in a 3D texture.

typedef struct D3D10_MAPPED_TEXTURE3D {
    void *pData;
    UINT RowPitch;
    UINT DepthPitch;
} D3D10_MAPPED_TEXTURE3D;

Members

pData
Pointer to the underlying bits of the subresource.
RowPitch
Number of bytes in one row of the subresource.
DepthPitch
Number of bytes in one depth slice of the subresource.

Remarks

This structure is used in a call to ID3D10Texture3D::Map.

Applications must cast the pData pointer to the appropriate type to meaningfully access the underlying subresource data. See D3D10_MAPPED_TEXTURE2D for an example.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_RENDER_TARGET_VIEW_DESC

A render-target-view description describes how the pipeline will interpret a render-target resource.

typedef struct D3D10_RENDER_TARGET_VIEW_DESC {
    DXGI_FORMAT Format;
    D3D10_RTV_DIMENSION ViewDimension;
    union {
        D3D10_BUFFER_RTV Buffer;
        D3D10_TEX1D_RTV Texture1D;
        D3D10_TEX1D_ARRAY_RTV Texture1DArray;
        D3D10_TEX2D_RTV Texture2D;
        D3D10_TEX2D_ARRAY_RTV Texture2DArray;
        D3D10_TEX2DMS_RTV Texture2DMS;
        D3D10_TEX2DMS_ARRAY_RTV Texture2DMSArray;
        D3D10_TEX3D_RTV Texture3D;
    };
} D3D10_RENDER_TARGET_VIEW_DESC;

Members

Format
The format of the resource data (see DXGI_FORMAT).
ViewDimension
The resource type (see D3D10_RTV_DIMENSION), which specifies how the render-target resource will be accessed.
Buffer
Specifies which buffer elements to use in a render-target view. See D3D10_BUFFER_RTV.
Texture1D
Specifies the subresources in a 1D texture to use as the render target. See D3D10_TEX1D_RTV.
Texture1DArray
Specifies the textures and mipmap levels in a 1D texture array to use as the render target . See D3D10_TEX1D_ARRAY_RTV.
Texture2D
Specifies the subresources in a 2D texture to use as a render target. See D3D10_TEX2D_RTV.
Texture2DArray
Specifies the textures and subresources in a 2D texture array to use as a render target. See D3D10_TEX2D_ARRAY_RTV.
Texture2DMS
Specifies nothing, because a multisampled 2D texture always contains a single subresource. See D3D10_TEX2DMS_RTV.
Texture2DMSArray
Specifies the textures in a multisampled 2D texture array to use as a render target. See D3D10_TEX2DMS_ARRAY_RTV.
Texture3D
Specifies subresources and depth levels in a 3D texture to use as the render target. See D3D10_TEX3D_RTV.

Remarks

A render-target-view description is passed into ID3D10Device::CreateRenderTargetView to create a render target.

The following formats are not allowed for a render-target-view description:

  • Any typeless format.
  • DXGI_FORMAT_R32G32B32 if the view will be used to bind a buffer (vertex, index, constant, or stream-output).

If the format is set to DXGI_FORMAT_UNKNOWN, then the format of the resource that the view binds to the pipeline will be used.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_SUBRESOURCE_DATA

Specifies data for initializing a subresource.

typedef struct D3D10_SUBRESOURCE_DATA {
    const void *pSysMem;
    UINT SysMemPitch;
    UINT SysMemSlicePitch;
} D3D10_SUBRESOURCE_DATA;

Members

pSysMem
Pointer to the initial subresource data to initialize the resource. See remarks.
SysMemPitch
Pitch of the memory, in bytes; this may or may not be the same as the size of one row in the resource. This member is used only for 2D and 3D texture resources; it is ignored for the other resource types.
SysMemSlicePitch
Size of one depth level, in bytes. This member is only used for 3D texture resources; it is ignored for the other resource types.

Remarks

This structure is used in calls to create buffers (ID3D10Device::CreateBuffer) and textures (ID3D10Device::CreateTexture1D, ID3D10Device::CreateTexture2D, and ID3D10Device::CreateTexture3D).

If the resource being created does not require SysMemPitch or SysMemSlicePitch, then it may be useful to use those members when debugging by specifying the total size of the resource in bytes. This way, if the wrong creation function is called (for example, calling ID3D10Device::CreateTexture2D and initializing it with a pointer to a buffer) a memory error will occur when ID3D10Device::UpdateSubresource is called.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX1D_ARRAY_DSV

Specifies which mipmap level and textures in a 1D texture array to use in a depth-stencil view.

typedef struct D3D10_TEX1D_ARRAY_DSV {
    UINT MipSlice;
    UINT FirstArraySlice;
    UINT ArraySize;
} D3D10_TEX1D_ARRAY_DSV;

Members

MipSlice
Mipmap level to use in a depth-stencil view. A value of 0 indicates the first, most detailed mipmap level.
FirstArraySlice
First texture in the array to use in the depth-stencil view.
ArraySize
Number of textures in the array to use in the depth-stencil view, starting from FirstArraySlice. A value of -1 indicates all array slices starting from FirstArraySlice.

Remarks

This structure is one member of a depth-stencil view. See D3D10_DEPTH_STENCIL_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3d10core.

See Also

Resource Structures


D3D10_TEX1D_ARRAY_RTV

Specifies which mipmap level and textures in a 1D texture array to use in a render-target view.

typedef struct D3D10_TEX1D_ARRAY_RTV {
    UINT MipSlice;
    UINT FirstArraySlice;
    UINT ArraySize;
} D3D10_TEX1D_ARRAY_RTV;

Members

MipSlice
Mipmap level to use in a render-target view. A value of 0 indicates the first, most detailed mipmap level.
FirstArraySlice
First texture in the array to use in the render-target view.
ArraySize
Number of textures in the array to use in the render-target view, starting from FirstArraySlice. A value of -1 indicates all array slices starting from FirstArraySlice.

Remarks

This structure is one member of a render-target view. See D3D10_RENDER_TARGET_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3d10core.

See Also

Resource Structures


D3D10_TEX1D_ARRAY_SRV

Specifies the mipmap levels and textures in a 1D texture array to use in a shader-resource view.

typedef struct D3D10_TEX1D_ARRAY_SRV {
    UINT MostDetailedMip;
    UINT MipLevels;
    UINT FirstArraySlice;
    UINT ArraySize;
} D3D10_TEX1D_ARRAY_SRV;

Members

MostDetailedMip
Starting mipmap level, where 0 is the biggest and most detailed.
MipLevels
Number of mipmap levels to make accessible, starting from MostDetailedMip.
FirstArraySlice
First texture in the array to use in the shader-resource view.
ArraySize
Number of textures in the array to use in the shader-resource view, starting from FirstArraySlice. A value of -1 indicates all array slices starting from FirstArraySlice.

Remarks

This structure is one member of a shader-resource view. See D3D10_SHADER_RESOURCE_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3d10core.h.

See Also

Resource Structures


D3D10_TEX1D_DSV

Specifies which mipmap level of a 1D texture to use in a depth-stencil view.

typedef struct D3D10_TEX1D_DSV {
    UINT MipSlice;
} D3D10_TEX1D_DSV;

Members

MipSlice
Mipmap level to use in a depth-stencil view. A value of 0 indicates the first, most detailed mipmap level.

Remarks

This structure is one member of a depth-stencil view. See D3D10_DEPTH_STENCIL_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX1D_RTV

Specifies which mipmap level of a 1D texture to use in a render-target view.

typedef struct D3D10_TEX1D_RTV {
    UINT MipSlice;
} D3D10_TEX1D_RTV;

Members

MipSlice
Mipmap level to use in a render-target view. A value of 0 indicates the first, most detailed mipmap level.

Remarks

This structure is one member of a render-target view. See D3D10_RENDER_TARGET_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX1D_SRV

Specifies which mipmap level of a 1D texture to use in a shader-resource view.

typedef struct D3D10_TEX1D_SRV {
    UINT MostDetailedMip;
    UINT MipLevels;
} D3D10_TEX1D_SRV;

Members

MostDetailedMip
Starting mipmap level, where 0 is the biggest and most detailed.
MipLevels
Number of mipmap levels to make accessible, starting from MostDetailedMip.

Remarks

This structure is one member of a shader-resource view. See D3D10_SHADER_RESOURCE_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX2D_ARRAY_DSV

Specifies which mipmap level and which textures in a 2D texture array to use in a depth-stencil view.

typedef struct D3D10_TEX2D_ARRAY_DSV {
    UINT MipSlice;
    UINT FirstArraySlice;
    UINT ArraySize;
} D3D10_TEX2D_ARRAY_DSV;

Members

MipSlice
Mipmap level to use in a depth-stencil view. A value of 0 indicates the first, most detailed mipmap level.
FirstArraySlice
First texture in the array to use in the depth-stencil view.
ArraySize
Number of textures in the array to use in the depth-stencil view, starting from FirstArraySlice. A value of -1 indicates all array slices, starting from FirstArraySlice.

Remarks

This structure is one member of a depth-stencil view. See D3D10_DEPTH_STENCIL_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3d10core.

See Also

Resource Structures


D3D10_TEX2D_ARRAY_RTV

Specifies which mipmap level and which textures in a 2D texture array to use in a render-target view.

typedef struct D3D10_TEX2D_ARRAY_RTV {
    UINT MipSlice;
    UINT FirstArraySlice;
    UINT ArraySize;
} D3D10_TEX2D_ARRAY_RTV;

Members

MipSlice
Mipmap level to use in a render-target view. A value of 0 indicates the first, most detailed mipmap level.
FirstArraySlice
First texture in the array to use in the render-target view.
ArraySize
Number of textures in the array to use in the render target view, starting from FirstArraySlice. A value of -1 indicates all array slices, starting from FirstArraySlice.

Remarks

This structure is one member of a render-target view. See D3D10_RENDER_TARGET_VIEW_DESC.

Figure 1. Texture Array With Associated Mipmap Chains

Texture arrays are accessed with two indices; the FirstArraySlice specifies which texture within the texture array to access, and MipSlice indicates the particular mipmap level.

Requirements

Header: Declared in D3d10core.

See Also

Resource Structures


D3D10_TEX2D_ARRAY_SRV

Specifies the mipmap levels and textures in a 2D texture array to use in a shader-resource view.

typedef struct D3D10_TEX2D_ARRAY_SRV {
    UINT MostDetailedMip;
    UINT MipLevels;
    UINT FirstArraySlice;
    UINT ArraySize;
} D3D10_TEX2D_ARRAY_SRV;

Members

MostDetailedMip
Starting mipmap level, where 0 is the biggest and most detailed.
MipLevels
Number of mipmap levels to make accessible, starting from MostDetailedMip.
FirstArraySlice
First texture in the array to use in the shader-resource view.
ArraySize
Number of textures in the array to use in the shader-resource view, starting from FirstArraySlice. A value of -1 indicates all array slices starting from FirstArraySlice.

Remarks

This structure is one member of a shader-resource view. See D3D10_SHADER_RESOURCE_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3d10core.h.

See Also

Resource Structures


D3D10_TEX2D_DSV

Specifies which mipmap level of a 2D texture to use in a depth-stencil view.

typedef struct D3D10_TEX2D_DSV {
    UINT MipSlice;
} D3D10_TEX2D_DSV;

Members

MipSlice
Mipmap level to use in a depth-stencil view. A value of 0 indicates the first, most detailed mipmap level.

Remarks

This structure is one member of a depth-stencil view. See D3D10_DEPTH_STENCIL_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX2D_RTV

Specifies which mipmap level of a 2D texture to use in a render-target view.

typedef struct D3D10_TEX2D_RTV {
    UINT MipSlice;
} D3D10_TEX2D_RTV;

Members

MipSlice
Mipmap level to use in a render-target view. A value of 0 indicates the first, most detailed mipmap level.

Remarks

This structure is one member of a render-target view. See D3D10_RENDER_TARGET_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX2D_SRV

Specifies which mipmap level of a 2D texture to use in a shader-resource view.

typedef struct D3D10_TEX2D_SRV {
    UINT MostDetailedMip;
    UINT MipLevels;
} D3D10_TEX2D_SRV;

Members

MostDetailedMip
Starting mipmap level, where 0 is the biggest and most detailed.
MipLevels
Number of mipmap levels to make accessible, starting from MostDetailedMip.

Remarks

This structure is one member of a shader-resource view. See D3D10_SHADER_RESOURCE_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX2DMS_ARRAY_DSV

Specifies which textures in a 2D texture array to use in a multisampled depth-stencil view.

typedef struct D3D10_TEX2D_ARRAY_RTV {
    UINT FirstArraySlice;
    UINT ArraySize;
} D3D10_TEX2DMS_ARRAY_DSV;

Members

FirstArraySlice
First texture in the array to use in the depth-stencil view.
ArraySize
Number of textures in the array to use in the depth-stencil view, starting from FirstArraySlice. A value of -1 indicates all array slices, starting from FirstArraySlice.

Remarks

This structure is one member of a depth-stencil view. See D3D10_DEPTH_STENCIL_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3d10core.h.

See Also

Resource Structures


D3D10_TEX2DMS_ARRAY_RTV

Specifies which textures in a 2D texture array to use in a multisampled render-target view.

typedef struct D3D10_TEX2D_ARRAY_RTV {
    UINT FirstArraySlice;
    UINT ArraySize;
} D3D10_TEX2DMS_ARRAY_RTV;

Members

FirstArraySlice
First texture in the array to use in the render-target view.
ArraySize
Number of textures in the array to use in the render-target view, starting from FirstArraySlice. A value of -1 indicates all array slices, starting from FirstArraySlice.

Remarks

This structure is one member of a render-target view. See D3D10_RENDER_TARGET_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3d10core.h.

See Also

Resource Structures


D3D10_TEX2DMS_ARRAY_SRV

Specifies which textures in a 2D texture array to use in a multisampled shader-resource view.

typedef struct D3D10_TEX2D_ARRAY_RTV {
    UINT FirstArraySlice;
    UINT ArraySize;
} D3D10_TEX2DMS_ARRAY_SRV;

Members

FirstArraySlice
First texture in the array to use in the render-target view.
ArraySize
Number of textures in the array to use in the render-target view, starting from FirstArraySlice. A value of -1 indicates all array slices, starting from FirstArraySlice.

Remarks

This structure is one member of a shader-resource view. See D3D10_SHADER_RESOURCE_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3d10core.h.

See Also

Resource Structures


D3D10_TEX2DMS_DSV

Specifies a depth-stencil view for a multisampled 2D resource.

typedef struct D3D10_TEX2D_DSV {
    UINT UnusedField_NothingToDefine;
} D3D10_TEX2DMS_DSV;

Members

UnusedField_NothingToDefine
Integer of any value. See remarks.

Remarks

Since a multisampled 2D texture contains a single subresource, there is actually nothing to specify in D3D10_TEX2DMS_DSV. Consequently, UnusedField_NothingToDefine is included so that this structure will compile in C.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX2DMS_RTV

Specifies a render-target view for a multisampled 2D resource.

typedef struct D3D10_TEX2D_RTV {
    UINT UnusedField_NothingToDefine;
} D3D10_TEX2DMS_RTV;

Members

UnusedField_NothingToDefine
Integer of any value. See remarks.

Remarks

Since a multisampled 2D texture contains a single subresource, there is actually nothing to specify in D3D10_TEX2DMS_RTV. Consequently, UnusedField_NothingToDefine is included so that this structure will compile in C.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX2DMS_SRV

Specifies a shader-resource view for a multisampled 2D resource.

typedef struct D3D10_TEX2D_SRV {
    UINT UnusedField_NothingToDefine;
} D3D10_TEX2DMS_SRV;

Members

UnusedField_NothingToDefine
Integer of any value. See remarks.

Remarks

Since a multisampled 2D texture contains a single subresource, there is actually nothing to specify in D3D10_TEX2DMS_RTV. Consequently, UnusedField_NothingToDefine is included so that this structure will compile in C.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX3D_RTV

Specifies which mipmap level and which depth levels of a 3D texture to use in a render-target view.

typedef struct D3D10_TEX3D_RTV {
    UINT MipSlice;
    UINT FirstWSlice;
    UINT WSize;
} D3D10_TEX3D_RTV;

Members

MipSlice
Mipmap level to use in a render-target view. A value of 0 indicates the first, most detailed mipmap level.
FirstWSlice
First depth level to use in the render-target view.
WSize
Number of depth levels to use in the render-target view, starting from FirstWSlice. A value of -1 indicates all of the slices along the w axis, starting from FirstWSlice.

Remarks

This structure is one member of a render target view. See D3D10_RENDER_TARGET_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEX3D_SRV

Specifies which mipmap level and which depth levels of a 3D texture to use in a shader-resource view.

typedef struct D3D10_TEX3D_SRV {
    UINT MostDetailedMip;
    UINT MipLevels;
} D3D10_TEX3D_SRV;

Members

MostDetailedMip
Starting mipmap level, where 0 is the biggest and most detailed.
MipLevels
Number of mipmap levels to make accessible, starting from MostDetailedMip.

Remarks

This structure is one member of a shader-resource view. See D3D10_SHADER_RESOURCE_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEXCUBE_SRV

Specifies which mipmap level of a cube map to use in a shader-resource view.

typedef struct D3D10_TEXCUBE_SRV {
    UINT MostDetailedMip;
    UINT MipLevels;
} D3D10_TEXCUBE_SRV;

Members

MostDetailedMip
Starting mipmap slice, where 0 is the biggest and most detailed.
MipLevels
Number of mipmap levels to make accessible, starting from MostDetailedMip.

Remarks

This structure is one member of a shader-resource view. See D3D10_SHADER_RESOURCE_VIEW_DESC.

Please see D3D10_TEX2D_ARRAY_RTV, for a visual representation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEXTURE1D_DESC

Describes a 1D texture resource.

typedef struct D3D10_TEXTURE1D_DESC {
    UINT Width;
    UINT MipLevels;
    UINT ArraySize;
    DXGI_FORMAT Format;
    D3D10_USAGE Usage;
    UINT BindFlags;
    UINT CPUAccessFlags;
    UINT MiscFlags;
} D3D10_TEXTURE1D_DESC;

Members

Width
Width of the texture in texels.
MipLevels
Number of mipmap levels in the texture. If the number is 0, a full mipmap chain will be created. Use 1 if the texture is multisampled (since multisampled textures cannot be mipmapped)
ArraySize
Number of textures in the texture array.
Format
Format of the texels within the texture. See DXGI_FORMAT.
Usage
Value that identifies how the texture is to be read from and written to. The most common value is typically D3D10_USAGE-DEFAULT. See D3D10_USAGE.
BindFlags
Flag that indicates how the texture is to be bound to the pipeline; which can be combined by a logical OR. See D3D10_BIND_FLAG.
CPUAccessFlags
Flag that specifies the types of CPU access allowed for the texture; which can be combined by a logical OR. If access by the CPU is not required, set to 0. See D3D10_CPU_ACCESS_FLAG.
MiscFlags
Flag that identifies other, less common resource options; which can be combined by a logical OR. If none of these flags apply, set to 0. See D3D10_RESOURCE_MISC_FLAG.

Remarks

This structure is used in a call to ID3D10Device::CreateTexture1D.

In addition, a helpful derived structure, CD3D10_TEXTURE1D_DESC, which behaves like an inherited class, is available to help create a texture description. See D3D10.h for the full implementation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEXTURE2D_DESC

Describes a 2D texture resource.

typedef struct D3D10_TEXTURE2D_DESC {
    UINT Width;
    UINT Height;
    UINT MipLevels;
    UINT ArraySize;
    DXGI_FORMAT Format;
    DXGI_SAMPLE_DESC SampleDesc;
    D3D10_USAGE Usage;
    UINT BindFlags;
    UINT CPUAccessFlags;
    UINT MiscFlags;
} D3D10_TEXTURE2D_DESC;

Members

Width
Width of the texture in texels.
Height
Height of the texture in texels.
MipLevels
Number of mipmap levels in the texture. Use 0 to create a full mipmap chain. Use 1 if the texture is multisampled (since multisampled textures cannot be mipmapped).
ArraySize
Number of textures in the texture array.
Format
Format of the texels within the texture. See DXGI_FORMAT.
SampleDesc
Structure that specifies multisampling parameters for the texture. See DXGI_SAMPLE_DESC.
Usage
Value that identifies how the texture is to be read from and written to. The most common value is typically D3D10_USAGE-DEFAULT. See D3D10_USAGE.
BindFlags
Flag that indicates how the texture is to be bound to the pipeline; which can be combined by a logical OR. See D3D10_BIND_FLAG.
CPUAccessFlags
Flag that specifies the types of CPU access allowed for the texture; which can be combined by a logical OR. If access by the CPU is not required, set to 0. See D3D10_CPU_ACCESS_FLAG.
MiscFlags
Flag that identifies other, less common resource options; which can be combined by a logical OR. If none of these flags apply, set to 0. See D3D10_RESOURCE_MISC_FLAG.

Remarks

This structure is used in a call to ID3D10Device::CreateTexture2D.

In addition, a helpful derived structure, CD3D10_TEXTURE2D_DESC, which behaves like an inherited class, is available to help create a texture description. See D3D10.h for the full implementation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


D3D10_TEXTURE3D_DESC

Describes a 3D texture resource.

typedef struct D3D10_TEXTURE3D_DESC {
    UINT Width;
    UINT Height;
    UINT Depth;
    UINT MipLevels;
    DXGI_FORMAT Format;
    D3D10_USAGE Usage;
    UINT BindFlags;
    UINT CPUAccessFlags;
    UINT MiscFlags;
} D3D10_TEXTURE3D_DESC;

Members

Width
Width of the texture in texels.
Height
Height of the texture in texels.
Depth
Depth of the texture in texels
MipLevels
Number of mipmap levels in the texture. If the number is 0, a full mipmap chain will be created. Use 1 if the texture is multisampled (since multisampled textures cannot be mipmapped)
Format
Format of the texels within the texture. See DXGI_FORMAT.
Usage
Value that identifies how the texture is to be read from and written to. The most common value is typically D3D10_USAGE-DEFAULT. See D3D10_USAGE.
BindFlags
Flag that indicates how the texture is to be bound to the pipeline; which can be combined by a logical OR. See D3D10_BIND_FLAG.
CPUAccessFlags
Flag that specifies the types of CPU access allowed for the texture; which can be combined by a logical OR. If access by the CPU is not required, set to 0. See D3D10_CPU_ACCESS_FLAG.
MiscFlags
Flag that identifies other, less common resource options; which can be combined by a logical OR. If none of these flags apply, set to 0. See D3D10_RESOURCE_MISC_FLAG.

Remarks

This structure is used in a call to ID3D10Device::CreateTexture3D.

In addition, a helpful derived structure, CD3D10_TEXTURE3D_DESC, which behaves like an inherited class, is available to help create a texture description. See D3D10.h for the full implementation.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Structures


Resource Enumerations

The following enumerations are used to specify information about how resources are created and accessed during rendering.

Enumeration | Description
D3D10_BIND_FLAG | Identifies how a resource will be used by the pipeline and determines which pipeline stage(s) a resource can be bound to.
D3D10_CPU_ACCESS_FLAG | Specifies the types of CPU access allowed for a resource.
D3D10_DSV_DIMENSION | Specifies how to access a resource that is used in a depth-stencil view.
D3D10_MAP | Identifies a resource to be mapped for reading and writing by the CPU.
D3D10_MAP_FLAG | Specifies how the CPU should respond to any Map methods when the GPU is not yet finished with the resource.
D3D10_RESOURCE_DIMENSION | Identifies the type of resource that is in use.
D3D10_RESOURCE_MISC_FLAG | Identifies less common resource creation options.
D3D10_RTV_DIMENSION | Specifies how to access a resource used in a render target view.
D3D10_USAGE | Identifies how a resource is expected to be read and written by the CPU and/or the GPU.

See Also

Resource Reference


D3D10_BIND_FLAG

Identifies how a resource will be bound to the pipeline.

typedef enum D3D10_BIND_FLAG
{
    D3D10_BIND_VERTEX_BUFFER = 0x1L,
    D3D10_BIND_INDEX_BUFFER = 0x2L,
    D3D10_BIND_CONSTANT_BUFFER = 0x4L,
    D3D10_BIND_SHADER_RESOURCE = 0x8L,
    D3D10_BIND_STREAM_OUTPUT = 0x10L,
    D3D10_BIND_RENDER_TARGET = 0x20L,
    D3D10_BIND_DEPTH_STENCIL = 0x40L,
} D3D10_BIND_FLAG;

Constants

D3D10_BIND_VERTEX_BUFFER
Use the resource as a vertex buffer; not valid on texture resources.
D3D10_BIND_INDEX_BUFFER
Use the resource as an index buffer; not valid on texture resources.
D3D10_BIND_CONSTANT_BUFFER
Use the resource as a constant buffer; not valid on texture resources. This flag does the following.
  • Disallows other binding flags.
  • Prevents partial updates of the resource (ID3D10Device::UpdateSubresource must update the full buffer).
  • Restricts the buffers' byte width to be less than or equal to 4096×(conceptual size of DXGI_FORMAT_R32G32B32A32, which is 16) and be a multiple of 16.
D3D10_BIND_SHADER_RESOURCE
Use the resource as a shader resource; cannot be used with D3D10_MAP_WRITE_NO_OVERWRITE.
D3D10_BIND_STREAM_OUTPUT
Use the resource as an output buffer for the stream output stage; not valid on texture resources.
D3D10_BIND_RENDER_TARGET
Use the resource (or any subresource) as a render target.
D3D10_BIND_DEPTH_STENCIL
Use the resource (or any subresource) as a depth-stencil buffer.

Remarks

This enumeration is used in D3D10_BUFFER_DESC, D3D10_TEXTURE1D_DESC, D3D10_TEXTURE2D_DESC, and D3D10_TEXTURE3D_DESC during resource creation. See Creating Buffer Resources (Direct3D 10) for more details.

Applications may combine one or more of these flags by using a logical OR. When possible, use a single bind flag; as this allows the device to better optimize how it handles the resource.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Enumerations


D3D10_CPU_ACCESS_FLAG

Specifies the types of CPU access allowed for a resource.

typedef enum D3D10_CPU_ACCESS_FLAG
{
    D3D10_CPU_ACCESS_WRITE = 0x10000L,
    D3D10_CPU_ACCESS_READ = 0x20000L,
} D3D10_CPU_ACCESS_FLAG;

Constants

D3D10_CPU_ACCESS_WRITE
The resource is to be mappable so that the CPU can change its contents. Resources created with this flag cannot be set as outputs of the pipeline and must be created with either dynamic or staging usage (see D3D10_USAGE).
D3D10_CPU_ACCESS_READ
The resource is to be mappable so that the CPU can read its contents. Resources created with this flag cannot be set as either inputs or outputs to the pipeline and must be created with staging usage (see D3D10_USAGE).

Remarks

This enumeration is used in D3D10_BUFFER_DESC, D3D10_TEXTURE1D_DESC, D3D10_TEXTURE2D_DESC, D3D10_TEXTURE3D_DESC, and D3DX10_IMAGE_LOAD_INFO. See Creating Buffer Resources (Direct3D 10) for more details.

Applications may combine one or more of these flags with a logical OR. When possible, create resources with no CPU access flags, as this enables better resource optimiztion.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Enumerations


D3D10_DSV_DIMENSION

Specifies how to access a resource used in a depth-stencil view.

typedef enum D3D10_DSV_DIMENSION
{
    D3D10_DSV_DIMENSION_UNKNOWN = 0,
    D3D10_DSV_DIMENSION_TEXTURE1D = 1,
    D3D10_DSV_DIMENSION_TEXTURE1DARRAY = 2,
    D3D10_DSV_DIMENSION_TEXTURE2D = 3,
    D3D10_DSV_DIMENSION_TEXTURE2DARRAY = 4,
    D3D10_DSV_DIMENSION_TEXTURE2DMS = 5,
    D3D10_DSV_DIMENSION_TEXTURE2DMSARRAY = 6,
} D3D10_DSV_DIMENSION;

Constants

D3D10_DSV_DIMENSION_UNKNOWN
The resource will be accessed according to its type as determined from the actual instance this enumeration is paired with when the depth-stencil view is created.
D3D10_DSV_DIMENSION_TEXTURE1D
The resource will be accessed as a 1D texture.
D3D10_DSV_DIMENSION_TEXTURE1DARRAY
The resource will be accessed as an array of 1D textures.
D3D10_DSV_DIMENSION_TEXTURE2D
The resource will be accessed as a 2D texture.
D3D10_DSV_DIMENSION_TEXTURE2DARRAY
The resource will be accessed as an array of 2D texture.
D3D10_DSV_DIMENSION_TEXTURE2DMS
The resource will be accessed as a 2D texture with multisampling.
D3D10_DSV_DIMENSION_TEXTURE2DMSARRAY
The resource will be accessed as an array of 2D textures with multisampling.

Remarks

This enumeration is used in D3D10_DEPTH_STENCIL_VIEW_DESC to create a depth-stencil view.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Enumerations


D3D10_MAP

Identifies a resource to be accessed for reading and writing by the CPU. Applications may combine one or more of these flags.

typedef enum D3D10_MAP
{
    D3D10_MAP_READ = 1,
    D3D10_MAP_WRITE = 2,
    D3D10_MAP_READ_WRITE = 3,
    D3D10_MAP_WRITE_DISCARD = 4,
    D3D10_MAP_WRITE_NO_OVERWRITE = 5,
} D3D10_MAP;

Constants

D3D10_MAP_READ
Resource is mapped for reading. The resource must have been created with read access (see D3D10_CPU_ACCESS_READ).
D3D10_MAP_WRITE
Resource is mapped for writing. The resource must have been created with write access (see D3D10_CPU_ACCESS_WRITE).
D3D10_MAP_READ_WRITE
Resource is mapped for reading and writing. The resource must have been created with read and write access (see D3D10_CPU_ACCESS_READ and D3D10_CPU_ACCESS_WRITE).
D3D10_MAP_WRITE_DISCARD
Resource is mapped for writing; the previous contents of the resource will be undefined. The resource must have been created with write access (see D3D10_CPU_ACCESS_WRITE).
D3D10_MAP_WRITE_NO_OVERWRITE
Resource is mapped for writing; the existing contents of the resource cannot be overwritten (see Remarks). This flag is only valid on vertex and index buffers. The resource must have been created with write access (see D3D10_CPU_ACCESS_WRITE). Cannot be used on a resource created with the D3D10_BIND_CONSTANT_BUFFER flag.

Remarks

This enumeration is used in ID3D10Buffer::Map, ID3D10Texture1D::Map, ID3D10Texture2D::Map, and ID3D10Texture3D::Map.

These remarks are divided into the following topics:

  • Meaning of D3D10_MAP_WRITE_NO_OVERWRITE
  • Common Usage of D3D10_MAP_WRITE_DISCARD with D3D10_MAP_WRITE_NO_OVERWRITE
Meaning of D3D10_MAP_WRITE_NO_OVERWRITE

D3D10_MAP_WRITE_NO_OVERWRITE signifies that the application promises not to write to data that the Input Assembler (IA) stage is using. In exchange, the GPU allows the application to write to other parts of the same buffer. The application must ensure that it does not write over any data in use by the IA stage.

For example, consider the buffer illustrated in Figure 1. If a Draw call has been issued that uses vertices 4-6, then an application that calls Map on this buffer must ensure that it does not write to the vertices that the Draw call will access during rendering.

Figure 1. Vertex Data in Different Stages of Utilization

However, ensuring this can be difficult, because the GPU is often many frames behind the CPU in terms of which frame it is currently processing. Keeping track of which sections of a resource are being used because of calls made 2 to 5 frames ago is difficult and error-prone. Because of this, it is recommended that applications only write to the uninitialized portions of a resource when using D3D10_MAP_WRITE_NO_OVERWRITE.

Common Usage of D3D10_MAP_WRITE_DISCARD with D3D10_MAP_WRITE_NO_OVERWRITE

D3D10_MAP_WRITE_DISCARD and D3D10_MAP_WRITE_NO_OVERWRITE are normally used in conjunction with dynamic index/vertex buffers, although they can also be used with dynamic textures.

A common use of these two flags involves filling dynamic index/vertex buffers with geometry that can be seen from the camera's current position. The first time that data is entered into the buffer on a given frame, Map is called with D3D10_MAP_WRITE_DISCARD; doing so invalidates the previous contents of the buffer. The buffer is then filled with all available data.

Subsequent writes to the buffer within the same frame should use D3D10_MAP_WRITE_NO_OVERWRITE. This will enable the CPU to access a resource that is potentially being used by the GPU as long as the restrictions described previously are respected.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Enumerations


D3D10_MAP_FLAG

Specifies how the CPU should respond when Map is called on a resource being used by the GPU.

typedef enum D3D10_MAP_FLAG
{
    D3D10_MAP_FLAG_DO_NOT_WAIT = 0x100000L,
} D3D10_MAP_FLAG;

Constants

D3D10_MAP_FLAG_DO_NOT_WAIT
Specifies that Map should return E_WASSTILLRENDERING when the GPU blocks the CPU from accessing a resource.

Remarks

This enumeration is used by ID3D10Buffer::Map, ID3D10Texture1D::Map, ID3D10Texture2D::Map, and ID3D10Texture3D::Map.

D3D10_MAP_FLAG_DO_NOT_WAIT cannot be used with D3D10_MAP_WRITE_DISCARD or D3D10_MAP_WRITE_NOOVERWRITE.

For more information about potential conflicts between the GPU and CPU during resource mapping, see Copying and Accessing Resource Data (Direct3D 10).

Requirements

Header: Declared in D3D10.h.

See Also

Resource Enumerations


D3D10_RESOURCE_DIMENSION

Identifies the type of resource being used.

typedef enum D3D10_RESOURCE_DIMENSION
{
    D3D10_RESOURCE_DIMENSION_UNKNOWN = 0,
    D3D10_RESOURCE_DIMENSION_BUFFER = 1,
    D3D10_RESOURCE_DIMENSION_TEXTURE1D = 2,
    D3D10_RESOURCE_DIMENSION_TEXTURE2D = 3,
    D3D10_RESOURCE_DIMENSION_TEXTURE3D = 4,
} D3D10_RESOURCE_DIMENSION;

Constants

D3D10_RESOURCE_DIMENSION_UNKNOWN
Resource is of unknown type.
D3D10_RESOURCE_DIMENSION_BUFFER
Resource is a buffer.
D3D10_RESOURCE_DIMENSION_TEXTURE1D
Resource is a 1D texture.
D3D10_RESOURCE_DIMENSION_TEXTURE2D
Resource is a 2D texture.
D3D10_RESOURCE_DIMENSION_TEXTURE3D
Resource is a 3D texture.

Remarks

This enumeration is used in ID3D10Resource::GetType, and D3DX10_IMAGE_INFO.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Enumerations


D3D10_RESOURCE_MISC_FLAG

Identifies other, less common options for resources.

typedef enum D3D10_RESOURCE_MISC_FLAG
{
    D3D10_RESOURCE_MISC_GENERATE_MIPS = 0x1L,
    D3D10_RESOURCE_MISC_SHARED = 0x2L,
    D3D10_RESOURCE_MISC_TEXTURECUBE = 0x4L,
} D3D10_RESOURCE_MISC_FLAG;

Constants

D3D10_RESOURCE_MISC_GENERATE_MIPS
Enables an application to call ID3D10Device::GenerateMips on a texture resource. The resource must be created with the bind flags that specify that the resource is a render target and a shader resource.
D3D10_RESOURCE_MISC_SHARED
Enables the sharing of resource data between two or more Direct3D devices.
D3D10_RESOURCE_MISC_TEXTURECUBE
Enables an application to create a cube texture from a Texture2DArray that contains 6 textures.

Remarks

This enumeration is used in D3D10_BUFFER_DESC, D3D10_TEXTURE1D_DESC, D3D10_TEXTURE2D_DESC, D3D10_TEXTURE3D_DESC, D3DX10_IMAGE_INFO, and D3DX10_IMAGE_LOAD_INFO.

These flags can be combined by bitwise OR.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Enumerations


D3D10_RTV_DIMENSION

Specifies how to access a resource used in a render-target view.

typedef enum D3D10_RTV_DIMENSION
{
    D3D10_RTV_DIMENSION_UNKNOWN = 0,
    D3D10_RTV_DIMENSION_BUFFER = 1,
    D3D10_RTV_DIMENSION_TEXTURE1D = 2,
    D3D10_RTV_DIMENSION_TEXTURE1DARRAY = 3,
    D3D10_RTV_DIMENSION_TEXTURE2D = 4,
    D3D10_RTV_DIMENSION_TEXTURE2DARRAY = 5,
    D3D10_RTV_DIMENSION_TEXTURE2DMS = 6,
    D3D10_RTV_DIMENSION_TEXTURE2DMSARRAY = 7,
    D3D10_RTV_DIMENSION_TEXTURE3D = 8,
} D3D10_RTV_DIMENSION;

Constants

D3D10_RTV_DIMENSION_UNKNOWN
The resource will be accessed according to its type as determined from the actual instance this enumeration is paired with when the render-target view is created.
D3D10_RTV_DIMENSION_BUFFER
The resource will be accessed as a buffer.
D3D10_RTV_DIMENSION_TEXTURE1D
The resource will be accessed as a 1D texture.
D3D10_RTV_DIMENSION_TEXTURE1DARRAY
The resource will be accessed as an array of 1D textures.
D3D10_RTV_DIMENSION_TEXTURE2D
The resource will be accessed as a 2D texture.
D3D10_RTV_DIMENSION_TEXTURE2DARRAY
The resource will be accessed as an array of 2D textures.
D3D10_RTV_DIMENSION_TEXTURE2DMS
The resource will be accessed as a 2D texture with multisampling.
D3D10_RTV_DIMENSION_TEXTURE2DMSARRAY
The resource will be accessed as an array of 2D textures with multisampling.
D3D10_RTV_DIMENSION_TEXTURE3D
The resource will be accessed as a 3D texture.

Remarks

This enumeration is used in D3D10_RENDER_TARGET_VIEW_DESC to create a render-target view.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Enumerations


D3D10_USAGE

Identifies expected resource use during rendering. The usage directly reflects whether a resource is accessible by the CPU and/or the GPU.

typedef enum D3D10_USAGE
{
    D3D10_USAGE_DEFAULT = 0,
    D3D10_USAGE_IMMUTABLE = 1,
    D3D10_USAGE_DYNAMIC = 2,
    D3D10_USAGE_STAGING = 3,
} D3D10_USAGE;

Constants

D3D10_USAGE_DEFAULT
A resource that requires read and write access by the GPU. This is likely to be the most common usage choice.
D3D10_USAGE_IMMUTABLE
A resource that can only be read by the GPU. It cannot be written by the GPU, and cannot be accessed at all by the CPU. This type of resource must be initialized when it is created, since it cannot be changed after creation.
D3D10_USAGE_DYNAMIC
A resource that is accessible by both the GPU (read only) and the CPU (write only). A dynamic resource is a good choice for a resource that will be updated by the CPU at least once per frame.
D3D10_USAGE_STAGING
A resource that supports data transfer (copy) from the GPU to the CPU.

Remarks

An application identifies the way a resource is intended to be used (its usage) in a resource description. There are several structures for creating resources including: D3D10_TEXTURE1D_DESC, D3D10_TEXTURE2D_DESC, D3D10_TEXTURE3D_DESC, D3D10_BUFFER_DESC, and D3DX10_IMAGE_LOAD_INFO.

Differences between Direct3D 9 and Direct3D 10:

In Direct3D 9, you specify the type of memory a resource should be created in at resource creation time (using D3DPOOL). It was an application's job to decide what memory pool would provide the best combination of functionality and performance.

In Direct3D 10, an application no longer specifies what type of memory (the pool) to create a resource in. Instead, you specify the intended usage of the resource, and let the runtime (in concert with the driver and a memory manager) choose the type of memory that will achieve the best performance.
Resource Usage Restrictions

Each usage dictates a tradeoff between functionality and performance. In general, resource accessing is accomplished with the following APIs.

  • CPU access is done with ID3D10Buffer::Map, ID3D10Texture1D::Map, ID3D10Texture2D::Map, or ID3D10Texture3D::Map
  • GPU access is done with ID3D10Device::CopySubresourceRegion, ID3D10Device::CopyResource, or ID3D10Device::UpdateSubresource.

Use the following table to choose the usage that best describes how the resource will need to be accessed by the CPU and/or the GPU. Of course, there will be performance tradeoffs.

Resource Usage | Default | Dynamic | Immutable | Staging
GPU-Read | yes | yes1 | yes | yes1, 2
GPU-Write | yes1 |  |  |
CPU-Read |  |  |  | yes1, 2
CPU-Write |  | yes |  | yes1, 2
  • 1 - This is restricted to ID3D10Device::CopySubresourceRegion and ID3D10Device::CopyResource.
  • 2 - Cannot be a depth-stencil buffer or a multisampled render target.
Resource Bind Options

To maximize performance, not all resource usage options can be used as input or output resources to the pipeline. This table identifies these limitations.

Resource Can Be Bound As | Default | Dynamic | Immutable | Staging
Input to a Stage | yes3 | yes4 | yes |
Output from a Stage | yes3 |  |  |
  • 3 - If bound as an input and an output using different views, each view must use different subresources.
  • 4 - The resource can only be created with a single subresource. The resource cannot be a texture array. The resource cannot be a mipmap chain.

Requirements

Header: Declared in D3D10.h.

See Also

Resource Enumerations


Resource Constants

The following constants are used to specify information about how resources are created and accessed during rendering.

#define | Description
D3D10_REQ | Resource limitation constants.

See Also

Resource Reference


D3D10_REQ

Resource limitation constants.

#define | Value | Description
D3D10_REQ_MIP_LEVELS | 14 | Maximum number of mipmap levels a texture resource may have.
D3D10_REQ_RESOURCE_SIZE_IN_MEGABYTES | 128 | Maximum possible size of a resource in megabytes.
D3D10_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION | 512 | Maximum array size of a 1D texture array.
D3D10_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION | 512 | Maximum array size of a 2D texture array.
D3D10_REQ_TEXTURE1D_U_DIMENSION | 8192 | Maximum width of a 1D texture.
D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION | 8192 | Maximum width and height of a 2D texture.
D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION | 2048 | Maximum width, height, and depth of a 3D texture.
D3D10_REQ_TEXTURECUBE_DIMENSION | 8192 | Maximum size of a cube texture.

The constants are defined in D3D10.h.

See Also

Direct3D Reference


Shader Reference

The Direct3D API defines several API elements to help you create and manage programmable shaders.

  • Shader Interfaces
  • Shader Functions
  • Shader Structures
  • Shader Enumerations
  • Shader Constants

Shaders are executable programs that control the vertex shader, geometry shader and pixel shader pipeline stages. Shaders are programmed exclusively using HLSL.

See Also

Direct3D Reference


Shader Interfaces

This section contains information about the following shader interfaces:

Figure 1. Shader Interfaces for Pipeline Stages

Each of these shader interfaces manages a compiled shader. The interface is created when a shader is compiled, and is then passed to various APIs that need access to a compiled shader; such as when binding a shader to a pipeline stage or getting a shader signature.

Pipeline-Stage Interfaces | Description
ID3D10GeometryShader Interface | A geometry-shader implements per-primitive processing in the geometry-shader stage.
ID3D10PixelShader Interface | A pixel-shader implements per-pixel processing in the pixel-shader stage.
ID3D10VertexShader Interface | A vertex-shader implements per-vertex processing in the vertex-shader stage.

Figure 2. Shader Reflection Interfaces

Shader-reflection interfaces allow an application to inspect the contents of a shader at design/author time. Shader reflection is not useful for setting variables at runtime as it is a mirror of the shader data, and therefore supports no methods for setting data.

Shader-Reflection Interfaces | Description
ID3D10ShaderReflection Interface | A COM interface for reading information from a compiled shader at author time.
ID3D10ShaderReflectionConstantBuffer Interface | A helper interface for getting a shader-reflection constant-buffer interface.
ID3D10ShaderReflectionType Interface | A helper interface for getting a shader-reflection-type interface.
ID3D10ShaderReflectionVariable Interface | A helper interface for getting a shader-reflection-variable interface.
ID3D10ShaderResourceView Interface | A shader-reflection interface for reading information from a shader-resource view.

Shader reflection APIs implement one COM shader reflection interface (ID3D10ShaderReflection Interface) and several non-COM helper interfaces (the rest of the interfaces). ID3D10ShaderReflection Interface is created when a shader reflection object is created. It follows standard COM rules; creating the interface increases a reference count and the interface must be released when it is no longer needed. The remaining shader-reflection interfaces are helper interfaces that do not inherit from IUnknown. This means that they do not change any reference count when they are created, and they do not need to be destroyed when you are finished with them.

See Also

Shader Reference


ID3D10GeometryShader Interface

A geometry-shader interface manages an executable program (a geometry shader) that controls the geometry-shader stage.

Methods | Description
none | n/a

The geometry-shader interface has no methods; use HLSL to implement your shader functionality. All shaders in Direct3D 10 are implemented from a common set of features referred to as the common shader core.

To create a geometry shader interface, call either ID3D10Device::CreateGeometryShader or ID3D10Device::CreateGeometryShaderWithStreamOutput. Before using a geometry shader you must bind it to the device by calling ID3D10Device::GSSetShader.

This interface is defined in d3d10.h.

See Also

Shader Interfaces


ID3D10PixelShader Interface

A pixel-shader interface manages an executable program (a pixel shader) that controls the pixel-shader stage.

Methods | Description
none | n/a

The pixel-shader interface has no methods; use HLSL to implement your shader functionality. All shaders in Direct3D 10 are implemented from a common set of features referred to as the common shader core.

To create a pixel shader interface, call ID3D10Device::CreatePixelShader. Before using a pixel shader you must bind it to the device by calling ID3D10Device::PSSetShader.

This interface is defined in d3d10.h.

See Also

Shader Interfaces


ID3D10ShaderReflection Interface

A shader-reflection interface is used to get shader information at design/author time.

Method | Description
ID3D10ShaderReflection::GetConstantBufferByIndex | Get a constant buffer by index.
ID3D10ShaderReflection::GetConstantBufferByName | Get a constant buffer by name.
ID3D10ShaderReflection::GetDesc | Get a shader description.
ID3D10ShaderReflection::GetInputParameterDesc | Get an input-parameter description for a shader.
ID3D10ShaderReflection::GetOutputParameterDesc | Get an output-parameter description for a shader.
ID3D10ShaderReflection::GetResourceBindingDesc | Get a description of the resources bound to a shader.

ID3D10ShaderReflection Interface is a COM interface. Create the interface by calling D3DX10ReflectShader. Since it is a COM interface, creating the interface increases a reference count and the interface must be released when it is no longer needed. The remaining shader-reflection interfaces are not COM interfaces.

See Also

Shader Interfaces


ID3D10ShaderReflection::GetConstantBufferByIndex

Get a constant buffer by index.

ID3D10ShaderReflectionConstantBuffer* GetConstantBufferByIndex(
  UINT Index
);

Parameters

Index
[in] Zero-based index.

Return Values

A pointer to a constant buffer (see ID3D10ShaderReflectionConstantBuffer Interface).

Remarks

A constant buffer supplies either scalar constants or texture constants to a shader. A shader can use one or more constant buffers. For best performance, separate constants into buffers based on the frequency they are updated.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflection Interface


ID3D10ShaderReflection::GetConstantBufferByName

Get a constant buffer by name.

ID3D10ShaderReflectionConstantBuffer* GetConstantBufferByName(
  LPCSTR Name
);

Parameters

Name
[in] The constant-buffer name.

Return Values

A pointer to a constant buffer (see ID3D10ShaderReflectionConstantBuffer Interface).

Remarks

A constant buffer supplies either scalar constants or texture constants to a shader. A shader can use one or more constant buffers. For best performance, separate constants into buffers based on the frequency they are updated.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflection Interface


ID3D10ShaderReflection::GetDesc

Get a shader description.

HRESULT GetDesc(
  D3D10_SHADER_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to a shader description. See D3D10_SHADER_DESC.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflection Interface


ID3D10ShaderReflection::GetInputParameterDesc

Get an input-parameter description for a shader.

HRESULT GetInputParameterDesc(
  UINT ParameterIndex,
  D3D10_SIGNATURE_PARAMETER_DESC *pDesc
);

Parameters

ParameterIndex
[in] A zero-based parameter index.
pDesc
[in] A pointer to a shader-input-signature description. See D3D10_SIGNATURE_PARAMETER_DESC.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

An input-parameter description is also called a shader signature. The shader signature contains information about the input parameters such as the order or parameters, their data type, and a parameter semantic.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflection Interface


ID3D10ShaderReflection::GetOutputParameterDesc

Get an output-parameter description for a shader.

HRESULT GetOutputParameterDesc(
  UINT ParameterIndex,
  D3D10_SIGNATURE_PARAMETER_DESC *pDesc
);

Parameters

ParameterIndex
[in] A zero-based parameter index.
pDesc
[in] A pointer to a shader-output-parameter description. See D3D10_SIGNATURE_PARAMETER_DESC.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

An output-parameter description is also called a shader signature. The shader signature contains information about the output parameters such as the order or parameters, their data type, and a parameter semantic.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflection Interface


ID3D10ShaderReflection::GetResourceBindingDesc

Get a description of the resources bound to a shader.

HRESULT GetResourceBindingDesc(
  UINT ResourceIndex,
  D3D10_SHADER_INPUT_BIND_DESC *pDesc
);

Parameters

ResourceIndex
[in] A zero-based resource index.
pDesc
[in] A pointer to an input-binding description. See D3D10_SHADER_INPUT_BIND_DESC.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

A shader consists of executable code (the compiled HLSL functions) and a set of resources that supply the shader with input data. This API gets a list of the resources that are bound as inputs to the shader.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflection Interface


ID3D10ShaderReflectionConstantBuffer Interface

This shader-reflection interface provides access to a constant buffer.

Method | Description
ID3D10ShaderReflectionConstantBuffer::GetDesc | Get a constant-buffer description.
ID3D10ShaderReflectionConstantBuffer::GetVariableByIndex | Get a shader-reflection variable by index.
ID3D10ShaderReflectionConstantBuffer::GetVariableByName | Get a constant-buffer variable by name.

To create a constant-buffer interface, call ID3D10ShaderReflection::GetConstantBufferByIndex or ID3D10ShaderReflection::GetConstantBufferByName. This is not a COM interface; therefore, you do not need to worry about reference counts or releasing the interface when you are done with it.

See Also

Shader Interfaces


ID3D10ShaderReflectionConstantBuffer::GetDesc

Get a constant-buffer description.

HRESULT GetDesc(
  D3D10_SHADER_BUFFER_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to a shader-buffer description (see D3D10_SHADER_BUFFER_DESC.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflectionConstantBuffer Interface


ID3D10ShaderReflectionConstantBuffer::GetVariableByIndex

Get a shader-reflection variable by index.

ID3D10ShaderReflectionVariable* GetVariableByIndex(
  UINT Index
);

Parameters

Index
[in] Zero-based index.

Return Values

A pointer to a shader-reflection variable interface (see ID3D10ShaderReflectionVariable Interface).

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflectionConstantBuffer Interface


ID3D10ShaderReflectionConstantBuffer::GetVariableByName

Get a shader-reflection variable by name.

ID3D10ShaderReflectionVariable* GetVariableByName(
  LPCSTR Name
);

Parameters

Name
[in] Variable name.

Return Values

A pointer to a shader-reflection variable interface (see ID3D10ShaderReflectionVariable Interface).

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflectionConstantBuffer Interface


ID3D10ShaderReflectionType Interface

This shader-reflection interface provides access to variable type.

Method | Description
ID3D10ShaderReflectionType::GetDesc | Get a shader-type description.
ID3D10ShaderReflectionType::GetMemberTypeByIndex | Get a variable type by index.
ID3D10ShaderReflectionType::GetMemberTypeByName | Get a variable type by name.
ID3D10ShaderReflectionType::GetMemberTypeName | Get a variable type.

The get a shader-reflection-type interface, call ID3D10ShaderReflectionVariable::GetType.

See Also

Shader Interfaces


ID3D10ShaderReflectionType::GetDesc

Get the description of a shader-reflection-variable type.

HRESULT GetDesc(
  D3D10_SHADER_TYPE_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to a shader-type description (see D3D10_SHADER_TYPE_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflectionType Interface


ID3D10ShaderReflectionType::GetMemberTypeName

Get a shader-reflection-variable type.

LPCSTR GetMemberTypeName(
  UINT Index
);

Parameters

Index
[in] Zero-based index.

Return Values

The variable type.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflectionType Interface


ID3D10ShaderReflectionType::GetMemberTypeByIndex

Get a shader-reflection-variable type by index.

ID3D10ShaderReflectionType* GetMemberTypeByIndex(
  UINT Index
);

Parameters

Index
[in] Zero-based index.

Return Values

A pointer to a ID3D10ShaderReflectionType Interface.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflectionType Interface


ID3D10ShaderReflectionType::GetMemberTypeByName

Get a shader-reflection-variable type by name.

ID3D10ShaderReflectionType* GetMemberTypeByName(
  LPCSTR Name
);

Parameters

Name
[in] Member name.

Return Values

A pointer to a ID3D10ShaderReflectionType Interface.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflectionType Interface


ID3D10ShaderReflectionVariable Interface

This shader-reflection interface provides access to a variable.

Method | Description
ID3D10ShaderReflectionVariable::GetDesc | Get a shader-variable description.
ID3D10ShaderReflectionVariable::GetType | Get a shader-variable type.

The get a shader-reflection-variable interface, call a method like ID3D10ShaderReflectionConstantBuffer::GetVariableByIndex.

See Also

Shader Interfaces


ID3D10ShaderReflectionVariable::GetDesc

Get a shader-variable description.

HRESULT GetDesc(
  D3D10_SHADER_VARIABLE_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to a shader-variable description (see D3D10_SHADER_VARIABLE_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflectionVariable Interface


ID3D10ShaderReflectionVariable::GetType

Get a shader-variable type.

ID3D10ShaderReflectionType* GetType();

Parameters

None.

Return Values

A pointer to a ID3D10ShaderReflectionType Interface.

Requirements

Header: Declared in D3D10Shader.h.

See Also

ID3D10ShaderReflectionVariable Interface


ID3D10VertexShader Interface

A vertex-shader interface manages an executable program (a vertex shader) that controls the vertex-shader stage.

Methods | Description
none | n/a

The vertex-shader interface has no methods; use HLSL to implement your shader functionality. All shaders in Direct3D 10 are implemented from a common set of features referred to as the common shader core.

To create a vertex shader interface, call ID3D10Device::CreateVertexShader. Before using a vertex shader you must bind it to the device by calling ID3D10Device::VSSetShader.

This interface is defined in d3d10.h.

See Also

Shader Interfaces


Shader Functions

This section contains information about the following shader functions:

Functions | Description
D3D10CompileShader | Compile a shader.
D3D10DisassembleShader | Deprecated. See D3DX10DisassembleShader.
D3D10GetGeometryShaderProfile | Get the geometry-shader profile best suited to a given device.
D3D10GetInputAndOutputSignatureBlob | Get a buffer that contains shader signatures.
D3D10GetInputSignatureBlob | Get a buffer that contains shader input signatures.
D3D10GetOutputSignatureBlob | Get a buffer that contains shader output signatures.
D3D10GetPixelShaderProfile | Get the pixel-shader profile best suited to a given device.
D3D10GetShaderDebugInfo | Get shader debug info from a compiled shader.
D3D10GetVertexShaderProfile | Get the vertex-shader profile best suited to a given device.
D3D10PreprocessShader | Generate a text string that contains the shader token stream.
D3D10ReflectShader | Deprecated. See D3DX10ReflectShader.

See Also

Shader Reference


D3D10CompileShader

Compile an HLSL shader.

HRESULT D3D10CompileShader(
  LPCSTR pSrcData,
  SIZE_T SrcDataLen,
  LPCSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE *pInclude,
  LPCSTR pFunctionName,
  LPCSTR pProfile,
  UINT Flags,
  ID3D10Blob **ppShader,
  ID3D10Blob **ppErrorMsgs
);

Parameters

pSrcData
[in] Pointer to a string containing the shader source code.
SrcDataLen
[in] Size of pSrcData, in bytes.
pFileName
[in] The name of the file that contains the shader code.
pDefines
[in] Optional. Pointer to a NULL-terminated array of macro definitions. See D3D10_SHADER_MACRO. If not used, set this to NULL.
pInclude
[in] Optional. Pointer to an ID3D10Include Interface interface for handling include files. Setting this to NULL will cause a compile error if a shader contains a #include.
pFunctionName
[in] Name of the shader-entrypoint function where shader execution begins.
pProfile
[in] A string that specifies the shader profile or shader model.
Flags
[in] Shader compile options.
ppShader
[out] A pointer to an ID3D10Blob Interface which contains the compiled shader, as well as any embedded debug and symbol-table information.
ppErrorMsgs
[out] A pointer to an ID3D10Blob Interface which contains a listing of errors and warnings that occured during compilation. These errors and warnings are identical to the the debug output from a debugger.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

To setup a programmable-pipeline stage, compile a shader and then bind the shader to the appropriate pipeline stage. For instance, here is an example compiling a geometry shader (see Compile a Geometry Shader).

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Functions


D3D10DisassembleShader

This function has been deprecated. Instead, use D3DX10DisassembleShader.

HRESULT D3D10DisassembleShader(
  CONST void *pShader,
  SIZE_T BytecodeLength,
  BOOL EnableColorCode,
  LPCSTR pComments,
  ID3D10Blob **ppDisassembly
);

Parameters

pShader
[in] A pointer to the compiled shader.
BytecodeLength
[in] The size of pShader.
EnableColorCode
[in] Include HTML tags in the output to color code the result.
pComments
[in] The comment string at the top of the shader that identifies the shader constants and variables.
ppDisassembly
[out] Address of a buffer which contains the disassembled shader.

Return Values

Return value

See Also

Shader Functions


D3D10GetGeometryShaderProfile

Get the geometry shader profile best suited to a given device.

LPCSTR D3D10GetGeometryShaderProfile(
  ID3D10Device *pDevice
);

Parameters

pDevice
[in] Pointer to the device (see ID3D10Device Interface).

Return Values

The shader profile.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Functions


D3D10GetInputAndOutputSignatureBlob

Get a buffer that contains shader signatures.

HRESULT D3D10GetInputAndOutputSignatureBlob(
  CONST void *pShaderBytecode,
  SIZE_T BytecodeLength,
  ID3D10Blob **ppSignatureBlob
);

Parameters

pShaderBytecode
[in] A pointer to the compiled shader. To get this pointer see Getting a Pointer to a Compiled Shader.
BytecodeLength
[in] The size of the shader bytecode in bytes.
ppSignatureBlob
[out] The address of a pointer to the buffer (see ID3D10Blob Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Core Functions


D3D10GetInputSignatureBlob

Get a buffer that contains shader-input signatures.

HRESULT D3D10GetInputSignatureBlob(
  CONST void *pShaderBytecode,
  SIZE_T BytecodeLength,
  ID3D10Blob **ppSignatureBlob
);

Parameters

pShaderBytecode
[in] A pointer to the compiled shader. To get this pointer see Getting a Pointer to a Compiled Shader.
BytecodeLength
[in] The size of the shader bytecode in bytes.
ppSignatureBlob
[out] The address of a pointer to the buffer (see ID3D10Blob Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Core Functions


D3D10GetOutputSignatureBlob

Get a buffer that contains shader-output signatures.

HRESULT D3D10GetOutputSignatureBlob(
  CONST void *pShaderBytecode,
  SIZE_T BytecodeLength,
  ID3D10Blob **ppSignatureBlob
);

Parameters

pShaderBytecode
[in] A pointer to the compiled shader. To get this pointer see Getting a Pointer to a Compiled Shader.
BytecodeLength
[in] The size of the shader bytecode in bytes.
ppSignatureBlob
[out] The address of a pointer to the buffer (see ID3D10Blob Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Core Functions


D3D10GetPixelShaderProfile

Get the pixel shader profile best suited to a given device.

LPCSTR D3D10GetPixelShaderProfile(
  ID3D10Device *pDevice
);

Parameters

pDevice
[in] Pointer to the device (see ID3D10Device Interface).

Return Values

The shader profile.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Functions


D3D10GetShaderDebugInfo

Get shader debug info. Debug info is generated by D3D10CompileShader and is embedded in the body of the shader.

HRESULT D3D10GetShaderDebugInfo(
  CONST void *pShaderBytecode,
  SIZE_T BytecodeLength,
  ID3D10Blob **ppDebugInfo
);

Parameters

pShaderBytecode
A pointer to the compiled shader. To get this pointer see Getting a Pointer to a Compiled Shader.
BytecodeLength
Length of the shader bytecode buffer.
ppDebugInfo
Buffer used to return debug info. For information about the layout of this buffer, see D3D10_SHADER_DEBUG_INFO.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Functions


D3D10GetVertexShaderProfile

Get the vertex shader profile best suited to a given device.

LPCSTR D3D10GetVertexShaderProfile(
  ID3D10Device *pDevice
);

Parameters

pDevice
[in] Pointer to the device (see ID3D10Device Interface).

Return Values

The shader profile.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Functions


D3D10PreprocessShader

Generate a shader-text string that contains the shader tokens that would be found in a compiled shader.

HRESULT D3D10PreprocessShader(
  LPCSTR pSrcData,
  SIZE_T SrcDataSize,
  LPCSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE *pInclude,
  ID3D10Blob **ppShaderText,
  ID3D10Blob **ppErrorMsgs
);

Parameters

pSrcData
[in] Pointer to a string containing the shader source code.
SrcDataSize
[in] Size of pSrcData, in bytes.
pFileName
[in] The name of the file that contains the shader code.
pDefines
[in] Optional. Pointer to a NULL-terminated array of macro definitions. See D3D10_SHADER_MACRO.
pInclude
[in] Optional. Pointer to an ID3D10Include Interface interface for handling include files. Setting this to NULL will cause a compile error if a shader contains a #include.
ppShaderText
[out] A pointer to an ID3D10Blob Interface which contains a single string containing shader-tokens.
ppErrorMsgs
[out] A pointer to an ID3D10Blob Interface which contains a listing of errors and warnings that occured during compilation. These errors and warnings are identical to the the debug output from a debugger.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Use this function to generate a shader-token stream, which is the compiled output of the shader compiler.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Functions


D3D10ReflectShader

This function has been deprecated. Instead, use D3DX10ReflectShader.

HRESULT D3D10ReflectShader(
  CONST void *pShaderBytecode,
  SIZE_T BytecodeLength,
  ID3D10ShaderReflection **ppReflector
);

Parameters

pShaderBytecode
[in] A pointer to the compiled shader.
BytecodeLength
[in] Length of pShaderBytecode.
ppReflector
[out] Address of a reflection interface.

Return Values

Return value.

See Also

Shader Functions


Shader Structures

This section contains information about the following shader structures:

Structures | Description
D3D10_SHADER_BUFFER_DESC | Describes a shader-constant buffer or a shader-texture buffer.
D3D10_SHADER_DESC | Describes a shader.
D3D10_SHADER_DEBUG_FILE_INFO | TBD
D3D10_SHADER_DEBUG_INFO | TBD
D3D10_SHADER_DEBUG_INPUT_INFO | TBD
D3D10_SHADER_DEBUG_INST_INFO | TBD
D3D10_SHADER_DEBUG_OUTPUTREG_INFO | TBD
D3D10_SHADER_DEBUG_OUTPUTVAR | TBD
D3D10_SHADER_DEBUG_SCOPE_INFO | TBD
D3D10_SHADER_DEBUG_SCOPEVAR_INFO | TBD
D3D10_SHADER_DEBUG_TOKEN_INFO | TBD
D3D10_SHADER_DEBUG_VARTYPE | TBD
D3D10_SHADER_DEBUG_VAR_INFO | TBD
D3D10_SHADER_INPUT_BIND_DESC | Describes how a shader resource is bound to a shader input.
D3D10_SHADER_MACRO | Defines a shader macro.
D3D10_SHADER_RESOURCE_VIEW_DESC | Describes a shader-resource view.
D3D10_SHADER_TYPE_DESC | Describes a shader-variable type.
D3D10_SHADER_VARIABLE_DESC | Describes a shader variable.
D3D10_SIGNATURE_PARAMETER_DESC | Describes a shader signature.

See Also

Shader Reference


D3D10_SHADER_BUFFER_DESC

Describes a shader constant-buffer.

typedef struct D3D10_SHADER_BUFFER_DESC {
    LPCSTR Name;
    D3D10_CBUFFER_TYPE Type;
    UINT Variables;
    UINT Size;
    UINT uFlags;
} D3D10_SHADER_BUFFER_DESC;

Members

Name
The name of the buffer.
Type
The intended use of the constant data. See D3D10_CBUFFER_TYPE.
Variables
The number of unique variables.
Size
Buffer size (in bytes).
uFlags
Shader buffer properties. See D3D10_SHADER_CBUFFER_FLAGS.

Remarks

Constants are supplied to shaders in a shader-constant buffer. Get the description of a shader-constant-buffer by calling ID3D10ShaderReflectionConstantBuffer::GetDesc.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Structures


D3D10_SHADER_DESC

Describes a shader.

typedef struct D3D10_SHADER_DESC {
    UINT Version;
    LPCSTR Creator;
    UINT Flags;
    UINT ConstantBuffers;
    UINT BoundResources;
    UINT InputParameters;
    UINT OutputParameters;
    UINT InstructionCount;
    UINT TempRegisterCount;
    UINT TempArrayCount;
    UINT DefCount;
    UINT DclCount;
    UINT TextureNormalInstructions;
    UINT TextureLoadInstructions;
    UINT TextureCompInstructions;
    UINT TextureBiasInstructions;
    UINT TextureGradientInstructions;
    UINT FloatInstructionCount;
    UINT IntInstructionCount;
    UINT UintInstructionCount;
    UINT StaticFlowControlCount;
    UINT DynamicFlowControlCount;
    UINT MacroInstructionCount;
    UINT ArrayInstructionCount;
    UINT CutInstructionCount;
    UINT EmitInstructionCount;
    D3D10_PRIMITIVE_TOPOLOGY GSOutputTopology;
    UINT GSMaxOutputVertexCount;
    UINT MovInstructionCount;
    UINT MovcInstructionCount;
    UINT ConversionInstructionCount;
    UINT BitwiseInstructionCount;
} D3D10_SHADER_DESC;

Members

Version
Shader version.
Creator
The name of the originator of the shader.
Flags
Shader compilation/parse flags.
ConstantBuffers
The number of shader-constant buffers.
BoundResources
The number of resource (textures and buffers) bound to a shader.
InputParameters
The number of parameters in the input signature.
OutputParameters
The number of parameters in the output signature.
InstructionCount
The number of intermediate-language instructions in the compiled shader.
TempRegisterCount
The number of temporary registers in the compiled shader.
TempArrayCount
Number of temporary arrays used.
DefCount
Number of constant defines.
DclCount
Number of declarations (input + output).
TextureNormalInstructions
Number of non-categorized texture instructions.
TextureLoadInstructions
Number of texture load instructions
TextureCompInstructions
Number of texture comparison instructions
TextureBiasInstructions
Number of texture bias instructions
TextureGradientInstructions
Number of texture gradient instructions.
FloatInstructionCount
Number of floating point arithmetic instructions used.
IntInstructionCount
Number of signed integer arithmetic instructions used.
UintInstructionCount
Number of unsigned integer arithmetic instructions used.
StaticFlowControlCount
Number of static flow control instructions used.
DynamicFlowControlCount
Number of dynamic flow control instructions used.
MacroInstructionCount
Number of macro instructions used.
ArrayInstructionCount
Number of array instructions used.
CutInstructionCount
Number of cut instructions used.
EmitInstructionCount
Number of emit instructions used.
GSOutputTopology
Geometry shader output topology.
GSMaxOutputVertexCount
Geometry shader maximum output vertex count.
MovInstructionCount
Number of mov instructions.
MovcInstructionCount
Number of movc instructions.
ConversionInstructionCount
Number of conversion operations.
BitwiseInstructionCount
Number of bitwise operations.

Remarks

A shader is written in HLSL and compiled into an intermediate language by the HLSL compiler. The shader description returns information about the compiled shader. Get a shader description by calling ID3D10ShaderReflection::GetDesc.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Structures


D3D10_SHADER_DEBUG_FILE_INFO

TBD

typedef struct _D3D10_SHADER_DEBUG_FILE_INFO {
    UINT FileName;
    UINT FileNameLen;
    UINT FileData;
    UINT FileLen;
} D3D10_SHADER_DEBUG_FILE_INFO;

Members

FileName
TBD
FileNameLen
TBD
FileData
TBD
FileLen
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_INFO

TBD

typedef struct _D3D10_SHADER_DEBUG_INFO {
    UINT Size;
    UINT Creator;
    UINT EntrypointName;
    UINT ShaderTarget;
    UINT CompileFlags;
    UINT Files;
    UINT FileInfo;
    UINT Instructions;
    UINT InstructionInfo;
    UINT Variables;
    UINT VariableInfo;
    UINT InputVariables;
    UINT InputVariableInfo;
    UINT Tokens;
    UINT TokenInfo;
    UINT Scopes;
    UINT ScopeInfo;
    UINT ScopeVariables;
    UINT ScopeVariableInfo;
    UINT UintOffset;
    UINT StringOffset;
} D3D10_SHADER_DEBUG_INFO;

Members

Size
TBD
Creator
TBD
EntrypointName
TBD
ShaderTarget
TBD
CompileFlags
TBD
Files
TBD
FileInfo
TBD
Instructions
TBD
InstructionInfo
TBD
Variables
TBD
VariableInfo
TBD
InputVariables
TBD
InputVariableInfo
TBD
Tokens
TBD
TokenInfo
TBD
Scopes
TBD
ScopeInfo
TBD
ScopeVariables
TBD
ScopeVariableInfo
TBD
UintOffset
TBD
StringOffset
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_INPUT_INFO

TBD

typedef struct _D3D10_SHADER_DEBUG_INPUT_INFO {
    UINT Var;
    D3D10_SHADER_DEBUG_REGTYPE InitialRegisterSet;
    UINT InitialBank;
    UINT InitialRegister;
    UINT InitialComponent;
    UINT InitialValue;
} D3D10_SHADER_DEBUG_INPUT_INFO;

Members

Var
TBD
InitialRegisterSet
TBD
InitialBank
TBD
InitialRegister
TBD
InitialComponent
TBD
InitialValue
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_INST_INFO

TBD

typedef struct _D3D10_SHADER_DEBUG_INST_INFO {
    UINT Id;
    UINT Opcode;
    UINT uOutputs;
    D3D10_SHADER_DEBUG_OUTPUTREG_INFO pOutputs[2];
    UINT TokenId;
    UINT NestingLevel;
    UINT Scopes;
    UINT ScopeInfo;
} D3D10_SHADER_DEBUG_INST_INFO;

Members

Id
TBD
Opcode
TBD
uOutputs
TBD
pOutputs
TBD
TokenId
TBD
NestingLevel
TBD
Scopes
TBD
ScopeInfo
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_OUTPUTREG_INFO

TBD

typedef struct _D3D10_SHADER_DEBUG_OUTPUTREG_INFO {
    D3D10_SHADER_DEBUG_REGTYPE OutputRegisterSet;
    UINT OutputReg;
    UINT TempArrayReg;
    UINT OutputComponents[4];
    D3D10_SHADER_DEBUG_OUTPUTVAR OutputVars[4];
    UINT IndexReg;
    UINT IndexComp;
} D3D10_SHADER_DEBUG_OUTPUTREG_INFO;

Members

OutputRegisterSet
TBD
OutputReg
TBD
TempArrayReg
TBD
OutputComponents
TBD
OutputVars
TBD
IndexReg
TBD
IndexComp
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_OUTPUTVAR

TBD

typedef struct _D3D10_SHADER_DEBUG_OUTPUTVAR {
    UINT Var;
    UINT uValueMin;
    UINT uValueMax;
    INT iValueMin;
    INT iValueMax;
    FLOAT fValueMin;
    FLOAT fValueMax;
    BOOL bNaNPossible;
    BOOL bInfPossible;
} D3D10_SHADER_DEBUG_OUTPUTVAR;

Members

Var
TBD
uValueMin
TBD
uValueMax
TBD
iValueMin
TBD
iValueMax
TBD
fValueMin
TBD
fValueMax
TBD
bNaNPossible
TBD
bInfPossible
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_SCOPE_INFO

TBD

typedef struct _D3D10_SHADER_DEBUG_SCOPE_INFO {
    D3D10_SHADER_DEBUG_SCOPETYPE ScopeType;
    UINT Name;
    UINT uNameLen;
    UINT uVariables;
    UINT VariableData;
} D3D10_SHADER_DEBUG_SCOPE_INFO;

Members

ScopeType
TBD
Name
TBD
uNameLen
TBD
uVariables
TBD
VariableData
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_SCOPEVAR_INFO

Index into variable token.

typedef struct _D3D10_SHADER_DEBUG_SCOPEVAR_INFO {
    UINT TokenId;
    D3D10_SHADER_DEBUG_VARTYPE VarType;
    D3D10_SHADER_VARIABLE_CLASS Class;
    UINT Rows;
    UINT Columns;
    UINT StructMemberScope;
    UINT uArrayIndices;
    UINT ArrayElements;
    UINT ArrayStrides;
    UINT uVariables;
    UINT uFirstVariable;
} D3D10_SHADER_DEBUG_SCOPEVAR_INFO;

Members

TokenId
TBD
VarType
TBD
Class
TBD
Rows
TBD
Columns
TBD
StructMemberScope
TBD
uArrayIndices
TBD
ArrayElements
TBD
ArrayStrides
TBD
uVariables
TBD
uFirstVariable
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_TOKEN_INFO

Serialized structures that get written to the file.

typedef struct _D3D10_SHADER_DEBUG_TOKEN_INFO {
    UINT File;
    UINT Line;
    UINT Column;
    UINT TokenLength;
    UINT TokenId;
} D3D10_SHADER_DEBUG_TOKEN_INFO;

Members

File
Offset into file list
Line
Line number.
Column
Column number.
TokenLength
TBD
TokenId
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_VARTYPE

TBD

typedef enum _D3D10_SHADER_DEBUG_VARTYPE
{
    D3D10_SHADER_DEBUG_VAR_VARIABLE,
    D3D10_SHADER_DEBUG_VAR_FUNCTION,
    D3D10_SHADER_DEBUG_VAR_FORCE_DWORD = 0x7fffffff,
} D3D10_SHADER_DEBUG_VARTYPE;

Constants

D3D10_SHADER_DEBUG_VAR_VARIABLE
TBD
D3D10_SHADER_DEBUG_VAR_FUNCTION
TBD
D3D10_SHADER_DEBUG_VAR_FORCE_DWORD
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_VAR_INFO

Variable list.

typedef struct _D3D10_SHADER_DEBUG_VAR_INFO {
    UINT TokenId;
    D3D10_SHADER_VARIABLE_TYPE Type;
    UINT Register;
    UINT Component;
    UINT ScopeVar;
    UINT ScopeVarOffset;
} D3D10_SHADER_DEBUG_VAR_INFO;

Members

TokenId
TBD
Type
TBD
Register
TBD
Component
TBD
ScopeVar
TBD
ScopeVarOffset
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_INPUT_BIND_DESC

Describes how a shader resource is bound to a shader input.

typedef struct D3D10_SHADER_INPUT_BIND_DESC {
    LPCSTR Name;
    D3D10_SHADER_INPUT_TYPE Type;
    UINT BindPoint;
    UINT BindCount;
    UINT uFlags;
    D3D10_RESOURCE_RETURN_TYPE ReturnType;
    D3D10_SRV_DIMENSION Dimension;
    UINT NumSamples;
} D3D10_SHADER_INPUT_BIND_DESC;

Members

Name
Name of the shader resource.
Type
Identifies the type of data in the resource. See D3D10_SHADER_INPUT_TYPE.
BindPoint
Starting bind point.
BindCount
Number of contiguous bind points for arrays.
uFlags
Shader input-parameter options. See D3D10_SHADER_INPUT_FLAGS.
ReturnType
If the input is a texture, the return type. See D3D10_RESOURCE_RETURN_TYPE.
Dimension
Identifies the amount of data in the resource. See D3D10_SRV_DIMENSION.
NumSamples
The number of samples for a multisampled texture; otherwise 0.

Remarks

Get a shader-input-signature description by calling ID3D10ShaderReflection::GetResourceBindingDesc.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Structures


D3D10_SHADER_MACRO

Defines a shader macro.

typedef struct D3D10_SHADER_MACRO {
    LPCSTR Name;
    LPCSTR Definition;
} D3D10_SHADER_MACRO, *LPD3D10_SHADER_MACRO;

Members

Name
The macro name.
Definition
The macro definition.

Remarks

You may use macros in your shaders. This enables the application to #define tokens at runtime, before the file is parsed. This structure defines a single macro. For example:

D3D10_SHADER_MACRO Shader_Macros[1] = { "zero", "0"  };

There are several shader or effect creation methods (such as D3D10CompileShader, D3DX10CreateEffectFromFile or D3DX10PreprocessShaderFromFile) that take an array of macros as an input parameter.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Structures


D3D10_SHADER_RESOURCE_VIEW_DESC

Describes a shader-resource view.

typedef struct D3D10_SHADER_RESOURCE_VIEW_DESC {
    DXGI_FORMAT Format;
    D3D10_SRV_DIMENSION ViewDimension;
    union {
        D3D10_BUFFER_SRV Buffer;
        D3D10_TEX1D_SRV Texture1D;
        D3D10_TEX1D_ARRAY_SRV Texture1DArray;
        D3D10_TEX2D_SRV Texture2D;
        D3D10_TEX2D_ARRAY_SRV Texture2DArray;
        D3D10_TEX2DMS_SRV Texture2DMS;
        D3D10_TEX2DMS_ARRAY_SRV Texture2DMSArray;
        D3D10_TEX3D_SRV Texture3D;
        D3D10_TEXCUBE_SRV TextureCube;
    };
} D3D10_SHADER_RESOURCE_VIEW_DESC;

Members

Format
The viewing format. See remarks.
ViewDimension
The resource type of the view. See D3D10_SRV_DIMENSION. This should be the same as the resource type of the underlying resource. This parameter also determines which _SRV to use in the union below.
Buffer
View the resource as a buffer using information from a shader-resource view (see D3D10_BUFFER_SRV).
Texture1D
View the resource as a 1D texture using information from a shader-resource view (see D3D10_TEX1D_SRV).
Texture1DArray
View the resource as a 1D-texture array using information from a shader-resource view (see D3D10_TEX1D_ARRAY_SRV.
Texture2D
View the resource as a 2D-texture using information from a shader-resource view (see D3D10_TEX2D_SRV.
Texture2DArray
View the resource as a 2D-texture array using information from a shader-resource view (see D3D10_TEX2D_ARRAY_SRV.
Texture2DMS
View the resource as a 2D-multisampled texture using information from a shader-resource view (see D3D10_TEX2DMS_SRV.
Texture2DMSArray
View the resource as a 2D-multisampled-texture array using information from a shader-resource view (see D3D10_TEX2DMS_ARRAY_SRV.
Texture3D
View the resource as a 3D texture using information from a shader-resource view (see D3D10_TEX3D_SRV.
TextureCube
View the resource as a 3D-cube texture using information from a shader-resource view (see D3D10_TEXCUBE_SRV).

Remarks

A view is a format-specific way to look at the data in a resource. The view determines what data to look at, and how it is cast when read. For more information about how views work, see Views

When viewing a resource, the resource-view description must specify a typed format, that is compatible with the resource format. So that means that you cannot create a resource-view description using any format with _TYPELESS in the name. You can however view a typeless resource by specifying a typed format for the view. For example, a DXGI_FORMAT_R32G32B32_TYPELESS resource can be viewed with one of these typed formats: DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32_UINT, and DXGI_FORMAT_R32G32B32_SINT, since these typed formats are compatible with the typeless resource.

Create a shader-resource-view description by calling ID3D10Device::CreateShaderResourceView. To view a shader-resource-view description, call ID3D10ShaderResourceView::GetDesc.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Structures


D3D10_SHADER_TYPE_DESC

Describes a shader-variable type.

typedef struct D3D10_SHADER_TYPE_DESC {
    D3D10_SHADER_VARIABLE_CLASS Class;
    D3D10_SHADER_VARIABLE_TYPE Type;
    UINT Rows;
    UINT Columns;
    UINT Elements;
    UINT Members;
    UINT Offset;
} D3D10_SHADER_TYPE_DESC;

Members

Class
Identifies the variable class as one of scalar, vector, matrix or object. See D3D10_SHADER_VARIABLE_CLASS.
Type
The variable type. See D3D10_SHADER_VARIABLE_TYPE.
Rows
Number of rows in a matrix. Otherwise a numeric type returns 1, any other type returns 0.
Columns
Number of columns in a matrix. Otherwise a numeric type returns 1, any other type returns 0.
Elements
Number of elements in an array; otherwise 0.
Members
Number of members in the structure; otherwise 0.
Offset
Offset, in bytes, between the start of the parent structure and this variable.

Remarks

Get a shader-variable-type description by calling ID3D10ShaderReflectionType::GetDesc.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Structures


D3D10_SHADER_VARIABLE_DESC

Describes a shader variable.

typedef struct D3D10_SHADER_VARIABLE_DESC {
    LPCSTR Name;
    UINT StartOffset;
    UINT Size;
    UINT uFlags;
    LPVOID DefaultValue;
} D3D10_SHADER_VARIABLE_DESC;

Members

Name
The variable name.
StartOffset
Offset from the start of the parent structure, to the beginning of the variable.
Size
Size of the variable (in bytes).
uFlags
Shader variable options. See D3D10_SHADER_VARIABLE_FLAGS.
DefaultValue
The default value for initializing the variable.

Remarks

Get a shader-variable description by calling ID3D10ShaderReflectionVariable::GetDesc.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Structures


D3D10_SIGNATURE_PARAMETER_DESC

Describes a shader signature.

typedef struct D3D10_SIGNATURE_PARAMETER_DESC {
    LPCSTR SemanticName;
    UINT SemanticIndex;
    UINT Register;
    D3D10_NAME SystemValueType;
    D3D10_REGISTER_COMPONENT_TYPE ComponentType;
    BYTE Mask;
    BYTE ReadWriteMask;
} D3D10_SIGNATURE_PARAMETER_DESC;

Members

SemanticName
A per-parameter string that identifies how the data will be used. See Shader Semantic Syntax (Direct3D 10 HLSL).
SemanticIndex
Semantic index that modifies the semantic. Used to differentiate different parameters that use the same semantic.
Register
The register that will contain this variable's data.
SystemValueType
A predefined string that determines the functionality of certain pipeline stages. See D3D10_NAME.
ComponentType
The per-component-data type that is stored in a register. See D3D10_REGISTER_COMPONENT_TYPE. Each register can store up to four-components of data.
Mask
Mask which indicates which components of a register are used.
ReadWriteMask
Mask which indicates whether a given component is never written (if the signature is an output signature) or always read (if the signature is an input signature). The mask is a combination of D3D10_REGISTER_COMPONENT_TYPE values.

Remarks

A shader can take n inputs and can produce m outputs. The order of the input (or output) parameters, their associated types, and any attached semantics make up the shader signature. Each shader has an input and an output signature.

When compiling a shader or an effect, some API calls validate shader signatures (such as D3D10CompileShader and D3D10CompileEffectFromMemory). That is, they compare the output signature of one shader (like a vertex shader) with the input signature of another shader (like a pixel shader). This ensures that a shader outputs data that is compatible with a downstream shader that is consuming that data. Compatible means that a shader signature is a exact-match subset of the preceeding shader stage. Exact match means parameter types and semantics must exactly match. Subset means that a parameter that is not required by a downstream stage, does not need to include that parameter in its shader signature.

Get a shader-signature from a shader or an effect by calling APIs such as ID3D10ShaderReflection::GetInputParameterDesc or ID3D10EffectShaderVariable::GetInputSignatureElementDesc.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Structures


Shader Enumerations

This section contains information about the following shader enumerations:

Enumeration | Description
D3D10_CBUFFER_TYPE | These flags identify constant-buffer-data types.
D3D10_INCLUDE_TYPE | These flags identify the location of an include file.
D3D10_SHADER_DEBUG_REGTYPE | TBD.
D3D10_SHADER_DEBUG_SCOPETYPE | TBD.
D3D10_NAME | These flags identify shader parameters that use system-value semantics.
D3D10_SHADER_CBUFFER_FLAGS | These flags identify constant-buffer properties.
D3D10_SHADER_INPUT_FLAGS | These flags identify shader-input properties.
D3D10_SHADER_INPUT_TYPE | These flags identify a shader-resource type.
D3D10_SHADER_VARIABLE_CLASS | These flags identify the shader-variable class.
D3D10_SHADER_VARIABLE_FLAGS | These flags identify a shader-variable property.
D3D10_SHADER_VARIABLE_TYPE | These flags identify the shader-variable type.
D3D10_SRV_DIMENSION | These flags identify the type of resource that will be viewed.

See Also

Shader Reference


D3D10_CBUFFER_TYPE

These flags identify constant-buffer-data types.

typedef enum D3D10_CBUFFER_TYPE
{
    D3D10_CT_CBUFFER = 0,
    D3D10_CT_TBUFFER = 1,
} D3D10_CBUFFER_TYPE, *LPD3D10_CBUFFER_TYPE;

Constants

D3D10_CT_CBUFFER
A buffer containing scalar constants.
D3D10_CT_TBUFFER
A buffer containing texture data.

Remarks

The flags are used in a shader buffer description (see D3D10_SHADER_BUFFER_DESC.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Enumerations


D3D10_INCLUDE_TYPE

Flags for indicating the location of an include file.

typedef enum D3D10_INCLUDE_TYPE
{
    D3D10_INCLUDE_LOCAL,
    D3D10_INCLUDE_SYSTEM,
    D3D10_INCLUDE_FORCE_DWORD,
} D3D10_INCLUDE_TYPE, *LPD3D10_INCLUDE_TYPE;

Constants

D3D10_INCLUDE_LOCAL
The local directory.
D3D10_INCLUDE_SYSTEM
The system directory.
D3D10_INCLUDE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Core Enumerations


D3D10_SHADER_DEBUG_REGTYPE

Shader debugging structures.

typedef enum _D3D10_SHADER_DEBUG_REGTYPE
{
    D3D10_SHADER_DEBUG_REG_INPUT,
    D3D10_SHADER_DEBUG_REG_OUTPUT,
    D3D10_SHADER_DEBUG_REG_CBUFFER,
    D3D10_SHADER_DEBUG_REG_TBUFFER,
    D3D10_SHADER_DEBUG_REG_TEMP,
    D3D10_SHADER_DEBUG_REG_TEMPARRAY,
    D3D10_SHADER_DEBUG_REG_TEXTURE,
    D3D10_SHADER_DEBUG_REG_SAMPLER,
    D3D10_SHADER_DEBUG_REG_IMMEDIATECBUFFER,
    D3D10_SHADER_DEBUG_REG_LITERAL,
    D3D10_SHADER_DEBUG_REG_UNUSED,
    D3D10_SHADER_DEBUG_REG_FORCE_DWORD = 0x7fffffff,
} D3D10_SHADER_DEBUG_REGTYPE;

Constants

D3D10_SHADER_DEBUG_REG_INPUT
TBD
D3D10_SHADER_DEBUG_REG_OUTPUT
TBD
D3D10_SHADER_DEBUG_REG_CBUFFER
TBD
D3D10_SHADER_DEBUG_REG_TBUFFER
TBD
D3D10_SHADER_DEBUG_REG_TEMP
TBD
D3D10_SHADER_DEBUG_REG_TEMPARRAY
TBD
D3D10_SHADER_DEBUG_REG_TEXTURE
TBD
D3D10_SHADER_DEBUG_REG_SAMPLER
TBD
D3D10_SHADER_DEBUG_REG_IMMEDIATECBUFFER
TBD
D3D10_SHADER_DEBUG_REG_LITERAL
TBD
D3D10_SHADER_DEBUG_REG_UNUSED
TBD
D3D10_SHADER_DEBUG_REG_FORCE_DWORD
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_SHADER_DEBUG_SCOPETYPE

TBD

typedef enum _D3D10_SHADER_DEBUG_SCOPETYPE
{
    D3D10_SHADER_DEBUG_SCOPE_GLOBAL,
    D3D10_SHADER_DEBUG_SCOPE_BLOCK,
    D3D10_SHADER_DEBUG_SCOPE_FORLOOP,
    D3D10_SHADER_DEBUG_SCOPE_STRUCT,
    D3D10_SHADER_DEBUG_SCOPE_FUNC_PARAMS,
    D3D10_SHADER_DEBUG_SCOPE_STATEBLOCK,
    D3D10_SHADER_DEBUG_SCOPE_NAMESPACE,
    D3D10_SHADER_DEBUG_SCOPE_ANNOTATION,
    D3D10_SHADER_DEBUG_SCOPE_FORCE_DWORD = 0x7fffffff,
} D3D10_SHADER_DEBUG_SCOPETYPE;

Constants

D3D10_SHADER_DEBUG_SCOPE_GLOBAL
TBD
D3D10_SHADER_DEBUG_SCOPE_BLOCK
TBD
D3D10_SHADER_DEBUG_SCOPE_FORLOOP
TBD
D3D10_SHADER_DEBUG_SCOPE_STRUCT
TBD
D3D10_SHADER_DEBUG_SCOPE_FUNC_PARAMS
TBD
D3D10_SHADER_DEBUG_SCOPE_STATEBLOCK
TBD
D3D10_SHADER_DEBUG_SCOPE_NAMESPACE
TBD
D3D10_SHADER_DEBUG_SCOPE_ANNOTATION
TBD
D3D10_SHADER_DEBUG_SCOPE_FORCE_DWORD
TBD

Requirements

Header: Declared in D3D10Shader.h.


D3D10_NAME

These flags identify shader parameters that use system-value semantics.

typedef enum D3D10_NAME
{
    D3D10_NAME_UNDEFINED = 0,
    D3D10_NAME_POSITION = 1,
    D3D10_NAME_CLIP_DISTANCE = 2,
    D3D10_NAME_CULL_DISTANCE = 3,
    D3D10_NAME_RENDER_TARGET_ARRAY_INDEX = 4,
    D3D10_NAME_VIEWPORT_ARRAY_INDEX = 5,
    D3D10_NAME_VERTEX_ID = 6,
    D3D10_NAME_PRIMITIVE_ID = 7,
    D3D10_NAME_INSTANCE_ID = 8,
    D3D10_NAME_IS_FRONT_FACE = 9,
    D3D10_NAME_SAMPLE_INDEX = 10,
    D3D10_NAME_TARGET = 64,
    D3D10_NAME_DEPTH = 65,
} D3D10_NAME;

Constants

D3D10_NAME_UNDEFINED
This parameter does not use a predefined system-value semantic.
D3D10_NAME_POSITION
This parameter contains position data.
D3D10_NAME_CLIP_DISTANCE
This parameter contains clip-distance data.
D3D10_NAME_CULL_DISTANCE
This parameter contains cull distance data.
D3D10_NAME_RENDER_TARGET_ARRAY_INDEX
This parameter contains a render-target-array index.
D3D10_NAME_VIEWPORT_ARRAY_INDEX
This parameter contains a viewport-array index.
D3D10_NAME_VERTEX_ID
This parameter contains a vertex ID.
D3D10_NAME_PRIMITIVE_ID
This parameter contains a primitive ID.
D3D10_NAME_INSTANCE_ID
This parameter contains a instance ID.
D3D10_NAME_IS_FRONT_FACE
This parameter contains data that identifies whether or not the primitive faces the camera.
D3D10_NAME_SAMPLE_INDEX
This parameter a sampler-array index.
D3D10_NAME_TARGET
This parameter contains render-target data.
D3D10_NAME_DEPTH
This parameter contains depth data.

Remarks

These flags identify shader parameters that have predefined system-value semantics. These flags are used in a shader-signature description (see D3D10_SIGNATURE_PARAMETER_DESC).

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Enumerations


D3D10_SHADER_CBUFFER_FLAGS

These flags identify constant-buffer properties.

typedef enum D3D10_SHADER_CBUFFER_FLAGS
{
    D3D10_CBF_USERPACKED = 1,
    D3D10_CBF_FORCE_DWORD = 0x7fffffff,
} D3D10_SHADER_CBUFFER_FLAGS, *LPD3D10_SHADER_CBUFFER_FLAGS;

Constants

D3D10_CBF_USERPACKED
Bind the constant buffer to an input slot defined in HLSL code (instead of letting the compiler choose the input slot).
D3D10_CBF_FORCE_DWORD
This value is not used by a programmer; it exists to force the enumeration to compile to 32 bits.

Remarks

These flags are used in a a shader buffer description (see D3D10_SHADER_BUFFER_DESC.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Enumerations


D3D10_SHADER_INPUT_FLAGS

These flags identify shader-input options.

typedef enum D3D10_SHADER_INPUT_FLAGS
{
    D3D10_SIF_USERPACKED = 1,
    D3D10_SIF_COMPARISON_SAMPLER = 2,
    D3D10_SIF_TEXTURE_COMPONENT_0 = 4,
    D3D10_SIF_TEXTURE_COMPONENT_1 = 8,
    D3D10_SIF_TEXTURE_COMPONENTS = 12,
    D3D10_SIF_FORCE_DWORD = 0x7fffffff,
} D3D10_SHADER_INPUT_FLAGS, *LPD3D10_SHADER_INPUT_FLAGS;

Constants

D3D10_SIF_USERPACKED
Assign a shader input to a register based on the register assignment in the HLSL code (instead of letting the compiler choose the register).
D3D10_SIF_COMPARISON_SAMPLER
Use a comparison sampler, which uses the SampleCmp (Direct3D 10 HLSL) and SampleCmpLevelZero (Direct3D 10 HLSL) sampling functions.
D3D10_SIF_TEXTURE_COMPONENT_0
A 2-bit value for encoding texture components.
D3D10_SIF_TEXTURE_COMPONENT_1
A 2-bit value for encoding texture components.
D3D10_SIF_TEXTURE_COMPONENTS
A 2-bit value for encoding texture components.
D3D10_SIF_FORCE_DWORD
This value is not used by a programmer; it exists to force the enumeration to compile to 32 bits.

Remarks

These flags are used in a shader-input-signature description (see D3D10_SHADER_INPUT_BIND_DESC).

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Enumerations


D3D10_SHADER_INPUT_TYPE

These flags identify a shader-resource type.

typedef enum D3D10_SHADER_INPUT_TYPE
{
    D3D10_SIT_CBUFFER,
    D3D10_SIT_TBUFFER,
    D3D10_SIT_TEXTURE,
    D3D10_SIT_SAMPLER,
} D3D10_SHADER_INPUT_TYPE, *LPD3D10_SHADER_INPUT_TYPE;

Constants

D3D10_SIT_CBUFFER
The shader resource is a constant buffer.
D3D10_SIT_TBUFFER
The shader resource is a texture buffer.
D3D10_SIT_TEXTURE
The shader resource is a texture.
D3D10_SIT_SAMPLER
The shader resource is a sampler.

Remarks

These flags describe a shader resource that is used as an input in a shader-input-signature description. See D3D10_SHADER_INPUT_BIND_DESC.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Enumerations


D3D10_SHADER_VARIABLE_CLASS

These flags identify the shader-variable class.

typedef enum D3D10_SHADER_VARIABLE_CLASS
{
    D3D10_SVC_SCALAR,
    D3D10_SVC_VECTOR,
    D3D10_SVC_MATRIX_ROWS,
    D3D10_SVC_MATRIX_COLUMNS,
    D3D10_SVC_OBJECT,
    D3D10_SVC_STRUCT,
    D3D10_SVC_FORCE_DWORD = 0x7fffffff,
} D3D10_SHADER_VARIABLE_CLASS, *LPD3D10_SHADER_VARIABLE_CLASS;

Constants

D3D10_SVC_SCALAR
The shader variable is a scalar.
D3D10_SVC_VECTOR
The shader variable is a vector.
D3D10_SVC_MATRIX_ROWS
The shader variable is a row-major matrix.
D3D10_SVC_MATRIX_COLUMNS
The shader variable is a column-major matrix.
D3D10_SVC_OBJECT
The shader variable is an object.
D3D10_SVC_STRUCT
The shader variable is a structure.
D3D10_SVC_FORCE_DWORD
This value is not used by a programmer; it exists to force the enumeration to compile to 32 bits.

Remarks

These flags describe the class of a shader variable. This is not a programming class; the class identifies whether the variable class such as scalar, vector, object, etc. The shader-variable class is used in a shader-input-signature description (see D3D10_SHADER_INPUT_BIND_DESC).

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Enumerations


D3D10_SHADER_VARIABLE_FLAGS

These flags identify a shader-variable property.

typedef enum D3D10_SHADER_VARIABLE_FLAGS
{
    D3D10_SVF_USERPACKED = 1,
    D3D10_SVF_USED = 2,
    D3D10_SVF_FORCE_DWORD = 0x7fffffff,
} D3D10_SHADER_VARIABLE_FLAGS, *LPD3D10_SHADER_VARIABLE_FLAGS;

Constants

D3D10_SVF_USERPACKED
The registers for the shader variable were assigned in HLSL code (instead of assigned by the compiler).
D3D10_SVF_USED
D3D10_SVF_FORCE_DWORD
This value is not used by a programmer; it exists to force the enumeration to compile to 32 bits.

Remarks

These flags are used in a a shader-variable description (see D3D10_SHADER_VARIABLE_DESC.

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Enumerations


D3D10_SHADER_VARIABLE_TYPE

These flags identify the shader-variable type.

typedef enum D3D10_SHADER_VARIABLE_TYPE
{
    D3D10_SVT_VOID = 0,
    D3D10_SVT_BOOL = 1,
    D3D10_SVT_INT = 2,
    D3D10_SVT_FLOAT = 3,
    D3D10_SVT_STRING = 4,
    D3D10_SVT_TEXTURE = 5,
    D3D10_SVT_TEXTURE1D = 6,
    D3D10_SVT_TEXTURE2D = 7,
    D3D10_SVT_TEXTURE3D = 8,
    D3D10_SVT_TEXTURECUBE = 9,
    D3D10_SVT_SAMPLER = 10,
    D3D10_SVT_PIXELSHADER = 15,
    D3D10_SVT_VERTEXSHADER = 16,
    D3D10_SVT_UINT = 19,
    D3D10_SVT_UINT8 = 20,
    D3D10_SVT_GEOMETRYSHADER = 21,
    D3D10_SVT_RASTERIZER = 22,
    D3D10_SVT_DEPTHSTENCIL = 23,
    D3D10_SVT_BLEND = 24,
    D3D10_SVT_BUFFER = 25,
    D3D10_SVT_CBUFFER = 26,
    D3D10_SVT_TBUFFER = 27,
    D3D10_SVT_TEXTURE1DARRAY = 28,
    D3D10_SVT_TEXTURE2DARRAY = 29,
    D3D10_SVT_RENDERTARGETVIEW = 30,
    D3D10_SVT_DEPTHSTENCILVIEW = 31,
    D3D10_SVT_TEXTURE2DMS = 32,
    D3D10_SVT_TEXTURE2DMSARRAY = 33,
    D3D10_SVT_TEXTURECUBEARRAY = 34,
    D3D10_SVT_FORCE_DWORD = 0x7fffffff,
} D3D10_SHADER_VARIABLE_TYPE, *LPD3D10_SHADER_VARIABLE_TYPE;

Constants

D3D10_SVT_VOID
The variable is a void pointer.
D3D10_SVT_BOOL
The variable is a boolean.
D3D10_SVT_INT
The variable is a integer.
D3D10_SVT_FLOAT
The variable is a floating-point number.
D3D10_SVT_STRING
The variable is a string.
D3D10_SVT_TEXTURE
The variable is a texture.
D3D10_SVT_TEXTURE1D
The variable is a 1D texture.
D3D10_SVT_TEXTURE2D
The variable is a 2D texture.
D3D10_SVT_TEXTURE3D
The variable is a 3D texture.
D3D10_SVT_TEXTURECUBE
The variable is a texture cube.
D3D10_SVT_SAMPLER
The variable is a sampler.
D3D10_SVT_PIXELSHADER
The variable is a pixel shader.
D3D10_SVT_VERTEXSHADER
The variable is a vertex shader.
D3D10_SVT_UINT
The variable is an unsigned integer.
D3D10_SVT_UINT8
The variable is an 8-bit unsigned integer.
D3D10_SVT_GEOMETRYSHADER
The variable is a geometry shader.
D3D10_SVT_RASTERIZER
The variable is a rasterizer-state object.
D3D10_SVT_DEPTHSTENCIL
The variable is a depth-stencil-state object.
D3D10_SVT_BLEND
The variable is a blend-state object.
D3D10_SVT_BUFFER
The variable is a buffer.
D3D10_SVT_CBUFFER
The variable is a constant buffer.
D3D10_SVT_TBUFFER
The variable is a texture buffer.
D3D10_SVT_TEXTURE1DARRAY
The variable is a 1D-texture array.
D3D10_SVT_TEXTURE2DARRAY
The variable is a 2D-texture array.
D3D10_SVT_RENDERTARGETVIEW
The variable is a render-target view.
D3D10_SVT_DEPTHSTENCILVIEW
The variable is a depth-stencil view.
D3D10_SVT_TEXTURE2DMS
The variable is a 2D-multisampled texture.
D3D10_SVT_TEXTURE2DMSARRAY
The variable is a 2D-multisampled-texture array.
D3D10_SVT_TEXTURECUBEARRAY
The variable is a texture-cube array.
D3D10_SVT_FORCE_DWORD
This value is not used by a programmer; it exists to force the enumeration to compile to 32 bits.

Remarks

These flags are used by a shader-type description (see D3D10_SHADER_TYPE_DESC) and an effect-type description (see D3D10_EFFECT_TYPE_DESC).

Requirements

Header: Declared in D3D10Shader.h.

See Also

Shader Enumerations


D3D10_SRV_DIMENSION

These flags identify the type of resource that will be viewed.

typedef enum D3D10_SRV_DIMENSION
{
    D3D10_SRV_DIMENSION_UNKNOWN = 0,
    D3D10_SRV_DIMENSION_BUFFER = 1,
    D3D10_SRV_DIMENSION_TEXTURE1D = 2,
    D3D10_SRV_DIMENSION_TEXTURE1DARRAY = 3,
    D3D10_SRV_DIMENSION_TEXTURE2D = 4,
    D3D10_SRV_DIMENSION_TEXTURE2DARRAY = 5,
    D3D10_SRV_DIMENSION_TEXTURE2DMS = 6,
    D3D10_SRV_DIMENSION_TEXTURE2DMSARRAY = 7,
    D3D10_SRV_DIMENSION_TEXTURE3D = 8,
    D3D10_SRV_DIMENSION_TEXTURECUBE = 9,
} D3D10_SRV_DIMENSION;

Constants

D3D10_SRV_DIMENSION_UNKNOWN
The type is unknown.
D3D10_SRV_DIMENSION_BUFFER
The resource is a buffer.
D3D10_SRV_DIMENSION_TEXTURE1D
The resource is a 1D texture.
D3D10_SRV_DIMENSION_TEXTURE1DARRAY
The resource is an array of 1D textures.
D3D10_SRV_DIMENSION_TEXTURE2D
The resource is a 2D texture.
D3D10_SRV_DIMENSION_TEXTURE2DARRAY
The resource is an array of 2D textures.
D3D10_SRV_DIMENSION_TEXTURE2DMS
The resource is a multisampling 2D texture.
D3D10_SRV_DIMENSION_TEXTURE2DMSARRAY
The resource is an array of multisampling 2D textures.
D3D10_SRV_DIMENSION_TEXTURE3D
The resource is a 3D texture.
D3D10_SRV_DIMENSION_TEXTURECUBE
The resource is a cube texture.

Remarks

These flags are used by a shader-resource-view description (see D3D10_SHADER_RESOURCE_VIEW_DESC, or a shader-input-signature description (see D3D10_SHADER_INPUT_BIND_DESC).

Requirements

Header: Declared in D3D10Shader.h.

See Also

Resource Enumerations


Shader Constants

This section contains information about the following shader constants:

Constants | Description
D3D10_SHADER Constants | These constants identify HLSL compile options.

See Also

Shader Reference


D3D10_SHADER Constants

HLSL compile options.

#define | Description
D3D10_SHADER_DEBUG | Insert debug file/line/type/symbol information.
D3D10_SHADER_SKIP_VALIDATION | Do not validate the generated code against known capabilities and constraints. Only use this with shaders that have been successfully compiled in the past. Shaders are always validated by DirectX before they are set to the device.
D3D10_SHADER_SKIP_OPTIMIZATION | Skip optimization during code generation; generally recommended for debug only.
D3D10_SHADER_PACK_MATRIX_ROW_MAJOR | Unless explicitly specified, matrices will be packed in row-major order on input and output from the shader.
D3D10_SHADER_PACK_MATRIX_COLUMN_MAJOR | Unless explicitly specified, matrices will be packed in column-major order on input and output from the shader. This is generally more efficient, since it allows vector-matrix multiplication to be performed using a series of dot-products.
D3D10_SHADER_PARTIAL_PRECISION | Force all computations to be done with partial precision; this may run faster on some hardware.
D3D10_SHADER_FORCE_VS_SOFTWARE_NO_OPT | Compile a vertex shader for the next highest shader profile. This option turns debugging on (and optimizations off).
D3D10_SHADER_FORCE_PS_SOFTWARE_NO_OPT | Compile a pixel shader for the next highest shader profile. This option turns debugging on (and optimizations off).
D3D10_SHADER_NO_PRESHADER | Disables Preshaders. Using this flag will cause the compiler to not pull out static expression for evaluation.
D3D10_SHADER_AVOID_FLOW_CONTROL | Tell compiler to not allow flow-control (when possible).
D3D10_SHADER_PREFER_FLOW_CONTROL | Tell compiler to use flow-control (when possible).
D3D10_SHADER_ENABLE_STRICTNESS | By default, the HLSL compiler disables strictness on deprecated syntax. Specifying this flag enables strictness which may not allow for legacy syntax.
D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY | This enables older shaders to compile to 4_0 targets.
D3D10_SHADER_IEEE_STRICTNESS | Enables IEEE strictness.
D3D10_SHADER_OPTIMIZATION_LEVEL0 | Optimize for level 0 warnings.
D3D10_SHADER_OPTIMIZATION_LEVEL1 | Optimize for level 1 warnings.
D3D10_SHADER_OPTIMIZATION_LEVEL2 | Optimize for level 2 warnings.
D3D10_SHADER_OPTIMIZATION_LEVEL3 | Optimize for level 3 warnings.

These constants are defined as macros in d3d10shader.h.

See Also

Shader Constants


Effect Reference

The Direct3D API defines several API elements to help you create and manage the effect system.

  • Interfaces
  • Functions
  • Structures
  • Constants

The effect system encapsulates state assignments in an effect. Each effect is a collection of pipeline state which can be broken down into state assignments using state blocks, resources, and shaders. Depending on the size of an effect, you can choose to implement one in an ASCII text string or an effect file (.fx). To organize information in an effect, see the effect format.

Having designed an effect, use the effect API to set state in the device during rendering. As well, the effect system supports a series of reflection API's for getting and setting effect data. For more information, see Effect System Interfaces (Direct3D 10).

See Also

Direct3D Reference


Effect Interfaces (Direct3D 10)

This section contains information about the following effect-system interfaces:

Interfaces | Description
ID3D10EffectBlendVariable Interface | Get and set blend state.
ID3D10EffectConstantBuffer Interface | Access data in a texture buffer or constant buffer.
ID3D10EffectDepthStencilVariable Interface | Get and set depth-stencil state.
ID3D10EffectDepthStencilViewVariable Interface | Access data in a depth-stencil resource.
ID3D10Effect Interface | Encapsulates pipeline state in one or more rendering techniques. Effects may contain variables that can be shared between effects.
ID3D10Include Interface | Encapsulates user-implemented methods for custom behaviors when reading include files.
ID3D10EffectMatrixVariable Interface | Get and set a matrix.
ID3D10EffectPass Interface | Encapsulates state within a pass.
ID3D10EffectPool Interface | Identifies effect variables that are shared between effects.
ID3D10EffectRasterizerVariable Interface | Get and set rasterizer state.
ID3D10EffectRenderTargetViewVariable Interface | Access data in a render target.
ID3D10EffectSamplerVariable Interface | Get and set sampler state.
ID3D10EffectScalarVariable Interface | Get and set a scalar.
ID3D10EffectShaderResourceVariable Interface | Access data in a shader resource.
ID3D10EffectShaderVariable Interface | Get and set a shader variable.
ID3D10EffectStringVariable Interface | Get and set a string.
ID3D10EffectTechnique Interface | Encapsulates state within a technique; a technique contains one or more passes.
ID3D10EffectType Interface | Implements methods for accessing effect variables.
ID3D10EffectVectorVariable Interface | Get and set a vector.

The effect system defines several interfaces for managing effect state. There are two kinds of interfaces: those used by the runtime to render an effect and reflection interfaces for getting and setting effect variables with the API. All reflection interfaces derive from ID3D10EffectVariable Interface.

See Also

Effect Reference


ID3D10Effect Interface

An ID3D10Effect interface manages a set of state objects, resources and shaders for implementing a rendering effect.

Method | Description
ID3D10Effect::GetConstantBufferByIndex | Get a constant buffer by it's index.
ID3D10Effect::GetConstantBufferByName | Get a constant buffer by it's name.
ID3D10Effect::GetDesc | Get a description of the effect.
ID3D10Effect::GetDevice | Get the device that created the effect.
ID3D10Effect::GetTechniqueByIndex | Get a technique by it's index.
ID3D10Effect::GetTechniqueByName | Get a technique by it's name.
ID3D10Effect::GetVariableByIndex | Get a variable by it's index.
ID3D10Effect::GetVariableByName | Get a variable by it's name.
ID3D10Effect::GetVariableBySemantic | Get a variable by it's semantic.
ID3D10Effect::IsOptimized | Test an effect to see if it is optimized.
ID3D10Effect::IsPool | Test an effect to see if it is part of a pool.
ID3D10Effect::IsValid | Test an effect to see if the HLSL code is valid.
ID3D10Effect::Optimize | Minimize the amount of memory used by an effect.

An effect is created by calling D3D10CreateEffectFromMemory.

The effect system groups the information required for rendering into an effect which contains: state objects for assigning state changes in groups, resources for supplying input data and storing output data, and programs that control how the rendering is done called shaders. For more information, see Effects (Direct3D 10).

Requirements

Header: Declared in Effect.h.

See Also

Effect Interfaces (Direct3D 10)


ID3D10Effect::GetConstantBufferByIndex

Get a constant buffer by it's index.

ID3D10EffectConstantBuffer* GetConstantBufferByIndex(
  UINT Index
);

Parameters

Index
[in] A zero-based index.

Return Values

A pointer to a ID3D10EffectConstantBuffer Interface.

Remarks

An effect that contains a variable that will be read/written by an application requires at least one constant buffer. For best performance, an effect should organize variables into one or more constant buffers based on their frequency of update.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::GetConstantBufferByName

Get a constant buffer by it'sname.

ID3D10EffectConstantBuffer* GetConstantBufferByName(
  LPCSTR Name
);

Parameters

Name
[in] The constant-buffer name.

Return Values

A pointer to the constant buffer indicated by the Name. See ID3D10EffectConstantBuffer.

Remarks

An effect that contains a variable that will be read/written by an application requires at least one constant buffer. For best performance, an effect should organize variables into one or more constant buffers based on their frequency of update.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::GetDesc

Get an effect description.

HRESULT GetDesc(
  D3D10_EFFECT_DESC *pDesc
);

Parameters

pDesc
[in, out] A pointer to an effect description (see D3D10_EFFECT_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

An effect description contains basic information about an effect such as the techniques it contains and the constant buffer resources it requires.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::GetDevice

Get the device that created the effect.

HRESULT GetDevice(
  ID3D10Device **ppDevice
);

Parameters

ppDevice
[out] A pointer to an ID3D10Device Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

An effect is created for a specific device, by calling a function such as D3DX10CreateEffectFromFile.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::GetTechniqueByIndex

Get a technique by it's index.

ID3D10EffectTechnique* GetTechniqueByIndex(
  UINT Index
);

Parameters

Index
[in] A zero-based index.

Return Values

A pointer to an ID3D10EffectTechnique Interface.

Remarks

An effect contains one or more techniques; each technique contains one or more passes. You can access a technique using its name or with an index. For more about techniques, see techniques and passes..

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::GetTechniqueByName

Get a technique by it's name.

ID3D10EffectTechnique* GetTechniqueByName(
  LPCSTR Name
);

Parameters

Name
[in] The name of the technique.

Return Values

A pointer to an ID3D10EffectTechnique Interface.

Remarks

An effect contains one or more techniques; each technique contains one or more passes. You can access a technique using its name or with an index. For more about techniques, see techniques and passes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::GetVariableByIndex

Get a variable by it's index.

ID3D10EffectVariable* GetVariableByIndex(
  UINT Index
);

Parameters

Index
[in] A zero-based index.

Return Values

A pointer to a ID3D10EffectVariable Interface.

Remarks

An effect may contain one or more variables. Variables outside of a technique are considered global to all effects, those located inside of a technique are local to that technique. You can access any local non-static effect variable using its name or with an index.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::GetVariableByName

Get a variable by it's name.

ID3D10EffectVariable* GetVariableByName(
  LPCSTR Name
);

Parameters

Name
[in] The variable name.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Remarks

An effect may contain one or more variables. Variables outside of a technique are considered global to all effects, those located inside of a technique are local to that technique. You can access an effect variable using its name or with an index.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::GetVariableBySemantic

Get a variable by it's semantic.

ID3D10EffectVariable* GetVariableBySemantic(
  LPCSTR Semantic
);

Parameters

Semantic
[in] The semantic name.

Return Values

A pointer to the effect variable indicated by the Semantic. See ID3D10EffectVariable Interface.

Remarks

Each effect variable can have a semantic attached, which is a user defined metadata string. Some system-value semantics are reserved words that trigger built in functionality by pipeline stages.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::IsOptimized

Test an effect to see if the reflection metadata has been removed from memory.

BOOL IsOptimized();

Parameters

None.

Return Values

TRUE if the effect is optimized; otherwise FALSE.

Remarks

An effect uses memory space two different ways: to store the information required by the runtime to execute an effect, and to store the metadata required to reflect information back to an application using the API. You can minimize the amount of memory required by an effect by calling ID3D10Effect::Optimize which removes the reflection metadata from memory. Of course, API methods to read variables will no longer work once reflection data has been removed.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::IsPool

Test an effect to see if it is part of a memory pool.

BOOL IsPool();

Parameters

None.

Return Values

TRUE if the effect is pooled; otherwise FALSE. See ID3D10EffectPool Interface.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::IsValid

Test an effect to see if it contains valid syntax.

BOOL IsValid();

Parameters

None.

Return Values

TRUE if the code syntax is valid; otherwise FALSE.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10Effect::Optimize

Minimize the amount of memory required for an effect.

HRESULT Optimize();

Parameters

None.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

An effect uses memory space two different ways: to store the information required by the runtime to execute an effect, and to store the metadata required to reflect information back to an application using the API. You can minimize the amount of memory required by an effect by calling ID3D10Effect::Optimize which removes the reflection metadata from memory. Of course, API methods to read variables will no longer work once reflection data has been removed.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10EffectBlendVariable Interface

The ID3D10EffectBlendVariable interface accesses blend-state variables.

Method | Description
ID3D10EffectBlendVariable::GetBackingStore | Get a blend state description.
ID3D10EffectBlendVariable::GetBlendState | Get a pointer to a blend-state interface.

An ID3D10EffectBlendVariable Interface is created when an effect is read into memory.

Effect variables are saved in memory in the backing store; when a technique is applied, the values in the backing store are copied to the device. You can use either of these methods to return state. For examples, see Two Ways to Get the State in an Effect Variable.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectBlendVariable::GetBackingStore

Get a pointer to a blend-state variable.

HRESULT GetBackingStore(
  UINT Index,
  D3D10_BLEND_DESC *pBlendDesc
);

Parameters

Index
[in] Index into an array of blend-state descriptions. If there is only one blend-state variable in the effect, use 0.
pBlendDesc
[in] A pointer to a blend-state description (see D3D10_BLEND_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Effect variables are saved in memory in the backing store; when a technique is applied, the values in the backing store are copied to the device. Backing store data can used to recreate the variable when necessary.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectBlendVariable Interface


ID3D10EffectBlendVariable::GetBlendState

Get a pointer to a blend-state interface.

HRESULT GetBlendState(
  UINT Index,
  ID3D10BlendState **ppBlendState
);

Parameters

Index
[in] Index into an array of blend-state interfaces. If there is only one blend-state interface, use 0.
ppBlendState
[out] The address of a pointer to a blend-state interface (see ID3D10BlendState Interface).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectBlendVariable Interface


ID3D10EffectConstantBuffer Interface

The ID3D10EffectConstantBuffer interface is used for accessing constant and texture buffers.

Method | Description
ID3D10EffectConstantBuffer::GetConstantBuffer | Get a constant-buffer.
ID3D10EffectConstantBuffer::GetTextureBuffer | Get a texture-buffer.
ID3D10EffectConstantBuffer::SetConstantBuffer | Set a constant-buffer.
ID3D10EffectConstantBuffer::SetTextureBuffer | Set a texture-buffer.

Use constant buffers to store many effect constants; grouping constants into buffers based on their frequency of update. This allows you to minimize the number of state changes as well as make the fewest API calls to change state. Both of these factors lead to better performance.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectConstantBuffer::GetConstantBuffer

Get a constant-buffer.

HRESULT GetConstantBuffer(
  ID3D10Buffer **ppConstantBuffer
);

Parameters

ppConstantBuffer
[out] The address of a pointer to a constant-buffer interface. See ID3D10Buffer Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectConstantBuffer Interface


ID3D10EffectConstantBuffer::GetTextureBuffer

Get a texture-buffer.

HRESULT GetTextureBuffer(
  ID3D10ShaderResourceView **ppTextureBuffer
);

Parameters

ppTextureBuffer
[out] The address of a pointer to a shader-resource-view interface for accessing a texture buffer. See ID3D10ShaderResourceView Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectConstantBuffer Interface


ID3D10EffectConstantBuffer::SetConstantBuffer

Set a constant-buffer.

HRESULT SetConstantBuffer(
  ID3D10Buffer *pConstantBuffer
);

Parameters

pConstantBuffer
[in] A pointer to a constant-buffer interface. See ID3D10Buffer Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectConstantBuffer Interface


ID3D10EffectConstantBuffer::SetTextureBuffer

Set a texture-buffer.

HRESULT SetTextureBuffer(
  ID3D10ShaderResourceView *pTextureBuffer
);

Parameters

pTextureBuffer
[in] A pointer to a shader-resource-view interface for accessing a texture buffer.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectConstantBuffer Interface


ID3D10EffectDepthStencilVariable Interface

The ID3D10EffectDepthStencilVariable interface accesses depth-stencil variables.

Method | Description
ID3D10EffectDepthStencilVariable::GetBackingStore | Get a depth-stencil state description.
ID3D10EffectDepthStencilVariable::GetDepthStencilState | Get a pointer to a depth-stencil interface.

An ID3D10EffectDepthStencilVariable Interface is created when an effect is read into memory.

Effect variables are saved in memory in the backing store; when a technique is applied, the values in the backing store are copied to the device. You can use either of these methods to return state. For examples, see Two Ways to Get the State in an Effect Variable.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectDepthStencilVariable::GetBackingStore

Get a pointer to a variable that contains depth-stencil state.

HRESULT GetBackingStore(
  UINT Index,
  D3D10_DEPTH_STENCIL_DESC *pDepthStencilDesc
);

Parameters

Index
[in] Index into an array of depth-stencil-state descriptions. If there is only one depth-stencil variable in the effect, use 0.
pDepthStencilDesc
[in] A pointer to a depth-stencil-state description (see D3D10_DEPTH_STENCIL_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Effect variables are saved in memory in the backing store; when a technique is applied, the values in the backing store are copied to the device. Backing store data can used to recreate the variable when necessary.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectDepthStencilVariable Interface


ID3D10EffectDepthStencilVariable::GetDepthStencilState

Get a pointer to a depth-stencil interface.

HRESULT GetDepthStencilState(
  UINT Index,
  ID3D10DepthStencilState **ppDepthStencilState
);

Parameters

Index
[in] Index into an array of depth-stencil interfaces. If there is only one depth-stencil interface, use 0.
ppDepthStencilState
[out] The address of a pointer to a blend-state interface (see ID3D10DepthStencilState Interface).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectDepthStencilVariable Interface


ID3D10EffectDepthStencilViewVariable Interface

The ID3D10EffectDepthStencilViewVariable interface accesses depth-stencil-view variables.

Method | Description
ID3D10EffectDepthStencilViewVariable::GetDepthStencil | Get a depth-stencil-view resource.
ID3D10EffectDepthStencilViewVariable::GetDepthStencilArray | Get an array of depth-stencil-view resources.
ID3D10EffectDepthStencilViewVariable::SetDepthStencil | Set a depth-stencil-view resource.
ID3D10EffectDepthStencilViewVariable::SetDepthStencilArray | Set an array of depth-stencil-view resources.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectDepthStencilViewVariable::GetDepthStencil

Get a depth-stencil-view resource.

HRESULT GetDepthStencil(
  ID3D10DepthStencilView **ppResource
);

Parameters

ppResource
[out] The address of a pointer to a depth-stencil-view interface. See ID3D10DepthStencilView Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3d10.

See Also

ID3D10EffectDepthStencilViewVariable Interface


ID3D10EffectDepthStencilViewVariable::GetDepthStencilArray

Get an array of depth-stencil-view resources.

HRESULT GetDepthStencilArray(
  ID3D10DepthStencilView **ppResources,
  UINT Offset,
  UINT Count
);

Parameters

ppResources
[out] A pointer to an array of depth-stencil-view interfaces. See ID3D10DepthStencilView Interface.
Offset
[in] The zero-based array index to get the first interface.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3d10.

See Also

ID3D10EffectDepthStencilViewVariable Interface


ID3D10EffectDepthStencilViewVariable::SetDepthStencil

Set a depth-stencil-view resource.

HRESULT SetDepthStencil(
  ID3D10DepthStencilView *pResource
);

Parameters

pResource
[in] A pointer to a depth-stencil-view interface. See ID3D10DepthStencilView Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3d10.

See Also

ID3D10EffectDepthStencilViewVariable Interface


ID3D10EffectDepthStencilViewVariable::SetDepthStencilArray

Set an array of depth-stencil-view resources.

HRESULT SetDepthStencilArray(
  ID3D10DepthStencilView **ppResources,
  UINT Offset,
  UINT Count
);

Parameters

ppResources
[out] A pointer to an array of depth-stencil-view interfaces. See ID3D10DepthStencilView Interface.
Offset
[in] The zero-based array index to set the first interface.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3d10.

See Also

ID3D10EffectDepthStencilViewVariable Interface


ID3D10EffectMatrixVariable Interface

The ID3D10EffectMatrixVariable interface accesses a matrix variable.

Method | Description
ID3D10EffectMatrixVariable::GetMatrix | Get a matrix.
ID3D10EffectMatrixVariable::GetMatrixArray | Get an array of matrices.
ID3D10EffectMatrixVariable::GetMatrixTranspose | Transpose and get a matrix.
ID3D10EffectMatrixVariable::GetMatrixTransposeArray | Transpose and get an array of matrices.
ID3D10EffectMatrixVariable::SetMatrix | Set a matrix.
ID3D10EffectMatrixVariable::SetMatrixArray | Set an array of matrices.
ID3D10EffectMatrixVariable::SetMatrixTranspose | Transpose and set a matrix.
ID3D10EffectMatrixVariable::SetMatrixTransposeArray | Transpose and set an array of matrices.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectMatrixVariable::GetMatrix

Get a matrix.

HRESULT GetMatrix(
  float *pData
);

Parameters

pData
[out] A pointer to the first element in a matrix.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectMatrixVariable Interface


ID3D10EffectMatrixVariable::GetMatrixArray

Get an array of matrices.

HRESULT GetMatrixArray(
  float *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[out] A pointer to the first element of the first matrix in an array of matrices.
Offset
[in] The offset (in number of matrices) between the start of the array and the first matrix returned.
Count
[in] The number of matrices in the returned array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectMatrixVariable Interface


ID3D10EffectMatrixVariable::GetMatrixTranspose

Transpose and get a floating-point matrix.

HRESULT GetMatrixTranspose(
  float *pData
);

Parameters

pData
[out] A pointer to the first element of a transposed matrix.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectMatrixVariable Interface


ID3D10EffectMatrixVariable::GetMatrixTransposeArray

Transpose and get an array of floating-point matrices.

HRESULT GetMatrixTransposeArray(
  float *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[out] A pointer to the first element of an array of tranposed matrices.
Offset
[in] The offset (in number of matrices) between the start of the array and the first matrix to get.
Count
[in] The number of matrices in the array to get.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectMatrixVariable Interface


ID3D10EffectMatrixVariable::SetMatrix

Set a floating-point matrix.

HRESULT SetMatrix(
  float *pData
);

Parameters

pData
[in] A pointer to the first element in the matrix.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectMatrixVariable Interface


ID3D10EffectMatrixVariable::SetMatrixArray

Set an array of floating-point matrices.

HRESULT SetMatrixArray(
  float *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the first matrix.
Offset
[in] The number of matrix elements to skip from the start of the array.
Count
[in] The number of elements to set.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectMatrixVariable Interface


ID3D10EffectMatrixVariable::SetMatrixTranspose

Transpose and set a floating-point matrix.

HRESULT SetMatrixTranspose(
  float *pData
);

Parameters

pData
[in] A pointer to the first element of a matrix.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectMatrixVariable Interface


ID3D10EffectMatrixVariable::SetMatrixTransposeArray

Transpose and set an array of floating-point matrices.

HRESULT SetMatrixTransposeArray(
  float *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to an array of matrices.
Offset
[in] The offset (in number of matrices) between the start of the array and the first matrix to set.
Count
[in] The number of matrices in the array to set.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Transposing a matrix will rearrange the data order from row-column order to column-row order (or vice versa).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectMatrixVariable Interface


ID3D10EffectPass Interface

An ID3D10EffectPass interface encapsulates state assignments within a technique.

Method | Description
ID3D10EffectPass::Apply | Set the state contained in a pass to the device.
ID3D10EffectPass::ComputeStateBlockMask | Generate a mask for allowing/preventing state changes.
ID3D10EffectPass::GetAnnotationByIndex | Get an annotation by it's index.
ID3D10EffectPass::GetAnnotationByName | Get an annotation by it's name.
ID3D10EffectPass::GetDesc | Get a pass description.
ID3D10EffectPass::GetGeometryShaderDesc | Get a geometry-shader description.
ID3D10EffectPass::GetPixelShaderDesc | Get a pixel-shader description.
ID3D10EffectPass::GetVertexShaderDesc | Get a vertex-shader description.
ID3D10EffectPass::IsValid | Test the code in a pass to see if it is compilable.

A pass is a block of code that sets render-state objects and shaders. A pass is declared within a technique; the syntax for a technique is shown in Effect Technique Syntax (Direct3D 10).

To get an effect-pass interface, call a method like ID3D10EffectTechnique::GetPassByName.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectPass::Apply

Set the state contained in a pass to the device.

HRESULT Apply(
  UINT Flags
);

Parameters

Flags
[in] Unused.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10EffectPass::ComputeStateBlockMask

Generate a mask for allowing/preventing state changes.

HRESULT ComputeStateBlockMask(
  D3D10_STATE_BLOCK_MASK *pStateBlockMask
);

Parameters

pStateBlockMask
[in] A pointer to a state-block mask (see D3D10_STATE_BLOCK_MASK).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10EffectPass::GetAnnotationByIndex

Get an annotation by it's index.

ID3D10EffectVariable* GetAnnotationByIndex(
  UINT Index
);

Parameters

Index
[in] A zero-based index.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10EffectPass::GetAnnotationByName

Get an annotation by it's name.

ID3D10EffectVariable* GetAnnotationByName(
  LPCSTR Name
);

Parameters

Name
[in] The name of the annotation.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10EffectPass::GetDesc

Get a pass description.

HRESULT GetDesc(
  D3D10_PASS_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to a pass description (see D3D10_PASS_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

A pass is a block of code that sets render state and shaders (which in turn sets constant buffers, samplers and textures). An effect technique contains one or more passes. See techniques and passes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10EffectPass::GetGeometryShaderDesc

Get a geometry-shader description.

HRESULT GetGeometryShaderDesc(
  D3D10_PASS_SHADER_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to a geometry-shader description (see D3D10_PASS_SHADER_DESC.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

An effect pass can contain render state assignments and shader object assignments.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10EffectPass::GetPixelShaderDesc

Get a pixel-shader description.

HRESULT GetPixelShaderDesc(
  D3D10_PASS_SHADER_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to a pixel-shader description (see D3D10_PASS_SHADER_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

An effect pass can contain render state assignments and shader object assignments.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10EffectPass::GetVertexShaderDesc

Get a vertex-shader description.

HRESULT GetVertexShaderDesc(
  D3D10_PASS_SHADER_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to a vertex-shader description (see D3D10_PASS_SHADER_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

An effect pass can contain render state assignments and shader object assignments.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10EffectPass::IsValid

Test a pass to see if it contains valid syntax.

BOOL IsValid();

Parameters

None.

Return Values

TRUE if the code syntax is valid; otherwise FALSE.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10Effect Interface


ID3D10EffectPool Interface

An ID3D10EffectPool interface represents a common memory space (or pool) for sharing variables between effects.

Method | Description
ID3D10EffectPool::AsEffect | Get the effect that created the effect pool.

To create an effect pool, call a function like D3DX10CreateEffectPoolFromFile. Effect pools can improve performance by reducing the number of API calls required to make state changes (see Using Effect Pools).

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectPool::AsEffect

Get the effect that created the effect pool.

ID3D10Effect* AsEffect();

Parameters

None.

Return Values

A pointer to an ID3D10Effect Interface interface.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectPool Interface


ID3D10EffectRasterizerVariable Interface

The ID3D10EffectRasterizerVariable interface accesses rasterizer-state variables.

Method | Description
ID3D10EffectRasterizerVariable::GetBackingStore | Get a rasterizer-state description.
ID3D10EffectRasterizerVariable::GetRasterizerState | Get a pointer to a rasterizer-state interface.

An ID3D10EffectRasterizerVariable Interface is created when an effect is read into memory.

Effect variables are saved in memory in the backing store; when a technique is applied, the values in the backing store are copied to the device. You can use either of these methods to return state. For examples, see Two Ways to Get the State in an Effect Variable.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectRasterizerVariable::GetBackingStore

Get a pointer to a variable that contains rasteriser state.

HRESULT GetBackingStore(
  UINT Index,
  D3D10_RASTERIZER_DESC *pRasterizerDesc
);

Parameters

Index
[in] Index into an array of rasteriser-state descriptions. If there is only one rasteriser variable in the effect, use 0.
pRasterizerDesc
[in] A pointer to a rasteriser-state description (see D3D10_RASTERIZER_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Effect variables are saved in memory in the backing store; when a technique is applied, the values in the backing store are copied to the device. Backing store data can used to recreate the variable when necessary.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectRasterizerVariable Interface


ID3D10EffectRasterizerVariable::GetRasterizerState

Get a pointer to a rasterizer interface.

HRESULT GetRasterizerState(
  UINT Index,
  ID3D10RasterizerState **ppRasterizerState
);

Parameters

Index
[in] Index into an array of rasterizer interfaces. If there is only one rasterizer interface, use 0.
ppRasterizerState
[out] The address of a pointer to a rasterizer interface (see ID3D10RasterizerState Interface).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectRasterizerVariable Interface


ID3D10EffectRenderTargetViewVariable Interface

The ID3D10EffectRenderTargetViewVariable interface accesses render-target variables.

Method | Description
ID3D10EffectRenderTargetViewVariable::GetRenderTarget | Get a render-target-view.
ID3D10EffectRenderTargetViewVariable::GetRenderTargetArray | Get an array of render-target-views.
ID3D10EffectRenderTargetViewVariable::SetRenderTarget | Set a render-target-view.
ID3D10EffectRenderTargetViewVariable::SetRenderTargetArray | Set an array of render-target-views.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectRenderTargetViewVariable::GetRenderTarget

Get a render-target.

HRESULT GetRenderTarget(
  ID3D10RenderTargetView **ppResource
);

Parameters

ppResource
[out] The address of a pointer to a render-target-view interface. See ID3D10RenderTargetView Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3d10.

See Also

ID3D10EffectRenderTargetViewVariable Interface


ID3D10EffectRenderTargetViewVariable::GetRenderTargetArray

Get an array of render-targets.

HRESULT GetRenderTargetArray(
  ID3D10RenderTargetView **ppResources,
  UINT Offset,
  UINT Count
);

Parameters

ppResources
[out] A pointer to an array of render-target-view interfaces. See ID3D10RenderTargetView Interface.
Offset
[in] The zero-based array index to get the first interface.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3d10.

See Also

ID3D10EffectRenderTargetViewVariable Interface


ID3D10EffectRenderTargetViewVariable::SetRenderTarget

Set a render-target.

HRESULT SetRenderTarget(
  ID3D10RenderTargetView *pResource
);

Parameters

pResource
[in] A pointer to a render-target-view interface. See ID3D10RenderTargetView Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3d10.

See Also

ID3D10EffectRenderTargetViewVariable Interface


ID3D10EffectRenderTargetViewVariable::SetRenderTargetArray

Set an array of render-targets.

HRESULT SetRenderTargetArray(
  ID3D10RenderTargetView **ppResources,
  UINT Offset,
  UINT Count
);

Parameters

ppResources
[out] Set an array of render-target-view interfaces. See ID3D10RenderTargetView Interface.
Offset
[in] The zero-based array index to store the first interface.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3d10.

See Also

ID3D10EffectRenderTargetViewVariable Interface


ID3D10EffectSamplerVariable Interface

The ID3D10EffectSamplerVariable interface accesses sampler variables.

Method | Description
ID3D10EffectSamplerVariable::GetBackingStore | Get a sampler-state description.
ID3D10EffectSamplerVariable::GetSampler | Get a pointer to a sampler-state interface.

An ID3D10EffectSamplerVariable Interface is created when an effect is read into memory.

Effect variables are saved in memory in the backing store; when a technique is applied, the values in the backing store are copied to the device. You can use either of these methods to return state. For examples, see Two Ways to Get the State in an Effect Variable.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectSamplerVariable::GetBackingStore

Get a pointer to a variable that contains sampler state.

HRESULT GetBackingStore(
  UINT Index,
  D3D10_SAMPLER_DESC *pSamplerDesc
);

Parameters

Index
[in] Index into an array of sampler descriptions. If there is only one sampler variable in the effect, use 0.
pSamplerDesc
[in] A pointer to a sampler description (see D3D10_SAMPLER_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectSamplerVariable Interface


ID3D10EffectSamplerVariable::GetSampler

Get a pointer to a sampler interface.

HRESULT GetSampler(
  UINT Index,
  ID3D10SamplerState **ppSampler
);

Parameters

Index
[in] Index into an array of sampler interfaces. If there is only one sampler interface, use 0.
ppSampler
[out] The address of a pointer to a sampler interface (see ID3D10SamplerState Interface).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectSamplerVariable Interface


ID3D10EffectScalarVariable Interface

The ID3D10EffectScalarVariable interface accesses scalar variables.

Method | Description
ID3D10EffectScalarVariable::GetBool | Get a boolean variable.
ID3D10EffectScalarVariable::GetBoolArray | Get an array of boolean variables.
ID3D10EffectScalarVariable::GetFloat | Get a floating-point variable.
ID3D10EffectScalarVariable::GetFloatArray | Get an array of floating-point variables.
ID3D10EffectScalarVariable::GetInt | Get an integer variable.
ID3D10EffectScalarVariable::GetIntArray | Get an array of integer variables.
ID3D10EffectScalarVariable::SetBool | Set a boolean variable.
ID3D10EffectScalarVariable::SetBoolArray | Set an array of boolean variables.
ID3D10EffectScalarVariable::SetFloat | Set a floating-point variable.
ID3D10EffectScalarVariable::SetFloatArray | Set an array of floating-point variables.
ID3D10EffectScalarVariable::SetInt | Set an integer variable.
ID3D10EffectScalarVariable::SetIntArray | Set an array of integer variables.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectScalarVariable::GetBool

Get a boolean variable.

HRESULT GetBool(
  BOOL *pValue
);

Parameters

pValue
[out] A pointer to the variable.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::GetBoolArray

Get an array of boolean variables.

HRESULT GetBoolArray(
  BOOL *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[out] A pointer to the first variable in the array.
Offset
[in] The offset (in elements) from the first element in the array to the element to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::GetFloat

Get a floating-point variable.

HRESULT GetFloat(
  float *pValue
);

Parameters

pValue
[out] A pointer to the variable.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::GetFloatArray

Get an array of floating-point variables.

HRESULT GetFloatArray(
  float *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[out] A pointer to the first variable in the array.
Offset
[in] The offset (in elements) from the first element in the array to the element to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::GetInt

Get an integer variable.

HRESULT GetInt(
  int *pValue
);

Parameters

pValue
[out] A pointer to the variable.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::GetIntArray

Get an array of integer variables.

HRESULT GetIntArray(
  int *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[out] A pointer to the first variable in the array.
Offset
[in] The offset (in elements) from the first element in the array to the element to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::SetBool

Set a boolean variable.

HRESULT SetBool(
  BOOL Value
);

Parameters

Value
[in] A pointer to the variable.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::SetBoolArray

Set an array of boolean variables.

HRESULT SetBoolArray(
  BOOL *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the first variable in the array.
Offset
[in] The offset (in elements) from the first element in the array to the element to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::SetFloat

Set a floating-point variable.

HRESULT SetFloat(
  float Value
);

Parameters

Value
[in] A pointer to the variable.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::SetFloatArray

Set an array of floating-point variables.

HRESULT SetFloatArray(
  float *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the first variable in the array.
Offset
[in] The offset (in elements) from the first element in the array to the element to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::SetInt

Set an integer variable.

HRESULT SetInt(
  int Value
);

Parameters

Value
[in] A pointer to the variable.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectScalarVariable::SetIntArray

Set an array of integer variables.

HRESULT SetIntArray(
  int *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the first variable in the array.
Offset
[in] The offset (in elements) from the first element in the array to the element to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectScalarVariable Interface


ID3D10EffectShaderResourceVariable Interface

The ID3D10EffectShaderResourceVariable interface accesses shader-resource variables.

Method | Description
ID3D10EffectShaderResourceVariable::GetResource | Get a shader resource.
ID3D10EffectShaderResourceVariable::GetResourceArray | Get an array of shader resources.
ID3D10EffectShaderResourceVariable::SetResource | Set a shader resource.
ID3D10EffectShaderResourceVariable::SetResourceArray | Set an array of shader resources.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectShaderResourceVariable::GetResource

Get a shader resource.

HRESULT GetResource(
  ID3D10ShaderResourceView **ppResource
);

Parameters

ppResource
[out] The address of a pointer to a shader-resource-view interface. See ID3D10ShaderResourceView Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectShaderResourceVariable Interface


ID3D10EffectShaderResourceVariable::GetResourceArray

Get an array of shader resources.

HRESULT GetResourceArray(
  ID3D10ShaderResourceView **ppResources,
  UINT Offset,
  UINT Count
);

Parameters

ppResources
[out] The address of an array of shader-resource-view interfaces. See ID3D10ShaderResourceView Interface.
Offset
[in] The zero-based array index to get the first interface.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectShaderResourceVariable Interface


ID3D10EffectShaderResourceVariable::SetResource

Set a shader resource.

HRESULT SetResource(
  ID3D10ShaderResourceView *pResource
);

Parameters

pResource
[in] The address of a pointer to a shader-resource-view interface. See ID3D10ShaderResourceView Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectShaderResourceVariable Interface


ID3D10EffectShaderResourceVariable::SetResourceArray

Set an array of shader resources.

HRESULT SetResourceArray(
  ID3D10ShaderResourceView **ppResources,
  UINT Offset,
  UINT Count
);

Parameters

ppResources
[out] The address of an array of shader-resource-view interfaces. See ID3D10ShaderResourceView Interface.
Offset
[in] The zero-based array index to get the first interface.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectShaderResourceVariable Interface


ID3D10EffectShaderVariable Interface

This ID3D10EffectShaderVariable interface accesses shader variables.

Method | Description
ID3D10EffectShaderVariable::GetGeometryShader | Get a geometry shader.
ID3D10EffectShaderVariable::GetInputSignatureElementDesc | Get a shader-input signature.
ID3D10EffectShaderVariable::GetOutputSignatureElementDesc | Get a shader-output signature.
ID3D10EffectShaderVariable::GetPixelShader | Get a pixel shader.
ID3D10EffectShaderVariable::GetShaderDesc | Get a shader description.
ID3D10EffectShaderVariable::GetVertexShader | Get a vertex shader.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectShaderVariable::GetGeometryShader

Get a geometry shader.

HRESULT GetGeometryShader(
  UINT ShaderIndex,
  ID3D10GeometryShader **ppGS
);

Parameters

ShaderIndex
[in] A zero-based index.
ppGS
[out] A pointer to a ID3D10GeometryShader Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectShaderResourceVariable Interface


ID3D10EffectShaderVariable::GetInputSignatureElementDesc

Get an input-signature description.

HRESULT GetInputSignatureElementDesc(
  UINT ShaderIndex,
  UINT Element,
  D3D10_SIGNATURE_PARAMETER_DESC *pDesc
);

Parameters

ShaderIndex
[in] A zero-based shader index.
Element
[in] A zero-based shader-element index.
pDesc
[in] A pointer to a parameter description (see D3D10_SIGNATURE_PARAMETER_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

An effect contains one or more shaders; each shader has an input and output signature; each signature contains one or more elements (or parameters). The shader index identifies the shader and the element index identifies the element (or parameter) in the shader signature.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectShaderResourceVariable Interface


ID3D10EffectShaderVariable::GetOutputSignatureElementDesc

Get an output-signature description.

HRESULT GetOutputSignatureElementDesc(
  UINT ShaderIndex,
  UINT Element,
  D3D10_SIGNATURE_PARAMETER_DESC *pDesc
);

Parameters

ShaderIndex
[in] A zero-based shader index.
Element
[in] A zero-based element index.
pDesc
[in] A pointer to a parameter description (see D3D10_SIGNATURE_PARAMETER_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

An effect contains one or more shaders; each shader has an input and output signature; each signature contains one or more elements (or parameters). The shader index identifies the shader and the element index identifies the element (or parameter) in the shader signature.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectShaderResourceVariable Interface


ID3D10EffectShaderVariable::GetPixelShader

Get a pixel shader.

HRESULT GetPixelShader(
  UINT ShaderIndex,
  ID3D10PixelShader **ppPS
);

Parameters

ShaderIndex
[in] A zero-based index.
ppPS
[out] A pointer to a ID3D10PixelShader Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectShaderResourceVariable Interface


ID3D10EffectShaderVariable::GetShaderDesc

Get a shader description.

HRESULT GetShaderDesc(
  UINT ShaderIndex,
  D3D10_EFFECT_SHADER_DESC *pDesc
);

Parameters

ShaderIndex
[in] A zero-based index.
pDesc
[in] A pointer to a shader description (see D3D10_EFFECT_SHADER_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectShaderResourceVariable Interface


ID3D10EffectShaderVariable::GetVertexShader

Get a vertex shader.

HRESULT GetVertexShader(
  UINT ShaderIndex,
  ID3D10VertexShader **ppVS
);

Parameters

ShaderIndex
[in] A zero-based index.
ppVS
[out] A pointer to a ID3D10VertexShader Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectShaderResourceVariable Interface


ID3D10EffectStringVariable Interface

The ID3D10EffectStringVariable interface accesses string variables.

Method | Description
ID3D10EffectStringVariable::GetString | Get a string.
ID3D10EffectStringVariable::GetStringArray | Get an array of strings.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectStringVariable::GetString

Get the string.

HRESULT GetString(
  LPCSTR *ppString
);

Parameters

ppString
[out] A pointer to the string.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectStringVariable Interface


ID3D10EffectStringVariable::GetStringArray

Get an array of strings.

HRESULT GetStringArray(
  LPCSTR *ppStrings,
  UINT Offset,
  UINT Count
);

Parameters

ppStrings
[out] A pointer to the first string in the array.
Offset
[in] The offset (in number of strings) between the start of the array and the first string to get.
Count
[in] The number of strings in the returned array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectStringVariable Interface


ID3D10EffectTechnique Interface

An ID3D10EffectTechnique interface is a collection of passes.

Method | Description
ID3D10EffectTechnique::ComputeStateBlockMask | Compute a state-block mask to allow/prevent state changes.
ID3D10EffectTechnique::GetAnnotationByIndex | Get an annotation by it's index.
ID3D10EffectTechnique::GetAnnotationByName | Get an annotation by it's name.
ID3D10EffectTechnique::GetDesc | Get a technique description.
ID3D10EffectTechnique::GetPassByIndex | Get a pass by it's index.
ID3D10EffectTechnique::GetPassByName | Get a pass by it's name.
ID3D10EffectTechnique::IsValid | Test a technique to see if it contains valid syntax.

An effect contains one or more techniques; each technique contains one or more passes; each pass contains state assignments (see Organizing State in an Effect (Direct3D 10)). The syntax for creating a technique is shown in Effect Technique Syntax (Direct3D 10).

To get an effect-technique interface, call a method like ID3D10Effect::GetTechniqueByName.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectTechnique::ComputeStateBlockMask

Compute a state-block mask to allow/prevent state changes.

HRESULT ComputeStateBlockMask(
  D3D10_STATE_BLOCK_MASK *pStateBlockMask
);

Parameters

pStateBlockMask
[in] A pointer to a state-block mask (see D3D10_STATE_BLOCK_MASK).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectTechnique Interface


ID3D10EffectTechnique::GetAnnotationByIndex

Get an annotation by it's index.

ID3D10EffectVariable* GetAnnotationByIndex(
  UINT Index
);

Parameters

Index
[in] The zero-based index of the interface pointer.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Remarks

Use an annotation to attach a piece of metadata to a technique.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectTechnique Interface


ID3D10EffectTechnique::GetAnnotationByName

Get an annotation by it's name.

ID3D10EffectVariable* GetAnnotationByName(
  LPCSTR Name
);

Parameters

Name
[in] Name of the annotation.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Remarks

Use an annotation to attach a piece of metadata to a technique.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectTechnique Interface


ID3D10EffectTechnique::GetDesc

Get a technique description.

HRESULT GetDesc(
  D3D10_TECHNIQUE_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to a technique description (see D3D10_TECHNIQUE_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectTechnique Interface


ID3D10EffectTechnique::GetPassByIndex

Get a pass by it's index.

ID3D10EffectPass* GetPassByIndex(
  UINT Index
);

Parameters

Index
[in] A zero-based index.

Return Values

A pointer to a ID3D10EffectPass Interface.

Remarks

A technique contains one or more passes; get a pass using it's name or an index.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectTechnique Interface


ID3D10EffectTechnique::GetPassByName

Get a pass by it's name.

ID3D10EffectPass* GetPassByName(
  LPCSTR Name
);

Parameters

Name
[in] The name of the pass.

Return Values

A pointer to an ID3D10EffectPass Interface.

Remarks

A technique contains one or more passes; get a pass using it's name or an index.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectTechnique Interface


ID3D10EffectTechnique::IsValid

Test a technique to see if it contains valid syntax.

BOOL IsValid();

Parameters

None.

Return Values

TRUE if the code syntax is valid; otherwise FALSE.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectTechnique Interface


ID3D10EffectType Interface

The ID3D10EffectType interface accesses effect variables by type.

Method | Description
ID3D10EffectType::GetDesc | Get a description.
ID3D10EffectType::GetMemberName | Get a member name.
ID3D10EffectType::GetMemberSemantic | Get a member semantic.
ID3D10EffectType::GetMemberTypeByIndex | Get a member type by it's index.
ID3D10EffectType::GetMemberTypeByName | Get a member type by it's name.
ID3D10EffectType::GetMemberTypeBySemantic | Get a member type by it's semantic.
ID3D10EffectType::IsValid | Test that the effect type is valid.

To get information about an effect type from an effect variable, call ID3D10EffectVariable::GetType.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectType::GetDesc

Get an effect-type description.

HRESULT GetDesc(
  D3D10_EFFECT_TYPE_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to an effect-type description. See D3D10_EFFECT_TYPE_DESC.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

The effect-variable description contains data about the name, annotations, semantic, flags and buffer offset of the effect type.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectType Interface


ID3D10EffectType::GetMemberName

Get the name of a member.

LPCSTR GetMemberName(
  UINT Index
);

Parameters

Index
[in] A zero-based index.

Return Values

The name of the member.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectType Interface


ID3D10EffectType::GetMemberSemantic

Get the semantic attached to a member.

LPCSTR GetMemberSemantic(
  UINT Index
);

Parameters

Index
[in] A zero-based index.

Return Values

A string that contains the semantic.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectType Interface


ID3D10EffectType::GetMemberTypeByIndex

Get a member type by it's index.

ID3D10EffectType* GetMemberTypeByIndex(
  UINT Index
);

Parameters

Index
[in] A zero-based index.

Return Values

A pointer to an ID3D10EffectType Interface.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectType Interface


ID3D10EffectType::GetMemberTypeByName

Get an member type by it's name.

ID3D10EffectType* GetMemberTypeByName(
  LPCSTR Name
);

Parameters

Name
[in] A member's name.

Return Values

A pointer to an ID3D10EffectType Interface.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectType Interface


ID3D10EffectType::GetMemberTypeBySemantic

Get a member type by it's semantic.

ID3D10EffectType* GetMemberTypeBySemantic(
  LPCSTR Semantic
);

Parameters

Semantic
[in] A semantic.

Return Values

A pointer to an Unknown Topic.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectType Interface


ID3D10EffectType::IsValid

Tests that the effect type is valid.

BOOL IsValid();

Parameters

None.

Return Values

TRUE if it is valid; otherwise FALSE.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectType Interface


ID3D10EffectVariable Interface

The ID3D10EffectVariable interface is the base class for all effect variables.

Method | Description
AsBlend | Cast the interface to an ID3D10EffectBlendVariable interface.
AsConstantBuffer | Cast the interface to an ID3D10EffectConstantBuffer interface.
AsDepthStencil | Cast the interface to an ID3D10EffectDepthStencilVariable interface.
AsMatrix | Cast the interface to an ID3D10EffectMatrixVariable interface.
AsRasterizer | Cast the interface to an ID3D10EffectRasterizerVariable interface.
AsSampler | Cast the interface to an ID3D10EffectSamplerVariable interface.
AsScalar | Cast the interface to an ID3D10EffectScalarVariable interface.
AsShader | Cast the interface to an ID3D10EffectShaderVariable interface.
AsShaderResource | Cast the interface to an ID3D10EffectShaderResourceVariable interface.
AsString | Cast the interface to an ID3D10EffectStringVariable interface.
AsVector | Cast the interface to an ID3D10EffectBlendVariable interface.
ID3D10EffectVariable::GetAnnotationByIndex | Get an annotation by it's index.
ID3D10EffectVariable::GetAnnotationByName | Get an annotation by it's name.
ID3D10EffectVariable::GetDesc | Get a descripion.
ID3D10EffectVariable::GetElement | Get an array element.
ID3D10EffectVariable::GetMemberByIndex | Get a structure member by it's index.
ID3D10EffectVariable::GetMemberByName | Get a structure member by it's name.
ID3D10EffectVariable::GetMemberBySemantic | Get a structure member by it's semantic.
ID3D10EffectVariable::GetParentConstantBuffer | Get a constant buffer.
ID3D10EffectVariable::GetRawValue | Get the value.
ID3D10EffectVariable::GetType | Get the type.
ID3D10EffectVariable::IsValid | Compare the data type with the data stored.
ID3D10EffectVariable::SetRawValue | Set the value.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectVariable::AsBlend

Get a effect-blend variable.

ID3D10EffectBlendVariable* AsBlend();

Parameters

None.

Return Values

A pointer to an effect blend variable. See ID3D10EffectBlendVariable.

Remarks

AsBlend returns a version of the effect variable that has been specialized to an effect-blend variable. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain effect-blend data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::AsConstantBuffer

Get a constant buffer.

ID3D10EffectConstantBuffer* AsConstantBuffer();

Parameters

None.

Return Values

A pointer to a constant buffer. See ID3D10EffectConstantBuffer.

Remarks

AsConstantBuffer returns a version of the effect variable that has been specialized to a constant buffer. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain constant buffer data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::AsDepthStencil

Get a depth-stencil variable.

ID3D10EffectDepthStencilVariable* AsDepthStencil();

Parameters

None.

Return Values

A pointer to a depth-stencil variable. See ID3D10EffectDepthStencilVariable.

Remarks

AsDepthStencil returns a version of the effect variable that has been specialized to a depth-stencil variable. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain depth-stencil data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::AsMatrix

Get a matrix variable.

ID3D10EffectMatrixVariable* AsMatrix();

Parameters

None.

Return Values

A pointer to a matrix variable. See ID3D10EffectMatrixVariable.

Remarks

AsMatrix returns a version of the effect variable that has been specialized to a matrix variable. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain matrix data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::AsRasterizer

Get a rasterizer variable.

ID3D10EffectRasterizerVariable* AsRasterizer();

Parameters

None.

Return Values

A pointer to a rasterizer variable. See ID3D10EffectRasterizerVariable.

Remarks

AsRasterizer returns a version of the effect variable that has been specialized to a rasterizer variable. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain rasterizer data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::AsSampler

Get a sampler variable.

ID3D10EffectSamplerVariable* AsSampler();

Parameters

None.

Return Values

A pointer to a sampler variable. See ID3D10EffectSamplerVariable.

Remarks

AsSampler returns a version of the effect variable that has been specialized to a sampler variable. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain sampler data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::AsScalar

Get a scalar variable.

ID3D10EffectScalarVariable* AsScalar();

Parameters

None.

Return Values

A pointer to a scalar variable. See ID3D10EffectScalarVariable.

Remarks

AsScalar returns a version of the effect variable that has been specialized to a scalar variable. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain scalar data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::AsShader

Get a shader variable.

ID3D10EffectShaderVariable* AsShader();

Parameters

None.

Return Values

A pointer to a shader variable. See ID3D10EffectShaderVariable.

Remarks

AsShader returns a version of the effect variable that has been specialized to a shader variable. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain shader data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::AsShaderResource

Get a shader-resource variable.

ID3D10EffectShaderResourceVariable* AsShaderResource();

Parameters

None.

Return Values

A pointer to a shader-resource variable. See ID3D10EffectShaderResourceVariable.

Remarks

AsShaderResource returns a version of the effect variable that has been specialized to a shader-resource variable. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain shader-resource data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::AsString

Get a string variable.

ID3D10EffectStringVariable* AsString();

Parameters

None.

Return Values

A pointer to a string variable. See ID3D10EffectStringVariable.

Remarks

AsString returns a version of the effect variable that has been specialized to a string variable. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain string data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::AsVector

Get a vector variable.

ID3D10EffectVectorVariable* AsVector();

Parameters

None.

Return Values

A pointer to a vector variable. See ID3D10EffectVectorVariable.

Remarks

AsVector returns a version of the effect variable that has been specialized to a vector variable. Similar to a cast, this specialization will return an invalid object if the effect variable does not contain vector data.

Applications can test the returned object for validity by calling IsValid.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::GetAnnotationByIndex

Get an annotation by it's index.

ID3D10EffectVariable* GetAnnotationByIndex(
  UINT Index
);

Parameters

Index
[in] A zero-based index.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Remarks

Annonations can be attached to a technique, a pass or a gloval variable. For the syntax, see Effect Annotation Syntax (Direct3D 10).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::GetAnnotationByName

Get an annotation by it's name.

ID3D10EffectVariable* GetAnnotationByName(
  LPCSTR Name
);

Parameters

Name
[in] The annotation name.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Remarks

Annonations can be attached to a technique, a pass or a gloval variable. For the syntax, see Effect Annotation Syntax (Direct3D 10).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::GetDesc

Get a description.

HRESULT GetDesc(
  D3D10_EFFECT_VARIABLE_DESC *pDesc
);

Parameters

pDesc
[in] A pointer to an effect-variable description (see D3D10_EFFECT_VARIABLE_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::GetElement

Get an array element.

ID3D10EffectVariable* GetElement(
  UINT Index
);

Parameters

Index
[in] A zero-based index; otherwise 0.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Remarks

If the effect variable is an array, use this method to return one of the elements.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::GetMemberByIndex

Get a structure member by it's index.

ID3D10EffectVariable* GetMemberByIndex(
  UINT Index
);

Parameters

Index
[in] A zero-based index.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Remarks

If the effect variable is an structure, use this method to look up a member by it's index.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::GetMemberByName

Get a structure member by it's name.

ID3D10EffectVariable* GetMemberByName(
  LPCSTR Name
);

Parameters

Name
[in] Member name.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Remarks

If the effect variable is an structure, use this method to look up a member by it's name.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::GetMemberBySemantic

Get a structure member by it's semantic.

ID3D10EffectVariable* GetMemberBySemantic(
  LPCSTR Semantic
);

Parameters

Semantic
[in] The semantic.

Return Values

A pointer to an ID3D10EffectVariable Interface.

Remarks

If the effect variable is an structure, use this method to look up a member by it's attached semantic.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::GetParentConstantBuffer

Get a constant buffer.

ID3D10EffectConstantBuffer* GetParentConstantBuffer();

Parameters

None.

Return Values

A pointer to a ID3D10EffectConstantBuffer Interface.

Remarks

Effect variables are read-from or written-to a constant buffer.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::GetRawValue

Get data.

HRESULT GetRawValue(
  void *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the variable.
Offset
[in] The offset (in bytes) from the beginning of the pointer to the data.
Count
[in] The number of bytes to get.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

This method does no conversion or type checking; it is therefore a very quick way to access array items.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::GetType

Get type information.

ID3D10EffectType* GetType();

Parameters

None.

Return Values

A pointer to an ID3D10EffectType Interface.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::IsValid

Compare the data type with the data stored.

BOOL IsValid();

Parameters

None.

Return Values

TRUE if the syntax is valid; otherwise FALSE.

Remarks

This method checks that the data type matches the data stored after casting one interface to another (using any of the As methods).

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVariable::SetRawValue

Set data.

HRESULT SetRawValue(
  void *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the variable.
Offset
[in] The offset (in bytes) from the beginning of the pointer to the data.
Count
[in] The number of bytes to set.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

This method does no conversion or type checking; it is therefore a very quick way to access array items.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVariable Interface


ID3D10EffectVectorVariable Interface

The ID3D10EffectVectorVariable interface accesses four-component vectors.

Method | Description
ID3D10EffectVectorVariable::GetBoolVector | Get a four-component vector that contains boolean data.
ID3D10EffectVectorVariable::GetBoolVectorArray | Get an array of four-component vectors that contain boolean data.
ID3D10EffectVectorVariable::GetFloatVector | Get a four-component vector that contains floating-point data.
ID3D10EffectVectorVariable::GetFloatVectorArray | Get an array of four-component vectors that contain floating-point data.
ID3D10EffectVectorVariable::GetIntVector | Get a four-component vector that contains integer data.
ID3D10EffectVectorVariable::GetIntVectorArray | Get an array of four-component vectors that contain integer data.
ID3D10EffectVectorVariable::SetBoolVector | Set a four-component vector that contains boolean data.
ID3D10EffectVectorVariable::SetBoolVectorArray | Set an array of four-component vectors that contain boolean data.
ID3D10EffectVectorVariable::SetFloatVector | Set a four-component vector that contains floating-point data.
ID3D10EffectVectorVariable::SetFloatVectorArray | Set an array of four-component vectors that contain floating-point data.
ID3D10EffectVectorVariable::SetIntVector | Set a four-component vector that contains integer data.
ID3D10EffectVectorVariable::SetIntVectorArray | Set an array of four-component vectors that contain integer data.

See Also

Effect Interfaces (Direct3D 10)


ID3D10EffectVectorVariable::GetBoolVector

Get a four-component vector that contains boolean data.

HRESULT GetBoolVector(
  BOOL *pData
);

Parameters

pData
[in] A pointer to the first component.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::GetBoolVectorArray

Get an array of four-component vectors that contain boolean data.

HRESULT GetBoolVectorArray(
  BOOL *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the first component of the first vector in the array.
Offset
[in] The offset (in vectors) between the beginning of the array and the first vector to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::GetFloatVector

Get a four-component vector that contains floating-point data.

HRESULT GetFloatVector(
  float *pData
);

Parameters

pData
[in] A pointer to the first component.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::GetFloatVectorArray

Get an array of four-component vectors that contain floating-point data.

HRESULT GetFloatVectorArray(
  float *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the first component of the first vector in the array.
Offset
[in] The offset (in vectors) between the beginning of the array and the first vector to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::GetIntVector

Get a four-component vector that contains integer data.

HRESULT GetIntVector(
  int *pData
);

Parameters

pData
[in] A pointer to the first component.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::GetIntVectorArray

Get an array of four-component vectors that contain integer data.

HRESULT GetIntVectorArray(
  int *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the first component of the first vector in the array.
Offset
[in] The offset (in vectors) between the beginning of the array and the first vector to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::SetBoolVector

Set a four-component vector that contains boolean data.

HRESULT SetBoolVector(
  BOOL *pData
);

Parameters

pData
[in] A pointer to the first component.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::SetBoolVectorArray

Set an array of four-component vectors that contain boolean data.

HRESULT SetBoolVectorArray(
  BOOL *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the first component of the first vector in the array.
Offset
[in] The offset (in vectors) between the beginning of the array and the first vector to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::SetFloatVector

Set a four-component vector that contains floating-point data.

HRESULT SetFloatVector(
  float *pData
);

Parameters

pData
[in] A pointer to the first component.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::SetFloatVectorArray

Set an array of four-component vectors that contain floating-point data.

HRESULT SetFloatVectorArray(
  float *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the first component of the first vector in the array.
Offset
[in] The offset (in vectors) between the beginning of the array and the first vector to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::SetIntVector

Set a four-component vector that contains integer data.

HRESULT SetIntVector(
  int *pData
);

Parameters

pData
[in] A pointer to the first component.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


ID3D10EffectVectorVariable::SetIntVectorArray

Set an array of four-component vectors that contain integer data.

HRESULT SetIntVectorArray(
  int *pData,
  UINT Offset,
  UINT Count
);

Parameters

pData
[in] A pointer to the first component of the first vector in the array.
Offset
[in] The offset (in vectors) between the beginning of the array and the first vector to set.
Count
[in] The number of elements in the array.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10.h.

See Also

ID3D10EffectVectorVariable Interface


Effect Functions (Direct3D 10)

This section contains information about the following effect functions:

Functions | Description
D3D10CompileEffectFromMemory | Compile an effect.
D3D10CreateEffectFromMemory | Create an effect.
D3D10CreateEffectPoolFromMemory | Create an effect pool.
D3D10CreateStateBlock | Create a state block.
D3D10DisassembleEffect | Disassemble a compiled effect into shader assembly instructions.
D3D10StateBlockMaskDifference | Combine two state-block masks with a bitwise XOR.
D3D10StateBlockMaskDisableAll | Disable state capturing.
D3D10StateBlockMaskDisableCapture | Disable state capturing with a state-block mask.
D3D10StateBlockMaskEnableAll | Enable a state-block mask to capture and apply all state variables.
D3D10StateBlockMaskEnableCapture | Enable a range of state values in a state block mask.
D3D10StateBlockMaskGetSetting | Get an element in a state-block mask.
D3D10StateBlockMaskIntersect | Combine two state-block masks with a bitwise AND.
D3D10StateBlockMaskUnion | Combine two state-block masks with a bitwise OR.

See Also

Effect Reference


D3D10CompileEffectFromMemory

Compile an effect.

HRESULT D3D10CompileEffectFromMemory(
  void *pData,
  SIZE_T DataLength,
  LPCSTR pSrcFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  ID3D10Include *pInclude,
  UINT HLSLFlags,
  UINT FXFlags,
  ID3D10Blob **ppCompiledEffect,
  ID3D10Blob **ppErrors
);

Parameters

pData
[in] A pointer to effect data; either ASCII HLSL code or a compiled effect.
DataLength
[in] Length of pData.
pSrcFileName
[in] The name of the effect file.
pDefines
[in] Optional. An array of NULL-terminated macro definitions (see D3D10_SHADER_MACRO).
pInclude
[in] Optional. A pointer to an ID3D10Include Interface for handling include files. Setting this to NULL will cause a compile error if a shader contains a #include.
HLSLFlags
[in] Shader compile options.
FXFlags
[in] Effect compile options.
ppCompiledEffect
[out] The address of a ID3D10Blob Interface that contains the compiled effect.
ppErrors
[out] Optional. A pointer to an ID3D10Blob Interface that contains compiler error messages, or NULL if there were no errors.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Effect.h.

See Also

Effect Functions (Direct3D 10)


D3D10CreateEffectFromMemory

Creates an effect from memory.

HRESULT D3D10CreateEffectFromMemory(
  void *pData,
  SIZE_T DataLength,
  UINT FXFlags,
  ID3D10Device *pDevice,
  ID3D10EffectPool *pEffectPool,
  ID3D10Effect **ppEffect
);

Parameters

pData
[in] A pointer to effect data; either ASCII HLSL code or a compiled effect.
DataLength
[in] Length of pData.
FXFlags
[in] Effect compile options.
pDevice
[in] A pointer to the device (see ID3D10Device Interface).
pEffectPool
[in] Optional. A pointer to an memory space for effect variables that are shared across effects (see ID3D10EffectPool Interface).
ppEffect
[out] A pointer to an ID3D10Effect Interface which contains the created effect.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Effect.h.

See Also

Effect Functions (Direct3D 10)


D3D10CreateEffectPoolFromMemory

Create an effect pool (or shared memory location), to enable sharing variables between effects.

HRESULT D3D10CreateEffectPoolFromMemory(
  void *pData,
  SIZE_T DataLength,
  UINT FXFlags,
  ID3D10Device *pDevice,
  ID3D10EffectPool **ppEffectPool
);

Parameters

pData
[in] A pointer to effect data; either ASCII HLSL code or a compiled effect.
DataLength
[in] Length of pData.
FXFlags
[in] Effect compile options.
pDevice
[in] A pointer to the device (see ID3D10Device Interface).
ppEffectPool
[out] A pointer to the ID3D10EffectPool Interface that contains the effect pool.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

A pool is a shared location in memory. Effect variables that are located in a pool can be updated once, and the effect system will take care of updating each effect that uses that variable. To pool an effect variable, tell the effect to locate the variable in a pool when the effect is created, using a helper function such as D3DX10CreateEffectFromFile.

Requirements

Header: Declared in D3D10Effect.h.

See Also

Effect Functions (Direct3D 10)


D3D10CreateStateBlock

Create a state block.

HRESULT D3D10CreateStateBlock(
  ID3D10Device *pDevice,
  D3D10_STATE_BLOCK_MASK *pStateBlockMask,
  ID3D10StateBlock **ppStateBlock
);

Parameters

pDevice
[in] The device for which the state block will be created.
pStateBlockMask
[in] Indicates which parts of the device state will be captured when calling ID3D10StateBlock::Capture and reapplied when calling ID3D10StateBlock::Apply. See remarks.
ppStateBlock
[out] Address of a pointer to the buffer created (see ID3D10StateBlock Interface).

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

A state block is a collection of device state, and is used for saving and restoring device state. Use a state-block mask to enable subsets of state for saving and restoring.

The D3D10_STATE_BLOCK_MASK structure can be filled manually or by using any of the D3D10StateBlockMaskXXX APIs. A state block mask can also be obtained by calling ID3D10EffectTechnique::ComputeStateBlockMask or ID3D10EffectPass::ComputeStateBlockMask.

Requirements

Header: Declared in D3D10Effect.h.

See Also

Core Functions


D3D10DisassembleEffect

Disassemble a compiled effect into shader assembly instructions.

HRESULT D3D10DisassembleEffect(
  ID3D10Effect *pEffect,
  BOOL EnableColorCode,
  ID3D10Blob **ppDisassembly
);

Parameters

pEffect
[in] A pointer to an ID3D10Effect Interface, which contains the compiled effect.
EnableColorCode
[in] Include HTML tags in the output to color code the result.
ppDisassembly
[out] A pointer to an ID3D10Blob Interface which contains the disassembled shader.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

This returned text includes a header with the version of the HLSL compiler used to generate this object, comments describing the memory layout of the constant buffers used by the shader, input and output signatures, and resource binding points.

Here is an example of disassembling a compiled effect. The example assumes you start with a compiled effect (shown as l_pBlob_Effect which you can see in Compile an Effect (Direct3D 10)).

LPCSTR commentString = NULL;
ID3D10Blob* pIDisassembly = NULL;
char* pDisassembly = NULL;
if( pVSBuf )
{
    D3D10DisassembleEffect( (UINT*) l_pBlob_Effect->GetBufferPointer(),
        l_pBlob_Effect->GetBufferSize(), TRUE, commentString, &pIDisassembly );
    if( pIDisassembly )
    {
        FILE* pFile = fopen( "effect.htm", "w" );
        if( pFile)
        {
            fputs( (char*)pIDisassembly->GetBufferPointer(), pFile );
            fclose( pFile );
        }
    }
}

Requirements

Header: Declared in D3D10Effect.h.

See Also

Effect Functions (Direct3D 10)


D3D10StateBlockMaskDifference

Combine two state-block masks with a bitwise XOR.

HRESULT D3D10StateBlockMaskDifference(
  D3D10_STATE_BLOCK_MASK *pA,
  D3D10_STATE_BLOCK_MASK *pB,
  D3D10_STATE_BLOCK_MASK *pResult
);

Parameters

pA
[in] State block mask on the left side of the bitwise XOR operation. See D3D10_STATE_BLOCK_MASK.
pB
[in] State block mask on the right side of the bitwise XOR operation.
pResult
[out] The result of the bitwise XOR operation.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Effect.h.

See Also

Core Functions


D3D10StateBlockMaskDisableAll

Disable all state capturing with a state-block mask.

HRESULT D3D10StateBlockMaskDisableAll(
  D3D10_STATE_BLOCK_MASK *pMask
);

Parameters

pMask
[out] A mask filled with all zeroes.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Effect.h.

See Also

Core Functions


D3D10StateBlockMaskDisableCapture

Disable state capturing with a state-block mask.

HRESULT D3D10StateBlockMaskDisableCapture(
  D3D10_STATE_BLOCK_MASK *pMask,
  D3D10_DEVICE_STATE_TYPES StateType,
  UINT RangeStart,
  UINT RangeLength
);

Parameters

pMask
[in, out] A state block mask.
StateType
[in] The type of device state to disable. See D3D10_DEVICE_STATE_TYPES.
RangeStart
[in] The lower end of the range of values to set to false.
RangeLength
[in] The upper end of the range of values to set to false.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

This is an example of how to call this function. It creates a mask that cannot capture and apply to geometry-shader samplers in slots 2 ~ 23.

D3D10_STATE_BLOCK_MASK stateBlockMask;
D3D10StateBlockMaskDisableCapture(&stateBlockMask,
                                 D3D10_DST_GS_SAMPLERS,
                                 2, 23);

Requirements

Header: Declared in D3D10Effect.h.

See Also

Core Functions


D3D10StateBlockMaskEnableAll

Enable a state-block mask to capture and apply all state variables.

HRESULT D3D10StateBlockMaskEnableAll(
  D3D10_STATE_BLOCK_MASK *pMask
);

Parameters

pMask
[out] A mask with everything turned on.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Effect.h.

See Also

Core Functions


D3D10StateBlockMaskEnableCapture

Enable a range of state values in a state block mask.

HRESULT D3D10StateBlockMaskEnableCapture(
  D3D10_STATE_BLOCK_MASK *pMask,
  D3D10_DEVICE_STATE_TYPES StateType,
  UINT RangeStart,
  UINT RangeLength
);

Parameters

pMask
[in, out] A state block mask.
StateType
[in] The type of device state to enable. See D3D10_DEVICE_STATE_TYPES.
RangeStart
[in] The lower end of the range of values to set to true.
RangeLength
[in] The upper end of the range of values to set to true.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

This is an example of how to call this function. It create a mask that can capture and apply to geometry-shader samplers in slots 2 ~ 23.

D3D10_STATE_BLOCK_MASK stateBlockMask;
D3D10StateBlockMaskEnableCapture(&stateBlockMask,
                                 D3D10_DST_GS_SAMPLERS,
                                 2, 23);

Requirements

Header: Declared in D3D10Effect.h.

See Also

Core Functions


D3D10StateBlockMaskGetSetting

Get an element in a state-block mask; determine if an element is allowed by the mask for capturing and applying.

BOOL D3D10StateBlockMaskGetSetting(
  D3D10_STATE_BLOCK_MASK *pMask,
  D3D10_DEVICE_STATE_TYPES StateType,
  UINT Entry
);

Parameters

pMask
[in] State block mask. See D3D10_STATE_BLOCK_MASK.
StateType
[in] The type of device state. See D3D10_DEVICE_STATE_TYPES.
Entry
[in] The entry within the device state. This is only relevant for state types that have more than one entry, such as D3D10_DST_GS_SAMPLERS.

Return Values

Returns true if the specified feature is allowed by the mask for capturing and applying, and false otherwise.

Requirements

Header: Declared in D3D10Effect.h.

See Also

Core Functions


D3D10StateBlockMaskIntersect

Combine two state-block masks with a bitwise AND.

HRESULT D3D10StateBlockMaskIntersect(
  D3D10_STATE_BLOCK_MASK *pA,
  D3D10_STATE_BLOCK_MASK *pB,
  D3D10_STATE_BLOCK_MASK *pResult
);

Parameters

pA
[in] State block mask on the left side of the bitwise AND operation. See D3D10_STATE_BLOCK_MASK.
pB
[in] State block mask on the right side of the bitwise AND operation.
pResult
[out] The result of the bitwise AND operation.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Effect.h.

See Also

Core Functions


D3D10StateBlockMaskUnion

Combine two state-block masks with a bitwise OR.

HRESULT D3D10StateBlockMaskUnion(
  D3D10_STATE_BLOCK_MASK *pA,
  D3D10_STATE_BLOCK_MASK *pB,
  D3D10_STATE_BLOCK_MASK *pResult
);

Parameters

pA
[in] State block mask on the left side of the bitwise OR operation. See D3D10_STATE_BLOCK_MASK.
pB
[in] State block mask on the right side of the bitwise OR operation.
pResult
[out] The result of the bitwise OR operation.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3D10Effect.h.

See Also

Core Functions


Effect Structures (Direct3D 10)

This section contains information about the following effect structures:

Structures | Description
D3D10_EFFECT_DESC | Describes an effect.
D3D10_EFFECT_SHADER_DESC | Describes an effect shader.
D3D10_EFFECT_TYPE_DESC | Describes an effect-variable type.
D3D10_EFFECT_VARIABLE_DESC | Describes an effect variable.
D3D10_PASS_DESC | Describes a pass.
D3D10_PASS_SHADER_DESC | Describes a shader variable.
D3D10_TECHNIQUE_DESC | Describes a technique.

See Also

Effect Reference


D3D10_EFFECT_DESC

Describes an effect.

typedef struct D3D10_EFFECT_DESC {
    BOOL IsChildEffect;
    UINT ConstantBuffers;
    UINT SharedConstantBuffers;
    UINT GlobalVariables;
    UINT SharedGlobalVariables;
    UINT Techniques;
} D3D10_EFFECT_DESC;

Members

IsChildEffect
TRUE if the effect is a child effect; otherwise FALSE.
ConstantBuffers
The number of constant buffers.
SharedConstantBuffers
The number of constant buffers shared in an effect pool.
GlobalVariables
The number of global variables.
SharedGlobalVariables
The number of global variables shared in an effect pool.
Techniques
The number of techniques.

Remarks

To get an effect description, call ID3D10Effect::GetDesc.

Requirements

Header: Declared in D3D10.h.

See Also

Effect Structures (Direct3D 10)


D3D10_EFFECT_SHADER_DESC

Describes an effect shader.

typedef struct D3D10_EFFECT_SHADER_DESC {
    CONST BYTE *pInputSignature;
    BOOL IsInline;
    CONST BYTE *pBytecode;
    UINT BytecodeLength;
    LPCSTR SODecl;
    UINT NumInputSignatureEntries;
    UINT NumOutputSignatureEntries;
} D3D10_EFFECT_SHADER_DESC;

Members

pInputSignature
Passed into CreateInputLayout. Only valid on a vertex shader or geometry shader. See ID3D10Device_CreateInputLayout.
IsInline
TRUE is the shader is defined inline; otherwise FALSE.
pBytecode
A pointer to the compiled shader.
BytecodeLength
The length of pBytecode.
SODecl
A string that constains a declaration of the stream output from a geometry shader.
NumInputSignatureEntries
The number of entries in the input signature.
NumOutputSignatureEntries
The number of entries in the output signature.

Remarks

To get an effect-shader description, call ID3D10EffectShaderVariable::GetShaderDesc.

Requirements

Header: Declared in D3D10.h.

See Also

Effect Structures (Direct3D 10)


D3D10_EFFECT_TYPE_DESC

Describes an effect-variable type.

typedef struct D3D10_EFFECT_TYPE_DESC {
    LPCSTR TypeName;
    D3D10_SHADER_VARIABLE_CLASS Class;
    D3D10_SHADER_VARIABLE_TYPE Type;
    UINT Elements;
    UINT Members;
    UINT Rows;
    UINT Columns;
    UINT PackedSize;
    UINT UnpackedSize;
    UINT Stride;
} D3D10_EFFECT_TYPE_DESC;

Members

TypeName
A string that contains the variable name.
Class
The variable class (see D3D10_SHADER_VARIABLE_CLASS).
Type
The variable type (see D3D10_SHADER_VARIABLE_TYPE).
Elements
The number of elements if the variable is an array; otherwise 0.
Members
The number of members if the variable is a structure; otherwise 0.
Rows
The number of rows if the variable is a matrix; otherwise 0.
Columns
The number of columns if the variable is a matrix; otherwise 0.
PackedSize
The number of bytes that the variable consumes when it is packed tightly by the compiler.
UnpackedSize
The number of bytes that the variable consumes before it is packed by the compiler.
Stride
The number of bytes between elements.

Remarks

To get an effect-variable type, call ID3D10EffectType::GetDesc.

Requirements

Header: Declared in D3D10.h.

See Also

Effect Structures (Direct3D 10)


D3D10_EFFECT_VARIABLE_DESC

Describes an effect variable.

typedef struct D3D10_EFFECT_VARIABLE_DESC {
    LPCSTR Name;
    LPCSTR Semantic;
    UINT Flags;
    UINT Annotations;
    UINT BufferOffset;
    UINT ExplicitBindPoint;
} D3D10_EFFECT_VARIABLE_DESC;

Members

Name
A string that contains the variable name.
Semantic
The semantic attached to the variable; otherwise NULL.
Flags
Optional flags for effect variables.
Annotations
The number of annotations; otherwise 0.
BufferOffset
The offset between the begining of the constant buffer and this variable; otherwise 0.
ExplicitBindPoint
The register that this variable is bound to. To bind a variable explicitly use the D3D10_EFFECT_VARIABLE_EXPLICIT_BIND_POINT flag.

Remarks

To get an effect-variable description, call ID3D10EffectVariable::GetDesc.

Requirements

Header: Declared in D3D10.h.

See Also

Effect Structures (Direct3D 10)


D3D10_PASS_DESC

Describes a pass.

typedef struct D3D10_PASS_DESC {
    LPCSTR Name;
    UINT Annotations;
    BYTE *pIAInputSignature;
    SIZE_T IAInputSignatureSize;
    UINT StencilRef;
    UINT SampleMask;
    FLOAT BlendFactor[4];
} D3D10_PASS_DESC;

Members

Name
A string that contains the name of the pass; otherwise NULL.
Annotations
The number of annotations.
pIAInputSignature
The input signature or the vertex shader; otherwise NULL.
IAInputSignatureSize
The dingature size in bytes.
StencilRef
Stencil reference value used in the depth-stencil state (see Configuring Depth-Stencil Functionality (Direct3D 10)).
SampleMask
Sample mask for the blend state (see Configuring Blending Functionality (Direct3D 10)).
BlendFactor
Blend factors (RGBA) for the blend state (see Configuring Blending Functionality (Direct3D 10)).

Remarks

And effect technique contains between 1 and n passes. To get a pass description, call ID3D10EffectPass::GetDesc.

Requirements

Header: Declared in D3D10.h.

See Also

Effect Structures (Direct3D 10)


D3D10_PASS_SHADER_DESC

Describes an effect variable that contains a shader.

typedef struct D3D10_PASS_SHADER_DESC {
    ID3D10EffectShaderVariable *pShaderVariable;
    UINT ShaderIndex;
} D3D10_PASS_SHADER_DESC;

Members

pShaderVariable
A pointer to the variable that the shader came from. If it is an inline shader assignment, the returned interface will be an anonymous shader variable, which is not retrievable any other way. Its name in the variable description will be "$Anonymous". If there is no assignment of this type in the pass block, this will point to a shader variable that returns false when IsValid is called.
ShaderIndex
A zero-based array index; otherwise 0.

Remarks

To get a shader description, call a method like ID3D10EffectPass::GetVertexShaderDesc.

Requirements

Header: Declared in D3D10.h.

See Also

Effect Structures (Direct3D 10)


D3D10_TECHNIQUE_DESC

Describes an effect technique.

typedef struct D3D10_TECHNIQUE_DESC {
    LPCSTR Name;
    UINT Passes;
    UINT Annotations;
} D3D10_TECHNIQUE_DESC;

Members

Name
A string that contains the technique name; otherwise NULL.
Passes
The number of passes in the technique.
Annotations
The number of annotations.

Remarks

To get a technique, call ID3D10EffectTechnique::GetDesc.

Requirements

Header: Declared in D3D10.h.

See Also

Effect Structures (Direct3D 10)


Effect Constants (Direct3D 10)

This section contains information about the effect constants:

Constants | Description
D3D10_EFFECT Constants | These constants are effect compiler options.
D3D10_EFFECT_VARIABLE Constants | These constants are effect variable properties.

See Also

Effect Reference


D3D10_EFFECT Constants

These constants used when creating an effect to define either compilation behavior or runtime effect behavior.

#define | Value | Description
D3D10_EFFECT_COMPILE_CHILD_EFFECT | 1 << 0 | Compile the .fx file to a child effect. Child effects have no initializes for any shared values because these are initialized in the effect pool.
D3D10_EFFECT_COMPILE_ALLOW_SLOW_OPS | 1 << 1 | By default, performance mode is enabled. Performance mode disallows mutable state objects by preventing non-literal expressions from appearing in state object definitions. Specifying this flag will disable the mode and allow for mutable state objects.
D3D10_EFFECT_SINGLE_THREADED | 1 << 3 | Do not attempt to synchronize with other threads loading effects into the same pool.

These constants are defined as macros in d3d10effect.h.

See Also

Effect Constants (Direct3D 10)


D3D10_EFFECT_VARIABLE Constants

These constants apply to effect variables.

#define | Description | Value
D3D10_EFFECT_VARIABLE_ANNOTATION | 1 << 0 | Indicates that this is an annotation or a global variable.
D3D10_EFFECT_VARIABLE_POOLED | 1 << 1 | Indicates that this variable or constant buffer resides in an effect pool. If this flag is not set, then the variable resides in a standalone effect or a child effect (standalone effects return false from ID3D10Effect::IsPool.
D3D10_EFFECT_VARIABLE_EXPLICIT_BIND_POINT | 1 << 2 | Indicates that the variable has been explicitly bound using the register keyword.

These flags are defined as macros in d3d10effect.h.

See Also

Effect Constants (Direct3D 10)


Effect Format (Direct3D 10)

An effect file (.fx) contains all of the pipeline state set by an effect. This conceptual diagram helps break down the types of information in an effect.

  • Effect Annotation Syntax (Direct3D 10)
  • Effect Function Syntax (Direct3D 10)
  • Effect Sampler Syntax (Direct3D 10)
  • Effect States (Direct3D 10)
  • Effect Technique Syntax (Direct3D 10)
  • Effect Variable Syntax (Direct3D 10)

Setting state in an effect requires mapping an effect state to the corresponding API element value. Here is a table of the mappings available Effect States (Direct3D 10).

See Also

Effect Reference


Effect Annotation Syntax (Direct3D 10)

An annotation is a user-defined piece of information, that is declared with the following syntax.

Syntax

< DataType AnnotationName [ = Initializer ];

Name | Description
DataType | Any basic type.
AnnotationName | An ASCII string.
Initializer | The initial value of the annotation.

Annotation are ignored by the effect system, and must be initialized.

Example

Here are some examples.

bool bAlphaBlend < int maxAlpha = 255; >


Effect Function Syntax (Direct3D 10)

An effect function is written in HLSL and is declared with the following syntax.

Syntax

ReturnType FunctionName  ( [ ParameterList ] )
{
  [ StatementBlock ]
};

Name | Description
ReturnType | Any HLSL type
FunctionName | An ASCII string that uniquely identifies the name of the shader function.
ParameterList | One or more parameters separated by commas. See Function Parameter List Syntax (Direct3D 10 HLSL).
StatementBlock | One or more statements that make up the body of the function. See Statement Block Syntax (Direct3D 10 HLSL). If a function is defined without a body, it is considered to be a prototype. The function must be redefined, with a body, later on in the code.

An effect function may be a shader or it may simply be a function called by a shader. A function is uniquely identified by its name, the types of its parameters, and the target platform; therefore, functions can be overloaded.

Example

The BasicHLSL10 Sample uses both a pixel shader and a vertex shader. The pixel shader function is called RenderScenePS and is shown below.

PS_OUTPUT RenderScenePS( VS_OUTPUT In,
                         uniform bool bTexture )
{
    PS_OUTPUT Output;

    // Lookup mesh texture and modulate it with diffuse
    if( bTexture )
        Output.RGBColor = g_MeshTexture.Sample(MeshTextureSampler, In.TextureUV) *
                              In.Diffuse;
    else
        Output.RGBColor = In.Diffuse;

    return Output;
}


Effect Sampler Syntax (Direct3D 10)

A texture sampler defines how a texture is sampled using a combination of sampler state with the following syntax.

Syntax

SamplerState SamplerName
{
  RenderState = RenderStateValue;
  RenderState = RenderStateValue;
  ...
};

Name | Description
SamplerName | An ASCII string.
RenderState | Render-state name.
RenderStateValue | Render-state value.

Example

The BasicHLSL10 Sample uses global variables without semantics for material colors, light properties and transformation matrices.

This example illustrates global effect variables.

Texture2D g_MeshTexture;            // Color texture for mesh

The last variable represents a texture. A texture requires a texture sampler, go here to see sampler state syntax.

SamplerState MeshTextureSampler
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};


Effect States (Direct3D 10)

Effect states are name value pairs in the form of an expression. For example:

FILTER = D3D10_FILTER_MIN_MAG_MIP_POINT;

The left hand side of the expression is an effect state name; the right hand side is an API element value.

Blend State

ALPHATOCOVERAGEENABLE

BLENDENABLE

SRCBLEND

DESTBLEND

BLENDOP

SRCBLENDALPHA

DESTBLENDALPHA

BLENDOPALPHA

RENDERTARGETWRITEMASK 		Members of D3D10_BLEND_DESC

Depth and Stencil State

DEPTHENABLE DEPTHWRITEMASK DEPTHFUNC STENCILENABLE STENCILREADMASK STENCILWRITEMASK | Members of D3D10_DEPTH_STENCIL_DESC
FRONTFACESTENCILFAIL FRONTFACESTENCILZFAIL FRONTFACESTENCILPASS FRONTFACESTENCILFUNC BACKFACESTENCILFAIL BACKFACESTENCILZFAIL BACKFACESTENCILPASS BACKFACESTENCILFUNC | Member of D3D10_DEPTH_STENCILOP_DESC

Rasterizer State

FILLMODE | D3D10_FILL_MODE
CULLMODE | D3D10_CULL_MODE
FRONTCOUNTERCLOCKWISE DEPTHBIAS DEPTHBIASCLAMP SLOPESCALEDDEPTHBIAS ZCLIPENABLE SCISSORENABLE MULTISAMPLEENABLE ANTIALIASEDLINEENABLE | Members of D3D10_RASTERIZER_DESC

Sampler State

FILTER ADDRESSU ADDRESSV ADDRESSW MIPMAPLODBIAS MAXANISOTROPY COMPARISONFUNC BORDERCOLORR BORDERCOLORG BORDERCOLORB BORDERCOLORA MINLOD MAXLOD | Members of D3D10_SAMPLER_DESC
TEXTURE |

Effect Objects

This Effect Object | Maps to
RASTERIZERSTATE | An object that contains all of the Rasterizer State states.
DEPTHSTENCILSTATE | An object that contains all of the Depth and Stencil State states.
BLENDSTATE | An object that contains all of the Blend State states.
VERTEXSHADER | An object that contains a compiled vertex shader.
PIXELSHADER | An object that contains a compiled pixel shader.
GEOMETRYSHADER | An object that contains a compiled geometry shader.
DS_STENCILREF AB_BLENDFACTOR AB_SAMPLEMASK | D3D10_PASS_DESC

See Also

Effect Format (Direct3D 10)


Effect Technique Syntax (Direct3D 10)

An effect technique is declared with the following syntax.

Syntax

technique10 TechniqueName < Annotations >
{
    pass PassName
    {
       [ SetStateGroup; ]
       [ SetStateGroup; ]
       ...
       [ SetStateGroup; ]
    }
}
Name | Description
TechniqueName | Optional. An ASCII string that uniquely identifies the name of the effect technique.
< Annotations > | Optional. One or more pieces of user-supplied information (metadata) that is ignored by the effect system. For syntax, see Effect Annotation Syntax (Direct3D 10).
PassName | Optional. An ASCII string that uniquely identifies the name of the pass.
SetStateGroup Set one or more groups of state. The groups of state that can be set include:
  • Blend state. The syntax for this is:
    SetBlendState( arguments );

    See ID3D10Device::OMSetBlendState for the argument list.

  • Depth-stencil state. The syntax for this is:
    SetDepthStencilState( arguments );

    See ID3D10Device::OMSetDepthStencilState for the argument list.

  • Compiled shader statements. The syntax for this is:
    SetXXXShader( CompileShader( shader_profile, ShaderFunction( args ) ) );
or
SetXXXShader( CompileShader( NULL ) );
or
SetXXXShader( NULL );

    SetXXXShader is one of ID3D10Device::VSSetShader, ID3D10Device::GSSetShader, or ID3D10Device::PSSetShader.

Example

Here is an example of setting shaders in a technique. This example is from BasicHLSL10 Sample, which uses a vertex and pixel shader.

technique10 RenderSceneWithTexture1Light
{
    pass P0
    {
        SetVertexShader( CompileShader( vs_4_0, RenderSceneVS( 1, true, true ) ) );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_4_0, RenderScenePS( true ) ) );
    }
}

Here is an example of setting effect state in a technique to render an object in wireframe.

RasterizerState rsWireframe { FillMode = WireFrame; };

...

technique10
{
    pass p1
    {
        ....
        SetRasterizerState( rsWireframe );
    }
}

Here is an example from CubeMapGS Sample for setting blending state.

BlendState NoBlend
{
    BlendEnable[0] = False;
};

...

technique10
{
    pass p2
    {
        ...
        SetBlendState( NoBlend, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
    }
}


Effect Variable Syntax (Direct3D 10)

An effect variable is declared with the following syntax.

Syntax

DataType VariableName [ : SemanticName ] < Annotations >;

Name | Description
DataType | Any basic or texture type.
VariableName | An ASCII string that uniquely identifies the name of the effect variable.
SemanticName | A ASCII string that denotes additional information about how a variable should be used. A semantic is an ASCII string that can be either a predefined system-value or a custom-user string.
Annotations | One or more pieces of user-supplied information (metadata) that is ignored by the effect system. For syntax, see Effect Annotation Syntax (Direct3D 10).

An effect variable that is declared outside of all functions, is considered global in scope; variables declared within a function are local to that function.

Example

The BasicHLSL10 Sample uses global variables without semantics for material colors, light properties and transformation matrices.

This example illustrates global effect variables.

float4 g_MaterialAmbientColor;      // Material's ambient color
float4 g_MaterialDiffuseColor;      // Material's diffuse color
float3 g_LightDir[3];               // Light's direction in world space
float4x4 g_mWorld;                  // World matrix for object

This example illustrates effect variables that are local to a shader function.

VS_OUTPUT RenderSceneVS( ... )
{
    float3 vNormalWorldSpace;
    float4 vAnimatedPos;

    // shader body
}

This example illustrates function parameters that have semantics.

VS_OUTPUT RenderSceneVS( float4 vPos : SV_POSITION,
                         float3 vNormal : NORMAL,
                         float2 vTexCoord0 : TEXCOORD0,
                         uniform int nNumLights,
                         uniform bool bTexture,
                         uniform bool bAnimate )
{
  ...
}

This example illustrates declaring a texture variable.

Texture2D g_MeshTexture;            // Color texture for mesh

Sampling a texture is done with a texture sampler. To set up a sampler in an effect, see sampler state syntax .


Direct3D 10 Return Codes

The following table contains return codes from API functions.

HRESULT | Description
D3D10_ERROR_FILE_NOT_FOUND | The file was not found.
D3D10_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS | There are too many unique instances of a particular type of state object.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may not be a valid pointer.
D3DERR_WASSTILLDRAWING | The previous blit operation that is transferring information to or from this surface is incomplete.
E_FAIL | Attempted to create a device with the debug layer enabled and the layer is not installed.
E_INVALIDARG | An invalid parameter was passed to the returning function.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.
S_FALSE | Alternate success value, indicating a successful but nonstandard completion (the precise meaning depends on context).
S_OK | No error occurred.

See Also

Direct3D Reference


D3DX Reference

This section contains the following sections:

  • D3DX Interfaces
  • D3DX Functions
  • D3DX Structures
  • D3DX Enumerations


D3DX Interfaces

D3DX contains the following interfaces:

Figure 1. D3DX10 Interface Inheritance Tree

This section contains reference information for the component object model (COM) interfaces provided by the D3DX utility library. The following interfaces are used with the D3DX utility library:

Interfaces | Description
ID3DX10DataLoader Interface | Data loading object used by ID3DX10ThreadPump Interface for loading data asynchronously.
ID3DX10DataProcessor Interface | Data processing object used by ID3DX10ThreadPump Interface for processing loaded data asynchronously.
ID3DX10Font Interface | The ID3DX10Font interface encapsulates the textures and resources needed to render a specific font on a specific device.
ID3DX10Mesh Interface | Applications use the methods of the ID3DX10Mesh interface to manipulate mesh objects.
ID3DX10MeshBuffer Interface |
ID3DX10SkinInfo Interface | ID3DX10SkinInfo allows you to optimize, process, and manually set the relationship between bones and vertices in your meshes (see Skeletal Animation on Wikipedia). It is most useful for making .x files exported by DCC Apps (such as 3DS Max and Maya) more hardware-friendly, and for improving the render speed of your skinned meshes in software render mode.
ID3DX10Sprite Interface | The ID3DX10Sprite interface provides a set of methods that simplify the process of drawing sprites using Microsoft Direct3D.
ID3DX10ThreadPump Interface | Used to execute tasks asynchronously. This object takes up a substantial amount of resources, so generally only one should be created per application.
ID3DXMatrixStack Interface | Applications use the methods of the ID3DXMATRIXStack interface to manipulate a matrix stack.


ID3DX10DataLoader Interface

Data loading object used by ID3DX10ThreadPump Interface for loading data asynchronously.

ID3DX10DataLoader Members

Method | Description
ID3DX10DataLoader::Decompress | Used to decompress encoded data.
ID3DX10DataLoader::Destroy | Used by a ID3DX10ThreadPump Interface to destroy the loader after a work item completes.
ID3DX10DataLoader::Load | Used by a ID3DX10ThreadPump Interface to load data from a disk.

Remarks

This object can be inherited and its members redefined. Doing so would enable you to customize the API for loading and decompressing your own custom file formats.

See Also

D3DX Interfaces


ID3DX10DataLoader::Decompress

Used to decompress encoded data. Typically this would be used to load resources from file systems, such as ZIP files. When loading from an uncompressed resource, the decompression stage does not have to do any work.

HRESULT Decompress(
  void **ppData,
  SIZE_T *pcBytes
);

Parameters

ppData
[out] Pointer to the raw data to decompress.
pcBytes
[in] The size of the data pointed to by ppData.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

ID3DX10DataLoader Interface can be inherited and its members redefined. Decompress could be redefined to support your own custom file formats.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10DataLoader::Destroy

Used by a ID3DX10ThreadPump Interface to destroy the loader after a work item completes.

HRESULT Destroy();

Parameters

None.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10DataLoader::Load

Used by a ID3DX10ThreadPump Interface to load data from a disk.

HRESULT Load();

Parameters

None.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10DataProcessor Interface

Data processing object used by ID3DX10ThreadPump Interface for processing loaded data asynchronously.

ID3DX10DataProcessor Members

Method | Description
ID3DX10DataProcessor::CreateDeviceObject | Create a device object.
ID3DX10DataProcessor::Destroy | Used by a ID3DX10ThreadPump Interface to destroy the processor after a work item completes.
ID3DX10DataProcessor::Process | Process some data.

Remarks

This object can be inherited and its members redefined. Doing so would enable you to customize the API for processing your own custom file formats.

See Also

D3DX Interfaces


ID3DX10DataProcessor::CreateDeviceObject

Create a device object.

HRESULT CreateDeviceObject(
  void **ppDataObject
);

Parameters

ppDataObject
[out] Address of a pointer to the created device object.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10DataProcessor::Destroy

Used by a ID3DX10ThreadPump Interface to destroy the processor after a work item completes.

HRESULT Destroy();

Parameters

None.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10DataProcessor::Process

Process some data.

HRESULT Process(
  void *pData,
  SIZE_T cBytes
);

Parameters

pData
[in] Pointer to the data to be processed.
cBytes
[in] Size of the data to be processed.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Font Interface

The ID3DX10Font interface encapsulates the textures and resources needed to render a specific font on a specific device.

ID3DX10Font Members

Method | Description
ID3DX10Font::DrawText | Draw formatted text. This method supports ANSI and Unicode strings.
ID3DX10Font::GetDC | Return a handle to a display device context (DC) that has the font set.
ID3DX10Font::GetDesc | Get a description of the current font object. GetDescW and GetDescA are identical to this method, except that a pointer is returned to a D3DX10FONT_DESCW or D3DX10FONT_DESCA structure, respectively.
ID3DX10Font::GetDevice | Retrieve the Direct3D device associated with the font object.
ID3DX10Font::GetGlyphData | Return information about the placement and orientation of a glyph in a character cell.
ID3DX10Font::GetTextMetrics | Retrieve font characteristics. This method supports ANSI and Unicode compiler settings.
ID3DX10Font::PreloadCharacters | Load a series of characters into video memory to improve the efficiency of rendering to the device.
ID3DX10Font::PreloadGlyphs | Load a series of glyphs into video memory to improve the efficiency of rendering to the device.
ID3DX10Font::PreloadText | Load formatted text into video memory to improve the efficiency of rendering to the device. This method supports ANSI and Unicode strings.

Remarks

The ID3DX10Font interface is obtained by calling D3DX10CreateFont or D3DX10CreateFontIndirect.

The LPD3DX10FONT type is defined as a pointer to the ID3DX10Font interface.

typedef interface ID3DX10Font ID3DX10Font;
typedef interface ID3DX10Font *LPD3DX10FONT;

See Also

D3DX Interfaces


ID3DX10Font::DrawText

Draw formatted text. This method supports ANSI and Unicode strings.

INT DrawText(
  LPD3DX10SPRITE pSprite,
  LPCTSTR pString,
  INT Count,
  LPRECT pRect,
  UINT Format,
  D3DXCOLOR Color
);

Parameters

pSprite
[in] Pointer to an ID3DX10Sprite object that contains the string you wish to draw. Can be NULL, in which case Direct3D will render the string with its own sprite object. To improve efficiency, a sprite object should be specified if ID3DX10Font::DrawText is to be called more than once in a row.
pString
[in] Pointer to a string to draw. If UNICODE is defined, this parameter type resolves to an LPCWSTR, otherwise, the type resolves to an LPCSTR. If the Count parameter is -1, the string must be NULL terminated.
Count
[in] The number of characters in the string. If Count is -1, then the pString parameter is assumed to be a pointer to a sprite containing a NULL-terminated string and ID3DX10Font::DrawText computes the character count automatically.
pRect
[in] Pointer to a RECT structure that contains the rectangle, in logical coordinates, in which the text is to be formatted. As with any RECT object, the coordinate value of the rectangle's right side must be greater than that of its left side. Likewise, the coordinate value of the bottom must be greater than that of the top.
Format
[in] Specify the method of formatting the text. It can be any combination of the following values:
DT_BOTTOM
Justify the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.
DT_CALCRECT
Tell DrawText to automatically calculate the width and height of the rectangle based on the length of the string you tell it to draw. If there are multiple lines of text, ID3DX10Font::DrawText uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, ID3DX10Font::DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, ID3DX10Font::DrawText returns the height of the formatted text but does not draw the text.
DT_CENTER
Center text horizontally in the rectangle.
DT_EXPANDTABS
Expand tab characters. The default number of characters per tab is eight.
DT_LEFT
Align text to the left.
DT_NOCLIP
Draw without clipping. ID3DX10Font::DrawText is somewhat faster when DT_NOCLIP is used.
DT_RIGHT
Align text to the right.
DT_RTLREADING
Display text in right-to-left reading order for bidirectional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.
DT_SINGLELINE
Display text on a single line only. Carriage returns and line feeds do not break the line.
DT_TOP
Top-justify text.
DT_VCENTER
Center text vertically (single line only).
DT_WORDBREAK
Break words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.
Color
[in] Color of the text. See D3DXCOLOR.

Return Values

If the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from pRect (top to the bottom) of the drawn text. If the function fails, the return value is zero.

Remarks

The parameters of this method are very similar to those of the GDI DrawText function.

This method supports both ANSI and Unicode strings.

This method must be called inside a ID3D10Device::BeginScene ... ID3D10Device::EndScene block. The only exception is when an application calls ID3DX10Font::DrawText with DT_CALCRECT to calculate the size of a given block of text.

Unless the DT_NOCLIP format is used, this method clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified.

If the selected font is too large for the rectangle, this method does not attempt to substitute a smaller font.

This method supports only fonts whose escapement and orientation are both zero.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Font::GetDC

Return a handle to a display device context (DC) that has the font set onto it.

HDC GetDC();

Parameters

None.

Return Values

Handle to a display DC.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Font::GetDesc

Get a description of the current font object.

HRESULT GetDesc(
  D3DX10FONT_DESC *pDesc
);

Parameters

pDesc
[in] Pointer to a D3DX10_FONT_DESC structure that describes the font object. If UNICODE is defined, a pointer to a D3DX10FONT_DESCW is returned; otherwise a pointer to a D3DX10FONT_DESCA is returned.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

This method describes Unicode font objects if UNICODE is defined. Otherwise GetDescA is called, which returns a pointer to the D3DX10FONT_DESCA structure.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Font::GetDevice

Retrieve the Direct3D device associated with the font object.

HRESULT GetDevice(
  ID3D10Device **ppDevice
);

Parameters

ppDevice
[out] Address of a pointer to an ID3D10Device interface, representing the Direct3D device object associated with the font object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

Note Calling this method will increase the internal reference count on the ID3D10Device interface. Be sure to call IUnknown when you are done using this ID3D10Device interface or you will have a memory leak.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Font::GetGlyphData

Return information about the placement and orientation of a glyph in a character cell.

HRESULT GetGlyphData(
  UINT Glyph,
  ID3D10ShaderResourceView **ppTexture,
  RECT *pBlackBox,
  POINT *pCellInc
);

Parameters

Glyph
[in] Glyph identifier.
ppTexture
[out] Address of a pointer to a ID3D10Texture object that contains the glyph.
pBlackBox
[in] Pointer to the smallest rectangle object that completely encloses the glyph. See RECT.
pCellInc
[in] Pointer to the two-dimensional vector that connects the origin of the current character cell to the origin of the next character cell. See POINT.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Font::GetTextMetrics

Retrieve font characteristics.

BOOL GetTextMetrics(
  TEXTMETRIC *pTextMetrics
);

Parameters

pTextMetrics
[in] Pointer to a TEXTMETRIC structure, which contains font properties. If Unicode is defined, the function returns a TEXTMETRICW structure. Otherwise, the function returns a TEXTMETRICA structure.

Return Values

Nonzero if the function is successful; otherwise 0.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Font::PreloadCharacters

Load a series of characters into video memory to improve the efficiency of rendering to the device.

HRESULT PreloadCharacters(
  UINT First,
  UINT Last
);

Parameters

First
[in] ID of the first character to be loaded into video memory.
Last
[in] ID of the last character to be loaded into video memory.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

This method generates textures containing glyphs that represent the input characters. The glyphs are drawn as a series of triangles.

Characters will not be rendered to the device; ID3DX10Font::DrawText must still be called to render the characters. However, by pre-loading characters into video memory, ID3DX10Font::DrawText will use substantially fewer CPU resources.

This method internally converts characters to glyphs using the GDI function GetCharacterPlacement.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Font::PreloadGlyphs

Load a series of glyphs into video memory to improve the efficiency of rendering to the device.

HRESULT PreloadGlyphs(
  UINT First,
  UINT Last
);

Parameters

First
[in] ID of the first glyph to be loaded into video memory.
Last
[in] ID of the last glyph to be loaded into video memory.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

This method generates textures that contain the input glyphs. The glyphs are drawn as a series of triangles.

Glyphs will not be rendered to the device; ID3DX10Font::DrawText must still be called to render the glyphs. However, by pre-loading glyphs into video memory, ID3DX10Font::DrawText will use substantially fewer CPU resources.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Font::PreloadText

Load formatted text into video memory to improve the efficiency of rendering to the device. This method supports ANSI and Unicode strings.

HRESULT PreloadText(
  LPCSTR pString,
  INT Count
);

Parameters

pString
[in] Pointer to a string of characters to be loaded into video memory. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR; otherwise, the data type resolves to LPCSTR. See Remarks.
Count
[in] Number of characters in the text string.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to PreloadTextW. Otherwise, the function call resolves to PreloadTextA because ANSI strings are being used.

This method generates textures that contain glyphs that represent the input text. The glyphs are drawn as a series of triangles.

Text will not be rendered to the device; ID3DX10Font::DrawText must still be called to render the text. However, by preloading text into video memory, ID3DX10Font::DrawText will use substantially fewer CPU resources.

This method internally converts characters to glyphs using the GDI function GetCharacterPlacement.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh Interface

Applications use the methods of the ID3DX10Mesh interface to manipulate mesh objects.

ID3DX10Mesh Members

Method | Description
ID3DX10Mesh::CloneMesh | Creates a new mesh and fills it with the data of a previously loaded mesh.
ID3DX10Mesh::CommitToDevice | Commit any changes made to a mesh to the device so that the changes can be rendered. This should be called after a mesh's data is altered and before it is rendered. A mesh cannot be rendered unless it is committed to the device. See remarks.
ID3DX10Mesh::Discard | Removes mesh data from the device that has been committed to the device (with ID3DX10Mesh::CommitToDevice).
ID3DX10Mesh::DrawSubset | Draws a subset of a mesh.
ID3DX10Mesh::DrawSubsetInstanced | Draw several instances of the same subset of a mesh.
ID3DX10Mesh::GenerateAdjacencyAndPointReps | Generate a list of mesh edges, as well as a list of faces that share each edge.
ID3DX10Mesh::GenerateAttributeBufferFromTable | Generate an attribute buffer from the data in the mesh's attribute table. An attribute buffer is another format for storing the data in the attribute table. Both the attribute buffer and the attribute table are internal data structures in the mesh.
ID3DX10Mesh::GenerateGSAdjacency | Adds adjacency data to the mesh's index buffer. When the mesh is to be sent to a geometry shader that takes adjacency data, it is neccessary for the mesh's index buffer to contain adjacency data.
ID3DX10Mesh::GetAdjacencyBuffer | Access the mesh's adjacency buffer.
ID3DX10Mesh::GetAttributeBuffer | Access the mesh's attribute buffer.
ID3DX10Mesh::GetAttributeTable | Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.
ID3DX10Mesh::GetDeviceIndexBuffer | Access the mesh's index buffer after it has been committed to the device with ID3DX10Mesh::CommitToDevice. This is different from ID3DX10Mesh::GetIndexBuffer, which returns the index buffer before it has been committed to the device.
ID3DX10Mesh::GetDeviceVertexBuffer | Access the mesh's vertex buffer after it has been committed to the device with ID3DX10Mesh::CommitToDevice. This is different from ID3DX10Mesh::GetVertexBuffer, which returns the vertex buffer before it has been committed to the device.
ID3DX10Mesh::GetFaceCount | Retrieves the number of faces in the mesh.
ID3DX10Mesh::GetFlags | Access the mesh's creation flags.
ID3DX10Mesh::GetIndexBuffer | Retrieves the data in an index buffer.
ID3DX10Mesh::GetPointRepBuffer | Get the mesh's point rep buffer.
ID3DX10Mesh::GetVertexBuffer | Retrieves the vertex buffer associated with the mesh.
ID3DX10Mesh::GetVertexBufferCount | Get the number of vertex buffers in the mesh.
ID3DX10Mesh::GetVertexCount | Get the number of vertices in the mesh. A mesh may contain multiple vertex buffers (i.e. one vertex buffer may contain all position data, another may contains all texture coordinate data, etc.), however each vertex buffer will contain the same number of elements.
ID3DX10Mesh::GetVertexDescription | Access the vertex description passed into D3DX10CreateMesh. The vertex description describes the layout of the mesh's vertex buffers.
ID3DX10Mesh::Intersect | Determines if a ray intersects with this mesh.
ID3DX10Mesh::IntersectSubset | Determines if a ray intersects with a subset of this mesh.
ID3DX10Mesh::Optimize | Generates a new mesh with reordered faces and vertices to optimize drawing performance.
ID3DX10Mesh::SetAdjacencyData | Set the mesh's adjacency data.
ID3DX10Mesh::SetAttributeData | Set the mesh's attribute data.
ID3DX10Mesh::SetAttributeTable | Sets the attribute table for a mesh and the number of entries stored in the table.
ID3DX10Mesh::SetIndexData | Set the mesh's index data.
ID3DX10Mesh::SetPointRepData | Set the point rep data for the mesh.
ID3DX10Mesh::SetVertexData | Set vertex data into one of the mesh's vertex buffers.

Remarks

To obtain the ID3DX10Mesh interface, call D3DX10CreateMesh.

See Also

D3DX Interfaces


ID3DX10Mesh::CloneMesh

Creates a new mesh and fills it with the data of a previously loaded mesh.

HRESULT CloneMesh(
  UINT Flags,
  LPCSTR pPosSemantic,
  CONST D3D10_INPUT_ELEMENT_DESC *pDesc,
  UINT DeclCount,
  ID3DX10Mesh **ppCloneMesh
);

Parameters

Flags
[in] Creation flags to be applied to the new mesh. See D3DX10_MESH.
pPosSemantic
[in] The semantic name for the position data.
pDesc
[in] Array of D3D10_INPUT_ELEMENT_DESC structures, describing the vertex format for the returned mesh. See D3D10_INPUT_ELEMENT_DESC.
DeclCount
[in] The number of elements in the pDesc array.
ppCloneMesh
[out] The new mesh.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::CommitToDevice

Commit any changes made to a mesh to the device so that the changes can be rendered. This should be called after a mesh's data is altered and before it is rendered. A mesh cannot be rendered unless it is committed to the device. See remarks.

HRESULT CommitToDevice();

Parameters

None.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

When a mesh is loaded, it's data is loaded into staging resources, meaning the data can be altered but not rendered. When CommitToDevice is called, the data from the staging resources are copied into device resources so that they can be rendered. Although the data is committed to the device, the staging resources remain and can be modified. If any modifications are made to the staging resources, the staging resources must be committed to the device again in order for those changes to be rendered on screen.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::Discard

Removes mesh data from the device that has been committed to the device (with ID3DX10Mesh::CommitToDevice).

HRESULT Discard(
  D3DX10_MESH_DISCARD_FLAGS dwDiscard
);

Parameters

dwDiscard
[in] Specifies which pieces of mesh data to discard from the device. See D3DX10_MESH_DISCARD_FLAGS.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::DrawSubset

Draws a subset of a mesh.

HRESULT DrawSubset(
  UINT AttribId
);

Parameters

AttribId
[in] Specifies which subset of the mesh to draw. This value is used to differentiate faces in a mesh as belonging to one or more attribute groups.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::DrawSubsetInstanced

Draw several instances of the same subset of a mesh.

HRESULT DrawSubsetInstanced(
  UINT AttribId,
  UINT InstanceCount,
  UINT StartInstanceLocation
);

Parameters

AttribId
[in] Specifies which subset of the mesh to draw. This value is used to differentiate faces in a mesh as belonging to one or more attribute groups. See remarks.
InstanceCount
[in] Number of instances to render.
StartInstanceLocation
[in] Which instance to start fetching from in each buffer marked as instance data.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

A mesh contains an attribute table. The attribute table can divide a mesh into subsets, where each subset is identified with an attribute ID. For example, a mesh with 200 faces, divided into three subsets, might have an attribute table that looks like this:

AttribID 0 | Faces 0 ~ 50
AttribID 1 | Faces 51 ~ 125
AttribID 2 | Faces 126 ~ 200

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GenerateAdjacencyAndPointReps

Generate a list of mesh edges, as well as a list of faces that share each edge.

HRESULT GenerateAdjacencyAndPointReps(
  FLOAT Epsilon
);

Parameters

Epsilon
[in] Specifies that vertices that differ in position by less than epsilon should be treated as coincident.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized for better drawing performance.

The order of the entries in the adjacency buffer is determined by the order of the vertex indices in the index buffer. The adjacent triangle 0 always corresponds to the edge between the indices of the corners 0 and 1. The adjacent triangle 1 always corresponds to the edge between the indices of the corners 1 and 2 while the adjacent triangle 2 corresponds to the edge between the indices of the corners 2 and 0.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GenerateAttributeBufferFromTable

Generate an attribute buffer from the data in the mesh's attribute table. An attribute buffer is another format for storing the data in the attribute table. Both the attribute buffer and the attribute table are internal data structures in the mesh.

HRESULT GenerateAttributeBufferFromTable();

Parameters

None.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GenerateGSAdjacency

Adds adjacency data to the mesh's index buffer. When the mesh is to be sent to a geometry shader that takes adjacency data, it is neccessary for the mesh's index buffer to contain adjacency data.

HRESULT GenerateGSAdjacency();

Parameters

None.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetAdjacencyBuffer

Access the mesh's adjacency buffer.

HRESULT GetAdjacencyBuffer(
  ID3DX10MeshBuffer **ppAdjacency
);

Parameters

ppAdjacency
[out] The adjacency buffer. See ID3DX10MeshBuffer.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetAttributeBuffer

Access the mesh's attribute buffer.

HRESULT GetAttributeBuffer(
  ID3DX10MeshBuffer **ppAttributeBuffer
);

Parameters

ppAttributeBuffer
[out] The attribute buffer. See ID3DX10MeshBuffer.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetAttributeTable

Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.

HRESULT GetAttributeTable(
  D3DX10_ATTRIBUTE_RANGE *pAttribTable,
  UINT *pAttribTableSize
);

Parameters

pAttribTable
[in] Pointer to an array of D3DX10_ATTRIBUTE_RANGE structures, representing the entries in the mesh's attribute table. Specify NULL to retrieve the value for pAttribTableSize.
pAttribTableSize
[in] Pointer to either the number of entries stored in pAttribTable or a value to be filled in with the number of entries stored in the attribute table for the mesh.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier when drawing the frame.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetDeviceIndexBuffer

Access the mesh's index buffer after it has been committed to the device with ID3DX10Mesh::CommitToDevice. This is different from ID3DX10Mesh::GetIndexBuffer, which returns the index buffer before it has been committed to the device.

HRESULT GetDeviceIndexBuffer(
  ID3D10Buffer **ppIndexBuffer
);

Parameters

ppIndexBuffer
[out] The index buffer after it has been committed to the device.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

If the mesh's index buffer has not already been committed to the device, this API will automatically commit the index buffer before it returns a pointer to the buffer.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetDeviceVertexBuffer

Access the mesh's vertex buffer after it has been committed to the device with ID3DX10Mesh::CommitToDevice. This is different from ID3DX10Mesh::GetVertexBuffer, which returns the vertex buffer before it has been committed to the device.

HRESULT GetDeviceVertexBuffer(
  UINT iBuffer,
  ID3D10Buffer **ppVertexBuffer
);

Parameters

iBuffer
[in] An index identifying which vertex buffer to access.
ppVertexBuffer
[out] The vertex buffer after it has been committed to the device.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetFaceCount

Retrieves the number of faces in the mesh.

UINT GetFaceCount();

Parameters

None.

Return Values

Returns the number of faces in the mesh.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetFlags

Access the mesh's creation flags.

UINT GetFlags();

Parameters

None.

Return Values

The creation flags passed into the options parameter of D3DX10CreateMesh when the mesh was created. See D3DX10_MESH.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetIndexBuffer

Retrieves the data in an index buffer.

HRESULT GetIndexBuffer(
  ID3DX10MeshBuffer **ppIndexBuffer
);

Parameters

ppIndexBuffer
[out] Address of a pointer to a ID3DX10MeshBuffer interface, representing the index buffer associated with the mesh.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetPointRepBuffer

Get the mesh's point rep buffer.

HRESULT GetPointRepBuffer(
  ID3DX10MeshBuffer **ppPointReps
);

Parameters

ppPointReps
[out] Pointer to a mesh buffer containing the mesh's point rep data. See ID3DX10MeshBuffer.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetVertexBuffer

Retrieves the vertex buffer associated with the mesh.

HRESULT GetVertexBuffer(
  UINT iBuffer,
  ID3DX10MeshBuffer **ppVertexBuffer
);

Parameters

iBuffer
[in] The vertex buffer to get. This is an index value.
ppVertexBuffer
[out] The vertex buffer. See ID3DX10MeshBuffer

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetVertexBufferCount

Get the number of vertex buffers in the mesh.

UINT GetVertexBufferCount();

Parameters

None.

Return Values

The number of vertex buffers in the mesh.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetVertexCount

Get the number of vertices in the mesh. A mesh may contain multiple vertex buffers (i.e. one vertex buffer may contain all position data, another may contains all texture coordinate data, etc.), however each vertex buffer will contain the same number of elements.

UINT GetVertexCount();

Parameters

None.

Return Values

The number of vertices in the mesh.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::GetVertexDescription

Access the vertex description passed into D3DX10CreateMesh. The vertex description describes the layout of the mesh's vertex buffers.

HRESULT GetVertexDescription(
  CONST D3D10_INPUT_ELEMENT_DESC **ppDesc,
  UINT *pDeclCount
);

Parameters

ppDesc
[out] Array of input elements that describe the layout of the mesh's vertex buffers. See D3D10_INPUT_ELEMENT_DESC.
pDeclCount
[in] The number of input elements in ppDesc.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::Intersect

Determines if a ray intersects with this mesh.

HRESULT Intersect(
  D3DXVECTOR3 *pRayPos,
  D3DXVECTOR3 *pRayDir,
  UINT *pHitCount,
  UINT *pFaceIndex,
  float *pU,
  float *pV,
  float *pDist,
  ID3D10Blob **ppAllHits
);

Parameters

pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pHitCount
[in] The number of times the ray intersected with the mesh.
pFaceIndex
[in] Pointer to an index value of the face closest to the ray origin, if pHit is TRUE.
pU
[in] Pointer to a barycentric hit coordinate, U.
pV
[in] Pointer to a barycentric hit coordinate, V.
pDist
[in] Pointer to a ray intersection parameter distance.
ppAllHits
[out] Pointer to an ID3D10Blob Interface, containing an array of D3DX10_INTERSECT_INFO structures. This is a list of all the hits that occurred in the intersection test.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

This API provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2 - V1) + V(V3 - V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result, and the parameter V controls how much V3 gets weighted into the result. Lastly, the value of [1 - (U + V)] controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::IntersectSubset

Determines if a ray intersects with a subset of this mesh.

HRESULT IntersectSubset(
  UINT AttribId,
  D3DXVECTOR3 *pRayPos,
  D3DXVECTOR3 *pRayDir,
  UINT *pHitCount,
  UINT *pFaceIndex,
  float *pU,
  float *pV,
  float *pDist,
  ID3D10Blob **ppAllHits
);

Parameters

AttribId
[in] Attribute ID indentifying the subset of the mesh.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pHitCount
[in] The number of times the ray intersected with the mesh.
pFaceIndex
[in] Pointer to an index value of the face closest to the ray origin, if pHit is TRUE.
pU
[in] Pointer to a barycentric hit coordinate, U.
pV
[in] Pointer to a barycentric hit coordinate, V.
pDist
[in] Pointer to a ray intersection parameter distance.
ppAllHits
[out] Pointer to an ID3D10Blob Interface, containing an array of D3DX10_INTERSECT_INFO structures. This is a list of all the hits that occurred in the intersection test.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

This API provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2 - V1) + V(V3 - V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result, and the parameter V controls how much V3 gets weighted into the result. Lastly, the value of [1 - (U + V)] controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::Optimize

Generates a new mesh with reordered faces and vertices to optimize drawing performance.

HRESULT Optimize(
  UINT Flags,
  UINT *pFaceRemap,
  LPD3D10BLOB *ppVertexRemap
);

Parameters

Flags
[in] Specifies the type of optimization to perform. This parameter can be set to a combination of one or more flags from D3DXMESHOPT and D3DXMESH (except D3DXMESH_32BIT, D3DXMESH_IB_WRITEONLY, and D3DXMESH_WRITEONLY).
pFaceRemap
[in] An array of UINTs, one per face, that identifies the original mesh face that corresponds to each face in the optimized mesh. If the value supplied for this argument is NULL, face remap data is not returned.
ppVertexRemap
[out] Address of a pointer to an ID3DX10Buffer interface, which contains a DWORD for each vertex that specifies how the new vertices map to the old vertices. This remap is useful if you need to alter external data based on the new vertex mapping.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

This method generates a new mesh. Before running Optimize, an application must generate an adjacency buffer by calling ID3DX10BaseMesh::GenerateAdjacency. The adjacency buffer contains adjacency data, such as a list of edges and the faces that are adjacent to each other.

This method is very similar to the ID3DX10BaseMesh::CloneMesh method, except that it can perform optimization while generating the new clone of the mesh. The output mesh inherits all of the creation parameters of the input mesh.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::SetAdjacencyData

Set the mesh's adjacency data.

HRESULT SetAdjacencyData(
  CONST UINT *pAdjacency
);

Parameters

pAdjacency
[in] The adjacency data to set.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::SetAttributeData

Set the mesh's attribute data.

HRESULT SetAttributeData(
  CONST UINT *pData
);

Parameters

pData
[in] The attribute data to set.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::SetAttributeTable

Sets the attribute table for a mesh and the number of entries stored in the table.

HRESULT SetAttributeTable(
  CONST D3DX10_ATTRIBUTE_RANGE *pAttribTable,
  UINT cAttribTableSize
);

Parameters

pAttribTable
[in] Pointer to an array of D3DX10_ATTRIBUTE_RANGE structures, representing the entries in the mesh attribute table.
cAttribTableSize
[in] Number of attributes in the mesh attribute table.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

If an application keeps track of the information in an attribute table, and rearranges the table as a result of changes to attributes or faces, this method allows the application to update the attribute tables instead of calling ID3DX10Mesh::Optimize again.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::SetIndexData

Set the mesh's index data.

HRESULT SetIndexData(
  CONST void *pData,
  UINT cIndices
);

Parameters

pData
[in] The index data.
cIndices
[in] The number of indices in pData.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::SetPointRepData

Set the point rep data for the mesh.

HRESULT SetPointRepData(
  CONST UINT *pPointReps
);

Parameters

pPointReps
[in] The point rep data to set.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Mesh::SetVertexData

Set vertex data into one of the mesh's vertex buffers.

HRESULT SetVertexData(
  UINT iBuffer,
  CONST void *pData
);

Parameters

iBuffer
[in] The vertex buffer to be filled with pData.
pData
[in] The vertex data to set.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10MeshBuffer Interface

A mesh buffer is a buffer that contains data about a mesh. It can contain one of five different types of data: vertex data, index data, adjacency data, attribute data, or point rep data. The structure is used to access these five pieces of data through the following five APIs: ID3DX10Mesh::GetVertexBuffer, ID3DX10Mesh::GetIndexBuffer, ID3DX10Mesh::GetAdjacencyBuffer, ID3DX10Mesh::GetAttributeBuffer, or ID3DX10Mesh::GetPointRepBuffer.

ID3DX10MeshBuffer Members

Method | Description
ID3DX10MeshBuffer::GetSize | Get the size of the mesh buffer, in bytes.
ID3DX10MeshBuffer::Map | Get a pointer to the mesh buffer memory to modify its contents.
ID3DX10MeshBuffer::Unmap | Unmap a buffer.

See Also

D3DX Interfaces


ID3DX10MeshBuffer::GetSize

Get the size of the mesh buffer, in bytes.

SIZE_T GetSize();

Parameters

None.

Return Values

The size of the mesh buffer, in bytes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10MeshBuffer::Map

Get a pointer to the mesh buffer memory to modify its contents.

HRESULT Map(
  void **ppData,
  SIZE_T *pSize
);

Parameters

ppData
[out] Pointer to the buffer data.
pSize
[out] Size of the buffer in bytes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

Differences between Direct3D 9 and Direct3D 10:

Map() in Direct3D 10 is analogous to resource Map() in Direct3D 9.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10MeshBuffer::Unmap

Unmap a buffer.

HRESULT Unmap();

Parameters

None.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

Differences between Direct3D 9 and Direct3D 10:

Unmap() in Direct3D 10 is analogous to resource Unlock() in Direct3D 9.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo Interface

ID3DX10SkinInfo allows you to optimize, process, and manually set the relationship between bones and vertices in your meshes (see Skeletal Animation on Wikipedia). It is most useful for making .x files exported by DCC Apps (such as 3DS Max and Maya) more hardware-friendly, and for improving the render speed of your skinned meshes in software render mode.

ID3DX10SkinInfo Members

Method | Description
ID3DX10SkinInfo::AddBoneInfluences | Enable an existing bone to influence a group of vertices and define how much influence the bone has on each vertex.
ID3DX10SkinInfo::AddBones | Allocate space for more bones.
ID3DX10SkinInfo::AddVertices | Allocate space for additional vertices.
ID3DX10SkinInfo::ClearBoneInfluences | Clear a bone's list of vertices that it influences.
ID3DX10SkinInfo::Compact | Limit the number of bones that can influence a vertex and/or limit the amount of influence a bone can have on a vertex.
ID3DX10SkinInfo::DoSoftwareSkinning | Do software skinning on an array of vertices.
ID3DX10SkinInfo::FindBoneInfluenceIndex | Find the index that indicates where a given vertex is in a given bone's list of influenced vertices.
ID3DX10SkinInfo::GetBoneInfluence | Get the amount of influence a given bone has over a given vertex.
ID3DX10SkinInfo::GetBoneInfluenceCount | Get the number of vertices that a given bone influences.
ID3DX10SkinInfo::GetBoneInfluences | Get a list of vertices that a given bone influences and a list of the amount of influence that bone has on each vertex.
ID3DX10SkinInfo::GetMaxBoneInfluences | Get the number of vertices a bone can maximally influence.
ID3DX10SkinInfo::GetNumBones | Get the number of bones in ID3DX10SkinInfo.
ID3DX10SkinInfo::GetNumVertices | Get the number of vertices in ID3DX10SkinInfo.
ID3DX10SkinInfo::RemapBones | Change which bones influence which vertices.
ID3DX10SkinInfo::RemapVertices | Change which vertices are influenced by which bones.
ID3DX10SkinInfo::RemoveBone | Remove a bone.
ID3DX10SkinInfo::SetBoneInfluence | Set the amount of influence a given bone has over a given vertex.

Remarks

Create a ID3DX10SkinInfo interface with D3DX10CreateSkinInfo, D3DX10CreateSkinInfoFromBlendedMesh, or D3DX10CreateSkinInfoFVF.

The LPD3DX10SKININFO type is defined as a pointer to the ID3DX10SkinInfo interface.

typedef struct ID3DX10SkinInfo *LPD3DX10SKININFO;

See Also

D3DX Interfaces


ID3DX10SkinInfo::AddBoneInfluences

Enable an existing bone to influence a group of vertices and define how much influence the bone has on each vertex.

HRESULT AddBoneInfluences(
  UINT BoneIndex,
  UINT InfluenceCount,
  UINT *pIndices,
  float *pWeights
);

Parameters

BoneIndex
[in] An index that specifies an existing bone. Must be between 0 and the value returned by ID3DX10SkinInfo::GetNumBones.
InfluenceCount
[in] Number of vertices to add to the bone's influence.
pIndices
[in] Pointer to an array of vertex indices. Each member of this array has a corresponding member in pWeights, such that pIndices[i] corresponds to pWeights[i]. The corresponding value in pWeights[i] determines how much influence BoneIndex will have on the vertex indexed by pIndices[i]. The size of the pIndices array must be equal to or greater than InfluenceCount.
pWeights
[in] Pointer to an array of bone weights. Each member of this array has a corresponding member in pIndices, such that pWeights[i] corresponds to pIndices[i]. Each value in pWeights is between 0 and 1 and defines the amount of influence the bone has over each vertex. The size of pWeights must be equal to or greater than InfluenceCount.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be: E_INVALIDARG or E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::AddBones

Allocate space for more bones.

HRESULT AddBones(
  UINT Count
);

Parameters

Count
[in] The number of bones to add.

Return Values

If this method succeeds, the return value is S_OK. If the method fails, the return value can be: E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::AddVertices

Allocate space for additional vertices.

HRESULT AddVertices(
  UINT Count
);

Parameters

Count
[in] The number of vertices to add.

Return Values

If this method succeeds, the return value is S_OK. If the method fails, the return value can be: E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::ClearBoneInfluences

Clear a bone's list of vertices that it influences.

HRESULT ClearBoneInfluences(
  UINT BoneIndex
);

Parameters

BoneIndex
[in] An index that specifies an existing bone. Must be between 0 and the value returned by ID3DX10SkinInfo::GetNumBones.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be: E_INVALIDARG.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::Compact

Limit the number of bones that can influence a vertex and/or limit the amount of influence a bone can have on a vertex.

HRESULT Compact(
  UINT MaxPerVertexInfluences,
  UINT ScaleMode,
  float MinWeight
);

Parameters

MaxPerVertexInfluences
[in] The maximum number of bones that can influence any given vertex. This value is ignored if it is greater than the value returned by ID3DX10SkinInfo::GetMaxBoneInfluences.
ScaleMode
[in] A flag describing how to scale the remaining weights on a given vertex after some have been chopped off by MinWeight. If D3DX10_SKININFO_NO_SCALING is specified, the weights will not be scaled at all. If D3DX10_SKININFO_SCALE_TO_1 is specified, the weights greater than MinWeight will be scaled up so that they add up to 1.0. If D3DX10_SKININFO_SCALE_TO_TOTAL is specified, the weights greater than MinWeight will be scaled up so that they add up to the original total.
MinWeight
[in] The minimum percentage of influence, or weight, that any bone can have on any vertex. This value must be between 0 and 1.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be: E_OUTOFMEMORY or E_INVALIDARG.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::DoSoftwareSkinning

Do software skinning on an array of vertices.

HRESULT DoSoftwareSkinning(
  UINT StartVertex,
  UINT VertexCount,
  void *pSrcVertices,
  UINT SrcStride,
  void *pDestVertices,
  UINT DestStride,
  D3DXMATRIX *pBoneMatrices,
  D3DXMATRIX *pInverseTransposeBoneMatrices,
  D3DX10_SKINNING_CHANNEL *pChannelDescs,
  UINT NumChannels
);

Parameters

StartVertex
[in] A 0-based index into pSrcVertices.
VertexCount
[in] Number of vertices to transform.
pSrcVertices
[in] Pointer to an array of vertices to transform.
SrcStride
[in] The size, in bytes, of a vertex in pSrcVertices.
pDestVertices
[in, out] Pointer to an array of vertices, which will be filled with the transformed vertices.
DestStride
[in] The size, in bytes, of a vertex in pDestVertices.
pBoneMatrices
[in] An array of matrices that will be used to transform the points mapped to each bone, such that the vertices mapped to bone[i] will be transformed by pBoneMatrices[i]. This array will be used to transform the matrices only if the IsNormal value in pChannelDescs is set to false, otherwise pInverseTransposeBoneMatrices will be used.
pInverseTransposeBoneMatrices
[in] If this value is NULL, it will be set equal to pBoneMatrices. This array of matrices will be used to transform the vertices only if the IsNormal value in pChannelDescs is set to true, otherwise pBoneMatrices will be used.
pChannelDescs
[in] Pointer to a D3DX10_SKINNING_CHANNEL structure, which determines the member of the vertex decl the software skinning will be done on.
NumChannels
[in] The number of D3DX10_SKINNING_CHANNEL structures in pChannelDescs.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be: E_INVALIDARG.

Remarks

Here is an example of how to use software skinning:

//vertex definition
struct MyVertex
{
    D3DXVECTOR3 Position;
    D3DXVECTOR2 Weight;
    D3DXVECTOR2 TexCoord;
};

//create vertex data
const UINT numVertices = 16;
MyVertex vertices[numVertices] = {...};
MyVertex destVertices[numVertices];

//create bone matrices
D3DXMATRIX boneMatrices[2];
D3DXMatrixIdentity(&boneMatrices[0]);
D3DXMatrixRotationX(&boneMatrices[1], 3.14159f / 180.0f);

//create bone indices and weights
UINT boneIndices[numVertices] = {...};
float boneWeights[2][numVertices] = {...};

//create skin info, populate it with bones and vertices, and then map them to each other
ID3DX10SkinInfo *pSkinInfo = NULL;
D3DX10CreateSkinInfo(&pSkinInfo);
pSkinInfo->AddBones(2);
pSkinInfo->AddVertices(numVertices);
pSkinInfo->AddBoneInfluences(0, numVertices, boneIndices, boneWeights[0]);
pSkinInfo->AddBoneInfluences(1, numVertices, boneIndices, boneWeights[1]);

//create channel desc
D3DX10_SKINNING_CHANNEL channelDesc;
channelDesc.SrcOffset = 0;
channelDesc.DestOffset = 0;
channelDesc.IsNormal = FALSE;

//do the skinning
pSkinInfo->DoSoftwareSkinning(0, numVertices,
                              vertices, sizeof(MyVertex),
                              destVertices, sizeof(MyVertex),
                              boneMatrices, NULL,
                              &channelDesc, 1);

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::FindBoneInfluenceIndex

Find the index that indicates where a given vertex is in a given bone's list of influenced vertices.

HRESULT FindBoneInfluenceIndex(
  UINT BoneIndex,
  UINT VertexIndex,
  UINT *pInfluenceIndex
);

Parameters

BoneIndex
[in] An index that specifies an existing bone. Must be between 0 and the value returned by ID3DX10SkinInfo::GetNumBones.
VertexIndex
[in] The index of the vertex in the vertex buffer.
pInfluenceIndex
[in] The index of the vertex in the bone's list of influenced vertices.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be: E_INVALIDARG.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::GetBoneInfluence

Get the amount of influence a given bone has over a given vertex.

HRESULT GetBoneInfluence(
  UINT BoneIndex,
  UINT InfluenceIndex,
  float *pWeight
);

Parameters

BoneIndex
[in] An index that specifies an existing bone. Must be between 0 and the value returned by ID3DX10SkinInfo::GetNumBones.
InfluenceIndex
[in] An index into the bone's list of vertices that it influences.
pWeight
[in] The amount of influence, between 0 and 1, that the bone has over the vertex.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be E_INVALIDARG.

Remarks

Use ID3DX10SkinInfo::GetBoneInfluenceCount to find out how many vertices the bone influences.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::GetBoneInfluenceCount

Get the number of vertices that a given bone influences.

UINT GetBoneInfluenceCount(
  UINT BoneIndex
);

Parameters

BoneIndex
[in] An index that specifies an existing bone. Must be between 0 and the value returned by ID3DX10SkinInfo::GetNumBones.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be: E_INVALIDARG.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::GetBoneInfluences

Get a list of vertices that a given bone influences and a list of the amount of influence that bone has on each vertex.

HRESULT GetBoneInfluences(
  UINT BoneIndex,
  UINT Offset,
  UINT Count,
  UINT *pDestIndices,
  float *pDestWeights
);

Parameters

BoneIndex
[in] An index that specifies an existing bone. Must be between 0 and the value returned by ID3DX10SkinInfo::GetNumBones.
Offset
[in] An offset from the top of the bone's list of influenced vertices. This must be between 0 and the value returned by ID3DX10SkinInfo::GetBoneInfluenceCount.
Count
[in] The number of indices and weights to retrieve. Must be between 0 and the value returned by ID3DX10SkinInfo::GetBoneInfluenceCount.
pDestIndices
[in, out] A list of indices into the vertex buffer, each one representing a vertex influenced by the bone. These values correspond to the values in pDestWeights, such that pDestIndices[i] corresponds to pDestWeights[i].
pDestWeights
[in, out] A list of the amount of influence the bone has on each vertex. These values correspond to the values in pDestIndices, such that pDestWeights[i] corresponds to pDestIndices[i].f

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be: E_INVALIDARG or E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::GetMaxBoneInfluences

Get the number of vertices a bone can maximally influence.

UINT GetMaxBoneInfluences();

Parameters

None.

Return Values

The number of vertices a bone can maximally influence.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::GetNumBones

Get the number of bones in ID3DX10SkinInfo.

UINT GetNumBones();

Parameters

None.

Return Values

The number of bones in ID3DX10SkinInfo.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::GetNumVertices

Get the number of vertices in ID3DX10SkinInfo.

UINT GetNumVertices();

Parameters

None.

Return Values

The number of vertices in ID3DX10SkinInfo.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::RemapBones

Change which bones influence which vertices.

HRESULT RemapBones(
  UINT NewBoneCount,
  UINT *pBoneRemap
);

Parameters

NewBoneCount
[in] The new number of bones.
pBoneRemap
[in] A pointer to an array of bone indices, which describe the remapping. For example, say SkinInfo contains some bones such that bone0 is mapped to v0, bone1 to v1, and bone2 to v2, and array with 2,1,0 is specified for pBoneRemap. This will cause bone0 to be mapped to v2, bone1 to v1, and bone2 to v0.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be: E_OUTOFMEMORY or E_INVALIDARG.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::RemapVertices

Change which vertices are influenced by which bones.

HRESULT RemapVertices(
  UINT NewVertexCount,
  UINT *pVertexRemap
);

Parameters

NewVertexCount
[in] The new number of vertices.
pVertexRemap
[in] A pointer to an array of vertex indices, which describe the remapping. For example, say SkinInfo contains some vertices such that bone0 is mapped to v0, bone1 to v1, and bone2 to v2, and array with 2,1,0 is specified for pBoneRemap. This will cause bone0 to be mapped to v2, bone1 to v1, and bone2 to v0.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be: E_OUTOFMEMORY or E_INVALIDARG.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::RemoveBone

Remove a bone.

HRESULT RemoveBone(
  UINT Index
);

Parameters

Index
[in] An index that specifies which bone to remove. Must be between 0 and the value returned by ID3DX10SkinInfo::GetNumBones.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be: E_INVALIDARG.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10SkinInfo::SetBoneInfluence

Set the amount of influence a given bone has over a given vertex.

HRESULT SetBoneInfluence(
  UINT BoneIndex,
  UINT InfluenceIndex,
  float Weight
);

Parameters

BoneIndex
[in] An index that specifies an existing bone. Must be between 0 and the value returned by ID3DX10SkinInfo::GetNumBones.
InfluenceIndex
[in] An index into the bone's list of vertices that it influences.
Weight
[in] The amount of influence, between 0 and 1, that the bone has over the vertex.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be E_INVALIDARG.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Sprite Interface

The ID3DX10Sprite interface provides a set of methods that simplify the process of drawing sprites using Microsoft Direct3D. This interface can operate on a set of many sprites.

ID3DX10Sprite Members

Method | Description
ID3DX10Sprite::Begin | Prepare a device for drawing sprites.
ID3DX10Sprite::DrawSpritesBuffered | Add an array of sprites to the batch of sprites to be rendered. This must be called in between calls to ID3DX10Sprite::Begin and ID3DX10Sprite::End, and ID3DX10Sprite::Flush must be called before End to send all of the batched sprites to the device for rendering. This draw method is most useful when drawing a small number of sprites that you want buffered into a large batch, such as fonts.
ID3DX10Sprite::DrawSpritesImmediate | Draw an array of sprites. This will immediately send the sprites to the device for rendering, which is different from ID3DX10Sprite::DrawSpritesBuffered which only adds an array of sprites to a batch of sprites to be rendered when ID3DX10Sprite::Flush is called. This draw method is most useful when drawing a large number of sprites that have already been sorted on the CPU (or do not need to be sorted), such as in a particle system. This must be called in between calls to ID3DX10Sprite::Begin and ID3DX10Sprite::End.
ID3DX10Sprite::End | Call this after ID3DX10Sprite::Flush and it will restore the device state to how it was before ID3DX10Sprite::Begin was called.
ID3DX10Sprite::Flush | Force all batched sprites to be submitted to the device. Device states remain as they were after the last call to ID3DX10Sprite::Begin. The list of batched sprites is then cleared.
ID3DX10Sprite::GetDevice | Retrieve the device associated with the sprite object.
ID3DX10Sprite::GetProjectionTransform | Get the sprite projection matrix that is applied to all sprites.
ID3DX10Sprite::GetViewTransform | Get the view transform that applies to all sprites.
ID3DX10Sprite::SetProjectionTransform | Set the projection matrix for all sprites.
ID3DX10Sprite::SetViewTransform | Set the view transform that applies to all sprites.

Remarks

The ID3DX10Sprite interface is obtained by calling the D3DX10CreateSprite function.

See Also

D3DX Interfaces


ID3DX10Sprite::Begin

Prepare a device for drawing sprites.

HRESULT Begin(
  UINT flags
);

Parameters

flags
[in] Flags that control how the sprites will be drawn. See D3DX10_SPRITE_FLAG.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

Every call to Begin must be matched with a call to ID3DX10Sprite::End.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Sprite::DrawSpritesBuffered

Add an array of sprites to the batch of sprites to be rendered. This must be called in between calls to ID3DX10Sprite::Begin and ID3DX10Sprite::End, and ID3DX10Sprite::Flush must be called before End to send all of the batched sprites to the device for rendering. This draw method is most useful when drawing a small number of sprites that you want buffered into a large batch, such as fonts.

HRESULT DrawSpritesBuffered(
  D3DX10_SPRITE *pSprites,
  UINT cSprites
);

Parameters

pSprites
[in] The array of sprites to draw. See D3DX10_SPRITE.
cSprites
[in] The number of sprites in pSprites.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Sprite::DrawSpritesImmediate

Draw an array of sprites. This will immediately send the sprites to the device for rendering, which is different from ID3DX10Sprite::DrawSpritesBuffered which only adds an array of sprites to a batch of sprites to be rendered when ID3DX10Sprite::Flush is called. This draw method is most useful when drawing a large number of sprites that have already been sorted on the CPU (or do not need to be sorted), such as in a particle system. This must be called in between calls to ID3DX10Sprite::Begin and ID3DX10Sprite::End.

HRESULT DrawSpritesImmediate(
  D3DX10_SPRITE *pSprites,
  UINT cSprites,
  UINT cbSprite,
  UINT flags
);

Parameters

pSprites
[in] The array of sprites to draw. See D3DX10_SPRITE.
cSprites
[in] The number of sprites in pSprites.
cbSprite
[in] The size of the sprite structure you are passing into pSprites. Passing in 0 is the equivalent of passing in sizeof(D3DX10_SPRITE).
flags
[in] Reserved.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Sprite::End

Call this after ID3DX10Sprite::Flush. If D3DX10_SPRITE_SAVE_STATE was specified when ID3DX10Sprite::Begin was called, this API will restore the device state to how it was before ID3DX10Sprite::Begin was called.

HRESULT End();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Sprite::Flush

Force all batched sprites to be submitted to the device. Device states remain as they were after the last call to ID3DX10Sprite::Begin. The list of batched sprites is then cleared.

HRESULT Flush();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Sprite::GetDevice

Retrieve the device associated with the sprite object.

HRESULT GetDevice(
  ID3D10Device **ppDevice
);

Parameters

ppDevice
[out] Address of a pointer to an ID3D10Device interface, representing the Direct3D device object associated with the sprite object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the ID3D10Device interface.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Sprite::GetProjectionTransform

Get the sprite projection matrix that is applied to all sprites.

HRESULT GetProjectionTransform(
  D3DXMATRIX *pProjectionTransform
);

Parameters

pProjectionTransform
[in] The sprite's projection matrix.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Sprite::GetViewTransform

Get the view transform that applies to all sprites.

HRESULT GetViewTransform(
  D3DXMATRIX *pViewTransform
);

Parameters

pViewTransform
[in] Pointer to a D3DX10MATRIX that contains a transform of the sprite from the original world space.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Sprite::SetProjectionTransform

Set the projection matrix for all sprites.

HRESULT SetProjectionTransform(
  D3DXMATRIX *pProjectionTransform
);

Parameters

pProjectionTransform
[in] The projection matrix to be used on all sprites.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10Sprite::SetViewTransform

Set the view transform that applies to all sprites.

HRESULT SetViewTransform(
  D3DXMATRIX *pViewTransform
);

Parameters

pViewTransform
[in] Pointer to a D3DXMATRIX that contains a transform of the sprite from the original world space. Use this transform to scale, rotate, or transform the sprite.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10ThreadPump Interface

Used to execute tasks asynchronously, and created with D3DX10CreateThreadPump. There are several D3DX10 APIs that can optionally take a thread pump as a parameter, such as D3DX10CreateTextureFromFile and D3DX10CompileFromFile (see remarks for complete list). If the thread pump is passed into these APIs, they will execute asynchronously on a separate thread pump thread. The advantage to doing this is that it can make loading and processing large amounts of data happen without seeing a noticable slow down in performance on screen.

The thread pump loads and processes data in a 3 step process. It goes:

  1. Load and decompress the data with a Data Loader. The data loader object has three methods that the thread pump will call internally as it is loading and decompressing the data: ID3DX10DataLoader::Load, ID3DX10DataLoader::Decompress, and ID3DX10DataLoader::Destroy. The specific functionality of these three APIs differs depending on the type of data being loaded and decompressed. The data loader interface can also be inherited and its APIs can be changed if one is loading a data file defined in one's own custom format.
  2. Process the data with a Data Processor. The data processor object has three methods that the thread pump will call internally as it is processing the data: ID3DX10DataProcessor::Process, ID3DX10DataProcessor::CreateDeviceObject, and ID3DX10DataProcessor::Destroy. The way it processes the data will be different depending on the type of data. For example, if the data is a texture stored as a JPEG, then ID3DX10DataProcessor::Process will do JPEG decompression to get the image's raw image bits. If the data is a shader, then ID3DX10DataProcessor::Process will compile the HLSL into bytecode. After the data has been processed a device object will be created for that data (with ID3DX10DataProcessor::CreateDeviceObject) and the object will be added to a queue of device objects. The data processor interface can also be inherited and its APIs can be changed if one is processing a data file defined in one's own custom format.
  3. Bind the device object to the device. This is done when one's application calls ID3DX10ThreadPump::ProcessDeviceWorkItems, which will bind a specified number of objects in the queue of device objects to the device.

The thread pump can be used to load data in one of two ways: by calling an API that takes a thread pump as a parameter, such as D3DX10CreateTextureFromFile and D3DX10CompileFromFile, or by calling ID3DX10ThreadPump::AddWorkItem. In the case of the APIs that take a thread pump, the data loader and data processor are created internally. In the case of AddWorkItem, the data loader and data processor must be created beforehand and are then passed into AddWorkItem. D3DX10 provides a set of APIs for creating data loaders and data processors that have functionality for loading and processing common data formats (see remarks for complete list of APIs). For custom data formats, the data loader and data processor interfaces must be inherited and their methods must be redefined.

The thread pump object takes up a substantial amount of resources, so generally only one should be created per application.

ID3DX10ThreadPump Members

Method | Description
ID3DX10ThreadPump::AddWorkItem | Add a work item to the thread pump.
ID3DX10ThreadPump::GetQueueStatus | Get the number of items in each of the three queues inside the thread pump.
ID3DX10ThreadPump::GetWorkItemCount | Get the number of work items currently in the thread pump.
ID3DX10ThreadPump::ProcessDeviceWorkItems | Set work items to the device after they have finished loading and processing.
ID3DX10ThreadPump::PurgeAllItems | Clear all work items from the thread pump.
ID3DX10ThreadPump::WaitForAllItems | Wait for all work items in the thread pump to finish.

Remarks

Built-in D3DX10 data loaders

D3DX10CreateAsyncFileLoader | Create a file loader asynchronously.
D3DX10CreateAsyncMemoryLoader | Create a data loader asynchronously.
D3DX10CreateAsyncResourceLoader | Create a resource loader asynchronously.

Built-in D3DX10 data processors

D3DX10CreateAsyncTextureProcessor | Create a data processor to be used with a thread pump. This API is similar to D3DX10CreateAsyncTextureInfoProcessor but it also loads the texture.
D3DX10CreateAsyncTextureInfoProcessor | Create a data processor to be used with a thread pump.
D3DX10CreateAsyncShaderCompilerProcessor | Compile a shader and create a data processor asynchronously.
D3DX10CreateAsyncEffectCompilerProcessor | Create an effect with a data processor asynchronously.
D3DX10CreateAsyncEffectCreateProcessor | Create an effect pool asynchronously.
D3DX10CreateAsyncEffectPoolCreateProcessor | Create a data processor asynchronously.
D3DX10CreateAsyncShaderPreprocessProcessor | Create a data processor for a shader asynchronously.

APIs that take a thread pump as a parameter.

D3DX10CompileFromFile | Compile a shader from a file.
D3DX10CompileFromMemory | Compile a shader residing in memory.
D3DX10CompileFromResource | Compile a shader from a resource.
D3DX10CreateEffectFromFile | Create an effect from a file.
D3DX10CreateEffectFromMemory | Create an effect from memory.
D3DX10CreateEffectFromResource | Create an effect from a resource.
D3DX10CreateEffectPoolFromFile | Create an effect pool from a file.
D3DX10CreateEffectPoolFromMemory | Create an effect pool from a file residing in memory.
D3DX10CreateEffectPoolFromResource | Create an effect pool from a resource.
D3DX10PreprocessShaderFromFile | Create a shader from a file without compiling it.
D3DX10PreprocessShaderFromMemory | Create a shader from memory without compiling it.
D3DX10PreprocessShaderFromResource | Create a shader from a resource without compiling it.
D3DX10CreateShaderResourceViewFromFile | Create a shader-resource view from a file.
D3DX10CreateShaderResourceViewFromMemory | Create a shader-resource view from a file in memory.
D3DX10CreateShaderResourceViewFromResource | Create a shader-resource view from a resource.
D3DX10GetImageInfoFromFile | Retrieves information about a given image file.
D3DX10GetImageInfoFromMemory | Get information about an image already loaded into memory.
D3DX10GetImageInfoFromResource | Retrieves information about a given image in a resource.
D3DX10CreateTextureFromFile | Create a texture resource from a file.
D3DX10CreateTextureFromMemory | Create a texture resource from a file residing in system memory.
D3DX10CreateTextureFromResource | Create a texture resource from another resource.

See Also

D3DX Interfaces


ID3DX10ThreadPump::AddWorkItem

Add a work item to the thread pump.

HRESULT AddWorkItem(
  ID3DX10DataLoader *pDataLoader,
  ID3DX10DataProcessor *pDataProcessor,
  HRESULT *pHResult,
  void **ppDeviceObject
);

Parameters

pDataLoader
[in] The loader that the thread pump will use when a work item requires data to be loaded.
pDataProcessor
[in] The processor that the thread pump will use when a work item requires data to be processed.
pHResult
[in] A pointer to the return value. May be NULL.
ppDeviceObject
[out] The device that uses the object.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10ThreadPump::GetQueueStatus

Get the number of items in each of the three queues inside the thread pump.

HRESULT GetQueueStatus(
  UINT *pIoQueue,
  UINT *pProcessQueue,
  UINT *pDeviceQueue
);

Parameters

pIoQueue
[in] Number of items in the I/O queue.
pProcessQueue
[in] Number of items in the process queue.
pDeviceQueue
[in] Number of items in the device queue.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10ThreadPump::GetWorkItemCount

Get the number of work items currently in the thread pump.

UINT GetWorkItemCount();

Parameters

None.

Return Values

The number of work items currently queued in the thread pump.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10ThreadPump::ProcessDeviceWorkItems

Set work items to the device after they have finished loading and processing. When the thread pump has finished loading and processing a resource or shader, it will hold it in a queue until this API is called, at which point the processed items will be set to the device. This is useful for controlling the amount of processing that is spent on binding resources to the device for each frame. See remarks.

HRESULT ProcessDeviceWorkItems(
  UINT iWorkItemCount
);

Parameters

iWorkItemCount
[in] The number of work items to set to the device. ProcessDeviceObjectCreation will create at most iWorkItemCount objects. If there are not enough work items in the queue to process iWorkItemCount objects, ProcessDeviceObjectCreation will create as many device objects as there are items in the queue.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

As an example of how one might use this API, say you are nearing the end of one level in your game and you want to begin preloading the textures, shaders, and other resources for the next level. The thread pump will begin loading, decompressing, and processing the resources and shaders on a separate thread until they are ready to be set to the device, at which point it will leave them in a queue. One may not want to set all the resources and shaders to the device at once because this may cause a noticable temporary slow down in the game's performance. So, this API could be called once per frame so that only a small number work items would be set to the device on each frame, thereby spreading the work load of binding resources to the device over several frames and minimizing the possibility of a noticable slow down in the game's performance.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10ThreadPump::PurgeAllItems

Clear all work items from the thread pump.

HRESULT PurgeAllItems();

Parameters

None.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DX10ThreadPump::WaitForAllItems

Wait for all work items in the thread pump to finish.

HRESULT WaitForAllItems();

Parameters

None.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack Interface

Applications use the methods of the ID3DXMATRIXStack interface to manipulate a matrix stack.

ID3DXMatrixStack Members

Method | Description
ID3DXMatrixStack::GetTop | Retrieves the current matrix at the top of the stack.
ID3DXMatrixStack::LoadIdentity | Loads identity in the current matrix.
ID3DXMatrixStack::LoadMatrix | Loads the given matrix into the current matrix.
ID3DXMatrixStack::MultMatrix | Determines the product of the current matrix and the given matrix.
ID3DXMatrixStack::MultMatrixLocal | Determines the product of the given matrix and the current matrix.
ID3DXMatrixStack::Pop | Removes the current matrix from the top of the stack.
ID3DXMatrixStack::Push | Adds a matrix to the stack.
ID3DXMatrixStack::RotateAxis | Rotates (relative to world coordinate space) around an arbitrary axis.
ID3DXMatrixStack::RotateAxisLocal | Rotates (relative to the object's local coordinate space) around an arbitrary axis.
ID3DXMatrixStack::RotateYawPitchRoll | Rotates (relative to world coordinate space) around an arbitrary axis.
ID3DXMatrixStack::RotateYawPitchRollLocal | Rotates (relative to the object's local coordinate space) around an arbitrary axis.
ID3DXMatrixStack::Scale | Scale the current matrix about the world coordinate origin.
ID3DXMatrixStack::ScaleLocal | Scale the current matrix about the object origin.
ID3DXMatrixStack::Translate | Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).
ID3DXMatrixStack::TranslateLocal | Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.

Remarks

The ID3DX10MATRIXStack interface is obtained by calling the D3DX10CreateMatrixStack function.

The LPD3DX10MATRIXSTACK type is defined as a pointer to the ID3DX10MATRIXStack interface.

typedef interface ID3DX10MATRIXStack ID3DX10MATRIXStack;
typedef interface ID3DX10MATRIXStack *LPD3DX10MATRIXSTACK;

See Also

D3DX Interfaces


ID3DXMatrixStack::GetTop

Retrieves the current matrix at the top of the stack.

D3DXMATRIX* GetTop();

Parameters

None.

Return Values

This method returns a pointer to a D3DXMATRIX structure representing the current matrix.

Remarks

The D3DXMATRIX pointer returned by this method is not guaranteed to be valid after subsequent stack operations.

Note that this method does not remove the current matrix from the top of the stack; rather, it just returns the current matrix.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::LoadIdentity

Loads identity in the current matrix.

HRESULT LoadIdentity();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The identity matrix is a matrix in which all coefficients are 0.0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1.0. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4x4 matrix.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::LoadMatrix

Loads the given matrix into the current matrix.

HRESULT LoadMatrix(
  CONST D3DXMATRIX *pM
);

Parameters

pM
[in] Pointer to the D3DXMATRIX structure loaded into the current matrix.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Note that this method does not add an item to the stack; rather, it replaces the current matrix with the supplied matrix.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::MultMatrix

Determines the product of the current matrix and the given matrix.

HRESULT MultMatrix(
  CONST D3DXMATRIX *pM
);

Parameters

pM
[in] Pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin).

m_pstack[m_currentPos] = m_pstack[m_currentPos] * (*pMat);

This method does not add an item to the stack, it replaces the current matrix with the product of the current matrix and the given matrix.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::MultMatrixLocal

Determines the product of the given matrix and the current matrix.

HRESULT MultMatrixLocal(
  CONST D3DXMATRIX *pM
);

Parameters

pM
[in] Pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object).

m_pstack[m_currentPos] = (*pMat) * m_pstack[m_currentPos];

This method does not add an item to the stack, it replaces the current matrix with the product of the given matrix and the current matrix.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::Pop

Removes the current matrix from the top of the stack.

HRESULT Pop();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

Note that this method decrements the count of items on the stack by 1, effectively removing the current matrix from the top of the stack and promoting a matrix to the top of the stack. If the current count of items on the stack is 0, then this method returns without performing any action. If the current count of items on the stack is 1, then this method empties the stack.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::Push

Adds a matrix to the stack.

HRESULT Push();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method increments the count of items on the stack by 1, duplicating the current matrix. The stack will grow dynamically as more items are added.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::RotateAxis

Rotates (relative to world coordinate space) around an arbitrary axis.

HRESULT RotateAxis(
  CONST D3DXVECTOR3 *pV,
  FLOAT Angle
);

Parameters

pV
[in] Pointer to the arbitrary axis of rotation. See D3DXVECTOR3.
Angle
[in] Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:

D3DXMATRIX tmp;
D3DXMatrixRotationAxis( &tmp, pV, angle );
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::RotateAxisLocal

Rotates (relative to the object's local coordinate space) around an arbitrary axis.

HRESULT RotateAxisLocal(
  CONST D3DXVECTOR3 *pV,
  FLOAT Angle
);

Parameters

pV
[in] Pointer to the arbitrary axis of rotation. See D3DXVECTOR3.
Angle
[in] Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:

D3DXMATRIX tmp;
D3DXMatrixRotationAxis( &tmp, pV, angle );
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::RotateYawPitchRoll

Rotates (relative to world coordinate space) around an arbitrary axis.

HRESULT RotateYawPitchRoll(
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

Yaw
[in] The yaw around the y-axis in radians.
Pitch
[in] The pitch around the x-axis in radians.
Roll
[in] The roll around the z-axis in radians.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:

D3DXMATRIX tmp;
D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::RotateYawPitchRollLocal

Rotates (relative to the object's local coordinate space) around an arbitrary axis.

HRESULT RotateYawPitchRollLocal(
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

Yaw
[in] The yaw around the y-axis in radians.
Pitch
[in] The pitch around the x-axis in radians.
Roll
[in] The roll around the z-axis in radians.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:

D3DXMATRIX tmp;
D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::Scale

Scale the current matrix about the world coordinate origin.

HRESULT Scale(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The scaling component in the x-direction.
y
[in] The scaling component in the y-direction.
z
[in] The scaling component in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed scale matrix. The transformation is about the current world origin.

D3DXMATRIX tmp;
D3DXMatrixScaling(&tmp, x, y, z);
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::ScaleLocal

Scale the current matrix about the object origin.

HRESULT ScaleLocal(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The scaling component in the x-direction.
y
[in] The scaling component in the y-direction.
z
[in] The scaling component in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed scale matrix. The transformation is about the local origin of the object.

D3DXMATRIX tmp;
D3DXMatrixScaling(&tmp, x, y, z);
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::Translate

Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).

HRESULT Translate(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The translation factor in the x-direction.
y
[in] The translation factor in the y-direction.
z
[in] The translation factor in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed translation matrix (transformation is about the current world origin).

D3DXMATRIX tmp;
D3DXMatrixTranslation( &tmp, x, y, z );
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


ID3DXMatrixStack::TranslateLocal

Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.

HRESULT TranslateLocal(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The translation factor in the x-direction.
y
[in] The translation factor in the y-direction.
z
[in] The translation factor in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed translation matrix (transformation is about the local origin of the object).

D3DXMATRIX tmp;
D3DXMatrixTranslation(&tmp, x, y, z );
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Interfaces


D3DX Functions

This section contains reference information for the functions that you need to implement when you work with the D3DX utility library. The following categories of functions are implemented:

  • General Purpose Functions
  • Math Functions
  • Mesh Functions
  • Texturing Functions


General Purpose Functions

D3DX supplies the following general purpose functions.

  • D3DX10CheckVersion
  • D3DX10CompileEffectFromFile
  • D3DX10CompileEffectFromMemory
  • D3DX10CompileEffectFromResource
  • D3DX10CompileFromFile
  • D3DX10CompileFromMemory
  • D3DX10CompileFromResource
  • D3DX10CompileShaderFromFile
  • D3DX10CompileShaderFromMemory
  • D3DX10CompileShaderFromResource
  • D3DX10CreateAsyncCompilerProcessor
  • D3DX10CreateAsyncEffectCompilerProcessor
  • D3DX10CreateAsyncEffectCreateProcessor
  • D3DX10CreateAsyncEffectPoolCreateProcessor
  • D3DX10CreateAsyncFileLoader
  • D3DX10CreateAsyncMemoryLoader
  • D3DX10CreateAsyncResourceLoader
  • D3DX10CreateAsyncShaderCompilerProcessor
  • D3DX10CreateAsyncShaderPreprocessProcessor
  • D3DX10CreateAsyncShaderResourceViewProcessor
  • D3DX10CreateEffectFromFile
  • D3DX10CreateEffectFromMemory
  • D3DX10CreateEffectFromResource
  • D3DX10CreateEffectPoolFromFile
  • D3DX10CreateEffectPoolFromMemory
  • D3DX10CreateEffectPoolFromResource
  • D3DX10CreateFont
  • D3DX10CreateFontIndirect
  • D3DX10CreateSprite
  • D3DX10CreateThreadPump
  • D3DX10DisassembleEffect
  • D3DX10DisassembleShader
  • D3DX10GetDriverLevel
  • D3DX10PreprocessShaderFromFile
  • D3DX10PreprocessShaderFromMemory
  • D3DX10PreprocessShaderFromResource
  • D3DX10ReflectShader
  • D3DX10UnsetAllDeviceObjects

See Also

General Purpose Functions

© 2007 Microsoft Corporation. All rights reserved.


D3DX10CheckVersion

Verify that the version of D3DX you compiled with is the version that you are running.

HRESULT D3DX10CheckVersion(
  UINT D3DSdkVersion,
  UINT D3DX10SdkVersion
);

Parameters

D3DSdkVersion
[in] Use D3D10_SDK_VERSION. See remarks.
D3DX10SdkVersion
[in] Use D3DX10_SDK_VERSION. See remarks.

Return Values

If the version doesn't match, the function will return FALSE (a number less than or equal to 0, the number itself has no meaning).

Remarks

Use this function during the initialization of your application.

HRESULT hr;

if( FAILED( D3DX10CheckVersion(D3D10_SDK_VERSION, D3DX10_SDK_VERSION) ) )
    return E_FAIL;

Requirements

Header: Declared in D3DX10Core.h.

See Also

General Purpose Functions


D3DX10CompileEffectFromFile

Deprecated. See D3DX10CompileFromFile.


D3DX10CompileEffectFromMemory

Deprecated. See D3DX10CompileFromMemory.


D3DX10CompileEffectFromResource

Deprecated. See D3DX10CompileFromResource.


D3DX10CompileShaderFromFile

Deprecated. See D3DX10CompileFromFile.


D3DX10CompileShaderFromMemory

Deprecated. See D3DX10CompileFromMemory.


D3DX10CompileShaderFromResource

Deprecated. See D3DX10CompileFromResource.


D3DX10CompileFromFile

Compile a shader or an effect from a file.

HRESULT D3DX10CompileFromFile(
  LPCTSTR pSrcFile,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  LPCSTR pFunctionName,
  LPCSTR pProfile,
  UINT Flags1,
  UINT Flags2,
  ID3DX10ThreadPump *pPump,
  ID3D10Blob **ppShader,
  ID3D10Blob **ppErrorMsgs,
  HRESULT *pHResult
);

Parameters

pSrcFile
[in] The name of the file that contains the shader code. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pDefines
[in] Optional. Pointer to a NULL-terminated array of macro definitions. See D3D10_SHADER_MACRO. If not used, set this to NULL.
pInclude
[in] Optional. Pointer to an ID3D10Include Interface interface for handling include files. Setting this to NULL will cause a compile error if a shader contains a #include.
pFunctionName
[in] Name of the shader-entrypoint function where shader execution begins.
pProfile
[in] A string that specifies the shader model; can be any profile in shader model 2, shader model 3, or shader model 4.
Flags1
[in] Shader compile flags.
Flags2
[in] Effect compile flags.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppShader
[out] A pointer to an ID3D10Blob Interface which contains the compiled shader, as well as any embedded debug and symbol-table information.
ppErrorMsgs
[out] A pointer to an ID3D10Blob Interface which contains a listing of errors and warnings that occured during compilation. These errors and warnings are identical to the the debug output from a debugger.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CompileFromMemory

Compile a shader or an effect that is loaded in memory.

HRESULT D3DX10CompileFromMemory(
  LPCSTR pSrcData,
  SIZE_T SrcDataLen,
  LPCSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  LPCSTR pFunctionName,
  LPCSTR pProfile,
  UINT Flags1,
  UINT Flags2,
  ID3DX10ThreadPump *pPump,
  ID3D10Blob **ppShader,
  ID3D10Blob **ppErrorMsgs,
  HRESULT *pHResult
);

Parameters

pSrcData
[in] Pointer to the shader in memory.
SrcDataLen
[in] Size of the shader in memory.
pFileName
[in] The name of the file that contains the shader code.
pDefines
[in] Optional. Pointer to a NULL-terminated array of macro definitions. See D3D10_SHADER_MACRO. If not used, set this to NULL.
pInclude
[in] Optional. Pointer to an ID3D10Include Interface interface for handling include files. Setting this to NULL will cause a compile error if a shader contains a #include.
pFunctionName
[in] Name of the shader-entrypoint function where shader execution begins.
pProfile
[in] A string that specifies the shader model; can be any profile in shader model 2, shader model 3, or shader model 4.
Flags1
[in] Shader compile flags.
Flags2
[in] Effect compile flags.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppShader
[out] A pointer to an ID3D10Blob Interface which contains the compiled shader, as well as any embedded debug and symbol-table information.
ppErrorMsgs
[out] A pointer to an ID3D10Blob Interface which contains a listing of errors and warnings that occured during compilation. These errors and warnings are identical to the the debug output from a debugger.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CompileFromResource

Compile a shader or an effect from a resource.

HRESULT D3DX10CompileFromResource(
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  LPCTSTR pSrcFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  LPCSTR pFunctionName,
  LPCSTR pProfile,
  UINT Flags1,
  UINT Flags2,
  ID3DX10ThreadPump *pPump,
  ID3D10Blob **ppShader,
  ID3D10Blob **ppErrorMsgs,
  HRESULT *pHResult
);

Parameters

hSrcModule
[in] Handle to the resource module containing the shader. HMODULE can be obtained with GetModuleHandle.
pSrcResource
[in] Name of the resource containing the shader. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pSrcFileName
[in] Name of the source file. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pDefines
[in] Optional. Pointer to a NULL-terminated array of macro definitions. See D3D10_SHADER_MACRO. If not used, set this to NULL.
pInclude
[in] Optional. Pointer to an ID3D10Include Interface interface for handling include files. Setting this to NULL will cause a compile error if a shader contains a #include.
pFunctionName
[in] Name of the shader-entrypoint function where shader execution begins.
pProfile
[in] A string that specifies the shader model; can be any profile in shader model 2, shader model 3, or shader model 4.
Flags1
[in] Shader compile flags.
Flags2
[in] Effect compile flags.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppShader
[out] A pointer to an ID3D10Blob Interface which contains the compiled shader, as well as any embedded debug and symbol-table information.
ppErrorMsgs
[out] A pointer to an ID3D10Blob Interface which contains a listing of errors and warnings that occured during compilation. These errors and warnings are identical to the the debug output from a debugger.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateAsyncCompilerProcessor

Create an asynchronous-data processor for a shader.

HRESULT D3DX10CreateAsyncCompilerProcessor(
  LPCSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  LPCSTR pFunctionName,
  LPCSTR pProfile,
  UINT Flags1,
  UINT Flags2,
  ID3D10Blob **ppCompiledShader,
  ID3D10Blob **ppErrorBuffer,
  ID3DX10DataProcessor **ppProcessor
);

Parameters

pFileName
[in] A string that contains the shader filename.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pFunctionName
[in] Name of the shader-entrypoint function where shader execution begins.
pProfile
[in] A string that specifies the shader profile or shader model.
Flags1
[in] Shader compile flags.
Flags2
[in] Effect compile flags.
ppCompiledShader
[out] Address of a pointer to the compiled effect (see ID3D10Blob Interface).
ppErrorBuffer
[out] Address of a pointer to compile errors (see ID3D10Blob Interface).
ppProcessor
[out] The address of a pointer to the asynchronous-data processor (see ID3DX10DataProcessor Interface).

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateAsyncEffectCompilerProcessor

Create an asynchronous-data processor for an effect.

HRESULT D3DX10CreateAsyncEffectCompilerProcessor(
  LPCSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  UINT Flags,
  UINT FXFlags,
  ID3D10Blob **ppCompiledShader,
  ID3D10Blob **ppErrorBuffer,
  ID3DX10DataProcessor **ppProcessor
);

Parameters

pFileName
[in] A string that contains the effect filename.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
Flags
[in] HLSL compile options.
FXFlags
[in] Effect compile options).
ppCompiledShader
[out] Address of a pointer to buffer (see ID3D10Blob Interface) that contains the compiled effect.
ppErrorBuffer
[out] Address of a pointer to a buffer (see ID3D10Blob Interface) that contains compile errors.
ppProcessor
[out] The address of a pointer to the asynchronous-data processor (see ID3DX10DataProcessor Interface).

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateAsyncEffectCreateProcessor

Create an effect pool asynchronously.

HRESULT D3DX10CreateAsyncEffectCreateProcessor(
  LPCSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  LPCSTR pProfile,
  UINT Flags,
  UINT FXFlags,
  ID3D10Device *pDevice,
  ID3D10EffectPool *pPool,
  ID3D10Blob **ppErrorBuffer,
  ID3DX10DataProcessor **ppProcessor
);

Parameters

pFileName
[in] A string that contains the effect filename.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pProfile
[in] A string that specifies the shader profile or shader model.
Flags
[in] HLSL compile options (see Shader Flags).
FXFlags
[in] Effect compile options (see Compile and Effect Flags).
pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resources.
pPool
[in] A pointer to an effect pool (see ID3D10EffectPool Interface) for sharing variables between effects.
ppErrorBuffer
[out] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect compile errors, if there were any.
ppProcessor
[out] The address of a pointer to the asynchronous-data processor (see ID3DX10DataProcessor Interface).

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateAsyncEffectPoolCreateProcessor

Create an asynchronous-data processor for a memory pool.

HRESULT D3DX10CreateAsyncEffectPoolCreateProcessor(
  LPCSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  LPCSTR pProfile,
  UINT Flags,
  UINT FXFlags,
  ID3D10Device *pDevice,
  ID3D10Blob **ppErrorBuffer,
  ID3DX10DataProcessor **ppProcessor
);

Parameters

pFileName
[in] A string that contains the effect filename.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pProfile
[in] A string that specifies the shader profile or shader model.
Flags
[in] HLSL compile options (see Shader Flags).
FXFlags
[in] Effect compile options (see Compile and Effect Flags).
pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resources.
ppErrorBuffer
[out] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect compile errors, if there were any.
ppProcessor
[out] The address of a pointer to the asynchronous-data processor (see ID3DX10DataProcessor Interface).

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateAsyncFileLoader

Create an asynchronous-file loader.

HRESULT D3DX10CreateAsyncFileLoader(
  LPCTSTR pFileName,
  ID3DX10DataLoader **ppDataLoader
);

Parameters

pFileName
[in] The name of the file to load. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
ppDataLoader
[out] Address of a pointer to the asynchronous-data loader (see ID3DX10DataLoader Interface).

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateAsyncMemoryLoader

Create an asynchronous-memory loader.

HRESULT D3DX10CreateAsyncMemoryLoader(
  LPCVOID pData,
  SIZE_T cbData,
  ID3DX10DataLoader **ppDataLoader
);

Parameters

pData
[in] Pointer to the data.
cbData
[in] Size of the data.
ppDataLoader
[out] The address of a pointer to the asynchronous-data processor (see ID3DX10DataProcessor Interface).

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateAsyncResourceLoader

Create an asynchronous-resource loader.

HRESULT D3DX10CreateAsyncResourceLoader(
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  ID3DX10DataLoader **ppDataLoader
);

Parameters

hSrcModule
[in] Handle to the resource module. Use GetModuleHandle to get the handle.
pSrcResource
[in] Name of the resource in hSrcModule. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
ppDataLoader
[out] The address of a pointer to the asynchronous-data processor (see ID3DX10DataProcessor Interface).

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateAsyncShaderCompilerProcessor

Compile a shader and create a data processor asynchronously.

HRESULT D3DX10CreateAsyncShaderCompilerProcessor(
  LPCSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  LPCSTR pFunctionName,
  LPCSTR pProfile,
  UINT Flags,
  ID3D10Blob **ppCompiledShader,
  ID3D10Blob **ppErrorBuffer,
  ID3DX10DataProcessor **ppProcessor
);

Parameters

pFileName
[in] Name of the shader file.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pFunctionName
[in] Name of the entry point function for the shader.
pProfile
[in] A string that specifies the shader profile or shader model.
Flags
[in] HLSL compile options (see Shader Flags).
ppCompiledShader
[out] Address of a pointer to the compiled shader. See ID3D10Blob Interface.
ppErrorBuffer
[out] Address of a pointer to compile errors.
ppProcessor
[out] The address of a pointer to the asynchronous-data processor (see ID3DX10DataProcessor Interface).

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateAsyncShaderPreprocessProcessor

Create a data processor for a shader asynchronously.

HRESULT D3DX10CreateAsyncShaderPreprocessProcessor(
  LPCSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  ID3D10Blob **ppShaderText,
  ID3D10Blob **ppErrorBuffer,
  ID3DX10DataProcessor **ppProcessor
);

Parameters

pFileName
[in] Name of the shader file.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
ppShaderText
[out] The ASCII text of the shader. See ID3D10Blob Interface.
ppErrorBuffer
[out] Address of a pointer to compile errors.
ppProcessor
[out] The address of a pointer to the asynchronous-data processor (see ID3DX10DataProcessor Interface).

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateAsyncShaderResourceViewProcessor

Create a data processor that will load a resource and then create a shader-resource view for it. Data processors are a component of the asynchronous data loading feature in D3DX10 that uses thread pumps.

HRESULT D3DX10CreateAsyncShaderResourceViewProcessor(
  ID3D10Device *pDevice,
  D3DX10_IMAGE_LOAD_INFO *pLoadInfo,
  ID3DX10DataProcessor **ppDataProcessor
);

Parameters

pDevice
[in] Pointer to the Direct3D device that will be used to create a resource and a shader-resource view for that resource.
pLoadInfo
[in] Optional information to control how to the texture is loaded. See D3DX10_IMAGE_LOAD_INFO. If NULL, the source image data is used.
ppDataProcessor
[out] Address of a pointer to a data processor.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateEffectFromFile

Create an effect from a file.

HRESULT D3DX10CreateEffectFromFile(
  LPCTSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  ID3D10Include *pInclude,
  LPCSTR pProfile,
  UINT HLSLFlags,
  UINT FXFlags,
  ID3D10Device *pDevice,
  ID3D10EffectPool *pEffectPool,
  ID3DX10ThreadPump *pPump,
  ID3D10Effect **ppEffect,
  ID3D10Blob **ppErrors
);

Parameters

pFileName
[in] Name of the ASCII effect file. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pProfile
[in] A string that specifies the shader profile, or shader model.
HLSLFlags
[in] HLSL compile options (see D3D10_SHADER Constants).
FXFlags
[in] Effect compile options (see Compile and Effect Flags).
pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resources.
pEffectPool
[in] Pointer to an effect pool (see ID3D10EffectPool Interface) for sharing variables between effects.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppEffect
[out] Address of a pointer to the effect (see ID3D10Effect Interface) that is created.
ppErrors
[out] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect compile errors, if there were any.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateEffectFromMemory

Create an effect from memory.

HRESULT D3DX10CreateEffectFromMemory(
  LPCVOID pData,
  SIZE_T DataLength,
  LPCSTR pSrcFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  ID3D10Include *pInclude,
  LPCSTR pProfile,
  UINT HLSLFlags,
  UINT FXFlags,
  ID3D10Device *pDevice,
  ID3D10EffectPool *pEffectPool,
  ID3DX10ThreadPump *pPump,
  ID3D10Effect **ppEffect,
  ID3D10Blob **ppErrors,
  HRESULT *pHResult
);

Parameters

pData
[in] Pointer to the effect in memory.
DataLength
[in] Size of the effect in memory.
pSrcFileName
[in] Name of the effect file in memory.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pProfile
[in] A string that specifies the shader profile, or shader model.
HLSLFlags
[in] HLSL compile options (see D3D10_SHADER Constants).
FXFlags
[in] Effect compile options (see Compile and Effect Flags).
pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resources.
pEffectPool
[in] Pointer to an effect pool (see ID3D10EffectPool Interface) for sharing variables between effects.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppEffect
[out] Address of a pointer to the effect (see ID3D10Effect Interface) that is created.
ppErrors
[out] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect compile errors, if there were any.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateEffectFromResource

Create an effect from a resource.

HRESULT D3DX10CreateEffectFromResource(
  HMODULE hModule,
  LPCTSTR pResourceName,
  LPCTSTR pSrcFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  ID3D10Include *pInclude,
  LPCSTR pProfile,
  UINT HLSLFlags,
  UINT FXFlags,
  ID3D10Device *pDevice,
  ID3D10EffectPool *pEffectPool,
  ID3DX10ThreadPump *pPump,
  ID3D10Effect **ppEffect,
  ID3D10Blob **ppErrors
);

Parameters

hModule
[in] A handle to the resource module containing the effect. HMODULE can be obtained with GetModuleHandle.
pResourceName
[in] Name of the resource in hModule. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pSrcFileName
[in] Effect's file name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pProfile
[in] A string that specifies the shader profile, or shader model.
HLSLFlags
[in] HLSL compile options (see D3D10_SHADER Constants).
FXFlags
[in] Effect compile options (see Compile and Effect Flags).
pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resources.
pEffectPool
[in] Pointer to an effect pool (see ID3D10EffectPool Interface) for sharing variables between effects.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppEffect
[out] Address of a pointer to the effect (see ID3D10Effect Interface) that is created.
ppErrors
[out] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect compile errors, if there were any.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateEffectPoolFromFile

Create an effect pool from an effect file.

HRESULT D3DX10CreateEffectPoolFromFile(
  LPCTSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  ID3D10Include *pInclude,
  LPCSTR pProfile,
  UINT HLSLFlags,
  UINT FXFlags,
  ID3D10Device *pDevice,
  ID3DX10ThreadPump *pPump,
  ID3D10EffectPool **ppEffectPool,
  ID3D10Blob **ppErrors,
  HRESULT *pHResult
);

Parameters

pFileName
[in] The effect filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pProfile
[in] A string that specifies the shader profile, or shader model.
HLSLFlags
[in] HLSL compile options (see D3D10_SHADER Constants).
FXFlags
[in] Effect compile options (see Compile and Effect Flags).
pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resources.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppEffectPool
[out] The address of a pointer to the effect pool (see ID3D10EffectPool Interface).
ppErrors
[out] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect compile errors, if there were any.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

This example creates an effect pool from the effect used in the BasicHLSL10 Sample.

// Create an effect pool from an effect in memory
ID3D10EffectPool * l_pEffectPool = NULL;
ID3D10Blob*	l_pBlob_Errors = NULL;
WCHAR str[MAX_PATH];
hr = DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL10.fx" );
hr = D3DX10CreateEffectPoolFromFile( str,
    NULL, NULL, D3D10_SHADER_ENABLE_STRICTNESS,
    0, pd3dDevice, NULL, &l_pEffectPool,
    &l_pBlob_Errors );

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateEffectPoolFromMemory

Create an effect pool from an effect in memory.

HRESULT D3DX10CreateEffectPoolFromMemory(
  LPCVOID pData,
  SIZE_T DataLength,
  LPCSTR pSrcFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  ID3D10Include *pInclude,
  LPCSTR pProfile,
  UINT HLSLFlags,
  UINT FXFlags,
  ID3D10Device *pDevice,
  ID3DX10ThreadPump *pPump,
  ID3D10EffectPool **ppEffectPool,
  ID3D10Blob **ppErrors,
  HRESULT *pHResult
);

Parameters

pData
[in] A pointer to the effect.
DataLength
[in] The size of the effect.
pSrcFileName
[in] The name of the effect file.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pProfile
[in] A string that specifies the shader profile, or shader model.
HLSLFlags
[in] HLSL compile options (see D3D10_SHADER Constants).
FXFlags
[in] Effect compile options (see Compile and Effect Flags).
pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resources.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppEffectPool
[out] The address of a pointer to the effect pool (see ID3D10EffectPool Interface).
ppErrors
[out] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect compile errors, if there were any.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateEffectPoolFromResource

Create an effect pool from a resource.

HRESULT D3DX10CreateEffectPoolFromResource(
  HMODULE hModule,
  LPCTSTR pResourceName,
  LPCTSTR pSrcFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  ID3D10Include *pInclude,
  LPCSTR pProfile,
  UINT HLSLFlags,
  UINT FXFlags,
  ID3D10Device *pDevice,
  ID3DX10ThreadPump *pPump,
  ID3D10EffectPool **ppEffectPool,
  ID3D10Blob **ppErrors
);

Parameters

hModule
[in] A handle to the resource module containing the effect. HMODULE can be obtained with GetModuleHandle.
pResourceName
[in] The name of the resource in hModule. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pSrcFileName
[in] The name of the effect file. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pProfile
[in] A string that specifies the shader profile, or shader model.
HLSLFlags
[in] HLSL compile options (see D3D10_SHADER Constants).
FXFlags
[in] Effect compile options (see Compile and Effect Flags).
pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resources.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppEffectPool
[in] The address of a pointer to the effect pool (see ID3D10EffectPool Interface).
ppErrors
[in] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect compile errors, if there were any.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10CreateFont

Creates a font object for a device and font.

HRESULT D3DX10CreateFont(
  ID3D10Device *pDevice,
  INT Height,
  UINT Width,
  UINT Weight,
  UINT MipLevels,
  BOOL Italic,
  UINT CharSet,
  UINT OutputPrecision,
  UINT Quality,
  UINT PitchAndFamily,
  LPCTSTR pFaceName,
  LPD3DX10FONT *ppFont
);

Parameters

pDevice
[in] Pointer to an ID3D10Device interface, the device to be associated with the font object.
Height
[in] The height of the characters in logical units.
Width
[in] The width of the characters in logical units.
Weight
[in] Typeface weight. One example is bold.
MipLevels
[in] The number of mipmap levels.
Italic
[in] True for italic font, false otherwise.
CharSet
[in] The character set of the font.
OutputPrecision
[in] Specifies how Windows should attempt to match the desired font sizes and characteristics with actual fonts. Use OUT_TT_ONLY_PRECIS for instance, to ensure that you always get a TrueType font.
Quality
[in] Specifies how Windows should match the desired font with a real font. It applies to raster fonts only and should not affect TrueType fonts.
PitchAndFamily
[in] Pitch and family index.
pFaceName
[in] String containing the typeface name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR. See Remarks.
ppFont
[out] Returns a pointer to an ID3DX10Font interface, representing the created font object.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateFontW. Otherwise, the function call resolves to D3DXCreateFontA because ANSI strings are being used.

If you want more information about font parameters, see The Logical Font.

Requirements

Header: Declared in D3DX10Core.h.

See Also

General Purpose Functions


D3DX10CreateFontIndirect

Creates a font object.

HRESULT D3DX10CreateFontIndirect(
  ID3D10Device *pDevice,
  CONST D3DX10_FONT_DESC *pDesc,
  LPD3DX10FONT *ppFont
);

Parameters

pDevice
[in] Pointer to an ID3D10Device Interface interface.
pDesc
[in] Pointer to a D3DX10_FONT_DESC structure, describing the attributes of the font object to create. If Unicode is defined, the function call resolves to D3DXCreateFontIndirectW. Otherwise, the function call resolves to D3DXCreateFontIndirectA because ANSI strings are being used.
ppFont
[out] Returns a pointer to an ID3DX10Font Interface.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Core.h.

See Also

General Purpose Functions


D3DX10CreateSprite

Create a sprite for drawing a 2D texture.

HRESULT D3DX10CreateSprite(
  ID3D10Device *pDevice,
  UINT cDeviceBufferSize,
  LPD3DX10SPRITE *ppSprite
);

Parameters

pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will draw the sprite.
cDeviceBufferSize
[in] The size of the vertex buffer, in number of sprites, that will be sent to the device when ID3DX10Sprite::Flush or ID3DX10Sprite::DrawSpritesImmediate is called. This should be a small number if you know you will be rendering a small number of sprites at a time (to save memory) and a large number if you know you will be rendering a large number of sprites at a time. The maximum value is 4096. If 0 is specified, the vertex buffer size will automatically be set to 4096.
ppSprite
[out] The address of a pointer to a sprite interface (see ID3DX10Sprite Interface).

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX10.h.

See Also

General Purpose Functions


D3DX10CreateThreadPump

Create a thread pump.

HRESULT D3DX10CreateThreadPump(
  UINT cIoThreads,
  UINT cProcThreads,
  ID3DX10ThreadPump **ppThreadPump
);

Parameters

cIoThreads
[in] The number of I/O threads to create. If 0 is specified, Direct3D will attempt to calculate the optimal number of threads based on the hardware configuration.
cProcThreads
[in] The number of process threads to create. If 0 is specified, Direct3D will attempt to calculate the optimal number of threads based on the hardware configuration.
ppThreadPump
[out] The created thread pump. See ID3DX10ThreadPump Interface.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Remarks

A thread pump is a very resource-intensive object. Only one thread pump should be created per application.

Requirements

Header: Declared in D3DX10.h.

See Also

General Purpose Functions


D3DX10DisassembleEffect

Disassemble a compiled (binary) effect into a text string that contains the shader-assembly instructions and register assignments.

HRESULT D3DX10DisassembleEffect(
  interface ID3D10Effect,
  BOOL EnableColorCode,
  ID3D10Blob **ppDisassembly
);

Parameters

ID3D10Effect
[in] A pointer to the effect interface (see ID3D10Effect Interface).
EnableColorCode
[in] Include HTML tags in the output to color code the result.
ppDisassembly
[out] Address of a buffer (see ID3D10Blob Interface) which contains the disassembled effect.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Core.h.

See Also

General Purpose Functions


D3DX10DisassembleShader

Disassemble a compiled (binary) shader into a text string that contains the shader-assembly instructions and register assignments.

HRESULT D3DX10DisassembleShader(
  CONST void *pShader,
  SIZE_T BytecodeLength,
  BOOL EnableColorCode,
  LPCSTR pComments,
  ID3D10Blob **ppDisassembly
);

Parameters

pShader
[in] A pointer to the compiled shader.
BytecodeLength
[in] The size of pShader.
EnableColorCode
[in] Include HTML tags in the output to color code the result.
pComments
[in] The comment string at the top of the shader that identifies the shader constants and variables.
ppDisassembly
[out] Address of a buffer (see ID3D10Blob Interface) which contains the disassembled shader.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

This returned text includes a header with the version of the HLSL compiler used to generate this object, comments describing the memory layout of the constant buffers used by the shader, input and output signatures, and resource binding points.

Here is an example of disassembling a compiled shader. The example assumes you start with a compiled shader (shown as pVSBuf which you can see in HLSLWithoutFX10 Sample).

LPCSTR commentString = NULL;
ID3D10Blob* pIDisassembly = NULL;
char* pDisassembly = NULL;
if( pVSBuf )
{
    D3D10DisassembleShader( (UINT*) pVSBuf->GetBufferPointer(),
        pVSBuf->GetBufferSize(), TRUE, commentString, &pIDisassembly );
    if( pIDisassembly )
    {
        FILE* pFile = fopen( "shader.htm", "w" );
        if( pFile)
        {
            fputs( (char*)pIDisassembly->GetBufferPointer(), pFile );
            fclose( pFile );
        }
    }
}

Requirements

Header: Declared in D3DX10Core.h.

See Also

General Purpose Functions


D3DX10GetDriverLevel

Returns the driver level.

UINT D3DX10GetDriverLevel(
  ID3D10Device *pDevice
);

Parameters

pDevice
[in] Pointer to an ID3D10Device interface representing the device.

Return Values

The driver level. See remarks.

Remarks

This method returns the driver version, which is one of the following:

  • 700 - DirectX 7 driver
  • 800 - DirectX 8 driver
  • 900 - Direct3D 9 driver
  • 1000 - Direct3D reference driver

Requirements

Header: Declared in D3DX10.h.

See Also

General Purpose Functions


D3DX10PreprocessShaderFromFile

Create a shader from a file without compiling it.

HRESULT D3DX10PreprocessShaderFromFile(
  LPCTSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  ID3DX10ThreadPump *pPump,
  ID3D10Blob **ppShaderText,
  ID3D10Blob **ppErrorMsgs
);

Parameters

pFileName
[in] Name of the shader file.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppShaderText
[out] A pointer to memory (see ID3D10Blob Interface) that contains the uncompiled shader.
ppErrorMsgs
[out] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect-creation errors, if any occurred.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Async.h.

See Also

General Purpose Functions


D3DX10PreprocessShaderFromMemory

Create a shader from memory without compiling it.

HRESULT D3DX10PreprocessShaderFromMemory(
  LPCSTR pSrcData,
  SIZE_T SrcDataSize,
  LPCSTR pFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  ID3DX10ThreadPump *pPump,
  ID3D10Blob **ppShaderText,
  ID3D10Blob **ppErrorMsgs
);

Parameters

pSrcData
[in] Pointer to the memory containing the shader.
SrcDataSize
[in] Size of the shader.
pFileName
[in] Name of the shader.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppShaderText
[out] A pointer to memory (see ID3D10Blob Interface) that contains the uncompiled shader.
ppErrorMsgs
[out] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect-creation errors, if any occurred.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

General Purpose Functions


D3DX10PreprocessShaderFromResource

Create a shader from a resource without compiling it.

HRESULT D3DX10PreprocessShaderFromResource(
  HMODULE hModule,
  LPCTSTR pResourceName,
  LPCTSTR pSrcFileName,
  CONST D3D10_SHADER_MACRO *pDefines,
  LPD3D10INCLUDE pInclude,
  ID3DX10ThreadPump *pPump,
  ID3D10Blob **ppShaderText,
  ID3D10Blob **ppErrorMsgs
);

Parameters

hModule
[in] Handle to the resource module containing the shader. HMODULE can be obtained with GetModuleHandle.
pResourceName
[in] The name of the resource in side hModule containing the shader. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pSrcFileName
[in] The shader filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pDefines
[in] A NULL-terminated array of shader macros (see D3D10_SHADER_MACRO). This parameter can be NULL.
pInclude
[in] A pointer to an include interface (see ID3D10Include Interface). This parameter can be NULL.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed.
ppShaderText
[out] A pointer to memory (see ID3D10Blob Interface) that contains the uncompiled shader.
ppErrorMsgs
[out] The address of a pointer to memory (see ID3D10Blob Interface) that contains effect-creation errors, if any occurred.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

General Purpose Functions


D3DX10ReflectShader

Create a shader-reflection object for retrieving information about a compiled shader.

HRESULT D3DX10ReflectShader(
  CONST void *pShaderBytecode,
  SIZE_T BytecodeLength,
  ID3D10ShaderReflection1 **ppReflector
);

Parameters

pShaderBytecode
[in] A pointer to the compiled shader. To get this pointer see Getting a Pointer to a Compiled Shader.
BytecodeLength
[in] Length of pShaderBytecode.
ppReflector
[out] Address of a shader reflection interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Here is an example of creating a shader-reflection object. The example assumes you start with a compiled shader (shown as pVSBuf which you can see in HLSLWithoutFX10 Sample).

ID3D10ShaderReflection* pIShaderReflection = NULL;
D3D10_SHADER_DESC desc;
hr = D3D10ReflectShader( (void*) pVSBuf->GetBufferPointer(), pVSBuf->GetBufferSize(),
    &pIShaderReflection );
if( pIShaderReflection )
{
    pIShaderReflection->GetDesc( &desc );
}

Requirements

Header: Declared in D3DX10Core.h.

See Also

General Purpose Functions


D3DX10UnsetAllDeviceObjects

Removes all resources from the device by setting their pointers to NULL. This should be called during shutdown of your application. It helps ensure that when one is releasing all of their resources that none of them are bound to the device.

HRESULT D3DX10UnsetAllDeviceObjects(
  ID3D10Device *pDevice
);

Parameters

pDevice
[in] Pointer to the device. See ID3D10Device Interface.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Core.h.

See Also

General Purpose Functions


Math Functions

The math library provided by the D3DX utility library supplies functions to compute 3D mathematical operations. Each of the functions can take the same object as the passed [in] and returned [out] parameters. Also, out parameters are typically returned as return values, so that the output of one math function can be used as a parameter for another math function.

The 3D math application functions can be organized into the following functions:

  • D3DXColorAdjustContrast
  • D3DXColorAdjustSaturation
  • D3DXCreateMatrixStack
  • D3DXCpuOptimizations
  • D3DXFloat16To32Array
  • D3DXFloat32To16Array
  • D3DXFresnelTerm
  • D3DXMatrixAffineTransformation
  • D3DXMatrixAffineTransformation2D
  • D3DXMatrixDecompose
  • D3DXMatrixDeterminant
  • D3DXMatrixInverse
  • D3DXMatrixLookAtLH
  • D3DXMatrixLookAtRH
  • D3DXMatrixMultiply
  • D3DXMatrixMultiplyTranspose
  • D3DXMatrixOrthoLH
  • D3DXMatrixOrthoRH
  • D3DXMatrixOrthoOffCenterLH
  • D3DXMatrixOrthoOffCenterRH
  • D3DXMatrixPerspectiveFovLH
  • D3DXMatrixPerspectiveFovRH
  • D3DXMatrixReflect
  • D3DXMatrixRotationAxis
  • D3DXMatrixRotationX
  • D3DXMatrixRotationY
  • D3DXMatrixRotationZ
  • D3DXMatrixRotationYawPitchRoll
  • D3DXMatrixScaling
  • D3DXMatrixShadow
  • D3DXMatrixTransformation
  • D3DXMatrixTransformation2D
  • D3DXMatrixTranslation
  • D3DXMatrixTranspose
  • D3DXPlaneFromPointNormal
  • D3DXPlaneFromPoints
  • D3DXPlaneIntersectLine
  • D3DXPlaneNormalize
  • D3DXPlaneTransform
  • D3DXPlaneTransformArray
  • D3DXQuaternionBaryCentric
  • D3DXQuaternionExp
  • D3DXQuaternionInverse
  • D3DXQuaternionLn
  • D3DXQuaternionMultiply
  • D3DXQuaternionNormalize
  • D3DXQuaternionRotationAxis
  • D3DXQuaternionRotationMatrix
  • D3DXQuaternionRotationYawPitchRoll
  • D3DXQuaternionSlerp
  • D3DXQuaternionSquad
  • D3DXQuaternionSquadSetup
  • D3DXQuaternionToAxisAngle
  • D3DXSHEvalConeLight
  • D3DXSHEvalDirection
  • D3DXSHEvalDirectionalLight
  • D3DXSHEvalHemisphereLight
  • D3DXSHMultiply2
  • D3DXSHMultiply3
  • D3DXSHMultiply4
  • D3DXSHMultiply5
  • D3DXSHMultiply6
  • D3DX10SHProjectCubeMap
  • D3DXSHRotate
  • D3DXSHRotateZ
  • D3DXSHScale
  • D3DXVec2BaryCentric
  • D3DXVec2CatmullRom
  • D3DXVec2Hermite
  • D3DXVec2Normalize
  • D3DXVec2Transform
  • D3DXVec2TransformArray
  • D3DXVec2TransformCoord
  • D3DXVec2TransformCoordArray
  • D3DXVec2TransformNormal
  • D3DXVec2TransformNormalArray
  • D3DXVec3BaryCentric
  • D3DXVec3CatmullRom
  • D3DXVec3Hermite
  • D3DXVec3Normalize
  • D3DXVec3Project
  • D3DXVec3ProjectArray
  • D3DXVec3Transform
  • D3DXVec3TransformArray
  • D3DXVec3TransformCoord
  • D3DXVec3TransformCoordArray
  • D3DXVec3TransformNormal
  • D3DXVec3TransformNormalArray
  • D3DXVec4BaryCentric
  • D3DXVec4CatmullRom
  • D3DXVec4Cross
  • D3DXVec4Hermite
  • D3DXVec4Normalize
  • D3DXVec4Transform
  • D3DXVec4TransformArray


D3DXColorAdjustContrast

Adjusts the contrast value of a color.

D3DXCOLOR* D3DXColorAdjustContrast(
  D3DXCOLOR *pOut,
  CONST D3DXCOLOR *pC,
  FLOAT c
);

Parameters

pOut
[in] [in, out] Pointer to a D3DXCOLOR that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
c
[in] Contrast value. This parameter linearly interpolates between fifty percent gray and the color, pC. There are no limits on the value of c. If this parameter is zero, then the returned color is fifty percent gray. If this parameter is 1, then the returned color is the original color.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the result of the contrast adjustment.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between fifty percent gray and a specified contrast value, as shown in the following example.

pOut->r = 0.5f + c * (pC->r - 0.5f);

If c is greater than 0 and less than 1, the contrast is decreased. If c is greater than 1, the contrast is increased.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXColorAdjustSaturation

Adjusts the saturation value of a color.

D3DXCOLOR* D3DXColorAdjustSaturation(
  D3DXCOLOR *pOut,
  CONST D3DXCOLOR *pC,
  FLOAT s
);

Parameters

pOut
[in] Pointer to a D3DXCOLOR that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Saturation value. This parameter linearly interpolates between the color converted to grayscale and the original color, pC. There are no limits on the value of s. If s is 0, the returned color is the grayscale color. If s is 1, the returned color is the original color.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the result of the saturation adjustment.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between an unsaturated color and a color, as shown in the following example.

//Approximate values for each component's contribution to luminance.
//Based upon the NTSC standard described in ITU-R Recommendation BT.709.
FLOAT grey = pC->r * 0.2125f + pC->g * 0.7154f + pC->b * 0.0721f;

pOut->r = grey + s * (pC->r - grey);

If s is greater than 0 and less than 1, the saturation is decreased. If s is greater than 1, the saturation is increased.

The grayscale color is computed as:

r = g = b = 0.2125*r + 0.7154*g + 0.0721*b;

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXCreateMatrixStack

Create a matrix stack.

HRESULT D3DXCreateMatrixStack(
  UINT Flags,
  LPD3DXMATRIXSTACK *ppStack
);

Parameters

Flags
[in] Not implemented. Specify zero.
ppStack
[out] The address of a pointer to a matrix stack (see ID3DXMatrixStack Interface).

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXCpuOptimizations

Enables or disables CPU optimizations.

D3DX_CPU_OPTIMIZATION D3DXCpuOptimizations(
  BOOL Enable
);

Parameters

Enable
[in] TRUE to enable CPU optimizations; otherwise FALSE.

Return Values

Returns the type of CPU detected, and for which optimizations exist (see D3DX_CPU_OPTIMIZATION).

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXFloat16To32Array

Converts an array of 16-bit floats to 32-bit floats.

FLOAT* D3DXFloat16To32Array(
  FLOAT *pOut,
  CONST D3DXFLOAT16 *pIn,
  UINT n
);

Parameters

pOut
[in] Pointer to the array of 32-bit floats.
pIn
[in] Pointer to an array of 16-bit floats.
n
[in] Number of elements in the array.

Return Values

Pointer to an array of 32-bit floats.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXFloat32To16Array

Converts an array of 32-bit floats to 16-bit floats.

D3DXFLOAT16* D3DXFloat32To16Array(
  D3DXFLOAT16 *pOut,
  CONST FLOAT *pIn,
  UINT n
);

Parameters

pOut
[in] Pointer to the array of 16-bit floats.
pIn
[in] Pointer to an array of 32-bit floats.
n
[in] The number of elements in the array.

Return Values

Pointer to an array of 16-bit floats.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXFresnelTerm

Calculate the Fresnel term.

FLOAT D3DXFresnelTerm(
  FLOAT CosTheta,
  FLOAT RefractionIndex
);

Parameters

CosTheta
[in] The value must be between 0 and 1.
RefractionIndex
[in] The refraction index of a material. The value must be greater than 1.

Return Values

This function returns the Fresnel term for unpolarized light. CosTheta is the cosine of the incident angle.

Remarks

To find the Fresnel term (F):

If A is angle of incidence and B is the angle of refraction, then

F = 0.5 * [tan2(A - B) / tan2(A + B) + sin2(A - B) / sin2(A + B)]
  = 0.5 * sin2(A - B) / sin2(A + B) * [cos2(A + B) / cos2(A - B) + 1]

Let r   = sina(A) / sin(B)      (the relative refractive index)
Let c   = cos(A)
Let g   = (r2 + c2 - 1)1/2

Then, expanding using the trig identities and simplifying, you get:

F = 0.5 * (g + c)2 / (g - c)2 * ([c(g + c) - 1]2 / [c(g - c) + 1]2 + 1)

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixAffineTransformation

Builds a 3D affine transformation matrix. NULL arguments are treated as identity transformations.

D3DXMATRIX* D3DXMatrixAffineTransformation(
  D3DXMATRIX *pOut,
  FLOAT Scaling,
  CONST D3DXVECTOR3 *pRotationCenter,
  CONST D3DXQUATERNION *pRotation,
  CONST D3DXVECTOR3 *pTranslation
);

Parameters

pOut
[in] Pointer to the D3DXMATRIX that is the result of the operation.
Scaling
[in] Scaling factor.
pRotationCenter
[in] Pointer to a D3DXVECTOR3, a point identifying the center of rotation. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
pRotation
[in] Pointer to a D3DXQUATERNION that specifies the rotation. If this argument is NULL, an identity Mr matrix is applied to the formula in Remarks.
pTranslation
[in] Pointer to a D3DXVECTOR3 structure representing the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Values

Pointer to a D3DXMATRIX structure that is an affine transformation matrix.

Remarks

This function calculates the affine transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = Ms * (Mrc)-1 * Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Ms = scaling matrix (Scaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (pRotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixAffineTransformation function can be used as a parameter for another function.

For 2D affine transformations, use D3DXMatrixAffineTransformation2D.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixAffineTransformation2D

Builds a 2D affine transformation matrix in the x-y plane. NULL arguments are treated as identity transformations.

D3DXMATRIX* D3DXMatrixAffineTransformation2D(
  D3DXMATRIX *pOut,
  FLOAT Scaling,
  CONST D3DXVECTOR2 *pRotationCenter,
  FLOAT Rotation,
  CONST D3DXVECTOR2 *pTranslation
);

Parameters

pOut
[in] Pointer to the D3DXMATRIX that is the result of the operation.
Scaling
[in] Scaling factor.
pRotationCenter
[in] Pointer to a D3DXVECTOR2, a point identifying the center of rotation. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
Rotation
[in] The angle of rotation.
pTranslation
[in] Pointer to a D3DXVECTOR2, representing the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Values

Pointer to a D3DXMATRIX structure that is an affine transformation matrix.

Remarks

This function calculates the affine transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = Ms * (Mrc)-1 * Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Ms = scaling matrix (Scaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (Rotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixAffineTransformation2D function can be used as a parameter for another function.

For 3D affine transformations, use D3DXMatrixAffineTransformation.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixDecompose

Breaks down a general 3D transformation matrix into its scalar, rotational, and translational components.

HRESULT D3DXMatrixDecompose(
  D3DXVECTOR3 *pOutScale,
  D3DXQUATERNION *pOutRotation,
  D3DXVECTOR3 *pOutTranslation,
  CONST D3DXMATRIX *pM
);

Parameters

pOutScale
[in] Pointer to the output D3DXVECTOR3 that contains scaling factors applied along the x, y, and z-axes.
pOutRotation
[in] Pointer to the D3DXQUATERNION that describes the rotation.
pOutTranslation
[in] Pointer to the D3DXVECTOR3 vector that describes the translation.
pM
[in] Pointer to an input D3DXMATRIX matrix to decompose.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixDeterminant

Returns the determinant of a matrix.

FLOAT D3DXMatrixDeterminant(
  CONST D3DXMATRIX *pM
);

Parameters

pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Returns the determinant of the matrix.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixInverse

Calculates the inverse of a matrix.

D3DXMATRIX * D3DXMatrixInverse(
  D3DXMATRIX *pOut,
  FLOAT *pDeterminant,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pDeterminant
[in, out] Pointer to a FLOAT value containing the determinant of the matrix. If the determinant is not needed, set this parameter to NULL.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXMATRIX structure that is the inverse of the matrix. If matrix inversion fails, NULL is returned.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixInverse function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixLookAtLH

Builds a left-handed, look-at matrix.

D3DXMATRIX * D3DXMatrixLookAtLH(
  D3DXMATRIX *pOut,
  CONST D3DXVECTOR3 *pEye,
  CONST D3DXVECTOR3 *pAt,
  CONST D3DXVECTOR3 *pUp
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
[in] Pointer to the D3DXVECTOR3 that defines the eye point. This value is used in translation.
pAt
[in] Pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
[in] Pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Values

Pointer to a D3DXMATRIX structure that is a left-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

zaxis = normal(At - Eye)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, eye)  -dot(yaxis, eye)  -dot(zaxis, eye)  l

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixLookAtRH

Builds a right-handed, look-at matrix.

D3DXMATRIX * D3DXMatrixLookAtRH(
  D3DXMATRIX *pOut,
  CONST D3DXVECTOR3 *pEye,
  CONST D3DXVECTOR3 *pAt,
  CONST D3DXVECTOR3 *pUp
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
[in] Pointer to the D3DXVECTOR3 that defines the eye point. This value is used in translation.
pAt
[in] Pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
[in] Pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Values

Pointer to a D3DXMATRIX structure that is a right-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

zaxis = normal(Eye - At)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, eye)  -dot(yaxis, eye)  -dot(zaxis, eye)  l

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixMultiply

Determines the product of two matrices.

D3DXMATRIX * D3DXMatrixMultiply(
  D3DXMATRIX *pOut,
  CONST D3DXMATRIX *pM1,
  CONST D3DXMATRIX *pM2
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM1
[in] Pointer to a source D3DXMATRIX structure (left hand side).
pM2
[in] Pointer to a source D3DXMATRIX structure (right hand side).

Return Values

Pointer to a D3DXMATRIX structure that is the product of two matrices.

Remarks

The result represents the transformation M1 followed by the transformation M2 (Out = M1 * M2).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixMultiply function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixMultiplyTranspose

Calculates the transposed product of two matrices.

D3DXMATRIX * D3DXMatrixMultiplyTranspose(
  D3DXMATRIX *pOut,
  CONST D3DXMATRIX *pM1,
  CONST D3DXMATRIX *pM2
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM1
[in] Pointer to a source D3DXMATRIX structure (left hand side).
pM2
[in] Pointer to a source D3DXMATRIX structure (right hand side).

Return Values

Pointer to a D3DXMATRIX structure that is the product of two matrices.

Remarks

The result is the transposed of the product of two transformation matrices, Out = T(M1*M2).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixMultiplyTranspose function can be used as a parameter for another function.

This function is useful to set matrices as constants for vertex and pixel shaders.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixOrthoLH

Builds a left-handed orthographic projection matrix.

D3DXMATRIX * D3DXMatrixOrthoLH(
  D3DXMATRIX *pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the resulting D3DXMATRIX.
w
[in] Width of the view volume.
h
[in] Height of the view volume.
zn
[in] Minimum z-value of the view volume which is referred to as z-near.
zf
[in] Maximum z-value of the view volume which is referred to as z-far.

Return Values

Pointer to the resulting D3DXMATRIX.

Remarks

All the parameters of the D3DXMatrixOrthoLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/w  0    0           0
0    2/h  0           0
0    0    1/(zf-zn)   0
0    0    zn/(zn-zf)  1

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixOrthoOffCenterLH

Builds a customized, left-handed orthographic projection matrix.

D3DXMATRIX * D3DXMatrixOrthoOffCenterLH(
  D3DXMATRIX *pOut,
  FLOAT l,
  FLOAT r,
  FLOAT b,
  FLOAT t,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the resulting D3DXMATRIX.
l
[in] Minimum x-value of view volume.
r
[in] Maximum x-value of view volume.
b
[in] Minimum y-value of view volume.
t
[in] Maximum y-value of view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to the resulting D3DXMATRIX.

Remarks

The D3DXMatrixOrthoLH is a special case of the D3DXMatrixOrthoOffCenterLH function. To create the same projection using D3DXMatrixOrthoOffCenterLH, use the following values:

l = -w/2,

r = w/2,

b = -h/2, and

t = h/2.

All the parameters of the D3DXMatrixOrthoOffCenterLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/(r-l)      0            0           0
0            2/(t-b)      0           0
0            0            1/(zf-zn)   0
(l+r)/(l-r)  (t+b)/(b-t)  zn/(zn-zf)  l

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixOrthoOffCenterRH

Builds a customized, right-handed orthographic projection matrix.

D3DXMATRIX * D3DXMatrixOrthoOffCenterRH(
  D3DXMATRIX *pOut,
  FLOAT l,
  FLOAT r,
  FLOAT b,
  FLOAT t,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the resulting D3DXMATRIX.
l
[in] Minimum x-value of view volume.
r
[in] Maximum x-value of view volume.
b
[in] Minimum y-value of view volume.
t
[in] Maximum y-value of view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to the resulting D3DXMATRIX.

Remarks

The D3DXMatrixOrthoRH function is a special case of the D3DXMatrixOrthoOffCenterRH function. To create the same projection using D3DXMatrixOrthoOffCenterRH, use the following values:

l = -w/2,

r = w/2,

b = -h/2, and

t = h/2.

All the parameters of the D3DXMatrixOrthoOffCenterRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/(r-l)      0            0           0
0            2/(t-b)      0           0
0            0            1/(zn-zf)   0
(l+r)/(l-r)  (t+b)/(b-t)  zn/(zn-zf)  l

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixOrthoRH

Builds a right-handed orthographic projection matrix.

D3DXMATRIX * D3DXMatrixOrthoRH(
  D3DXMATRIX *pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the resulting D3DXMATRIX.
w
[in] Width of the view volume.
h
[in] Height of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to the resulting D3DXMATRIX.

Remarks

All the parameters of the D3DXMatrixOrthoRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/w  0    0           0
0    2/h  0           0
0    0    1/(zn-zf)   0
0    0    zn/(zn-zf)  l

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixPerspectiveFovLH

Builds a left-handed perspective projection matrix based on a field of view.

D3DXMATRIX * D3DXMatrixPerspectiveFovLH(
  D3DXMATRIX *pOut,
  FLOAT fovy,
  FLOAT Aspect,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
fovy
[in] Field of view in the y direction, in radians.
Aspect
[in] Aspect ratio, defined as view space width divided by height.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovLH function can be used as a parameter for another function.

This function computes the returned matrix as shown:

xScale     0          0               0
0        yScale       0               0
0          0       zf/(zf-zn)         1
0          0       -zn*zf/(zf-zn)     0
where:
yScale = cot(fovY/2)

xScale = yScale / aspect ratio

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixPerspectiveFovRH

Builds a right-handed perspective projection matrix based on a field of view.

D3DXMATRIX * D3DXMatrixPerspectiveFovRH(
  D3DXMATRIX *pOut,
  FLOAT fovy,
  FLOAT Aspect,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
fovy
[in] Field of view in the y direction, in radians.
Aspect
[in] Aspect ratio, defined as view space width divided by height.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovRH function can be used as a parameter for another function.

This function computes the returned matrix as shown.

xScale     0          0              0
0        yScale       0              0
0          0      zf/(zn-zf)        -1
0          0      zn*zf/(zn-zf)      0
where:
yScale = cot(fovY/2)

xScale = yScale / aspect ratio

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixPerspectiveLH

Builds a left-handed perspective projection matrix

D3DXMATRIX * D3DXMatrixPerspectiveLH(
  D3DXMATRIX *pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view volume at the near view-plane.
h
[in] Height of the view volume at the near view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/w  0       0              0
0       2*zn/h  0              0
0       0       zf/(zf-zn)     1
0       0       zn*zf/(zn-zf)  0

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixPerspectiveOffCenterLH

Builds a customized, left-handed perspective projection matrix.

D3DXMATRIX * D3DXMatrixPerspectiveOffCenterLH(
  D3DXMATRIX *pOut,
  FLOAT l,
  FLOAT r,
  FLOAT b,
  FLOAT t,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of the view volume.
r
[in] Maximum x-value of the view volume.
b
[in] Minimum y-value of the view volume.
t
[in] Maximum y-value of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to a D3DXMATRIX structure that is a customized, left-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/(r-l)   0            0              0
0            2*zn/(t-b)   0              0
(l+r)/(l-r)  (t+b)/(b-t)  zf/(zf-zn)     1
0            0            zn*zf/(zn-zf)  0

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixPerspectiveOffCenterRH

Builds a customized, right-handed perspective projection matrix.

D3DXMATRIX * D3DXMatrixPerspectiveOffCenterRH(
  D3DXMATRIX *pOut,
  FLOAT l,
  FLOAT r,
  FLOAT b,
  FLOAT t,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of the view volume.
r
[in] Maximum x-value of the view volume.
b
[in] Minimum y-value of the view volume.
t
[in] Maximum y-value of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to a D3DXMATRIX structure that is a customized, right-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/(r-l)   0            0                0
0            2*zn/(t-b)   0                0
(l+r)/(r-l)  (t+b)/(t-b)  zf/(zn-zf)      -1
0            0            zn*zf/(zn-zf)    0

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixPerspectiveRH

Builds a right-handed perspective projection matrix.

D3DXMATRIX * D3DXMatrixPerspectiveRH(
  D3DXMATRIX *pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view volume at the near view-plane.
h
[in] Height of the view volume at the near view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/w  0       0              0
0       2*zn/h  0              0
0       0       zf/(zn-zf)    -1
0       0       zn*zf/(zn-zf)  0

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixReflect

Builds a matrix that reflects the coordinate system about a plane.

D3DXMATRIX * D3DXMatrixReflect(
  D3DXMATRIX *pOut,
  CONST D3DXPLANE *pPlane
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pPlane
[in] Pointer to the source D3DXPLANE.

Return Values

Pointer to a D3DXMATRIX structure that reflects the coordinate system about the source plane.

Remarks

This function normalizes the plane equation before it creates the reflected matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixReflect function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

P = normalize(Plane);

-2 * P.a * P.a + 1  -2 * P.b * P.a      -2 * P.c * P.a        0
-2 * P.a * P.b      -2 * P.b * P.b + 1  -2 * P.c * P.b        0
-2 * P.a * P.c      -2 * P.b * P.c      -2 * P.c * P.c + 1    0
-2 * P.a * P.d      -2 * P.b * P.d      -2 * P.c * P.d        l

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixRotationAxis

Builds a matrix that rotates around an arbitrary axis.

D3DXMATRIX * D3DXMatrixRotationAxis(
  D3DXMATRIX *pOut,
  CONST D3DXVECTOR3 *pV,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pV
[in] Pointer to the arbitrary axis. See D3DXVECTOR3.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationAxis function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixRotationQuaternion

Builds a rotation matrix from a quaternion.

D3DXMATRIX * D3DXMatrixRotationQuaternion(
  D3DXMATRIX *pOut,
  CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXMATRIX structure built from the source quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationQuaternion function can be used as a parameter for another function.

For information about how to calculate quaternion values from a direction vector ( x, y, z ) and an angle of rotation, see D3DXQUATERNION.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixRotationX

Builds a matrix that rotates around the x-axis.

D3DXMATRIX * D3DXMatrixRotationX(
  D3DXMATRIX *pOut,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the x-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationX function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixRotationY

Builds a matrix that rotates around the y-axis.

D3DXMATRIX * D3DXMatrixRotationY(
  D3DXMATRIX *pOut,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the y-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationY function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixRotationYawPitchRoll

Builds a matrix with a specified yaw, pitch, and roll.

D3DXMATRIX * D3DXMatrixRotationYawPitchRoll(
  D3DXMATRIX *pOut,
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Yaw
[in] Yaw around the y-axis, in radians.
Pitch
[in] Pitch around the x-axis, in radians.
Roll
[in] Roll around the z-axis, in radians.

Return Values

Pointer to a D3DXMATRIX structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationYawPitchRoll function can be used as a parameter for another function.

The order of transformations is roll first, then pitch, then yaw. Relative to the object's local coordinate axis, this is equivalent to rotation around the z-axis, followed by rotation around the x-axis, followed by rotation around the y-axis.

Figure 1. Roll, pitch, yaw diagram

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixRotationZ

Builds a matrix that rotates around the z-axis.

D3DXMATRIX * D3DXMatrixRotationZ(
  D3DXMATRIX *pOut,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when viewed from the rotation axis (positive side) toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the z-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationZ function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixScaling

Builds a matrix that scales along the x-axis, the y-axis, and the z-axis.

D3DXMATRIX * D3DXMatrixScaling(
  D3DXMATRIX *pOut,
  FLOAT sx,
  FLOAT sy,
  FLOAT sz
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
sx
[in] Scaling factor that is applied along the x-axis.
sy
[in] Scaling factor that is applied along the y-axis.
sz
[in] Scaling factor that is applied along the z-axis.

Return Values

Pointer to the scaling transformation D3DXMATRIX.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixScaling function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixShadow

Builds a matrix that flattens geometry into a plane.

D3DXMATRIX * D3DXMatrixShadow(
  D3DXMATRIX *pOut,
  CONST D3DXVECTOR4 *pLight,
  CONST D3DXPLANE *pPlane
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pLight
[in] Pointer to a D3DXVECTOR4 describing the light's position.
pPlane
[in] Pointer to the source D3DXPLANE.

Return Values

Pointer to a D3DXMATRIX structure that flattens geometry into a plane.

Remarks

The D3DXMatrixShadow function flattens geometry into a plane, as if casting a shadow from a light.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixShadow function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

P = normalize(Plane);
L = Light;
d = dot(P, L)

P.a * L.x + d  P.a * L.y      P.a * L.z      P.a * L.w
P.b * L.x      P.b * L.y + d  P.b * L.z      P.b * L.w
P.c * L.x      P.c * L.y      P.c * L.z + d  P.c * L.w
P.d * L.x      P.d * L.y      P.d * L.z      P.d * L.w + d

If the light's w-component is 0, the ray from the origin to the light represents a directional light. If it is 1, the light is a point light.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixTransformation

Builds a transformation matrix. NULL arguments are treated as identity transformations.

D3DXMATRIX * D3DXMatrixTransformation(
  D3DXMATRIX *pOut,
  CONST D3DXVECTOR3 *pScalingCenter,
  CONST D3DXQUATERNION *pScalingRotation,
  CONST D3DXVECTOR3 *pScaling,
  CONST D3DXVECTOR3 *pRotationCenter,
  CONST D3DXQUATERNION *pRotation,
  CONST D3DXVECTOR3 *pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pScalingCenter
[in] Pointer to a D3DXVECTOR3, identifying the scaling center point. If this argument is NULL, an identity Msc matrix is applied to the formula in Remarks.
pScalingRotation
[in] Pointer to a D3DXQUATERNION that specifies the scaling rotation. If this argument is NULL, an identity Msr matrix is applied to the formula in Remarks.
pScaling
[in] Pointer to a D3DXVECTOR3 structure, the scaling vector. If this argument is NULL, an identity Ms matrix is applied to the formula in Remarks.
pRotationCenter
[in] Pointer to a D3DXVECTOR3 structure, a point that identifies the center of rotation. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
pRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the rotation. If this argument is NULL, an identity Mr matrix is applied to the formula in Remarks.
pTranslation
[in] Pointer to a D3DXVECTOR3 structure, representing the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Values

Pointer to a D3DXMATRIX structure that is the transformation matrix.

Remarks

This function calculates the transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = (Msc)-1 * (Msr)-1* Ms * Msr * Msc * (Mrc)-1* Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Msc = scaling center matrix (pScalingCenter)

Msr = scaling rotation matrix (pScalingRotation)

Ms = scaling matrix (pScaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (pRotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTransformation function can be used as a parameter for another function.

For 2D transformations, use D3DXMatrixTransformation2D.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixTransformation2D

Builds a 2D transformation matrix that represents transformations in the xy plane. NULL arguments are treated as identity transformations.

D3DXMATRIX * D3DXMatrixTransformation2D(
  D3DXMATRIX *pOut,
  CONST D3DXVECTOR2 *pScalingCenter,
  FLOAT ScalingRotation,
  CONST D3DXVECTOR2 *pScaling,
  CONST D3DXVECTOR2 *pRotationCenter,
  FLOAT Rotation,
  CONST D3DXVECTOR2 *pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that contains the result of the transformations.
pScalingCenter
[in] Pointer to a D3DXVECTOR2, a point identifying the scaling center. If this argument is NULL, an identity Msc matrix is applied to the formula in Remarks.
ScalingRotation
[in] Pointer to the scaling rotation factor.
pScaling
[in] Pointer to a D3DXVECTOR2 structure, a point identifying the scale. If this argument is NULL, an identity Ms matrix is applied to the formula in Remarks.
pRotationCenter
[in] Pointer to a D3DXVECTOR2 structure, a point identifying the rotation center. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
Rotation
[in] The angle of rotation in radians.
pTranslation
[in] Pointer to a D3DXVECTOR2 structure, identifying the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Values

Pointer to a D3DXMATRIX structure that contains the transformation matrix.

Remarks

This function calculates the transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = (Msc)-1* (Msr)-1* Ms * Msr * Msc * (Mrc)-1* Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Msc = scaling center matrix (pScalingCenter)

Msr = scaling rotation matrix (pScalingRotation)

Ms = scaling matrix (pScaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (Rotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTransformation2D function can be used as a parameter for another function.

For 3D transformations, use D3DXMatrixTransformation.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixTranslation

Create a translation matrix.

D3DXMATRIX* D3DXMatrixTranslation(
  D3DXMATRIX *pOut,
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

pOut
[in, out] The matrix that will become a translation matrix. See D3DXMATRIX.
x
[in] The x-component of the translation.
y
[in] The y-component of the translation.
z
[in] The z-component of the translation.

Return Values

The translation matrix.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXMatrixTranspose

Returns the matrix transpose of a matrix.

D3DXMATRIX * D3DXMatrixTranspose(
  D3DXMATRIX *pOut,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to the D3DXMATRIX structure that is the matrix transpose of the matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTranspose function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXPlaneFromPointNormal

Constructs a plane from a point and a normal.

D3DXPLANE * D3DXPlaneFromPointNormal(
  D3DXPLANE *pOut,
  CONST D3DXVECTOR3 *pPoint,
  CONST D3DXVECTOR3 *pNormal
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE that is the result of the operation.
pPoint
[in] Pointer to a D3DXVECTOR3, defining the point used to construct the plane.
pNormal
[in] Pointer to a D3DXVECTOR3 structure, defining the normal used to construct the plane.

Return Values

Pointer to the D3DXPLANE structure constructed from the point and the normal.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPointNormal function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXPlaneFromPoints

Constructs a plane from three points.

D3DXPLANE * D3DXPlaneFromPoints(
  D3DXPLANE *pOut,
  CONST D3DXVECTOR3 *pV1,
  CONST D3DXVECTOR3 *pV2,
  CONST D3DXVECTOR3 *pV3
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE that is the result of the operation.
pV1
[in] Pointer to a D3DXVECTOR3, defining one of the points used to construct the plane.
pV2
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.
pV3
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.

Return Values

Pointer to the D3DXPLANE structure constructed from the given points.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPoints function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXPlaneIntersectLine

Finds the intersection between a plane and a line.

D3DXVECTOR3 * D3DXPlaneIntersectLine(
  D3DXVECTOR3 *pOut,
  CONST D3DXPLANE *pP,
  CONST D3DXVECTOR3 *pV1,
  CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to a D3DXVECTOR3, identifying the intersection between the specified plane and line.
pP
[in] Pointer to the source D3DXPLANE.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, defining a line starting point.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, defining a line ending point.

Return Values

Pointer to a D3DXVECTOR3 structure that is the intersection between the specified plane and line.

Remarks

If the line is parallel to the plane, NULL is returned.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneIntersectLine function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXPlaneNormalize

Normalizes the plane coefficients so that the plane normal has unit length.

D3DXPLANE * D3DXPlaneNormalize(
  D3DXPLANE *pOut,
  CONST D3DXPLANE *pP
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE that is the result of the operation.
pP
[in] Pointer to the source D3DXPLANE structure.

Return Values

Pointer to a D3DXPLANE structure that represents the normal of the plane.

Remarks

This function normalizes a plane so that |a,b,c| == 1.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXPlaneTransform

Transforms a plane by a matrix. The input matrix is the inverse transpose of the actual transformation.

D3DXPLANE * D3DXPlaneTransform(
  D3DXPLANE *pOut,
  CONST D3DXPLANE *pP,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE that contains the resulting transformed plane. See example.
pP
[in] Pointer to the input D3DXPLANE structure, which contains the plane that will be transformed. The vector (a,b,c) that describes the plane must be normalized before this function is called. See example.
pM
[in] Pointer to the source D3DXMATRIX structure, which contains the transformation values. This matrix must contain the inverse transpose of the transformation values.

Return Values

Pointer to a D3DXPLANE structure, representing the transformed plane. This is the same value returned in the pOut parameter so that this function can be used as a parameter for another function.

Remarks

Examples

This example transforms a plane by applying a non-uniform scale.

D3DXPLANE   planeNew;
D3DXPLANE   plane(0,1,1,0);
D3DXPlaneNormalize(&plane, &plane);

D3DXMATRIX  matrix;
D3DXMatrixScaling(&matrix, 1.0f,2.0f,3.0f);
D3DXMatrixInverse(&matrix, NULL, &matrix);
D3DXMatrixTranspose(&matrix, &matrix);
D3DXPlaneTransform(&planeNew, &plane, &matrix);

A plane is described by ax + by + cz + dw = 0. The first plane is created with (a,b,c,d) = (0,1,1,0), which is a plane described by y + z = 0. After scaling, the new plane contains (a,b,c,d) = (0, 0.353f, 0.235f, 0), which shows the new plane to be described by 0.353y + 0.235z = 0.

The parameter pM contains the inverse transpose of the transformation matrix. The inverse transpose is required by this method so that the normal vector of the transformed plane can be correctly transformed as well.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXPlaneTransformArray

Transforms an array of planes by a matrix. The vectors that describe each plane must be normalized.

D3DXPLANE * D3DXPlaneTransformArray(
  D3DXPLANE *pOut,
  UINT OutStride,
  CONST D3DXPLANE *pP,
  UINT PStride,
  CONST D3DXMATRIX *pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that contains the resulting transformed plane. See Example.
OutStride
[in] The stride of each transformed plane.
pP
[in] Pointer to the input D3DXPLANE structure, which contains the array of planes to transform. The vector (a, b, c) that describes the plane must be normalized before this function is called. See Example.
PStride
[in] The stride of each non-transformed plane.
pM
[in] Pointer to the source D3DXMATRIX structure, which contains the inverse transpose of the transformation values.
n
[in] The number of planes to transform.

Return Values

Pointer to a D3DXPLANE structure, representing the transformed plane. This is the same value returned in the pOut parameter so that this function can be used as a parameter for another function.

Remarks

This example transforms one plane by applying a non-uniform scale.

#define ARRAYSIZE 4
D3DXPLANE planeNew[ARRAYSIZE];
D3DXPLANE plane[ARRAYSIZE];

for(int i = 0; i < ARRAYSIZE; i++)
{
    plane = D3DXPLANE( 0.0f, 1.0f, 1.0f, 0.0f );
    D3DXPlaneNormalize( &plane[i], &plane[i] );
}

D3DXMATRIX  matrix;
D3DXMatrixScaling( &matrix, 1.0f, 2.0f, 3.0f );
D3DXMatrixInverse( &matrix, NULL, &matrix );
D3DXMatrixTranspose( &matrix, &matrix );
D3DXPlaneTransformArray( &planeNew, sizeof (D3DXPLANE), &plane,
                         sizeof (D3DXPLANE), &matrix, ARRAYSIZE );

A plane is described by ax + by + cz + dw = 0. The first plane is created with (a,b,c,d) = (0,1,1,0), which is a plane described by y + z = 0. After scaling, the new plane contains (a,b,c,d) = (0, 0.353f, 0.235f, 0), which shows the new plane to be described by 0.353y + 0.235z = 0.

The parameter pM, contains the inverse transpose of the transformation matrix. The inverse transpose is required by this method so that the normal vector of the transformed plane can be correctly transformed as well.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionBaryCentric

Returns a quaternion in barycentric coordinates.

D3DXQUATERNION * D3DXQuaternionBaryCentric(
  D3DXQUATERNION *pOut,
  CONST D3DXQUATERNION *pQ1,
  CONST D3DXQUATERNION *pQ2,
  CONST D3DXQUATERNION *pQ3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
pQ3
[in] Pointer to a source D3DXQUATERNION structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXQUATERNION structure in Barycentric coordinates.

Remarks

To compute the barycentric coordinates, the D3DXQuaternionBaryCentric function implements the following series of spherical linear interpolation operations:

Slerp(Slerp(Q1, Q2, f+g), Slerp(Q1, Q3, f+g), g/(f+g))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionBaryCentric function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionExp

Calculates the exponential.

D3DXQUATERNION * D3DXQuaternionExp(
  D3DXQUATERNION *pOut,
  CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the exponential.

Remarks

This method converts a pure quaternion to a unit quaternion. D3DXQuaternionExp expects a pure quaternion, where w is ignored in the calculation (w == 0).

Given a pure quaternion defined by:
q = (0, theta * v);

This method calculates the exponential result.
exp(Q) = (cos(theta), sin(theta) * v)

where v is the vector portion of a quaternion.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionExp function can be used as a parameter for another function.

The D3DXQuaternionSquadSetup method can also be used to set up the control points of a quaternion.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionInverse

Conjugates and renormalizes a quaternion.

D3DXQUATERNION * D3DXQuaternionInverse(
  D3DXQUATERNION *pOut,
  CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the inverse quaternion of the quaternion.

Remarks

A unit quaternion, is defined by:
Q == (cos(theta), sin(theta) * v) where |v| = 1
The natural logarithm of Q is, ln(Q) = (0, theta * v)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionInverse function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionLn

Calculates the natural logarithm.

D3DXQUATERNION * D3DXQuaternionLn(
  D3DXQUATERNION *pOut,
  CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the natural logarithm.

Remarks

The D3DXQuaternionLn function works only for unit quaternions.

A unit quaternion, is defined by:
Q == (cos(theta), sin(theta) * v) where |v| = 1
The natural logarithm of Q is, ln(Q) = (0, theta * v)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionLn function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionMultiply

Multiplies two quaternions.

D3DXQUATERNION * D3DXQuaternionMultiply(
  D3DXQUATERNION *pOut,
  CONST D3DXQUATERNION *pQ1,
  CONST D3DXQUATERNION *pQ2
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the product of two quaternions.

Remarks

The result represents the rotation Q1 followed by the rotation Q2 (Out = Q1 * Q2). This is done so that D3DXQuaternionMultiply maintain the same semantics as D3DXMatrixMultiply because unit quaternions can be considered as another way to represent rotation matrices.

Transformations are concatenated in the same order for both the D3DXQuaternionMultiply and D3DXMatrixMultiply Functions. For example, assuming mX and mY represent the same rotations as qX and qY, both m and q will represent the same rotations.

D3DXMatrixMultiply(&m, &mX, &mY);
D3DXQuaternionMultiply(&q, &qX, &qY);

The multiplication of quaternions is not commutative.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionMultiply function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionNormalize

Computes a unit length quaternion.

D3DXQUATERNION * D3DXQuaternionNormalize(
  D3DXQUATERNION *pOut,
  CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the normal of the quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionNormalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionRotationAxis

Rotates a quaternion about an arbitrary axis.

D3DXQUATERNION * D3DXQuaternionRotationAxis(
  D3DXQUATERNION *pOut,
  CONST D3DXVECTOR3 *pV,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
pV
[in] Pointer to the D3DXVECTOR3 that identifies the axis about which to rotate the quaternion.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXQUATERNION structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationAxis function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionRotationMatrix

Builds a quaternion from a rotation matrix.

D3DXQUATERNION * D3DXQuaternionRotationMatrix(
  D3DXQUATERNION *pOut,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to the D3DXQUATERNION structure built from a rotation matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationMatrix function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionRotationYawPitchRoll

Builds a quaternion with the given yaw, pitch, and roll.

D3DXQUATERNION * D3DXQuaternionRotationYawPitchRoll(
  D3DXQUATERNION *pOut,
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
Yaw
[in] Yaw around the y-axis, in radians.
Pitch
[in] Pitch around the x-axis, in radians.
Roll
[in] Roll around the z-axis, in radians.

Return Values

Pointer to a D3DXQUATERNION structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationYawPitchRoll function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionSlerp

Interpolates between two quaternions, using spherical linear interpolation.

D3DXQUATERNION * D3DXQuaternionSlerp(
  D3DXQUATERNION *pOut,
  CONST D3DXQUATERNION *pQ1,
  CONST D3DXQUATERNION *pQ2,
  FLOAT t
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
t
[in] Parameter that indicates how far to interpolate between the quaternions.

Return Values

Pointer to a D3DXQUATERNION structure that is the result of the interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSlerp function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionSquad

Interpolates between quaternions, using spherical quadrangle interpolation.

D3DXQUATERNION * D3DXQuaternionSquad(
  D3DXQUATERNION *pOut,
  CONST D3DXQUATERNION *pQ1,
  CONST D3DXQUATERNION *pA,
  CONST D3DXQUATERNION *pB,
  CONST D3DXQUATERNION *pC,
  FLOAT t
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pA
[in] Pointer to a source D3DXQUATERNION structure.
pB
[in] Pointer to a source D3DXQUATERNION structure.
pC
[in] Pointer to a source D3DXQUATERNION structure.
t
[in] Parameter that indicates how far to interpolate between the quaternions.

Return Values

Pointer to a D3DXQUATERNION structure that is the result of the spherical quadrangle interpolation.

Remarks

This function uses the following sequence of spherical linear interpolation operations:

Slerp(Slerp(pQ1, pC, t), Slerp(pA, pB, t), 2t(1 - t))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSquad function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionSquadSetup

Sets up control points for spherical quadrangle interpolation.

void D3DXQuaternionSquadSetup(
  D3DXQUATERNION *pAOut,
  D3DXQUATERNION *pBOut,
  D3DXQUATERNION *pCOut,
  CONST D3DXQUATERNION *pQ0,
  CONST D3DXQUATERNION *pQ1,
  CONST D3DXQUATERNION *pQ2,
  CONST D3DXQUATERNION *pQ3
);

Parameters

pAOut
[in] Pointer to AOut.
pBOut
[in] Pointer to BOut.
pCOut
[in] Pointer to COut.
pQ0
[in] Pointer to the input control point, Q0.
pQ1
[in] Pointer to the input control point, Q1.
pQ2
[in] Pointer to the input control point, Q2.
pQ3
[in] Pointer to the input control point, Q3.

Return Values

None.

Remarks

This function takes four control points, which are supplied to the inputs pQ0, pQ1, pQ2, and pQ3. The function then alters these values to find a curve that flows along the shortest path. The values of q0, q2, and q3 are calculated as shown below.

q0 = |Q0 + Q1| < |Q0 - Q1| ? -Q0 : Q0
q2 = |Q1 + Q2| < |Q1 - Q2| ? -Q2 : Q2
q3 = |Q2 + Q3| < |Q2 - Q3| ? -Q3 : Q3

Having calculated the new Q values, the values for AOut, BOut, and COut are calculated as follows:

AOut = q1 * e[-0.25 *( Ln[Exp(q1)*q2] + Ln[Exp(q1)*q0] ) ]

BOut = q2 * e[-0.25 *( Ln[Exp(q2)*q3] + Ln[Exp(q2)*q1] ) ]

COut = q2

Note Ln is the API method D3DXQuaternionLn and Exp is the API method D3DXQuaternionExp.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Examples

The following example shows how to use a set of quaternion keys (Q0, Q1, Q2, Q3) to compute the inner quadrangle points (A, B, C). This ensures that the tangents are continuous across adjacent segments.

      A     B
Q0    Q1    Q2    Q3

The following code example demonstrates how you can interpolate between Q1 and Q2.

// Rotation about the z-axis
D3DXQUATERNION Q0 = D3DXQUATERNION(0,  0, 0.707f, -.707f);
D3DXQUATERNION Q1 = D3DXQUATERNION(0,  0, 0.000f, 1.000f);
D3DXQUATERNION Q2 = D3DXQUATERNION(0,  0, 0.707f, 0.707f);
D3DXQUATERNION Q3 = D3DXQUATERNION(0,  0, 1.000f, 0.000f);
D3DXQUATERNION A, B, C, Qt;
FLOAT time = 0.5f;

D3DXQuaternionSquadSetup(&A, &B, &C, &Q0, &Q1, &Q2, &Q3);
D3DXQuaternionSquad(&Qt, &Q1, &A, &B, &C, time);

Note

  • C is +/- Q2 depending on the result of the function.
  • Qt is the result of the function.

The result is a rotation of 45 degrees around the z-axis for time = 0.5.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXQuaternionToAxisAngle

Computes a quaternion's axis and angle of rotation.

void D3DXQuaternionToAxisAngle(
  CONST D3DXQUATERNION *pQ,
  D3DXVECTOR3 *pAxis,
  FLOAT *pAngle
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION.
pAxis
[in, out] This function returns a pointer to a D3DXVECTOR3 that identifies the quaternion's axis of rotation.
pAngle
[in, out] This function returns a pointer to a FLOAT value that identifies the quaternion's angle of rotation in radians.

Return Values

No return value.

Remarks

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXSHAdd

Adds two spherical harmonic (SH) vectors; in other words, pOut[i] = pA[i] + pB[i].

FLOAT * D3DXSHAdd(
  FLOAT *pOut,
  UINT Order,
  CONST FLOAT *pA,
  CONST FLOAT *pB
);

Parameters

pOut
[in] Pointer to SH output coefficients. The evaluation generates Order2 coefficients. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pA
[in] Pointer to the first SH vector.
pB
[in] Pointer to the second SH vector.

Return Values

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Requirements

Header: Declared in D3DX10.h.

See Also

Math Functions


D3DXSHDot

Computes the dot product of two spherical harmonic (SH) vectors.

FLOAT D3DXSHDot(
  UINT Order,
  CONST FLOAT *pA,
  CONST FLOAT *pB
);

Parameters

Order
[in] Order of the spherical harmonic (SH) evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pA
[in] Pointer to the first SH vector.
pB
[in] Pointer to the second SH vector.

Return Values

SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Requirements

Header: Declared in D3DX10.h.

See Also

Math Functions


D3DXSHEvalConeLight

Evaluates a light that is a cone of constant intensity and returns spectral spherical harmonic (SH) data.

HRESULT D3DXSHEvalConeLight(
  UINT Order,
  CONST D3DXVECTOR3 *pDir,
  FLOAT Radius,
  FLOAT RIntensity,
  FLOAT GIntensity,
  FLOAT BIntensity,
  FLOAT *pROut,
  FLOAT *pGOut,
  FLOAT *pBOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] Pointer to the (x, y, z) hemisphere axis direction vector in which to evaluate the SH basis functions. See Remarks.
Radius
[in] Radius of cone in radians.
RIntensity
[in] The red intensity of the light.
GIntensity
[in] The green intensity of the light.
BIntensity
[in] The blue intensity of the light.
pROut
[in] Pointer to the output SH vector for the red component.
pGOut
[in] Pointer to the output SH vector for the green component.
pBOut
[in] Pointer to the output SH vector for the blue component.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

Evaluates a light that is a cone of constant intensity and returns spectral SH data. The output vector is computed so that if the intensity ratio R/G/B is equal to 1, the exit radiance of a point directly under the light (oriented in the cone direction on a diffuse object with an albedo of 1) would be 1.0. This will compute three spectral samples; pROut will be returned, while pGOut and pBOut may be returned.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Requirements

Header: Declared in D3DX10.h.

See Also

Math Functions


D3DXSHEvalDirection

Evaluates the spherical harmonic (SH) basis functions from an input direction vector.

FLOAT * D3DXSHEvalDirection(
  FLOAT *pOut,
  UINT Order,
  CONST D3DXVECTOR3 *pDir
);

Parameters

pOut
[in] Pointer to Spherical harmonic (SH) output coefficients. The evaluation generates Order2 coefficients. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] (x, y, z) direction vector in which to evaluate the SH basis functions. Must be normalized. See Remarks.

Return Values

Pointer to SH output coefficients. See Remarks.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Requirements

Header: Declared in D3DX10.h.

See Also

Math Functions


D3DXSHEvalDirectionalLight

Evaluates a directional light and returns spectral spherical harmonic (SH) data.

HRESULT D3DXSHEvalDirectionalLight(
  UINT Order,
  CONST D3DXVECTOR3 *pDir,
  FLOAT RIntensity,
  FLOAT GIntensity,
  FLOAT BIntensity,
  FLOAT *pROut,
  FLOAT *pGOut,
  FLOAT *pBOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] Pointer to the (x, y, z) hemisphere axis direction vector in which to evaluate the SH basis functions. See Remarks.
RIntensity
[in] The red intensity of the light.
GIntensity
[in] The green intensity of the light.
BIntensity
[in] The blue intensity of the light.
pROut
[in] Pointer to the output SH vector for the red component.
pGOut
[in] Optional pointer to the output SH vector for the green component.
pBOut
[in] Optional pointer to the output SH vector for the blue component.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

The output vector is computed so that if the intensity ratio R/G/B is equal to 1, the resulting exit radiance of a point directly under the light on a diffuse object with an albedo of 1 would be 1.0. This will compute three spectral samples; pROut will be returned, while pGOut and pBOut may be returned.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Requirements

Header: Declared in D3DX10.h.

See Also

Math Functions


D3DXSHEvalHemisphereLight

Evaluates a light that is a linear interpolation between two colors over the sphere.

HRESULT D3DXSHEvalHemisphereLight(
  UINT Order,
  CONST D3DXVECTOR3 *pDir,
  D3DXCOLOR Top,
  D3DXCOLOR Bottom,
  FLOAT *pROut,
  FLOAT *pGOut,
  FLOAT *pBOut
);

Parameters

Order
[in] Order of the spherical harmonic (SH) evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] Pointer to the (x, y, z) hemisphere axis direction vector in which to evaluate the SH basis functions. See Remarks.
Top
[in] The sky color.
Bottom
[in] The ground color.
pROut
[in] Pointer to the output SH vector for the red component.
pGOut
[in] Pointer to the output SH vector for the green component.
pBOut
[in] Pointer to the output SH vector for the blue component.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

The interpolation is done linearly between the two points, not over the surface of the sphere (that is, if the axis was (0,0,1) it is linear in Z, not in the azimuthal angle). The resulting spherical lighting function is normalized so that a point on a perfectly diffuse surface with no shadowing and a normal pointed in the direction pDir would result in exit radiance with a value of 1 (if the top color was white and the bottom color was black). This is a very simple model where Top represents the intensity of the "sky" and Bottom represents the intensity of the "ground."

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Requirements

Header: Declared in D3DX10.h.

See Also

Math Functions


D3DXSHEvalSphericalLight

Evaluates a spherical light and returns spectral spherical harmonic (SH) data.

HRESULT D3DXSHEvalSphericalLight(
  UINT Order,
  CONST D3DXVECTOR3 *pPos,
  FLOAT Radius,
  FLOAT RIntensity,
  FLOAT GIntensity,
  FLOAT BIntensity,
  FLOAT *pROut,
  FLOAT *pGOut,
  FLOAT *pBOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pPos
[in] Pointer to the light position.
Radius
[in] Radius of spherical light source.
RIntensity
[in] The red intensity of the light.
GIntensity
[in] The green intensity of the light.
BIntensity
[in] The blue intensity of the light.
pROut
[in] Pointer to the output SH vector for the red component.
pGOut
[in] Pointer to the output SH vector for the green component.
pBOut
[in] Pointer to the output SH vector for the blue component.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

Evaluates a spherical light and returns spectral SH data. There is no normalization of the intensity of the light like there is for directional lights, so care has to be taken when specifying the intensities. This will compute three spectral samples; pROut will be returned, while pGOut and pBOut may be returned.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Requirements

Header: Declared in D3DX10.h.

See Also

Math Functions


D3DXSHMultiply2

Computes the product of two spherical harmonics functions (f and g). Both functions are of order N = 2.

FLOAT * D3DXSHMultiply2(
  FLOAT *pOut,
  CONST FLOAT *pF,
  CONST FLOAT *pG
);

Parameters

pOut
[in] Pointer to the output SH coefficients — basis function Ylm is stored at l2 + m + l. The order N determines the length of the array, where there should always be N2 coefficients.
pF
[in] Input SH coefficients for first function.
pG
[in] Second set of input SH coefficients.

Return Values

Pointer to SH output coefficients.

Remarks

The product of two SH functions of order N = 2 generates an SH function of order 2 × N - 1 = 3, but the results are truncated. This means that the product commutes ( f × g = g × f ) but doesn't associate ( f × (g × h) ≠ (f × g) × h ).

This function uses the following equation:

pOut[i] = int(y_i(s) * f(s) * g(s))

where y_i(s) is the ith SH basis function, and where f(s) and g(s) use the following SH function:

sum_i(y_i(s)*c_i)

Requirements

Header: Declared in D3dx10math.h.

See Also

Math Functions


D3DXSHMultiply3

Computes the product of two spherical harmonics functions (f and g). Both functions are of order N = 3.

FLOAT * D3DXSHMultiply3(
  FLOAT *pOut,
  CONST FLOAT *pF,
  CONST FLOAT *pG
);

Parameters

pOut
[in] Pointer to the output SH coefficients — basis function Ylm is stored at l2 + m + l. The order N determines the length of the array, where there should always be N2 coefficients.
pF
[in] Input SH coefficients for first function.
pG
[in] Second set of input SH coefficients.

Return Values

Pointer to SH output coefficients.

Remarks

The product of two SH functions of order N = 3 generates an SH function of order 2 × N - 1 = 5, but the results are truncated. This means that the product commutes ( f × g = g × f ) but doesn't associate ( f × ( g × h ) ≠ ( f × g ) × h ).

This function uses the following equation:

pOut[i] = int(y_i(s) * f(s) * g(s))

where y_i(s) is the ith SH basis function, and where f(s) and g(s) use the following SH function:

sum_i(y_i(s)*c_i)

Requirements

Header: Declared in D3dx10math.h.

See Also

Math Functions


D3DXSHMultiply4

Computes the product of two spherical harmonics functions (f and g). Both functions are of order N = 4.

FLOAT * D3DXSHMultiply4(
  FLOAT *pOut,
  CONST FLOAT *pF,
  CONST FLOAT *pG
);

Parameters

pOut
[in] Pointer to the output SH coefficients — basis function Ylm is stored at l2 + m + l. The order N determines the length of the array, where there should always be N2 coefficients.
pF
[in] Input SH coefficients for first function.
pG
[in] Second set of input SH coefficients.

Return Values

Pointer to SH output coefficients.

Remarks

The product of two SH functions of order N = 4 generates an SH function of order 2 × N - 1 = 7, but the results are truncated. This means that the product commutes ( f × g = g × f ) but doesn't associate ( f × ( g × h ) ≠ ( f × g ) × h ).

This function uses the following equation:

pOut[i] = int(y_i(s) * f(s) * g(s))

where y_i(s) is the ith SH basis function, and where f(s) and g(s) use the following SH function:

sum_i(y_i(s)*c_i)

Requirements

Header: Declared in D3dx10math.h.

See Also

Math Functions


D3DXSHMultiply5

Computes the product of two spherical harmonics functions (f and g). Both functions are of order N = 5.

FLOAT * D3DXSHMultiply5(
  FLOAT *pOut,
  CONST FLOAT *pF,
  CONST FLOAT *pG
);

Parameters

pOut
[in] Pointer to the output SH coefficients — basis function Ylm is stored at l2 + m + l. The order N determines the length of the array, where there should always be N2 coefficients.
pF
[in] Input SH coefficients for first function.
pG
[in] Second set of input SH coefficients.

Return Values

Pointer to SH output coefficients.

Remarks

The product of two SH functions of order N = 5 generates an SH function of order 2 × N - 1 = 9, but the results are truncated. This means that the product commutes ( f × g = g × f ) but doesn't associate ( f × ( g × h ) ≠ ( f × g ) × h ).

This function uses the following equation:

pOut[i] = int(y_i(s) * f(s) * g(s))

where y_i(s) is the ith SH basis function, and where f(s) and g(s) use the following SH function:

sum_i(y_i(s)*c_i)

Requirements

Header: Declared in D3dx10math.h.

See Also

Math Functions


D3DXSHMultiply6

Computes the product of two spherical harmonics functions (f and g). Both functions are of order N = 6.

FLOAT * D3DXSHMultiply6(
  FLOAT *pOut,
  CONST FLOAT *pF,
  CONST FLOAT *pG
);

Parameters

pOut
[in] Pointer to the output SH coefficients — basis function Ylm is stored at l2 + m + l. The order N determines the length of the array, where there should always be N2 coefficients.
pF
[in] Input SH coefficients for first function.
pG
[in] Second set of input SH coefficients.

Return Values

Pointer to SH output coefficients.

Remarks

The product of two SH functions of order N = 6 generates an SH function of order 2 × N - 1 = 11, but the results are truncated. This means that the product commutes ( f × g = g × f ) but doesn't associate ( f × ( g × h ) ≠ ( f × g ) × h ).

This function uses the following equation:

pOut[i] = int(y_i(s) * f(s) * g(s))

where y_i(s) is the ith SH basis function, and where f(s) and g(s) use the following SH function:

sum_i(y_i(s)*c_i)

Requirements

Header: Declared in D3dx10math.h.

See Also

Math Functions


D3DX10SHProjectCubeMap

Projects a function represented in a cube map into spherical harmonics.

HRESULT D3DX10SHProjectCubeMap(
  UINT Order,
  ID3D10Texture2D *pCubeMap,
  FLOAT *pROut,
  FLOAT *pGOut,
  FLOAT *pBOut
);

Parameters

Order
Order of the SH evaluation, generates Order^2 coefs, degree is Order-1.
pCubeMap
Cubemap that is going to be projected into spherical harmonics. See ID3D10Texture2D
pROut
Output SH vector for red.
pGOut
Output SH vector for green.
pBOut
Output SH vector for blue.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3dx10tex.h.


D3DXSHRotate

Rotates the spherical harmonic (SH) vector by the given matrix.

FLOAT * D3DXSHRotate(
  FLOAT *pOut,
  UINT Order,
  CONST D3DXMATRIX *pMatrix,
  CONST FLOAT *pIn
);

Parameters

pOut
[in] Pointer to Spherical harmonic (SH) output coefficients. The evaluation generates Order2 coefficients. This pointer should not alias with pIn. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pMatrix
[in] Pointer to the rotation matrix. The rotation sub-matrix must be orthogonal, with a unit determinant.
pIn
[in] Pointer to rotated SH coefficients.

Return Values

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Requirements

Header: Declared in D3DX10.h.

See Also

Math Functions


D3DXSHRotateZ

Rotates the spherical harmonic (SH) vector in the z-axis by the given angle.

FLOAT * D3DXSHRotateZ(
  FLOAT *pOut,
  UINT Order,
  FLOAT Angle,
  CONST FLOAT *pIn
);

Parameters

pOut
[in] Pointer to Spherical harmonic (SH) output coefficients. The evaluation generates Order2 coefficients. This pointer should not alias with pIn. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
Angle
[in] Rotation angle in radians. The rotation is performed around the z-axis.
pIn
[in] Pointer to rotated SH coefficients.

Return Values

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Requirements

Header: Declared in D3DX10.h.

See Also

Math Functions


D3DXSHScale

Scales a spherical harmonic (SH) vector; in other words, pOut[i] = pA[i]*Scale.

FLOAT * D3DXSHScale(
  FLOAT *pOut,
  UINT Order,
  CONST FLOAT *pIn,
  CONST FLOAT Scale
);

Parameters

pOut
[in] Pointer to Spherical harmonic (SH) output coefficients. The evaluation generates Order2 coefficients. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pIn
[in] Pointer to the SH vector to scale.
Scale
[in] Pointer to the scale value.

Return Values

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Requirements

Header: Declared in D3DX10.h.

See Also

Math Functions


D3DXVec2BaryCentric

Returns a point in Barycentric coordinates, using the specified 2D vectors.

D3DXVECTOR2 * D3DXVec2BaryCentric(
  D3DXVECTOR2 *pOut,
  CONST D3DXVECTOR2 *pV1,
  CONST D3DXVECTOR2 *pV2,
  CONST D3DXVECTOR2 *pV3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[in] Pointer to the D3DXVECTOR2 that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.
pV3
[in] Pointer to a source D3DXVECTOR2 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR2 structure in Barycentric coordinates.

Remarks

The D3DXVec2BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result, and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 &, & g>=0 &, & 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 &, & g>=0 &, & 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 &, & g==0 &, & 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 &, & g>=0 &, & 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2BaryCentric function can be used as a parameter for another function.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec2CatmullRom

Performs a Catmull-Rom interpolation, using the specified 2D vectors.

D3DXVECTOR2 * D3DXVec2CatmullRom(
  D3DXVECTOR2 *pOut,
  CONST D3DXVECTOR2 *pV0,
  CONST D3DXVECTOR2 *pV1,
  CONST D3DXVECTOR2 *pV2,
  CONST D3DXVECTOR2 *pV3,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 that is the result of the operation.
pV0
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV1
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR2 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where:

v1 is the contents of pV0.

v2 is the contents of pV1.

p3 is the contents of pV2.

p4 is the contents of pV3.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s)(p3 - p1) / 2 + (s3 - s2)(p4 - p2)/2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 + (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec2Hermite

Performs a Hermite spline interpolation, using the specified 2D vectors.

D3DXVECTOR2 * D3DXVec2Hermite(
  D3DXVECTOR2 *pOut,
  CONST D3DXVECTOR2 *pV1,
  CONST D3DXVECTOR2 *pT1,
  CONST D3DXVECTOR2 *pV2,
  CONST D3DXVECTOR2 *pT2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR2 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR2 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR2 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec2Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t-1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Hermite function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec2Normalize

Returns the normalized version of a 2D vector.

D3DXVECTOR2 * D3DXVec2Normalize(
  D3DXVECTOR2 *pOut,
  CONST D3DXVECTOR2 *pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the normalized version of the vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Normalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec2Transform

Transforms a 2D vector by a given matrix.

D3DXVECTOR4 * D3DXVec2Transform(
  D3DXVECTOR4 *pOut,
  CONST D3DXVECTOR2 *pV,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the vector pV (x, y, 0, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec2TransformArray

Transforms an array (x, y, 0, 1) by a given matrix.

D3DXVECTOR4 * D3DXVec2TransformArray(
  D3DXVECTOR4 *pOut,
  UINT OutStride,
  CONST D3DXVECTOR2 *pV,
  UINT VStride,
  CONST D3DXMATRIX *pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed array.

Remarks

This function transforms the array pV (x, y, 0, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec2TransformCoord

Transforms a 2D vector by a given matrix, projecting the result back into w = 1.

D3DXVECTOR2 * D3DXVec2TransformCoord(
  D3DXVECTOR2 *pOut,
  CONST D3DXVECTOR2 *pV,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, 0, 1), by the matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformCoord function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec2TransformCoordArray

Transforms an array (x, y, 0, 1) by a given matrix, and projects the result back into w = 1.

D3DXVECTOR2 * D3DXVec2TransformCoordArray(
  D3DXVECTOR2 *pOut,
  UINT OutStride,
  CONST D3DXVECTOR2 *pV,
  UINT VStride,
  CONST D3DXMATRIX *pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR4 transformed array.

Remarks

This function transforms the array pV (x, y, 0, 1) by the matrix pM, projecting the result back into w = 1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformCoordArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec2TransformNormal

Transforms the 2D vector normal by the given matrix.

D3DXVECTOR2 * D3DXVec2TransformNormal(
  D3DXVECTOR2 *pOut,
  CONST D3DXVECTOR2 *pV,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector (pV->x, pV->y, 0, 0) by the matrix pointed to by pM.

If you want to transform a normal, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a point.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformNormal function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec2TransformNormalArray

Transforms an array (x, y, 0, 0) by a given matrix.

D3DXVECTOR2 * D3DXVec2TransformNormalArray(
  D3DXVECTOR2 *pOut,
  UINT OutStride,
  CONST D3DXVECTOR2 *pV,
  UINT VStride,
  CONST D3DXMATRIX *pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR2 structure that is the transformed array.

Remarks

This function transforms the vector (pV->x, pV->y, 0, 0) by the matrix pointed to by pM.

If you want to transform a normal, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a point.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformNormalArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3BaryCentric

Returns a point in Barycentric coordinates, using the specified 3D vectors.

D3DXVECTOR3 * D3DXVec3BaryCentric(
  D3DXVECTOR3 *pOut,
  CONST D3DXVECTOR3 *pV1,
  CONST D3DXVECTOR3 *pV2,
  CONST D3DXVECTOR3 *pV3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[in, retval] Pointer to the D3DXVECTOR3 that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.
pV3
[in] Pointer to a source D3DXVECTOR3 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR3 structure in Barycentric coordinates.

Remarks

The D3DXVec3BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 &, & g>=0 &, & 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 &, & g>=0 &, & 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 &, & g==0 &, & 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 &, & g>=0 &, & 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3BaryCentric function can be used as a parameter for another function.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3CatmullRom

Performs a Catmull-Rom interpolation, using the specified 3D vectors.

D3DXVECTOR3 * D3DXVec3CatmullRom(
  D3DXVECTOR3 *pOut,
  CONST D3DXVECTOR3 *pV0,
  CONST D3DXVECTOR3 *pV1,
  CONST D3DXVECTOR3 *pV2,
  CONST D3DXVECTOR3 *pV3,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 that is the result of the operation.
pV0
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR3 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where:

v1 is the contents of pV0.

v2 is the contents of pV1.

p3 is the contents of pV2.

p4 is the contents of pV3.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s)(p3 - p1) / 2 + (s3 - s2)(p4 - p2) / 2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 + (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3Hermite

Performs a Hermite spline interpolation, using the specified 3D vectors.

D3DXVECTOR3 * D3DXVec3Hermite(
  D3DXVECTOR3 *pOut,
  CONST D3DXVECTOR3 *pV1,
  CONST D3DXVECTOR3 *pT1,
  CONST D3DXVECTOR3 *pV2,
  CONST D3DXVECTOR3 *pT2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR3 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR3 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR3 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec3Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Hermite function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3Normalize

Returns the normalized version of a 3D vector.

D3DXVECTOR3 * D3DXVec3Normalize(
  D3DXVECTOR3 *pOut,
  CONST D3DXVECTOR3 *pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the normalized version of the specified vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Normalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3Project

Projects a 3D vector from object space into screen space.

D3DXVECTOR3 * D3DXVec3Project(
  D3DXVECTOR3 *pOut,
  CONST D3DXVECTOR3 *pV,
  CONST D3D10_VIEWPORT *pViewport,
  CONST D3DXMATRIX *pProjection,
  CONST D3DXMATRIX *pView,
  CONST D3DXMATRIX *pWorld
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pViewport
[in] Pointer to a D3D10_VIEWPORT, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.

Return Values

Pointer to a D3DXVECTOR3 structure that is the vector projected from object space to screen space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Project function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3ProjectArray

Projects an array (x, y, z, 0) from object space into screen space.

D3DXVECTOR3 * D3DXVec3ProjectArray(
  D3DXVECTOR3 *pOut,
  UINT OutStride,
  CONST D3DXVECTOR3 *pV,
  UINT VStride,
  CONST D3D10_VIEWPORT *pViewport,
  CONST D3DXMATRIX *pProjection,
  CONST D3DXMATRIX *pView,
  CONST D3DXMATRIX *pWorld,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
VStride
[in] Stride between vectors in the input data stream.
pViewport
[in] Pointer to a D3D10_VIEWPORT, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR3 structure that is the array projected from object space to screen space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3ProjectArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3Transform

Transforms vector (x, y, z, 1) by a given matrix.

D3DXVECTOR4 * D3DXVec3Transform(
  D3DXVECTOR4 *pOut,
  CONST D3DXVECTOR3 *pV,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3TransformArray

Transforms an array (x, y, z, 1) by a given matrix.

D3DXVECTOR4 * D3DXVec3TransformArray(
  D3DXVECTOR4 *pOut,
  UINT OutStride,
  CONST D3DXVECTOR3 *pV,
  UINT VStride,
  CONST D3DXMATRIX *pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR4 transformed array.

Remarks

This function transforms the array pV (x, y, z, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3TransformCoord

Transforms a 3D vector by a given matrix, projecting the result back into w = 1.

D3DXVECTOR3 * D3DXVec3TransformCoord(
  D3DXVECTOR3 *pOut,
  CONST D3DXVECTOR3 *pV,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformCoord function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3TransformCoordArray

Transforms an array (x, y, z, 1) by a given matrix, and projects the result back into w = 1.

D3DXVECTOR3 * D3DXVec3TransformCoordArray(
  D3DXVECTOR3 *pOut,
  UINT OutStride,
  CONST D3DXVECTOR3 *pV,
  UINT VStride,
  CONST D3DXMATRIX *pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR3 structure that is the transformed array.

Remarks

This function transforms the array pV (x, y, z, 1) by the matrix pM, projecting the result back into w = 1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformCoord function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3TransformNormal

Transforms the 3D vector normal by the given matrix.

D3DXVECTOR3 * D3DXVec3TransformNormal(
  D3DXVECTOR3 *pOut,
  CONST D3DXVECTOR3 *pV,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector (pV->x, pV->y, pV->z, 0) by the matrix pointed to by pM.

If you want to transform a normal, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a point.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformNormal function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3TransformNormalArray

Transforms an array (x, y, z, 0) by a given matrix.

D3DXVECTOR3 * D3DXVec3TransformNormalArray(
  D3DXVECTOR3 *pOut,
  UINT OutStride,
  CONST D3DXVECTOR3 *pV,
  UINT VStride,
  CONST D3DXMATRIX *pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR3 array that is the transformed array.

Remarks

This function transforms the vector (pV->x, pV->y, pV->z, 0) by the matrix pointed to by pM.

If you want to transform a normal, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a point.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformNormalArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3Unproject

Projects a vector from screen space into object space.

D3DXVECTOR3 * D3DXVec3Unproject(
  D3DXVECTOR3 *pOut,
  CONST D3DXVECTOR3 *pV,
  CONST D3D10_VIEWPORT *pViewport,
  CONST D3DXMATRIX *pProjection,
  CONST D3DXMATRIX *pView,
  CONST D3DXMATRIX *pWorld
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pViewport
[in] Pointer to a D3D10_VIEWPORT, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.

Return Values

Pointer to a D3DXVECTOR3 structure that is the vector projected from screen space to object space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Unproject function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec3UnprojectArray

Projects an array (x, y, z, 0) from screen space into object space.

D3DXVECTOR3 * D3DXVec3UnprojectArray(
  D3DXVECTOR3 *pOut,
  UINT OutStride,
  CONST D3DXVECTOR3 *pV,
  UINT VStride,
  CONST D3D10_VIEWPORT *pViewport,
  CONST D3DXMATRIX *pProjection,
  CONST D3DXMATRIX *pView,
  CONST D3DXMATRIX *pWorld,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
VStride
[in] Stride between vectors in the input data stream.
pViewport
[in] Pointer to a D3D10_VIEWPORT, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR3 structure that is the array projected from screen space to object space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Unproject function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec4BaryCentric

Returns a point in Barycentric coordinates, using the specified 4D vectors.

D3DXVECTOR4 * D3DXVec4BaryCentric(
  D3DXVECTOR4 *pOut,
  CONST D3DXVECTOR4 *pV1,
  CONST D3DXVECTOR4 *pV2,
  CONST D3DXVECTOR4 *pV3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[in] Pointer to the D3DXVECTOR4 that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
pV3
[in] Pointer to a source D3DXVECTOR4 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR4 structure in Barycentric coordinates.

Remarks

The D3DXVec4BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 &, & g>=0 &, & 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 &, & g>=0 &, & 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 &, & g==0 &, & 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 &, & g>=0 &, & 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4BaryCentric function can be used as a parameter for another function.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec4CatmullRom

Performs a Catmull-Rom interpolation, using the specified 4D vectors.

D3DXVECTOR4 * D3DXVec4CatmullRom(
  D3DXVECTOR4 *pOut,
  CONST D3DXVECTOR4 *pV0,
  CONST D3DXVECTOR4 *pV1,
  CONST D3DXVECTOR4 *pV2,
  CONST D3DXVECTOR4 *pV3,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 that is the result of the operation.
pV0
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV1
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR4 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where:

v1 is the contents of pV0.

v2 in the contents of pV1.

p3 is the contents of pV2.

p4 is the contents of pV3.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s)(p3 - p1) / 2 + (s3 - s2)(p4 - p2) / 2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 + (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec4Cross

Determines the cross-product in four dimensions.

D3DXVECTOR4 * D3DXVec4Cross(
  D3DXVECTOR4 *pOut,
  CONST D3DXVECTOR4 *pV1,
  CONST D3DXVECTOR4 *pV2,
  CONST D3DXVECTOR4 *pV3
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
pV3
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the cross product.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Cross function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec4Hermite

Performs a Hermite spline interpolation, using the specified 4D vectors.

D3DXVECTOR4 * D3DXVec4Hermite(
  D3DXVECTOR4 *pOut,
  CONST D3DXVECTOR4 *pV1,
  CONST D3DXVECTOR4 *pT1,
  CONST D3DXVECTOR4 *pV2,
  CONST D3DXVECTOR4 *pT2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR4 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR4 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR4 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec4Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t-1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Hermite function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec4Normalize

Returns the normalized version of a 4D vector.

D3DXVECTOR4 * D3DXVec4Normalize(
  D3DXVECTOR4 *pOut,
  CONST D3DXVECTOR4 *pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the normalized version of the vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Normalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec4Transform

Transforms a 4D vector by a given matrix.

D3DXVECTOR4 * D3DXVec4Transform(
  D3DXVECTOR4 *pOut,
  CONST D3DXVECTOR4 *pV,
  CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed 4D vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


D3DXVec4TransformArray

Transforms an array (x, y, 0, 1) by a given matrix.

D3DXVECTOR4 * D3DXVec4TransformArray(
  D3DXVECTOR4 *pOut,
  UINT OutStride,
  CONST D3DXVECTOR4 *pV,
  UINT VStride,
  CONST D3DXMATRIX *pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR4 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed array.

Remarks

This function transforms the array pV (x, y, 0, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4TransformArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3DX10Math.h.

See Also

Math Functions


Mesh Functions

D3DX supplies the following mesh functions.

  • D3DX10CreateMesh
  • D3DX10CreateSkinInfo
  • D3DXBoxBoundProbe
  • D3DXComputeBoundingBox
  • D3DXComputeBoundingSphere
  • D3DXIntersectTri
  • D3DXSphereBoundProbe


D3DX10CreateMesh

Creates a mesh object using a declarator.

HRESULT D3DX10CreateMesh(
  ID3D10Device *pDevice,
  CONST D3D10_INPUT_ELEMENT_DESC *pDeclaration,
  UINT DeclCount,
  LPCSTR pPositionSemantic,
  UINT VertexCount,
  UINT FaceCount,
  UINT Options,
  ID3DX10Mesh **ppMesh
);

Parameters

pDevice
[in] Pointer to an ID3D10Device Interface, the device object to be associated with the mesh.
pDeclaration
[in] Array of D3D10_INPUT_ELEMENT_DESC elements, describing the vertex format for the returned mesh. This parameter must map directly to a flexible vertex format (FVF).
DeclCount
[in] The number of elements in pDeclaration.
pPositionSemantic
[in] Semantic that identifies which part of the vertex declaration contains position information.
VertexCount
[in] Number of vertices for the mesh. This parameter must be greater than 0.
FaceCount
[in] Number of faces for the mesh. The valid range for this number is greater than 0, and one less than the maximum DWORD (typically 65534), because the last index is reserved.
Options
[in] Combination of one or more flags from the D3DX10_MESH, specifying options for the mesh.
ppMesh
[out] Address of a pointer to an ID3DX10Mesh Interface, representing the created mesh object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX10Mesh.h.

See Also

D3DX Functions


D3DX10CreateSkinInfo

Creates an empty skin mesh object using a declarator.

HRESULT D3DX10CreateSkinInfo(
  LPD3DX10SKININFO *ppSkinInfo
);

Parameters

ppSkinInfo
[out] Address of a pointer to an ID3DX10SkinInfo Interface, representing the created skin mesh object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: E_OUTOFMEMORY.

Remarks

Use the ID3DX10SkinInfo::SetBoneInfluence to populate the empty skin mesh object returned by this method.

Requirements

Header: Declared in D3DX10Mesh.h.

See Also

D3DX Functions


D3DXBoxBoundProbe

Determines whether a ray intersects the volume of a box's bounding box.

BOOL D3DXBoxBoundProbe(
  CONST D3DXVECTOR3 *pMin,
  CONST D3DXVECTOR3 *pMax,
  CONST D3DXVECTOR3 *pRayPosition,
  CONST D3DXVECTOR3 *pRayDirection
);

Parameters

pMin
[in] Pointer to a D3DXVECTOR3, describing the lower-left corner of the bounding box. See Remarks.
pMax
[in] Pointer to a D3DXVECTOR3 structure, describing the upper-right corner of the bounding box. See Remarks.
pRayPosition
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDirection
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray. This vector should not be (0,0,0) but does not need to be normalized.

Return Values

Returns TRUE if the ray intersects the volume of the box's bounding box. Otherwise, returns FALSE.

Remarks

D3DXBoxBoundProbe determines if the ray intersects the volume of the box's bounding box, not just the surface of the box.

The values passed to D3DXBoxBoundProbe are xmin, xmax, ymin, ymax, zmin, and zmax. Thus, the following defines the corners of the bounding box.

xmax, ymax, zmax
xmax, ymax, zmin
xmax, ymin, zmax
xmax, ymin, zmin
xmin, ymax, zmax
xmin, ymax, zmin
xmin, ymin, zmax
xmin, ymin, zmin

The depth of the bounding box in the z direction is zmax - zmin, in the y direction is ymax - ymin, and in the x direction is xmax - xmin. For example, with the following minimum and maximum vectors, min (-1, -1, -1) and max (1, 1, 1), the bounding box is defined in the following manner.

 1,  1,  1
 1,  1, -1
 1, -1,  1
 1, -1, -1
-1,  1,  1
-1,  1, -1
-1, -1,  1
-1, -1, -l

Requirements

Header: Declared in D3DX10.h.

See Also

Mesh Functions


D3DXComputeBoundingBox

Computes a coordinate-axis oriented bounding box.

HRESULT D3DXComputeBoundingBox(
  CONST D3DXVECTOR3 *pFirstPosition,
  DWORD NumVertices,
  DWORD dwStride,
  D3DXVECTOR3 *pMin,
  D3DXVECTOR3 *pMax
);

Parameters

pFirstPosition
[in] Pointer to the first position.
NumVertices
[in] Number of vertices.
dwStride
[in] Count or number of bytes between vertices.
pMin
[in] Pointer to a D3DXVECTOR3 structure, describing the returned lower-left corner of the bounding box. See Remarks.
pMax
[in] Pointer to a D3DXVECTOR3 structure, describing the returned upper-right corner of the bounding box. See Remarks.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

Remarks

Requirements

Header: Declared in D3DX10.h.

See Also

Mesh Functions


D3DXComputeBoundingSphere

Computes a bounding sphere for the mesh.

HRESULT D3DXComputeBoundingSphere(
  CONST D3DXVECTOR3 *pFirstPosition,
  DWORD NumVertices,
  DWORD dwStride,
  D3DXVECTOR3 *pCenter,
  FLOAT *pRadius
);

Parameters

pFirstPosition
[in] Pointer to first position.
NumVertices
[in] Number of vertices.
dwStride
[in] Number of bytes between position vectors.
pCenter
[in] D3DXVECTOR3 structure, defining the coordinate center of the returned bounding sphere.
pRadius
[in] Radius of the returned bounding sphere.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX10.h.

See Also

Mesh Functions


D3DXIntersectTri

Computes the intersection of a ray and a triangle.

BOOL D3DXIntersectTri(
  CONST D3DXVECTOR3 *p0,
  CONST D3DXVECTOR3 *p1,
  CONST D3DXVECTOR3 *p2,
  CONST D3DXVECTOR3 *pRayPos,
  CONST D3DXVECTOR3 *pRayDir,
  FLOAT *pU,
  FLOAT *pV,
  FLOAT *pDist
);

Parameters

p0
[in] Pointer to a D3DXVECTOR3 structure, describing the first triangle vertex position.
p1
[in] Pointer to a D3DXVECTOR3 structure, describing the second triangle vertex position.
p2
[in] Pointer to a D3DXVECTOR3 structure, describing the third triangle vertex position.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pU
[in] Barycentric hit coordinates, U.
pV
[in] Barycentric hit coordinates, V.
pDist
[in] Ray-intersection parameter distance.

Return Values

Returns TRUE if the ray intersects the area of the triangle. Otherwise, returns FALSE.

Remarks

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result, and the parameter V controls how much V3 gets weighted into the result. Lastly, the value of [1 - (U + V)] controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX10.h.

See Also

Mesh Functions


D3DXSphereBoundProbe

Determines if a ray intersects the volume of a sphere's bounding box.

BOOL D3DXSphereBoundProbe(
  CONST D3DXVECTOR3 *pCenter,
  FLOAT Radius,
  CONST D3DXVECTOR3 *pRayPosition,
  CONST D3DXVECTOR3 *pRayDirection
);

Parameters

pCenter
[in] Pointer to a D3DXVECTOR3 structure, specifying the center coordinate of the sphere.
Radius
[in] Radius of the sphere.
pRayPosition
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDirection
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray. This vector should not be (0,0,0) but does not need to be normalized.

Return Values

Returns TRUE if the ray intersects the volume of the sphere's bounding box. Otherwise, returns FALSE.

Remarks

D3DXSphereBoundProbe determines if the ray intersects the volume of the sphere's bounding box, not just the surface of the sphere.

Requirements

Header: Declared in D3DX10.h.

See Also

Mesh Functions


Texturing Functions

D3DX supplies the following texturing functions.

  • D3DX10ComputeNormalMap
  • D3DX10CreateAsyncTextureInfoProcessor
  • D3DX10CreateAsyncTextureProcessor
  • D3DX10CreateShaderResourceViewFromFile
  • D3DX10CreateShaderResourceViewFromMemory
  • D3DX10CreateShaderResourceViewFromResource
  • D3DX10CreateTextureFromFile
  • D3DX10CreateTextureFromMemory
  • D3DX10CreateTextureFromResource
  • D3DX10FilterTexture
  • D3DX10GetImageInfoFromFile
  • D3DX10GetImageInfoFromMemory
  • D3DX10GetImageInfoFromResource
  • D3DX10LoadTextureFromTexture
  • D3DX10SaveTextureToFile
  • D3DX10SaveTextureToMemory


D3DX10ComputeNormalMap

Converts a height map into a normal map. The (x,y,z) components of each normal are mapped to the (r,g,b) channels of the output texture.

HRESULT D3DX10ComputeNormalMap(
  ID3D10Texture2D *pSrcTexture,
  UINT Flags,
  UINT Channel,
  FLOAT Amplitude,
  ID3D10Texture2D *pDestTexture
);

Parameters

pSrcTexture
[in] Pointer to an ID3D10Texture2D interface, representing the source height-map texture.
Flags
[in] One or more D3DX_NORMALMAP flags that control generation of normal maps.
Channel
[in] One D3DX_CHANNEL flag specifying the source of height information.
Amplitude
[in] Constant value multiplier that increases (or decreases) the values in the normal map. Higher values usually make bumps more visible, lower values usually make bumps less visible.
pDestTexture
[in] Pointer to an ID3D10Texture2D interface, representing the destination texture.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following value: D3DERR_INVALIDCALL.

Remarks

This method computes the normal by using the central difference with a kernel size of 3x3. RGB channels in the destination contain biased (x,y,z) components of the normal. The central differencing denominator is hardcoded to 2.0.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Functions


D3DX10CreateAsyncTextureInfoProcessor

Create a data processor to be used with a thread pump.

HRESULT D3DX10CreateAsyncTextureInfoProcessor(
  D3DX10_IMAGE_INFO *pImageInfo,
  ID3DX10DataProcessor **ppDataProcessor
);

Parameters

pImageInfo
[in] Describes the type of image to load and converts . See D3DX10_IMAGE_INFO.
ppDataProcessor
[out] The data processor. See ID3DX10DataProcessor Interface.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Functions


D3DX10CreateAsyncTextureProcessor

Create a data processor to be used with a thread pump. This API is similar to D3DX10CreateAsyncTextureInfoProcessor but it also loads the texture.

HRESULT D3DX10CreateAsyncTextureProcessor(
  ID3D10Device *pDevice,
  D3DX10_IMAGE_LOAD_INFO *pLoadInfo,
  ID3DX10DataProcessor **ppDataProcessor
);

Parameters

pDevice
[in] The device to which the texture will be bound.
pLoadInfo
[in] Optional information to control how to the texture is loaded. See D3DX10_IMAGE_LOAD_INFO. If NULL, the source image data is used.
ppDataProcessor
[out] The data processor. See ID3DX10DataProcessor Interface.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Functions


D3DX10CreateShaderResourceViewFromFile

Create a shader-resource view from a file.

HRESULT D3DX10CreateShaderResourceViewFromFile(
  ID3D10Device *pDevice,
  LPCTSTR pSrcFile,
  D3DX10_IMAGE_LOAD_INFO *pLoadInfo,
  ID3DX10ThreadPump *pPump,
  ID3D10ShaderResourceView **ppShaderResourceView,
  HRESULT *pHResult
);

Parameters

pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resource.
pSrcFile
[in] Name of the file that contains the shader-resource view. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pLoadInfo
[in] Optional information to control how to the texture is loaded. See D3DX10_IMAGE_LOAD_INFO. If NULL, the source image data is used.
pPump
[in] Pointer to a thread-pump interface (see ID3DX10ThreadPump Interface). If NULL is specified, this function will behave synchronously and will not return until it is finished.
ppShaderResourceView
[out] Address of a pointer to the shader-resource view (see ID3D10ShaderResourceView Interface).
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

General Purpose Functions


D3DX10CreateShaderResourceViewFromMemory

Create a shader-resource view from a file in memory.

HRESULT D3DX10CreateShaderResourceViewFromMemory(
  ID3D10Device *pDevice,
  LPCVOID pSrcData,
  SIZE_T SrcDataSize,
  D3DX10_IMAGE_LOAD_INFO *pLoadInfo,
  ID3DX10ThreadPump *pPump,
  ID3D10ShaderResourceView **ppShaderResourceView,
  HRESULT *pHResult
);

Parameters

pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resource.
pSrcData
[in] Pointer to the file in memory that contains the shader-resource view.
SrcDataSize
[in] Size of the file in memory.
pLoadInfo
[in] Optional information to control how to the texture is loaded. See D3DX10_IMAGE_LOAD_INFO. If NULL, the source image data is used.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). If NULL is specified, this function will behave synchronously and will not return until it is finished.
ppShaderResourceView
[out] Address of a pointer to the newly created shader resource view. See ID3D10ShaderResourceView Interface.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

General Purpose Functions


D3DX10CreateShaderResourceViewFromResource

Create a shader-resource view from a resource.

HRESULT D3DX10CreateShaderResourceViewFromResource(
  ID3D10Device *pDevice,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  D3DX10_IMAGE_LOAD_INFO *pLoadInfo,
  ID3DX10ThreadPump *pPump,
  ID3D10ShaderResourceView **ppShaderResourceView,
  HRESULT *pHResult
);

Parameters

pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resource.
hSrcModule
[in] Handle to the resource module containing the shader-resource view. HMODULE can be obtained with GetModuleHandle.
pSrcResource
[in] Name of the shader resource view in hSrcModule. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pLoadInfo
[in] Optional information to control how to the texture is loaded. See D3DX10_IMAGE_LOAD_INFO. If NULL, the source image data is used.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). If NULL is specified, this function will behave synchronously and will not return until it is finished.
ppShaderResourceView
[out] Address of a pointer to the shader-resource view (see ID3D10ShaderResourceView Interface).
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

General Purpose Functions


D3DX10CreateTextureFromFile

Create a texture resource from a file.

HRESULT D3DX10CreateTextureFromFile(
  ID3D10Device *pDevice,
  LPCTSTR pSrcFile,
  D3DX10_IMAGE_LOAD_INFO *pLoadInfo,
  ID3DX10ThreadPump *pPump,
  ID3D10Resource **ppTexture,
  HRESULT *pHResult
);

Parameters

pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resource.
pSrcFile
[in] The name of the file containing the resource. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pLoadInfo
[in] Optional information to control how to the texture is loaded. See D3DX10_IMAGE_LOAD_INFO. If NULL, the source image data is used.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). If NULL is specified, this function will behave synchronously and will not return until it is finished.
ppTexture
[out] The address of a pointer to the texture resource (see ID3D10Resource Interface).
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

General Purpose Functions


D3DX10CreateTextureFromMemory

Create a texture resource from a file residing in system memory.

HRESULT D3DX10CreateTextureFromMemory(
  ID3D10Device *pDevice,
  LPCVOID pSrcData,
  SIZE_T SrcDataSize,
  D3DX10_IMAGE_LOAD_INFO *pLoadInfo,
  ID3DX10ThreadPump *pPump,
  ID3D10Resource **ppTexture,
  HRESULT *pHResult
);

Parameters

pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resource.
pSrcData
[in] Pointer to the resource in system memory.
SrcDataSize
[in] Size of the resource in system memory.
pLoadInfo
[in] Optional information to control how to the texture is loaded. See D3DX10_IMAGE_LOAD_INFO. If NULL, the source image data is used.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). If NULL is specified, this function will behave synchronously and will not return until it is finished.
ppTexture
[out] Address of a pointer to the created resource. See ID3D10Resource Interface.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

General Purpose Functions


D3DX10CreateTextureFromResource

Create a texture from another resource.

HRESULT D3DX10CreateTextureFromResource(
  ID3D10Device *pDevice,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  D3DX10_IMAGE_LOAD_INFO *pLoadInfo,
  ID3DX10ThreadPump *pPump,
  ID3D10Resource **ppTexture,
  HRESULT *pHResult
);

Parameters

pDevice
[in] A pointer to the device (see ID3D10Device Interface) that will use the resource.
hSrcModule
[in] A handle to the source resource. HMODULE can be obtained with GetModuleHandle.
pSrcResource
[in] A string that contains the name of the source resource. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.
pLoadInfo
[in] Optional information to control how to the texture is loaded. See D3DX10_IMAGE_LOAD_INFO. If NULL, the source image data is used.
pPump
[in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). If NULL is specified, this function will behave synchronously and will not return until it is finished.
ppTexture
[out] The address of a pointer to the texture resource (see ID3D10Resource Interface).
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10.h.

See Also

General Purpose Functions


D3DX10FilterTexture

Generates mipmap chain using a particular texture filter.

HRESULT D3DX10FilterTexture(
  ID3D10Resource *pTexture,
  UINT SrcLevel,
  UINT MipFilter
);

Parameters

pTexture
The texture object to be filtered. See ID3D10Resource.
SrcLevel
The mipmap level whose data is used to generate the rest of the mipmap chain.
MipFilter
Flags controlling how each miplevel is filtered (or D3DX10_DEFAULT for D3DX10_FILTER_BOX). See D3DX10_FILTER_FLAG.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Tex.h.


D3DX10GetImageInfoFromFile

Retrieves information about a given image file.

HRESULT D3DX10GetImageInfoFromFile(
  LPCTSTR pSrcFile,
  ID3DX10ThreadPump *pPump,
  D3DX10_IMAGE_INFO *pSrcInfo,
  HRESULT *pHResult
);

Parameters

pSrcFile
[in] File name of image to retrieve information about. If UNICODE or _UNICODE are defined, this parameter type is LPCWSTR, otherwise, the type is LPCSTR.
pPump
[in] Optional thread pump that can be used to load the info asynchronously. Can be NULL. See ID3DX10ThreadPump.
pSrcInfo
[in] Pointer to a D3DX10_IMAGE_INFO structure to be filled with the description of the data in the source file.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL

Remarks

This function supports both Unicode and ANSI strings.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Functions


D3DX10GetImageInfoFromMemory

Get information about an image already loaded into memory.

HRESULT D3DX10GetImageInfoFromMemory(
  LPCVOID pSrcData,
  SIZE_T SrcDataSize,
  ID3DX10ThreadPump *pPump,
  D3DX10_IMAGE_INFO *pSrcInfo,
  HRESULT *pHResult
);

Parameters

pSrcData
[in] Pointer to the image in memory.
SrcDataSize
[in] Size of the image in memory, in bytes.
pPump
[in] Optional thread pump that can be used to load the info asynchronously. Can be NULL. See ID3DX10ThreadPump.
pSrcInfo
[in] Information about the image in memory.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Functions


D3DX10GetImageInfoFromResource

Retrieves information about a given image in a resource.

HRESULT D3DX10GetImageInfoFromResource(
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  ID3DX10ThreadPump *pPump,
  D3DX10_IMAGE_INFO *pSrcInfo,
  HRESULT *pHResult
);

Parameters

hSrcModule
[in] Module where the resource is loaded. Set this parameter to NULL to specify the module associated with the image that the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR. See Remarks.
pPump
[in] Optional thread pump that can be used to load the info asynchronously. Can be NULL. See ID3DX10ThreadPump.
pSrcInfo
[in] Pointer to a D3DX10_IMAGE_INFO structure to be filled with the description of the data in the source file.
pHResult
[out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DX10GetImageInfoFromResourceW. Otherwise, the function call resolves to D3DX10GetImageInfoFromResourceA because ANSI strings are being used.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Functions


D3DX10LoadTextureFromTexture

Load a texture from a texture.

HRESULT D3DX10LoadTextureFromTexture(
  ID3D10Resource *pSrcTexture,
  D3DX10_TEXTURE_LOAD_INFO *pLoadInfo,
  ID3D10Resource *pDstTexture
);

Parameters

pSrcTexture
Pointer to the source texture. See ID3D10Resource.
pLoadInfo
Pointer to texture loading parameters. See D3DX10_TEXTURE_LOAD_INFO.
pDstTexture
Pointer to the destination texture. See ID3D10Resource Interface.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Tex.h.


D3DX10SaveTextureToFile

Save a texture to a file.

HRESULT D3DX10SaveTextureToFile(
  ID3D10Resource *pSrcTexture,
  D3DX10_IMAGE_FILE_FORMAT DestFormat,
  LPCTSTR pDestFile
);

Parameters

pSrcTexture
[in] Pointer to the texture to be saved. See ID3D10Resource Interface.
DestFormat
[in] The format the texture will be saved as. See D3DX10_IMAGE_FILE_FORMAT.
pDestFile
[in] Name of the destination output file where the texture will be saved. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the data type resolves to LPCSTR.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

General Purpose Functions


D3DX10SaveTextureToMemory

Save a texture to memory.

HRESULT D3DX10SaveTextureToMemory(
  ID3D10Resource *pSrcTexture,
  D3DX10_IMAGE_FILE_FORMAT DestFormat,
  LPD3D10BLOB *ppDestBuf,
  UINT Flags
);

Parameters

pSrcTexture
[in] Pointer to the texture to be saved. See ID3D10Resource Interface.
DestFormat
[in] The format the texture will be saved as. See D3DX10_IMAGE_FILE_FORMAT.
ppDestBuf
[out] Address of a pointer to the memory containing the saved texture. See ID3D10Blob Interface.
Flags
[in] Optional.

Return Values

The return value is one of the values listed in Direct3D 10 Return Codes.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

General Purpose Functions


D3DX Structures

This section contains information about the structures included in the D3DX utility library.

Structure | Description
D3DMATRIX |
D3DVECTOR |
D3DX10_ATTRIBUTE_RANGE | Stores an attribute table entry.
D3DX10_ATTRIBUTE_WEIGHTS | Specifies mesh weight attributes.
D3DX10_FONT_DESC | Defines the attributes of a font.
D3DX10_IMAGE_INFO | Returns a description of the original contents of an image file.
D3DX10_IMAGE_LOAD_INFO |
D3DX10_INTERSECT_INFO | Describes a ray-triangle intersection.
D3DX10_SPRITE | Defines position, texture, and color information about a sprite.
D3DX10_TEXTURE_LOAD_INFO | Texture load parameters.
D3DX10_WELD_EPSILONS | Specifies tolerance values for each vertex component when comparing vertices to determine if they are similar enough to be welded together.
D3DX10_SKINNING_CHANNEL |
D3DXCOLOR | Describes color values.
D3DXFLOAT16 | Describes a 16-bit floating point vector.
D3DXMATRIX | Describes a matrix.
D3DXMATRIXA16 | Defines a 16-byte aligned matrix.
D3DXPLANE | Describes a plane.
D3DXQUATERNION | Describes a quaternion.
D3DXVECTOR2 | Describes a vector in 2D space.
D3DXVECTOR2_16F | Same as a D3DXVECTOR2, but it uses 16-bit floating point values for x, y, and z.
D3DXVECTOR3 | Describes a vector in three-dimensional (3D) space.
D3DXVECTOR3_16F | Same as a D3DXVECTOR3, but it uses 16-bit floating point values for x, y, and z.
D3DXVECTOR4 | Describes a vector in 4D space.
D3DXVECTOR4_16F | Same as a D3DXVECTOR4, but it uses 16-bit floating point values for x, y, and z.


D3DMATRIX

A 4x4 row-major matrix.

typedef struct D3DMATRIX {
    float m[4][4];
} D3DMATRIX, *LPD3DMATRIX;

Members

m[4][4]
The 4x4 row-major matrix.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DVECTOR

A 3D vector.

typedef struct D3DVECTOR {
    float x;
    float y;
    float z;
} D3DVECTOR, *LPD3DVECTOR;

Members

x
The x component.
y
The y component.
z
The z component.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DX10_ATTRIBUTE_RANGE

Stores an attribute table entry.

typedef struct D3DX10_ATTRIBUTE_RANGE {
    UINT AttribId;
    UINT FaceStart;
    UINT FaceCount;
    UINT VertexStart;
    UINT VertexCount;
} D3DX10_ATTRIBUTE_RANGE, *LPD3DX10_ATTRIBUTE_RANGE;

Members

AttribId
Attribute table identifier.
FaceStart
Starting face.
FaceCount
Face count.
VertexStart
Starting vertex.
VertexCount
Vertex count.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

The LPD3DX_ATTRIBUTE_RANGE type is defined as a pointer to the D3DX_ATTRIBUTE_RANGE structure.

typedef D3DX_ATTRIBUTE_RANGE* LPD3DX_ATTRIBUTE_RANGE;

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Structures


D3DX10_ATTRIBUTE_WEIGHTS

Specifies mesh weight attributes.

typedef struct D3DX10_ATTRIBUTE_WEIGHTS {
    FLOAT Position;
    FLOAT Boundary;
    FLOAT Normal;
    FLOAT Diffuse;
    FLOAT Specular;
    FLOAT Texcoord[8];
    FLOAT Tangent;
    FLOAT Binormal;
} D3DX10_ATTRIBUTE_WEIGHTS, *LPD3DX10_ATTRIBUTE_WEIGHTS;

Members

Position
Position.
Boundary
Blend weight.
Normal
Normal.
Diffuse
Diffuse lighting value.
Specular
Specular lighting value.
Texcoord
Eight texture coordinates.
Tangent
Tangent.
Binormal
Binormal.

Remarks

This structure describes how a simplification operation will consider vertex data when calculating relative costs between collapsing edges. For example, if the Normal field is 0.0, the simplification operation will ignore the vertex normal component when calculating the error for the collapse. However, if the Normal field is 1.0, the simplification operation will use the vertex normal component. If the Normal field is 2.0, double the amount of errors; if the Normal field is 4.0, then quadruple the number of errors, and so on.

The LPD3DX_ATTRIBUTE_WEIGHTS type is defined as a pointer to the D3DX_ATTRIBUTE_WEIGHTS structure.

    typedef D3DX_ATTRIBUTE_WEIGHTS* LPD3DX_ATTRIBUTE_WEIGHTS;

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Structures


D3DX10_FONT_DESC

Defines font attributes.

typedef struct D3DX10_FONT_DESC {
    INT Height;
    UINT Width;
    UINT Weight;
    UINT MipLevels;
    BOOL Italic;
    BYTE CharSet;
    BYTE OutputPrecision;
    BYTE Quality;
    BYTE PitchAndFamily;
    TCHAR FaceName[LF_FACESIZE];
} D3DX10_FONT_DESC, *LPD3DX10_FONT_DESC;

Members

Height
Height, in logical units, of the font's character cell or character.
Width
Width, in logical units, of characters in the font.
Weight
Weight of the font in the range from 0 through 1000.
MipLevels
Number of mipmap levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created. If the value is 1, the texture space is mapped identically to the screen space.
Italic
Set to TRUE for an Italic font.
CharSet
Character set.
OutputPrecision
Output precision. The output precision defines how closely the output must match the requested font height, width, character orientation, escapement, pitch, and font type.
Quality
Output quality.
PitchAndFamily
Pitch and family of the font.
FaceName[LF_FACESIZE]
A NULL-terminated string that specifies the typeface name of the font. The length of the string must not exceed 32 characters, including the terminating NULL character. If FaceName is an empty string, the first font that matches the other specified attributes will be used. If the compiler settings require Unicode, the data type TCHAR resolves to WCHAR; otherwise, the data type resolves to CHAR. See Remarks.

Remarks

The compiler setting also determines the structure type. If Unicode is defined, the D3DX10_FONT_DESC structure type resolves to a D3DX10_FONT_DESCW; otherwise the structure type resolves to a D3DX10_FONT_DESCA.

Possible values of the above members are given in the GDI LOGFONT structure.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Structures


D3DX10_IMAGE_INFO

Returns a description of the original contents of an image file.

typedef struct D3DX10_IMAGE_INFO {
    UINT Width;
    UINT Height;
    UINT Depth;
    UINT ArraySize;
    UINT MipLevels;
    UINT MiscFlags;
    DXGI_FORMAT Format;
    D3D10_RESOURCE_DIMENSION ResourceDimension;
    D3DX10_IMAGE_FILE_FORMAT ImageFileFormat;
} D3DX10_IMAGE_INFO, *LPD3DX10_IMAGE_INFO;

Members

Width
Width of original image in pixels.
Height
Height of original image in pixels.
Depth
Depth of original image in pixels.
ArraySize
Size of the image in bytes.
MipLevels
Number of mipmap levels in original image.
MiscFlags
Miscellaneous resource properties (see D3D10_RESOURCE_MISC_FLAG).
Format
A value from the D3D10FORMAT enumerated type that most closely describes the data in the original image.
ResourceDimension
Represents the type of the texture stored in the file. See D3D10_RESOURCE_DIMENSION.
ImageFileFormat
Represents the format of the image file.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Structures


D3DX10_IMAGE_LOAD_INFO

Optionally provide information to texture loader APIs to control how textures get loaded. A value of D3DX10_DEFAULT for any of these parameters will cause D3DX to automatically pick use the value from the source file.

typedef struct D3DX10_IMAGE_LOAD_INFO {
    UINT Width;
    UINT Height;
    UINT Depth;
    UINT FirstMipLevel;
    UINT MipLevels;
    D3D10_USAGE Usage;
    UINT BindFlags;
    UINT CpuAccessFlags;
    UINT MiscFlags;
    DXGI_FORMAT Format;
    UINT Filter;
    UINT MipFilter;
    D3DX10_IMAGE_INFO *pSrcInfo;
} D3DX10_IMAGE_LOAD_INFO, *LPD3DX10_IMAGE_LOAD_INFO;

Members

Width
The target width of the texture. If the actual width of the texture is larger or smaller than this value then the texture will be scaled up or down to fit this target width.
Height
The target height of the texture. If the actual height of the texture is larger or smaller than this value then the texture will be scaled up or down to fit this target height.
Depth
The depth of the texture. This only applies to volume textures.
FirstMipLevel
The highest resolution mipmap level of the texture. If this is greater than 0, then after the texture is loaded FirstMipLevel will be mapped to mipmap level 0.
MipLevels
The maximum number of mipmap levels that the texture will have.
Usage
The way the texture resource is intended to be used. See D3D10_USAGE.
BindFlags
The pipeline stages that the texture will be allowed to bind to. See D3D10_BIND_FLAG.
CpuAccessFlags
The access permissions the cpu will have for the texture resource. See D3D10_CPU_ACCESS_FLAG.
MiscFlags
Miscellaneous resource properties (see D3D10_RESOURCE_MISC_FLAG).
Format
The format the texture will be in after it is loaded. See DXGI_FORMAT.
Filter
Filter the texture using the specified filter (only when resampling). See D3DX10_FILTER_FLAG.
MipFilter
Filter the texture mip levels using the specified filter (only if generating mipmaps). Valid values are D3DX10_FILTER_NONE, D3DX10_FILTER_POINT, D3DX10_FILTER_LINEAR, or D3DX10_FILTER_TRIANGLE. See D3DX10_FILTER_FLAG.
pSrcInfo
Information about the original image. See D3DX10_IMAGE_INFO. Can be obtained with D3DX10GetImageInfoFromFile, D3DX10GetImageInfoFromMemory, or D3DX10GetImageInfoFromResource.

Remarks

A default constructor is provided for this structure that initializes the parameters with the following values.

Requirements

Header: Declared in D3DX10tex.h.

See Also

D3DX Structures


D3DX10_INTERSECT_INFO

Describes a ray-triangle intersection.

typedef struct D3DX10_INTERSECT_INFO {
    UINT FaceIndex;
    FLOAT U;
    FLOAT V;
    FLOAT Dist;
} D3DX10_INTERSECT_INFO, *LPD3DX10_INTERSECT_INFO;

Members

FaceIndex
Index of the triangle that hit the ray.
U
Barycentric coordinate within the triangle where the ray intersects.
V
Barycentric coordinate within the triangle where the ray intersects.
Dist
Distance along the ray where the intersection occurred.

Remarks

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Structures


D3DX10_WELD_EPSILONS

Specifies tolerance values for each vertex component when comparing vertices to determine if they are similar enough to be welded together.

typedef struct D3DX10_WELD_EPSILONS {
    FLOAT Position;
    FLOAT BlendWeights;
    FLOAT Normal;
    FLOAT PSize;
    FLOAT Specular;
    FLOAT Diffuse;
    FLOAT Texcoord[8];
    FLOAT Tangent;
    FLOAT Binormal;
    FLOAT TessFactor;
} D3DX10_WELD_EPSILONS, *LPD3DX10_WELD_EPSILONS;

Members

Position
Position
BlendWeights
Blend weight
Normal
Normal
PSize
Point size value
Specular
Specular lighting value
Diffuse
Diffuse lighting value
Texcoord
Eight texture coordinates
Tangent
Tangent
Binormal
Binormal
TessFactor
Tessellation factor

Remarks

The LPD3DXWeldEpsilons type is defined as a pointer to the D3DXWeldEpsilons structure.

typedef D3DX_WELD_EPSILONS *LPD3DX_WELD_EPSILONS;

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Structures


D3DX10_SPRITE

Defines position, texture, and color information about a sprite.

typedef struct D3DX10_SPRITE {
    D3DXMATRIX matWorld;
    D3DXVECTOR2 TexCoord;
    D3DXVECTOR2 TexSize;
    D3DXCOLOR ColorModulate;
    ID3D10ShaderResourceView *pTexture;
    UINT TextureIndex;
} D3DX10_SPRITE;

Members

matWorld
The sprite's model-world transformation. This defines the position and orientation of the sprite in world space.
TexCoord
A vector from the upper-left corner of the texture to the upper-left corner of the sprite in texture coordinates.
TexSize
A vector from the upper-left corner of the sprite to the lower-right corner of the sprite.
ColorModulate
A color that will be multiplied with the pixel color before rendering.
pTexture
Pointer to a shader-resource view representing the sprite's texture. See ID3D10ShaderResourceView Interface.
TextureIndex
The index of the texture. If pTexture does not represent a texture array, then this should be 0.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Structures


D3DX10_SKINNING_CHANNEL

The member of the vertex decl to do the software skinning on. This is used with the ID3DX10SkinInfo::DoSoftwareSkinning API.

typedef struct D3DX10_SKINNING_CHANNEL {
    UINT SrcOffset;
    UINT DestOffset;
    BOOL IsNormal;
} D3DX10_SKINNING_CHANNEL, *LPD3DX10_SKINNING_CHANNEL;

Members

SrcOffset
Offset from the beginning of each source vertex.
DestOffset
Offset from the beginning of each destination vertex.
IsNormal
Determines which array of matrices to use in the ID3DX10SkinInfo::DoSoftwareSkinning API. If this is true, the pInverseTransposeBoneMatrices will be used, otherwise pBoneMatrices will be used.

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Structures


D3DX10_TEXTURE_LOAD_INFO

Describes parameters used to load a texture from another texture.

typedef struct _D3DX10_TEXTURE_LOAD_INFO {
    D3D10_BOX *pSrcBox;
    D3D10_BOX *pDstBox;
    UINT SrcFirstMip;
    UINT DstFirstMip;
    UINT NumMips;
    UINT SrcFirstElement;
    UINT DstFirstElement;
    UINT NumElements;
    UINT Filter;
    UINT MipFilter;
} D3DX10_TEXTURE_LOAD_INFO;

Members

pSrcBox
The source texture box. See D3D10_BOX.
pDstBox
The destination texture box. See D3D10_BOX.
SrcFirstMip
The source texture mipmap level. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.
DstFirstMip
The destination texture mip level. See Using D3D10CalcSubresource to Compute a Subresource Index for more details.
NumMips
The number of source texture mip levels.
SrcFirstElement
TBD
DstFirstElement
First element of the source texture.
NumElements
First element of the destination texture.
Filter
Filtering options (only when resampling). See D3DX10_FILTER_FLAG.
MipFilter
Filtering options (only when generating mip levels). See D3DX10_FILTER_FLAG.

Remarks

This structure is used in a call to D3DX10LoadTextureFromTexture.

Requirements

Header: Declared in D3dx10tex.h.


D3DXCOLOR

Describes color values.

typedef struct D3DXCOLOR {
    FLOAT r;
    FLOAT g;
    FLOAT b;
    FLOAT a;
} D3DXCOLOR, *LPD3DXCOLOR;

Members

r
Red component of the color.
g
Green component of the color.
b
Blue component of the color.
a
Alpha component of the color.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXFLOAT16

Describes a 16-bit floating point vector.

typedef struct D3DXFLOAT16 {
    WORD Value;
} D3DXFLOAT16, *LPD3DXFLOAT16;

Members

Value
The 16-bit data.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXMATRIX

Describes a matrix.

Syntax

typedef struct D3DXMATRIX {
    FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
    FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
    FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
    FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );
} D3DXMATRIX;

Members

_ij
The (i, j) component of the matrix, where i is the row number and j is the column number. For example, _34 means the same as [a34], the component in the third row and fourth column.

Remarks

In D3DX, the _34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by -1 instead.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXMATRIXA16

Defines a 16-byte aligned matrix.

Syntax

typedef struct _D3DXMATRIXA16 : public D3DXMATRIX
{
    _D3DXMATRIXA16();
    _D3DXMATRIXA16( CONST FLOAT * f);
    _D3DXMATRIXA16( CONST D3DMATRIX& m);
    _D3DXMATRIXA16( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                    FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                    FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                    FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );
    void* operator new(size_t s);
    void* operator new[](size_t s);

    // The two operators below are not virtual operators. If you cast
    //   to D3DXMATRIX, do not delete using them
    void operator delete(void* p);
    void operator delete[](void* p);

    struct _D3DXMATRIXA16& operator=(CONST D3DXMATRIX& rhs);
} _D3DXMATRIXA16;

typedef D3DX_ALIGN16 _D3DXMATRIXA16 D3DXMATRIXA16, *LPD3DXMATRIXA16;

Members

_ij
The (i, j) component of the matrix, where i is the row number and j is the column number. For example, _34 means the same as [a34], the component in the third row and fourth column.

Remarks

A 16-byte aligned matrix, when used by D3DX math functions, has been optimized for improved performance on Intel Pentium 4 processors. Matrices are aligned independent of where they are created: on the program stack, in the heap, or in global scope. Alignment is accomplished using __declspec(align(16)), which works with Visual C++ .NET and with Visual C++ 6.0 only when the processor pack is installed. Unfortunately, there is no way to detect the processor pack, so byte alignment is turned on by default only with Visual C++ .NET.

Vectors and quaternions are not byte aligned in D3DX. When using vectors and quaternions with D3DX math functions, use _declspec(align(16)) to generate byte aligned vectors and quaternions, because they will perform significantly better. The definition of _declspec is shown here.

#define D3DX_ALIGN16 __declspec(align(16))

Other compilers interpret D3DXMATRIXA16 as D3DXMATRIX. Using this structure on a compiler that does not actually align the matrix can be problematic because it will not expose bugs that ignore alignment. For example, if a D3DXMATRIXA16 object is inside a structure or class, a memcpy might be done with tight packing (ignoring 16-byte boundaries). This would cause build breaks if the compiler were to sometime add matrix aligning.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXPLANE

Describes a plane.

typedef struct D3DXPLANE {
    FLOAT a;
    FLOAT b;
    FLOAT c;
    FLOAT d;
} D3DXPLANE, *LPD3DXPLANE;

Members

a
The a coefficient of the clipping plane in the general plane equation. See Remarks.
b
The b coefficient of the clipping plane in the general plane equation. See Remarks.
c
The c coefficient of the clipping plane in the general plane equation. See Remarks.
d
The d coefficient of the clipping plane in the general plane equation. See Remarks.

Remarks

The members of the D3DXPLANE structure take the form of the general plane equation. They fit into the general plane equation so that ax + by + cz + dw = 0.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXQUATERNION

Describes a quaternion.

typedef struct D3DXQUATERNION {
    FLOAT x;
    FLOAT y;
    FLOAT z;
    FLOAT w;
} D3DXQUATERNION, *LPD3DXQUATERNION;

Members

x
The x-component.
y
The y-component.
z
The z-component.
w
The w-component.

Remarks

Quaternions add a fourth element to the [ x, y, z] values that define a vector, resulting in arbitrary 4D vectors. However, the following illustrates how each element of a unit quaternion relates to an axis-angle rotation (where q represents a unit quaternion (x, y, z, w), axis is normalized, and theta is the desired CCW rotation about the axis):

q.x = sin(theta/2) * axis.x
q.y = sin(theta/2) * axis.y
q.z = sin(theta/2) * axis.z
q.w = cos(theta/2)

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXVECTOR2

Describes a vector in 2D space.

typedef struct D3DXVECTOR2 {
    FLOAT x;
    FLOAT y;
} D3DXVECTOR2, *LPD3DXVECTOR2;

Members

x
The x-component.
y
The y-component.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXVECTOR2_16F

Same as a D3DXVECTOR2, but it uses 16-bit floating point values for x, y, and z.

typedef struct D3DXVECTOR2_16F {
} D3DXVECTOR2_16F, *LPD3DXVECTOR2_16F;

Members

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXVECTOR3

Describes a vector in three-dimensional (3D) space.

typedef struct D3DXVECTOR3 {
    FLOAT x;
    FLOAT y;
    FLOAT z;
} D3DXVECTOR3, *LPD3DXVECTOR3;

Members

x
The x-component.
y
The y-component.
z
The z-component.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXVECTOR3_16F

Same as a D3DXVECTOR3, but it uses 16-bit floating point values for x, y, and z.

typedef struct D3DXVECTOR3_16F {
} D3DXVECTOR3_16F, *LPD3DXVECTOR3_16F;

Members

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXVECTOR4

Describes a vector in 4D space.

typedef struct D3DXVECTOR4 {
    FLOAT x;
    FLOAT y;
    FLOAT z;
    FLOAT w;
} D3DXVECTOR4, *LPD3DXVECTOR4;

Members

x
The x-component.
y
The y-component.
z
The z-component.
w
The w-component.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DXVECTOR4_16F

Same as a D3DXVECTOR4, but it uses 16-bit floating point values for x, y, and z.

typedef struct D3DXVECTOR4_16F {
} D3DXVECTOR4_16F, *LPD3DXVECTOR4_16F;

Members

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Structures


D3DX Enumerations

This section contains information about the following enumerated types and flags used with D3DX.:

Enumeration | Description
D3DX10_CHANNEL_FLAG | These flags are used by functions which operate on one or more channels in a texture.
D3DX_CPU_OPTIMIZATION | Specifies the instruction set D3DX is currently optimized for.
D3DX10_ERR | Errors are represented by negative values and cannot be combined.
D3DX10_FILTER_FLAG | Texture filtering flags.
D3DX10_IMAGE_FILE_FORMAT | Describes the supported image file formats.
D3DX10_MESH | Flags used to specify creation options for a mesh.
D3DX10_MESH_DISCARD_FLAGS | Specifies which pieces of mesh data to discard from the device. Used with ID3DX10Mesh::Discard.
D3DX10_MESHOPT | Specifies the type of mesh optimization to be performed.
D3DX10_NORMALMAP_FLAG | These flags are used to control how D3DX10ComputeNormalMap generates normal maps. Any number of these flags may be OR'd together in any combination.
D3DX10_SAVE_TEXTURE_FLAG | Texture save options.

See Also

D3DX Reference


D3DX10_CHANNEL_FLAG

These flags are used by functions which operate on one or more channels in a texture.

typedef enum D3DX10_CHANNEL_FLAG
{
    D3DX10_CHANNEL_RED = (1 << 0),
    D3DX10_CHANNEL_BLUE = (1 << 1),
    D3DX10_CHANNEL_GREEN = (1 << 2),
    D3DX10_CHANNEL_ALPHA = (1 << 3),
    D3DX10_CHANNEL_LUMINANCE = (1 << 4),
} D3DX10_CHANNEL_FLAG, *LPD3DX10_CHANNEL_FLAG;

Constants

D3DX10_CHANNEL_RED
Indicates the red channel should be used.
D3DX10_CHANNEL_BLUE
Indicates the blue channel should be used.
D3DX10_CHANNEL_GREEN
Indicates the green channel should be used.
D3DX10_CHANNEL_ALPHA
Indicates the alpha channel should be used.
D3DX10_CHANNEL_LUMINANCE
Indicates the luminaces of the red, green, and blue channels should be used.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Enumerations


D3DX_CPU_OPTIMIZATION

Specifies the instruction set D3DX is currently optimized for.

typedef enum _D3DX_CPU_OPTIMIZATION
{
    D3DX_NOT_OPTIMIZED = 0,
    D3DX_3DNOW_OPTIMIZED = 1,
    D3DX_SSE2_OPTIMIZED = 2,
    D3DX_SSE_OPTIMIZED = 3,
} D3DX_CPU_OPTIMIZATION;

Constants

D3DX_NOT_OPTIMIZED
Do not optimize.
D3DX_3DNOW_OPTIMIZED
Optimize for a 3DNow! instruction set.
D3DX_SSE2_OPTIMIZED
Optimize for an SSE2 instruction set.
D3DX_SSE_OPTIMIZED
Optimize for an SSE instruction set.

Requirements

Header: Declared in D3DX10Math.h.

See Also

D3DX Enumerations


D3DX10_ERR

Errors are represented by negative values and cannot be combined. The following is a list of values that can be returned by methods included with the D3DX utility library. See the individual method descriptions for lists of the values that each can return. These lists are not necessarily comprehensive.

typedef enum D3DX10_ERR
{
    D3DX10_ERR_CANNOT_MODIFY_INDEX_BUFFER = MAKE_DDHRESULT(2900),
    D3DX10_ERR_INVALID_MESH = MAKE_DDHRESULT(2901),
    D3DX10_ERR_CANNOT_ATTR_SORT = MAKE_DDHRESULT(2902),
    D3DX10_ERR_SKINNING_NOT_SUPPORTED = MAKE_DDHRESULT(2903),
    D3DX10_ERR_TOO_MANY_INFLUENCES = MAKE_DDHRESULT(2904),
    D3DX10_ERR_INVALID_DATA = MAKE_DDHRESULT(2905),
    D3DX10_ERR_LOADED_MESH_HAS_NO_DATA = MAKE_DDHRESULT(2906),
    D3DX10_ERR_DUPLICATE_NAMED_FRAGMENT = MAKE_DDHRESULT(2907),
    D3DX10_ERR_CANNOT_REMOVE_LAST_ITEM = MAKE_DDHRESULT(2908),
} D3DX10_ERR, *LPD3DX10_ERR;

Constants

D3DX10_ERR_CANNOT_MODIFY_INDEX_BUFFER
The index buffer cannot be modified.
D3DX10_ERR_INVALID_MESH
The mesh is invalid.
D3DX10_ERR_CANNOT_ATTR_SORT
Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
D3DX10_ERR_SKINNING_NOT_SUPPORTED
Skinning is not supported.
D3DX10_ERR_TOO_MANY_INFLUENCES
Too many influences specified.
D3DX10_ERR_INVALID_DATA
The data is invalid.
D3DX10_ERR_LOADED_MESH_HAS_NO_DATA
The mesh has no data.
D3DX10_ERR_DUPLICATE_NAMED_FRAGMENT
A fragment with that name already exists.
D3DX10_ERR_CANNOT_REMOVE_LAST_ITEM
The last item cannot be deleted.

Remarks

The facility code _FACDD is used to generate error codes, as in the following macros.

#define _FACDD                  0x876
#define MAKE_DDHRESULT( code )  MAKE_HRESULT( 1, _FACDD, code )
enum _D3DXERR {
    D3DXERR_CANNOTMODIFYINDEXBUFFER = MAKE_DDHRESULT(2900),
    D3DXERR_INVALIDMESH             = MAKE_DDHRESULT(2901),
    ...
    };

Requirements

Header: Declared in D3DX10.h.

See Also

D3DX Enumerations


D3DX10_FILTER_FLAG

Texture filtering flags.

typedef enum D3DX10_FILTER_FLAG
{
    D3DX10_FILTER_NONE = (1 << 0),
    D3DX10_FILTER_POINT = (2 << 0),
    D3DX10_FILTER_LINEAR = (3 << 0),
    D3DX10_FILTER_TRIANGLE = (4 << 0),
    D3DX10_FILTER_BOX = (5 << 0),
    D3DX10_FILTER_MIRROR_U = (1 << 16),
    D3DX10_FILTER_MIRROR_V = (2 << 16),
    D3DX10_FILTER_MIRROR_W = (4 << 16),
    D3DX10_FILTER_MIRROR = (7 << 16),
    D3DX10_FILTER_DITHER = (1 << 19),
    D3DX10_FILTER_DITHER_DIFFUSION = (2 << 19),
} D3DX10_FILTER_FLAG, *LPD3DX10_FILTER_FLAG;

Constants

D3DX10_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX10_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX10_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX10_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.
D3DX10_FILTER_BOX
Each pixel is computed by averaging a 2x2(x2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX10_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX10_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX10_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX10_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX10_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm. This happens when converting from one format to another.
D3DX10_FILTER_DITHER_DIFFUSION
Do diffuse dithering on the image when changing from one format to another.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Enumerations


D3DX10_IMAGE_FILE_FORMAT

Image file formats supported by D3DXCreatexxx and D3DX10Savexxx functions.

typedef enum D3DX10_IMAGE_FILE_FORMAT
{
    D3DX10_IFF_BMP = 0,
    D3DX10_IFF_JPG = 1,
    D3DX10_IFF_PNG = 3,
    D3DX10_IFF_DDS = 4,
    D3DX10_IFF_TIFF = 10,
    D3DX10_IFF_GIF = 11,
    D3DX10_IFF_WMP = 12,
    D3DX10_IFF_FORCE_DWORD = 0x7fffffff,
} D3DX10_IMAGE_FILE_FORMAT, *LPD3DX10_IMAGE_FILE_FORMAT;

Constants

D3DX10_IFF_BMP
Windows bitmap (BMP) file format. Contains a header that describes the resolution of the device on which the rectangle of pixels was created, the dimensions of the rectangle, the size of the array of bits, a logical palette, and an array of bits that defines the relationship between pixels in the bitmapped image and entries in the logical palette.
D3DX10_IFF_JPG
Joint Photographic Experts Group (JPEG) compressed file format. Specifies variable compression of 24-bit RGB color and 8-bit gray-scale Tagged Image File Format (TIFF) image document files.
D3DX10_IFF_PNG
Portable Network Graphics (PNG) file format. A non-proprietary bitmap format using lossless compression.
D3DX10_IFF_DDS
DirectDraw surface (DDS) file format. Stores textures, volume textures, and cubic environment maps, with or without mipmap levels, and with or without pixel compression.
D3DX10_IFF_TIFF
Tagged Image File Format (TIFF).
D3DX10_IFF_GIF
Graphics Interchange Format (GIF).
D3DX10_IFF_WMP
Windows Media Player format (WMP).
D3DX10_IFF_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

See Types of Bitmaps (GDI+) for more information on some of these formats.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Enumerations


D3DX10_MESH

Flags used to specify creation options for a mesh.

typedef enum D3DX10_MESH
{
    D3DX10_MESH_32_BIT = 0x001,
    D3DX10_MESH_GS_ADJACENCY = 0x004,
} D3DX10_MESH, *LPD3DX10_MESH;

Constants

D3DX10_MESH_32_BIT
The mesh has 32-bit indices instead of 16-bit indices. See Remarks.
D3DX10_MESH_GS_ADJACENCY
Signals that the mesh contains geometry shader adjacency data.

Remarks

A 32-bit mesh (D3DXMESH_32BIT) can theoretically support (232)-1 faces and vertices. However, allocating memory for a mesh that large on a 32-bit operating system is not practical.

Requirements

Header: Declared in D3DX10Mesh.h.

See Also

D3DX Enumerations


D3DX10_MESH_DISCARD_FLAGS

Specifies which pieces of mesh data to discard from the device. Used with ID3DX10Mesh::Discard.

typedef enum D3DX10_MESH_DISCARD_FLAGS
{
    D3DX10_MESH_DISCARD_ATTRIBUTE_BUFFER = 0x01,
    D3DX10_MESH_DISCARD_ATTRIBUTE_TABLE = 0x02,
    D3DX10_MESH_DISCARD_POINTREPS = 0x04,
    D3DX10_MESH_DISCARD_ADJACENCY = 0x08,
    D3DX10_MESH_DISCARD_DEVICE_BUFFERS = 0x10,
} D3DX10_MESH_DISCARD_FLAGS, *LPD3DX10_MESH_DISCARD_FLAGS;

Constants

D3DX10_MESH_DISCARD_ATTRIBUTE_BUFFER
Discard the attribute buffer.
D3DX10_MESH_DISCARD_ATTRIBUTE_TABLE
Discard the attribute table.
D3DX10_MESH_DISCARD_POINTREPS
Discard the pointer reps buffer.
D3DX10_MESH_DISCARD_ADJACENCY
Discard the adjacency buffer.
D3DX10_MESH_DISCARD_DEVICE_BUFFERS
Discard the buffers committed to the device (with ID3DX10Mesh::CommitToDevice).

Requirements

Header: Declared in D3DX10Mesh.h.

See Also

D3DX Enumerations


D3DX10_MESHOPT

Specifies the type of mesh optimization to be performed.

typedef enum D3DX10_MESHOPT
{
    D3DX10_MESHOPT_COMPACT = 0x01000000,
    D3DX10_MESHOPT_ATTR_SORT = 0x02000000,
    D3DX10_MESHOPT_VERTEX_CACHE = 0x04000000,
    D3DX10_MESHOPT_STRIP_REORDER = 0x08000000,
    D3DX10_MESHOPT_IGNORE_VERTS = 0x10000000,
    D3DX10_MESHOPT_DO_NOT_SPLIT = 0x20000000,
    D3DX10_MESHOPT_DEVICE_INDEPENDENT = 0x00400000,
} D3DX10_MESHOPT, *LPD3DX10_MESHOPT;

Constants

D3DX10_MESHOPT_COMPACT
Reorders faces to remove unused vertices and faces.
D3DX10_MESHOPT_ATTR_SORT
Reorders faces to optimize for fewer attribute bundle state changes and enhanced DrawSubset performance.
D3DX10_MESHOPT_VERTEX_CACHE
Reorders faces to increase the cache hit rate of vertex caches.
D3DX10_MESHOPT_STRIP_REORDER
Reorders faces to maximize length of adjacent triangles.
D3DX10_MESHOPT_IGNORE_VERTS
Optimize the faces only; do not optimize the vertices.
D3DX10_MESHOPT_DO_NOT_SPLIT
While attribute sorting, do not split vertices that are shared between attribute groups.
D3DX10_MESHOPT_DEVICE_INDEPENDENT
Affects the vertex cache size. Using this flag specifies a default vertex cache size that works well on legacy hardware.

Remarks

The D3DXMESHOPT_STRIPREORDER and D3DXMESHOPT_VERTEXCACHE optimization flags are mutually exclusive.

The D3DXMESHOPT_SHAREVB flag has been removed from this enumeration. Use D3DXMESH_VB_SHARE instead, in D3DXMESH.

Requirements

Header: Declared in D3DX10Mesh.h.

See Also

D3DX Enumerations


D3DX10_NORMALMAP_FLAG

These flags are used to control how D3DX10ComputeNormalMap generates normal maps. Any number of these flags may be OR'd together in any combination.

typedef enum D3DX10_NORMALMAP_FLAG
{
    D3DX10_NORMALMAP_MIRROR_U = (1 << 16),
    D3DX10_NORMALMAP_MIRROR_V = (2 << 16),
    D3DX10_NORMALMAP_MIRROR = (3 << 16),
    D3DX10_NORMALMAP_INVERTSIGN = (8 << 16),
    D3DX10_NORMALMAP_COMPUTE_OCCLUSION = (16 << 16),
} D3DX10_NORMALMAP_FLAG, *LPD3DX10_NORMALMAP_FLAG;

Constants

D3DX10_NORMALMAP_MIRROR_U
Indicates that pixels off the edge of the texture on the U-axis should be mirrored, not wraped.
D3DX10_NORMALMAP_MIRROR_V
Indicates that pixels off the edge of the texture on the V-axis should be mirrored, not wraped.
D3DX10_NORMALMAP_MIRROR
Same as D3DX10_NORMALMAP_MIRROR_U | D3DX10_NORMALMAP_MIRROR_V.
D3DX10_NORMALMAP_INVERTSIGN
Inverts the direction of each normal.
D3DX10_NORMALMAP_COMPUTE_OCCLUSION
Computes the per pixel occlusion term and encodes it into the alpha. An Alpha of 1 means that the pixel is not obscured in any way, and an alpha of 0 would mean that the pixel is completly obscured.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Enumerations


D3DX10_SPRITE_FLAG

Sprite flags that tell the sprite drawing API how to behave. These are passed into ID3DX10Sprite::Begin.

typedef enum D3DX10_SPRITE_FLAG
{
    D3DX10_SPRITE_SORT_TEXTURE = 0x01,
    D3DX10_SPRITE_SORT_DEPTH_BACK_TO_FRONT = 0x02,
    D3DX10_SPRITE_SORT_DEPTH_FRONT_TO_BACK = 0x04,
    D3DX10_SPRITE_SAVE_STATE = 0x08,
    D3DX10_SPRITE_ADDREF_TEXTURES = 0x10,
} D3DX10_SPRITE_FLAG, *LPD3DX10_SPRITE_FLAG;

Constants

D3DX10_SPRITE_SORT_TEXTURE
Sort the sprites by texture before rendering so that when there are many sprites with the same texture that texture all of those sprites will be rendered at the same time, thereby improving performance.
D3DX10_SPRITE_SORT_DEPTH_BACK_TO_FRONT
Sort the sprites from back to front to that those farther away from the camera will be drawn first.
D3DX10_SPRITE_SORT_DEPTH_FRONT_TO_BACK
Sort the sprites from front to back so that those closer to the camera will be drawn first.
D3DX10_SPRITE_SAVE_STATE
Saves the state so that when ID3DX10Sprite::End is called, it will restore the state to the way it was before ID3DX10Sprite::Begin was called.
D3DX10_SPRITE_ADDREF_TEXTURES
Calls AddRef on all of the textures when they are passed into ID3DX10Sprite::DrawSpritesBuffered.

Remarks

After a front-to-back or back-to-front sort is done, it will automatically do a secondary sort by texture. This is helpful for when there are many sprites with the same texture all on the same plane, such as when drawing the user interface in a game.

Requirements

Header: Declared in D3DX10Core.h.

See Also

D3DX Enumerations


D3DX10_SAVE_TEXTURE_FLAG

Texture save options.

typedef enum D3DX10_SAVE_TEXTURE_FLAG
{
    D3DX10_STF_USEINPUTBLOB = 1,
} D3DX10_SAVE_TEXTURE_FLAG;

Constants

D3DX10_STF_USEINPUTBLOB
Do not optimize.

Requirements

Header: Declared in D3DX10Tex.h.

See Also

D3DX Enumerations


HLSL Reference (Direct3D 10 HLSL)

This page has been deprecated. See HLSL.


Variable Declaration Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Basic Types (Direct3D 10 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Vector Type Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Vector Type (DirectX HLSL).


Matrix Type Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Shader Type Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Texture Type Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Texture Objects (Direct3D 10 HLSL).

See Also

HLSL Reference (Direct3D 10 HLSL)


Sampler Type Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Struct Type Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


User-Defined Type Syntax (Direct3D 10 HLSL)

This page has been deprecated. See User-Defined Type (DirectX HLSL).


Function Declaration Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Functions (DirectX HLSL).


Function Parameter List Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Functions (DirectX HLSL).


Statement Block Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Statements (DirectX HLSL).


Intrinsic Functions (Direct3D 10 HLSL)

This page has been deprecated. See Intrinsic Functions (DirectX HLSL).


abs (Direct3D 10 HLSL)

This page has been deprecated. See abs (DirectX HLSL).


acos (Direct3D 10 HLSL)

This page has been deprecated. See acos (DirectX HLSL).


all (Direct3D 10 HLSL)

This page has been deprecated. See all (DirectX HLSL).


any (Direct3D 10 HLSL)

This page has been deprecated. See any (DirectX HLSL).


asfloat (Direct3D 10 HLSL)

This page has been deprecated. See asfloat (DirectX HLSL).


asin (Direct3D 10 HLSL)

This page has been deprecated. See asin (DirectX HLSL).


asint (Direct3D 10 HLSL)

This page has been deprecated. See asint (DirectX HLSL).


asuint (Direct3D 10 HLSL)

This page has been deprecated. See asuint (DirectX HLSL).


atan (Direct3D 10 HLSL)

This page has been deprecated. See atan (DirectX HLSL).


atan2 (Direct3D 10 HLSL)

This page has been deprecated. See atan2 (DirectX HLSL).


ceil (Direct3D 10 HLSL)

This page has been deprecated. See ceil (DirectX HLSL).


clamp (Direct3D 10 HLSL)

This page has been deprecated. See clamp (DirectX HLSL).


clip (Direct3D 10 HLSL)

This page has been deprecated. See clip (DirectX HLSL).


cos (Direct3D 10 HLSL)

This page has been deprecated. See clip (DirectX HLSL).


cosh (Direct3D 10 HLSL)

This page has been deprecated. See cosh (DirectX HLSL).


cross (Direct3D 10 HLSL)

This page has been deprecated. See cross (DirectX HLSL).


D3DCOLORtoUBYTE4 (Direct3D 10 HLSL)

This page has been deprecated. See D3DCOLORtoUBYTE4 (DirectX HLSL).


ddx (Direct3D 10 HLSL)

This page has been deprecated. See ddx (DirectX HLSL).


ddy (Direct3D 10 HLSL)

This page has been deprecated. See ddy (DirectX HLSL).


degrees (Direct3D 10 HLSL)

This page has been deprecated. See degrees (DirectX HLSL).


determinant (Direct3D 10 HLSL)

This page has been deprecated. See determinant (DirectX HLSL).


distance (Direct3D 10 HLSL)

This page has been deprecated. See distance (DirectX HLSL).


dot (Direct3D 10 HLSL)

This page has been deprecated. See dot (DirectX HLSL).


exp (Direct3D 10 HLSL)

This page has been deprecated. See exp (DirectX HLSL).


exp2 (Direct3D 10 HLSL)

This page has been deprecated. See exp2 (DirectX HLSL).


faceforward (Direct3D 10 HLSL)

This page has been deprecated. See faceforward (DirectX HLSL).


floor (Direct3D 10 HLSL)

This page has been deprecated. See floor (DirectX HLSL).


fmod (Direct3D 10 HLSL)

This page has been deprecated. See fmod (DirectX HLSL).


frac (Direct3D 10 HLSL)

This page has been deprecated. See frac (DirectX HLSL).


frexp (Direct3D 10 HLSL)

This page has been deprecated. See frexp (DirectX HLSL).


fwidth (Direct3D 10 HLSL)

This page has been deprecated. See fwidth (DirectX HLSL).


isfinite (Direct3D 10 HLSL)

This page has been deprecated. See isfinite (DirectX HLSL).


isinf (Direct3D 10 HLSL)

This page has been deprecated. See isinf (DirectX HLSL).


isnan (Direct3D 10 HLSL)

This page has been deprecated. See isnan (DirectX HLSL).


ldexp (Direct3D 10 HLSL)

This page has been deprecated. See ldexp (DirectX HLSL).


length (Direct3D 10 HLSL)

This page has been deprecated. See length (DirectX HLSL).


lerp (Direct3D 10 HLSL)

This page has been deprecated. See lerp (DirectX HLSL).


lit (Direct3D 10 HLSL)

This page has been deprecated. See lit (DirectX HLSL).


log (Direct3D 10 HLSL)

This page has been deprecated. See log (DirectX HLSL).


log2 (Direct3D 10 HLSL)

This page has been deprecated. See log2 (DirectX HLSL).


log10 (Direct3D 10 HLSL)

This page has been deprecated. See log10 (DirectX HLSL).


max (Direct3D 10 HLSL)

This page has been deprecated. See max (DirectX HLSL).


min (Direct3D 10 HLSL)

This page has been deprecated. See min (DirectX HLSL).


modf (Direct3D 10 HLSL)

This page has been deprecated. See modf (DirectX HLSL).


mul (Direct3D 10 HLSL)

This page has been deprecated. See mul (DirectX HLSL).


noise (Direct3D 10 HLSL)

This page has been deprecated. See noise (DirectX HLSL).


normalize (Direct3D 10 HLSL)

This page has been deprecated. See normalize (DirectX HLSL).


pow (Direct3D 10 HLSL)

This page has been deprecated. See pow (DirectX HLSL).


radians (Direct3D 10 HLSL)

This page has been deprecated. See radians (DirectX HLSL).


reflect (Direct3D 10 HLSL)

This page has been deprecated. See reflect (DirectX HLSL).


refract (Direct3D 10 HLSL)

This page has been deprecated. See refract (DirectX HLSL).


round (Direct3D 10 HLSL)

This page has been deprecated. See round (DirectX HLSL).


rsqrt (Direct3D 10 HLSL)

This page has been deprecated. See rsqrt (DirectX HLSL).


saturate (Direct3D 10 HLSL)

This page has been deprecated. See saturate (DirectX HLSL).


sign (Direct3D 10 HLSL)

This page has been deprecated. See sign (DirectX HLSL).


sin (Direct3D 10 HLSL)

This page has been deprecated. See sin (DirectX HLSL).


sincos (Direct3D 10 HLSL)

This page has been deprecated. See sincos (DirectX HLSL).


sinh (Direct3D 10 HLSL)

This page has been deprecated. See sinh (DirectX HLSL).


smoothstep (Direct3D 10 HLSL)

This page has been deprecated. See smoothstep (DirectX HLSL).


sqrt (Direct3D 10 HLSL)

This page has been deprecated. See sqrt (DirectX HLSL).


step (Direct3D 10 HLSL)

This page has been deprecated. See step (DirectX HLSL).


tan (Direct3D 10 HLSL)

This page has been deprecated. See tan (DirectX HLSL).


tanh (Direct3D 10 HLSL)

This page has been deprecated. See tanh (DirectX HLSL).


tex1D (Direct3D 10 HLSL)

This page has been deprecated. See tex1D (DirectX HLSL).


tex1Dlod (Direct3D 10 HLSL)

This page has been deprecated. See tex1Dlod (DirectX HLSL).


tex1Dgrad (Direct3D 10 HLSL)

This page has been deprecated. See tex1Dgrad (DirectX HLSL).


tex1Dproj (Direct3D 10 HLSL)

This page has been deprecated. See tex1Dproj (DirectX HLSL).


tex2D (Direct3D 10 HLSL)

This page has been deprecated. See tex2D (DirectX HLSL).


tex2Dlod (Direct3D 10 HLSL)

This page has been deprecated. See tex2Dlod (DirectX HLSL).


tex2Dgrad (Direct3D 10 HLSL)

This page has been deprecated. See tex2Dgrad (DirectX HLSL).


tex2Dproj (Direct3D 10 HLSL)

This page has been deprecated. See tex2Dproj (DirectX HLSL).


tex3D (Direct3D 10 HLSL)

This page has been deprecated. See tex3D (DirectX HLSL).


tex3Dlod (Direct3D 10 HLSL)

This page has been deprecated. See tex3Dlod (DirectX HLSL).


tex3Dgrad (Direct3D 10 HLSL)

This page has been deprecated. See tex3Dgrad (DirectX HLSL).


tex3Dproj (Direct3D 10 HLSL)

This page has been deprecated. See tex3Dproj (DirectX HLSL).


texCUBE (Direct3D 10 HLSL)

This page has been deprecated. See texCUBE (DirectX HLSL).


texCUBElod (Direct3D 10 HLSL)

This page has been deprecated. See texCUBElod (DirectX HLSL).


texCUBEgrad (Direct3D 10 HLSL)

This page has been deprecated. See texCUBEgrad (DirectX HLSL).


texCUBEproj (Direct3D 10 HLSL)

This page has been deprecated. See texCUBEproj (DirectX HLSL).


transpose (Direct3D 10 HLSL)

This page has been deprecated. See transpose (DirectX HLSL).


Stream Objects (Direct3D 10 HLSL)

This page has been deprecated. See Stream-Output Object (DirectX HLSL).


append (Direct3D 10 HLSL)

This page has been deprecated. See Append (DirectX HLSL Stream-Output Object).


restartstrip (Direct3D 10 HLSL)

This page has been deprecated. See RestartStrip (DirectX HLSL Stream-Output Object).


Texture Objects (Direct3D 10 HLSL)

This page has been deprecated. See Texture Object (DirectX HLSL).


GetDimensions (Direct3D 10 HLSL)

This page has been deprecated. See GetDimension (DirectX HLSL Texture Object).


Load (Direct3D 10 HLSL)

This page has been deprecated. See Load (DirectX HLSL Texture Object).


Sample (Direct3D 10 HLSL)

This page has been deprecated. See Sample (DirectX HLSL Texture Object).


SampleCmp (Direct3D 10 HLSL)

This page has been deprecated. See SampleCmp (DirectX HLSL Texture Object).


SampleCmpLevelZero (Direct3D 10 HLSL)

This page has been deprecated. See SampleCmpLevelZero (DirectX HLSL Texture Object).


SampleGrad (Direct3D 10 HLSL)

This page has been deprecated. See SampleGrad (DirectX HLSL Texture Object).


SampleLevel (Direct3D 10 HLSL)

This page has been deprecated. See SampleLevel (DirectX HLSL Texture Object).


Shader Semantic Syntax (Direct3D 10 HLSL)

This page has been deprecated. See Shader Semantics (DirectX HLSL).


Flow Control Statements (Direct3D 10 HLSL)

This page has been deprecated. See Flow Control (DirectX HLSL).


break statement (Direct3D 10 HLSL)

This page has been deprecated. See break Statement (DirectX HLSL).


continue statement (Direct3D 10 HLSL)

This page has been deprecated. See continue Statement (DirectX HLSL).


do statement (Direct3D 10 HLSL)

This page has been deprecated. See do Statement (DirectX HLSL).


for statement (Direct3D 10 HLSL)

This page has been deprecated. See for Statement (DirectX HLSL).


if statement (Direct3D 10 HLSL)

This page has been deprecated. See if Statement (DirectX HLSL).


stop statement (Direct3D 10 HLSL)

This page has been deprecated. See stop Statement (DirectX HLSL).


switch statement (Direct3D 10 HLSL)

This page has been deprecated. See switch Statement (DirectX HLSL).


while statement (Direct3D 10 HLSL)

This page has been deprecated. See while Statement (DirectX HLSL).


Packing Rules for Constant Variables (Direct3D 10 HLSL)

This page has been deprecated. See Packing Rules for Constant Variables (DirectX HLSL).


HLSL Appendix (Direct3D 10 HLSL)

This page has been deprecated. See Appendix (DirectX HLSL).


DXGI Reference

This reference sections defines the following data types:

  • DXGI Interfaces
  • DXGI Functions
  • DXGI Structures
  • DXGI Enumerations
  • DXGI Constants

See Also

Direct3D 10 Reference


DXGI Interfaces

This section contains information about the following DXGI interfaces.

IUnknown
IDXGIObject
IDXGIAdapter
IDXGIDevice
IDXGIFactory
IDXGIOutput
IDXGIDeviceSubObject
IDXGIResource
IDXGISurface
IDXGISwapChain
Interfaces | Description
IDXGIAdapter | Represents a display sub-system (including one or more GPU's, DACs and video memory).
IDXGIDevice | Implements a derived class for DXGI objects that produce image data.
IDXGIDeviceSubObject | Inherited from objects that are tied to the device so that they can retrieve a pointer to it.
IDXGIFactory | Implements methods for generating DXGI objects.
IDXGIObject | Implements a base class for all DXGI objects with methods for getting and setting data and retrieving parent interfaces.
IDXGIOutput | Represents an adapter output (such as a monitor).
IDXGIResource | Allows resource sharing and identifies the memory that a resource resides in.
IDXGISurface | Implements methods for image-data objects.
IDXGISwapChain | Implements one or more surfaces for storing rendered data before presenting it to an output.

See Also

DXGI Reference


IDXGIAdapter Interface

An IDXGIAdapter interface represents a display sub-system (including one or more GPU's, DACs and video memory).

IUnknown
IDXGIObject
IDXGIAdapter
Method | Description
IDXGIAdapter::CheckInterfaceSupport | Checks to see if a device interface for a graphics component is supported.
IDXGIAdapter::EnumOutputs | Enumerates outputs.
IDXGIAdapter::GetDesc | Gets a description of the adapter.

A display sub-system is often referred to as a video card, however, on some machines the display sub-system is part of the mother board.

To enumerate the display sub-systems, use IDXGIFactory::EnumAdapters. To get an interface to the adapter for a particular device, use IDXGIDevice::GetAdapter. To create a software adapter, use IDXGIFactory::CreateSoftwareAdapter.

See Also

DXGI Interfaces


IDXGIAdapter::CheckInterfaceSupport

Checks to see if a device interface for a graphics component is supported by the system.

HRESULT CheckInterfaceSupport(
  REFGUID InterfaceName,
  LARGE_INTEGER *pUMDVersion
);

Parameters

InterfaceName
[in] The GUID of the interface of the device version for which support is being checked. For example, __uuidof(ID3D10Device).
pUMDVersion
[out] The user mode driver version of InterfaceName. This is only returned if the interface is supported. This parameter can be NULL.

Return Values

S_OK indicates that the interface is supported, otherwise DXGI_ERROR_UNSUPPORTED is returned.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIAdapter::EnumOutputs

Enumerate the outputs on a given video card (or adapter).

HRESULT EnumOutputs(
  UINT Output,
  IDXGIOutput **ppOutput
);

Parameters

Output
[in] The index of the output. See remarks.
ppOutput
[in, out] The address of a pointer to an output. See IDXGIOutput.

Return Values

Returns a code that indicates success or failure. See Return Values. Will return DXGI_ERROR_NOT_FOUND if the value of Output is greater than the number of outputs. See remarks.

Remarks

When this function succeeds and ppOutput is filled, the reference count of IDXGIOutput will be incremented. When you are finished with the pointer to the output, be sure to call ::Release() on it to decrement the reference count before the pointer is destroyed.

Here is an example of how to use this function to enumerate all outputs on an adapter:

UINT i = 0;
IDXGIOutput * pOutput;
std::vector<IDXGIOutput*> vOutputs;
while(pAdapter->EnumOutputs(i, &pOutput) != DXGI_ERROR_NOT_FOUND)
{
    vOutputs.push_back(pOutput);
    ++i;
}

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIAdapter::GetDesc

Get a description of the video card (or adapter).

HRESULT GetDesc(
  DXGI_ADAPTER_DESC *pDesc
);

Parameters

pDesc
[out] A pointer to an adapter description. See DXGI_ADAPTER_DESC.

Return Values

Returns a code that indicates success or failure. S_OK indicates success, DXGI_ERR_INVALID_CALL indicates that pDesc was passed in as NULL.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIDevice Interface

An IDXGIDevice interface implements a derived class for DXGI objects that produce image data.

IUnknown
IDXGIObject
IDXGIDevice
Method | Description
IDXGIDevice::CreateSurface | Create a buffer to exchange data between one or more resources.
IDXGIDevice::GetAdapter | Gets the adapter.
IDXGIDevice::GetGPUThreadPriority | Gets the GPU thread priority.
IDXGIDevice::QueryResourceResidency | Gets the residency status of a number of resources.
IDXGIDevice::SetGPUThreadPriority | Sets the GPU thread priority.

IDXGIDevice is designed for use by DXGI objects that need access to other DXGI objects. This interface is useful to applications that do not use Direct3D to communicate with DXGI.

See Also

DXGI Interfaces


IDXGIDevice::CreateSurface

Create a buffer to exchange data between one or more resources.

HRESULT CreateSurface(
  const DXGI_SURFACE_DESC *pDesc,
  UINT NumSurfaces,
  DXGI_USAGE Usage,
  const DXGI_SHARED_RESOURCE *pSharedResource,
  IDXGISurface **ppSurface
);

Parameters

pDesc
[in] Description of the surface. See DXGI_SURFACE_DESC.
NumSurfaces
[in] Number of surfaces to create.
Usage
[in] A flag that specifies how the surface is expected to be used. For Direct3D 10, a surface can be used as a shader input or a render-target output (see DXGI_USAGE for the specific flags). These usages can be combined with any CPU access flags. See remarks.
pSharedResource
[in] Optional pointer to shared resource information for opening views of such resources. See DXGI_SHARED_RESOURCE.
ppSurface
[out] The address of a pointer to the first created surface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

These CPU access flags may be logically combined (ORed) with the usage to indicate what type of CPU access each surface has.

DXGI_CPU_ACCESS_NONE | Restrict access to the GPU only for this surface. | 0
DXGI_CPU_ACCESS_DYNAMIC | Allow the CPU to access this as a dynamic resource. |
DXGI_CPU_ACCESS_READ_WRITE | The CPU may read or write this surface. | 2
DXGI_CPU_ACCESS_SCRATCH |  | 3
DXGI_CPU_ACCESS_FIELD |  | 15

This method is used internally by DXGI; it is not useful to an application.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIDevice::GetAdapter

Returns an interface to the adapter for a particular device.

HRESULT GetAdapter(
  IDXGIAdapter **pAdapter
);

Parameters

pAdapter
[out] The address of a pointer to the adapter. See IDXGIAdapter.

Return Values

Returns a code that indicates success or failure. See Return Values. If successful it will return S_OK, if pAdapter is passed in as NULL this API will return DXGI_ERR_INVALID_CALL

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIDevice::GetGPUThreadPriority

Get the GPU thread priority.

HRESULT GetGPUThreadPriority(
  INT *pPriority
);

Parameters

pPriority
[out] The GPU thread priority. Will be between -7 and 7, inclusive, where 0 represents normal.

Return Values

If this API succeeds, it will return S_OK. Otherwise it may return E_POINTER (if pPriority is NULL).

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIDevice::QueryResourceResidency

Get the residency status of a number of resources.

HRESULT QueryResourceResidency(
  IUnknown *const *ppResources,
  DXGI_RESIDENCY *pResidencyStatus,
  UINT NumResources
);

Parameters

ppResources
[in] An array of IDXGIResource Interfaces to have their residency status checked.
pResidencyStatus
[out] An array of DXGI_RESIDENCYs describing the residency status of the resources. The size of the array is NumResources and each member of the array corresponds to a member of the ppResources array.
NumResources
[in] The number of resources to query.

Return Values

If this API succeeds, it will return S_OK. Otherwise it may return E_INVALIDARG or E_POINTER.

Remarks

The residency status of the resources is likely to be constantly changing, and therefore the data returned by the API serves as a snapshot of the data at a point in time.

The size of ppResources and pResidencyStatus arrays must be large enough to for NumResources.

If this API is called when the device is in the removed state, pResidencyStatus will return DXGI_RESIDENCY_EVICTED_TO_DISK.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIDevice::SetGPUThreadPriority

Set the GPU thread priority.

HRESULT SetGPUThreadPriority(
  INT Priority
);

Parameters

Priority
[in] The GPU thread priority. Must be between -7 and 7, inclusive, where 0 represents normal.

Return Values

If this API succeeds, it will return S_OK. Otherwise it may return E_INVALIDARG.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIDeviceSubObject Interface

Inherited from objects that are tied to the device so that they can retrieve a pointer to it.

IUnknown
IDXGIObject
IDXGIDeviceSubObject
Method | Description
IDXGIDeviceSubObject::GetDevice | Retrieves the device.

See Also

DXGI Interfaces


IDXGIDeviceSubObject::GetDevice

Retrieves the device.

HRESULT GetDevice(
  REFIID riid,
  void **ppDevice
);

Parameters

riid
[in] The identifier of the requested interface that ppDevice will be filled with. See remarks.
ppDevice
[out] The address of a pointer to the device.

Return Values

This method returns one of the following Direct3D 10 Return Codes.

Remarks

The type of interface that is returned can be any interface published by the device that is associated with this device sub object. For example, it could be an IDXGIDevice * called pDevice, and therefore the REFIID would be obtained by calling __uuidof(pDevice).

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIFactory Interface

An IDXGIFactory interface implements methods for generating DXGI objects (which handle fullscreen transitions).

IUnknown
IDXGIObject
IDXGIFactory
Method | Description
IDXGIFactory::CreateSoftwareAdapter | Creates an adapter implemented in software.
IDXGIFactory::CreateSwapChain | Creates a swap chain.
IDXGIFactory::EnumAdapters | Enumerates hardware adapters.
IDXGIFactory::GetWindowAssociation | Retrieves a handle to a window that was previously passed to MakeWindowAssociation.
IDXGIFactory::MakeWindowAssociation | Optional. Sets the window that DXGI will monitor fullscreen transitions initiated by an Alt-Enter key sequence.

Create a factory by calling CreateDXGIFactory.

See Also

DXGI Interfaces


IDXGIFactory::CreateSoftwareAdapter

Create an adapter interface that represents a software adapter.

HRESULT CreateSoftwareAdapter(
  HMODULE Module,
  IDXGIAdapter **ppAdapter
);

Parameters

Module
[in] Handle to the software adapter's dll. HMODULE can be obtained with GetModuleHandle or LoadLibrary.
ppAdapter
[out] Address of a pointer to an adapter (see IDXGIAdapter Interface).

Return Values

A return code indicating success or failure.

Remarks

A software adapter is a DLL that implements the entirety of a device driver interface, plus emulation, if necessary, of kernel-mode graphics components for Windows. Details on implementing a software adapter can be found in the Windows Vista Driver Development Kit. This is a very complex development task, and is not recommended for general readers.

Calling this method will increment the module's reference count by one. The reference count can be decremented by calling FreeLibrary.

The typical calling scenario is to call LoadLibrary, pass the handle to CreateSoftwareAdapter, then immediately call FreeLibrary on the DLL and forget the DLL's HMODULE. Since the software adapter calls FreeLibrary when it is destroyed, the lifetime of the DLL will now be owned by the adapter, and the application is free of any further consideration of its lifetime.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIFactory Interface


IDXGIFactory::CreateSwapChain

This method creates a swap chain.

HRESULT CreateSwapChain(
  IUnknown *pDevice,
  DXGI_SWAP_CHAIN_DESC *pDesc,
  IDXGISwapChain **ppSwapChain
);

Parameters

pDevice
[in] Pointer to the device that will write 2D images to the back buffers.
pDesc
[in] Describes the swapchain to be created. Cannot be NULL. See DXGI_SWAP_CHAIN_DESC
ppSwapChain
[out] A pointer to the returned interface. Cannot be NULL. See IDXGISwapChain Interface.

Return Values

DXGI_ERR_INVALIDCALL if pDesc or ppSwapChain is NULL, or E_OUTOFMEMORY. Other error codes defined by the type of device passed in may also be returned.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIFactory::EnumAdapters

Enumerates the adapters (video cards). See remarks.

HRESULT EnumAdapters(
  UINT Adapter,
  IDXGIAdapter **ppAdapter
);

Parameters

Adapter
[in] The index of the adapter. See remarks.
ppAdapter
[out] The adapter. See IDXGIAdapter Interface.

Return Values

DXGIERR_NOT_FOUND if Adapter is greater than or equal to the number of adapters in the local system, or DXGIERR_INVALID_CALL if ppAdapterInterface is NULL.

Remarks

Here is an example of how to use this function to enumerate all video cards:

UINT i = 0;
IDXGIAdapter * pAdapter;
std::vector<IDXGIAdapter*> vAdapters;
while(pFactory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND)
{
    vAdapters.push_back(pAdapter);
    ++i;
}

When this function succeeds and ppAdapter is filled, the reference count of IDXGIAdapter will be incremented. When you are finished with the pointer to the output, be sure to call Release to decrement the reference count before the pointer is destroyed.

The set of adapters available in the system is enumerated when the factory is created. Therefore, if you change the adapters in a system (add or remove a display card or dock or undock a laptop), the factory must be destroyed and recreated to get the correct enumeration.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIFactory::GetWindowAssociation

Get the window through which the user controls the transition to and from fullscreen.

HRESULT GetWindowAssociation(
  HWND *pWindowHandle
);

Parameters

pWindowHandle
[in] A pointer to a window handle.

Return Values

Returns a code that indicates success or failure. S_OK indicates success, DXGI_ERR_INVALID_CALL indicates pWindowHandle was passed in as NULL.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIFactory::MakeWindowAssociation

Allows DXGI to monitor an application's message queue for the alt-enter key sequence (which causes the application to switch from windowed to fullscreen or vice versa).

HRESULT MakeWindowAssociation(
  HWND WindowHandle,
  UINT Flags
);

Parameters

WindowHandle
[in] The handle of the window that is to be monitored. This parameter can be NULL; but only if Flags is 0.
Flags
[in] One or more of the following values:
  • DXGI_MWA_NO_WINDOW_CHANGES - Prevent DXGI from monitoring an applications message queue; this makes DXGI unable to respond to mode changes.
  • DXGI_MWA_NO_ALT_ENTER - Prevent DXGI from responding to an alt-enter sequence.
  • DXGI_MWA_NO_PRINT_SCREEN - Prevent DXGI from responding to a print-screen key.

Return Values

DXGIERR_INVALID_CALL if hWnd is invalid, or E_OUTOFMEMORY.

Remarks

The combination of WindowHandle and Flags tells DXGI to stop monitoring window messages for the previously-associated window.

If the application switches to full screen mode, DXGI will choose a fullscreen resolution to be the smallest supported resolution that is larger or the same size as the current back buffer size.

Applications can make some changes to make the transition from windowed to fullscreen more efficient. For example, on a WM_SIZE message, the application should release any outstanding swapchain back buffers, call IDXGISwapChain::ResizeBackBuffers, then re-acquire the back buffers from the swapchain(s). This gives the swapchain(s) an opportunity to re-size the back buffers, and/or recreate them to enable fullscreen flipping operation. If the application does not perform this sequence, DXGI will still make the fullscreen/windowed transition, but may be forced to use a stretch operation (since the back buffers may not be the correct size), which may be less efficient. Even if a stretch is not required, presentation may not be optimal because the back buffers might not be directly interchangeable with the front buffer. Thus, a call to ResizeBuffers on WM_SIZE is always recommended, since WM_SIZE is always sent during a fullscreen transition.

While windowed, the application can, if it chooses, restrict the size of its window's client area to sizes to which it is comfortable rendering. A fully flexible application would make no such restriction, but UI elements or other design considerations can, of course, make this flexibility untenable. If the application further chooses to restrict its window's client area to just those that match supported fullscreen resolutions, the application can field WM_SIZING, then check against IDXGIOutput::FindClosestMatchingMode. If a matching mode is found, allow the resize. (The IDXGIOutput can be retrieved from IDXGISwapChain::GetContainingOutput. Absent subsequent changes to desktop topology, this will be the same output that will be chosen when alt-enter is fielded and fullscreen mode is begun for that swapchain.)

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIObject Interface

An IDXGIObject interface is a base interface for all DXGI objects; IDXGIObject supports associating caller-defined (private data) with an object and retrieval of an interface to the parent object.

IUnknown
IDXGIObject
Method | Description
IDXGIObject::GetParent | Gets a pointer to the parent object.
IDXGIObject::GetPrivateData | Gets private data.
IDXGIObject::SetPrivateData | Sets an IUnknown interface as private data.
IDXGIObject::SetPrivateDataInterface | Sets a pointer to an interface.

IDXGIObject implements base class functionality for several other interfaces: IDXGIAdapter Interface, IDXGIDevice Interface, IDXGIFactory Interface, IDXGIOutput Interface

See Also

DXGI Interfaces


IDXGIObject::GetParent

Get the producer that created the object.

HRESULT GetParent(
  REFIID riid,
  void **ppParent
);

Parameters

riid
[in] The ID of the requested interface. See remarks.
ppParent
[out] The address of a pointer to the parent object.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

You may obtain the REFIID of the object like so:

__uuidof(*ppParent)

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIObject::GetPrivateData

Get a pointer to the object's data.

HRESULT GetPrivateData(
  REFGUID Name,
  UINT *pDataSize,
  void *pData
);

Parameters

Name
[in] A GUID identifying the data.
pDataSize
[in, out] The size of the data.
pData
[out] Pointer to the data.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

If the data returned is a pointer to an IUnknown, or one of its derivative classes, previously set by IDXGIObject::SetPrivateDataInterface, then ::Release() must be called on the pointer before the pointer is freed to decrement the reference count.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIObject::SetPrivateData

Sets an IUnknown interface as private data; this associates application-defined data with the object.

HRESULT SetPrivateData(
  REFGUID Name,
  UINT DataSize,
  const void *pData
);

Parameters

Name
[in] A GUID identifying the data. This GUID will also be used when getting the data.
DataSize
[in] The size of the object's data.
pData
[in] Pointer to the object's data.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

This API makes a copy of the specified data and stores it with the object.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIObject::SetPrivateDataInterface

Set an interface in the object's private data.

HRESULT SetPrivateDataInterface(
  REFGUID Name,
  const IUnknown *pUnknown
);

Parameters

Name
[in] A GUID identifying the interface.
pUnknown
[in] The interface to set.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

This API associates an interface pointer with the object.

When the interface is set its reference count is incremented. When the data are overwritten (by calling SPD or SPDI with the same GUID) or the object is destroyed, ::Release() is called and the interface's reference count is decremented.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIOutput Interface

An IDXGIOutput interface represents an adapter output (such as a monitor).

IUnknown
IDXGIObject
IDXGIOutput
Method | Description
IDXGIOutput::FindClosestMatchingMode | Finds a display mode that nearest matches (or exceeds the capabilities of) the requested mode.
IDXGIOutput::GetDesc | Gets a description.
IDXGIOutput::GetDisplayModeList | Gets a list of the display modes supported.
IDXGIOutput::GetDisplaySurfaceData | Gets a copy of the currently displayed surface.
IDXGIOutput::GetFrameStatistics | Gets rendered-frame statistics.
IDXGIOutput::GetGammaControlCapabilities | Gets gamma capabilities.
IDXGIOutput::ReleaseOwnership | Release the output.
IDXGIOutput::SetDisplaySurface | Change the display mode on a device.
IDXGIOutput::SetGammaControl | Set the output's gamma control.
IDXGIOutput::TakeOwnership | Take ownership of an output.
IDXGIOutput::WaitForVBlank | Wait for the next vertical blank.

To see the outputs available, use IDXGIAdapter::EnumOutputs. To see the specific output that the swapchain will update, use IDXGISwapChain::GetContainingOutput.

See Also

DXGI Interfaces


IDXGIOutput::FindClosestMatchingMode

Find the display mode that most closely matches the requested display mode.

HRESULT FindClosestMatchingMode(
  const DXGI_MODE_DESC *pModeToMatch,
  DXGI_MODE_DESC *pClosestMatch,
  IUnknown *pConcernedDevice
);

Parameters

pModeToMatch
[in] The desired display mode (see DXGI_MODE_DESC). See remarks.
pClosestMatch
[out] The mode that most closely matches pModeToMatch.
pConcernedDevice
[in] A pointer to the Direct3D device interface. If this parameter is NULL, only modes whose format matches that of pModeToMatch will be returned; otherwise, only those formats that are supported for scan-out by the device are returned.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

The following algorithm is applied when choosing the closest match.

  • If the resolution size cannot be matched, then find the next largest size.
  • If the format cannot be matched, then find a format that supports more bits of precision.

Direct3D devices require UNORM formats.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIOutput Interface


IDXGIOutput::GetDesc

Get a description of the output.

HRESULT GetDesc(
  DXGI_OUTPUT_DESC *pDesc
);

Parameters

pDesc
[out] A pointer to the output description (see DXGI_OUTPUT_DESC).

Return Values

Returns a code that indicates success or failure. S_OK if successful, DXGI_ERR_INVALID_CALL if pDesc is passed in as NULL.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIOutput::GetDisplayModeList

Get a list of the display modes that match the supplied color format, scanline order, and scale.

HRESULT GetDisplayModeList(
  DXGI_FORMAT EnumFormat,
  UINT Flags,
  UINT *pNumModes,
  DXGI_MODE_DESC *pDesc
);

Parameters

EnumFormat
[in] The color format (see DXGI_FORMAT).
Flags
[in] The display mode enumeration options which include DXGI_ENUM_MODES_INTERLACED and or DXGI_ENUM_MODES_SCALING.
pNumModes
[in, out] The number of display modes. Set pDesc to NULL to fill in pNumModes with the number of display modes for the given format, scanline order, and scaling.
pDesc
[out] An array of display modes that match the requested options (see DXGI_MODE_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

A swap chain automatically chooses the display mode when making switching from windowed to fullscreen mode. The display mode chosen will meet or exceed (if it cannot match) the resolution, color depth and refresh rate of the swap chain.

This API returns a set of display modes that are validated against the monitor's capabilities. If the current desktop settings are not validated against the monitor, all modes that match the desktop will be returned.

This API is designed to be called twice, as in the example below:

UINT num = 0;
DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_FLOAT;
UINT flags         = DXGI_ENUM_MODES_INTERLACED;

// Get the number of display modes available
pOutput->GetDisplayModeList( format, flags, &num, 0);

// Get the list of display modes
DXGI_MODE_DESC * pDescs = new DXGI_MODE_DESC[num];
pOutput->GetDisplayModeList( format, flags, &num, pDescs);

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIOutput Interface


IDXGIOutput::GetDisplaySurfaceData

Get a copy of the currently displayed surface.

HRESULT GetDisplaySurfaceData(
  IDXGISurface *pDestination
);

Parameters

pDestination
[in] A pointer to a surface interface (see IDXGISurface Interface) that will be filled by this API.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

A surface created by a graphics component (such as Direct3D 10) must have been created with CPU-write permission (DXGI_CPU_ACCESS_READ_WRITE); otherwise, the surface should be created with CPU read-write permission (DXGI_CPU_ACCESS_READ_WRITE).

This method may only be called between calls to IDXGIOutput::TakeOwnership and IDXGIOutput::ReleaseOwnership.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGIOutput::GetFrameStatistics

Get statistics about recently rendered frames.

HRESULT GetFrameStatistics(
  DXGI_FRAME_STATISTICS *pStats
);

Parameters

pStats
[out] A pointer to a frame statictics (see DXGI_FRAME_STATISTICS).

Return Values

If this function succeeds, it will return S_OK. Otherwise, it may return DXGI_ERR_INVALIDCALL.

Remarks

This API is similar to IDXGISwapChain::GetFrameStatistics.

This method may only be called between calls to IDXGIOutput::TakeOwnership and IDXGIOutput::ReleaseOwnership.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIOutput Interface


IDXGIOutput::GetGammaControl

Get the gamma control settings.

HRESULT GetGammaControl(
  DXGI_GAMMA_CONTROL *pArray
);

Parameters

pArray
[out] An array of gamma control settings (see DXGI_GAMMA_CONTROL).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIOutput Interface


IDXGIOutput::GetGammaControlCapabilities

Get a description of the gamma-control capabilities.

HRESULT GetGammaControlCapabilities(
  DXGI_GAMMA_CONTROL_CAPABILITIES *pGammaCaps
);

Parameters

pGammaCaps
[out] A description of the gamma-control capabilities (see DXGI_GAMMA_CONTROL_CAPABILITIES).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIOutput Interface


IDXGIOutput::ReleaseOwnership

Release ownership of the output.

void ReleaseOwnership();

Parameters

None.

Return Values

Returns nothing.

Remarks

Any application that uses a swap chain will typically not call IDXGIOutput::TakeOwnership or IDXGIOutput::ReleaseOwnership.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIOutput Interface


IDXGIOutput::SetDisplaySurface

Change the display mode.

HRESULT SetDisplaySurface(
  IDXGISurface *pScanoutSurface
);

Parameters

pScanoutSurface
[in] A pointer to a surface (see IDXGISurface Interface) used for rendering an image to the screen. The surface must have been created with as a back buffer (DXGI_USAGE_BACKBUFFER).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

IDXGIOutput::SetDisplaySurface should not be called directly by applications, since results will be unpredictable. It is called implicitly by the DXGI swap chain object during fullscreen transitions, and should not be used as a substitute for swap-chain methods.

This method should only be called between IDXGIOutput::TakeOwnership and IDXGIOutput::ReleaseOwnership calls.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIOutput Interface


IDXGIOutput::SetGammaControl

Set the gamma controls.

HRESULT SetGammaControl(
  const DXGI_GAMMA_CONTROL *pArray
);

Parameters

pArray
[in] A pointer to an array of gamma controls (see DXGI_GAMMA_CONTROL).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

This method may only be called between calls to IDXGIOutput::TakeOwnership and IDXGIOutput::ReleaseOwnership.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIOutput Interface


IDXGIOutput::TakeOwnership

Take ownership of an output.

HRESULT TakeOwnership(
  IUnknown *pDevice,
  BOOL Exclusive
);

Parameters

pDevice
[in] A pointer to the IUnknown interface of a device (such as an ID3D10Device Interface).
Exclusive
[in] A boolean value for enabling other threads or applications to take ownership of the device.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

This method should not be called directly by applications, since results will be unpredictable. It is called implicitly by the DXGI swap chain object during fullscreen transitions, and should not be used as a substitute for swap chain methods.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIOutput Interface


IDXGIOutput::WaitForVBlank

Halt a thread until the next vertical blank occurs.

HRESULT WaitForVBlank();

Parameters

None.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

A vertical blank occurs when the raster moves from the lower right corner to the upper left corner to begin drawing the next frame.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIOutput Interface


IDXGIResource Interface

An IDXGIResource interface allows resource sharing and identifies the memory that a resource resides in.

IUnknown
IDXGIObject
IDXGIDeviceSubObject
IDXGIResource
Method | Description
IDXGIResource::GetEvictionPriority | Gets the eviction priority.
IDXGIResource::GetSharedHandle | Gets a handle to enable sharing.
IDXGIResource::GetUsage | Gets the usage flags.
IDXGIResource::SetEvictionPriority | Sets the eviction priority.

To find out what type of memory a resource is currently located, use IDXGIDevice::QueryResourceResidency. To share resources between processes, use ID3D10Device::OpenSharedResource.

See Also

DXGI Interfaces


IDXGIResource::GetEvictionPriority

Get the eviction priority.

HRESULT GetEvictionPriority(
  UINT *pEvictionPriority
);

Parameters

pEvictionPriority
[out] A pointer to the eviction priority, which determines when a resource can be evicted from memory. Possible values are: DXGI_RESOURCE_PRIORITY_DISCARD, DXGI_RESOURCE_PRIORITY_NORMAL, or DXGI_RESOURCE_PRIORITY_MAXIMUM.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

The eviction priority is a memory-management variable that is used by DXGI to determine how to manage overcommitted memory.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIResource Interface


IDXGIResource::GetSharedHandle

Get the handle to a shared resource. The returned handle can be used to open the resource using different Direct3D devices.

HRESULT GetSharedHandle(
  HANDLE *pSharedHandle
);

Parameters

pSharedHandle
[out] A pointer to a handle.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIResource Interface


IDXGIResource::GetUsage

Get the expected resource usage.

HRESULT GetUsage(
  DXGI_USAGE *pUsage
);

Parameters

pUsage
[out] A pointer to a usage flag (see DXGI_USAGE). For Direct3D 10, a surface can be used as a shader input or a render-target output.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIResource Interface


IDXGIResource::SetEvictionPriority

Set the eviction priority.

HRESULT SetEvictionPriority(
  UINT EvictionPriority
);

Parameters

EvictionPriority
[in] The eviction priority which is one of the following values: DXGI_RESOURCE_PRIORITY_DISCARD, DXGI_RESOURCE_PRIORITY_NORMAL, or DXGI_RESOURCE_PRIORITY_MAXIMUM.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

The eviction priority is a memory management variable that is used by DXGI for determining how to populate overcommitted memory.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGIResource Interface


IDXGISurface Interface

An IDXGISurface interface implements methods for image-data objects.

IUnknown
IDXGIObject
IDXGIDeviceSubObject
IDXGISurface
Method | Description
IDXGISurface::GetDesc | Get a description.
IDXGISurface::Map | Get a pointer to the surface data and deny GPU access.
IDXGISurface::Unmap | Invalidate the pointer to the resource retrieved by IDXGISurface::Map and re-enable GPU access to the resource.

An image-data object is a 2D section of memory, commonly called a surface. To create a surface, call IDXGIDevice::CreateSurface. To get the surface from an output, call IDXGIOutput::GetDisplaySurfaceData.

See Also

DXGI Interfaces


IDXGISurface::GetDesc

Get a description of the surface.

HRESULT GetDesc(
  DXGI_SURFACE_DESC *pDesc
);

Parameters

pDesc
[out] A pointer to the description of the surface (see DXGI_SURFACE_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISurface Interface


IDXGISurface::Map

Get a pointer to the data contained in the surface and deny GPU access to the surface.

HRESULT Map(
  DXGI_MAPPED_RECT *pLockedRect,
  UINT MapFlags
);

Parameters

pLockedRect
[out] A pointer to a rectangle (see DXGI_MAPPED_RECT) that bounds the region of a surface to access.
MapFlags
[in] CPU read-write flags. These flags can be combined with a logical OR.
  • DXGI_MAP_READ - Allow CPU read access.
  • DXGI_MAP_WRITE - Allow CPU write access.
  • DXGI_MAP_DISCARD - Discard the previous contents of a resource when it is mapped.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Use IDXGISurface::Map to access a surface from the CPU. To release a mapped surface (for GPU access) call IDXGISurface::Unmap.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISurface Interface


IDXGISurface::Unmap

Invalidate the pointer to the surface retrieved by IDXGISurface::Map and re-enable GPU access to the resource.

HRESULT Unmap();

Parameters

None.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISurface Interface


IDXGISwapChain Interface

An IDXGISwapChain interface implements one or more surfaces for storing rendered data before presenting it to an output.

IUnknown
IDXGIObject
IDXGIDeviceSubObject
IDXGISwapChain
Method | Description
IDXGISwapChain::GetBuffer | Gets a back buffer.
IDXGISwapChain::GetContainingOutput | Gets the output.
IDXGISwapChain::GetDesc | Get a description.
IDXGISwapChain::GetFrameStatistics | Get rendering statistics.
IDXGISwapChain::GetFullscreenState | Get the swapchain mode.
IDXGISwapChain::GetLastPresentCount | Get the number of times Present was called in the last frame.
IDXGISwapChain::Present | Present the frame buffer to the output.
IDXGISwapChain::ResizeBuffers | Change the size and format of all the back buffers.
IDXGISwapChain::ResizeTarget | Change the output attributes.
IDXGISwapChain::SetFullscreenState | Toggle between fullscreen and windowed mode.

There are two ways to create a swap chain. If your application uses Direct3D, create a swap chain when you create a device by calling D3D10CreateDeviceAndSwapChain. If your application does not need Direct3D, create a swap chain for use directly with DXGI by calling IDXGIFactory::CreateSwapChain

See Also

DXGI Interfaces


IDXGISwapChain::GetBuffer

Access one of the swapchain's back buffers.

HRESULT GetBuffer(
  UINT Buffer,
  REFIID riid,
  void **ppSurface
);

Parameters

Buffer
[in] A zero-based buffer index.
riid
[in] The type of interface used to manipulate the buffer. See remarks.
ppSurface
[in, out] A pointer to a back-buffer interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Here is an example.

ID3D10Texture2D * p_RT;

... // Get the surface from the swap chain

pSwapChain->GetBuffer(0, __uiidof(p_RT), reinterpret_cast<void**>(p_RT));

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISwapChain Interface


IDXGISwapChain::GetContainingOutput

Get the output on which the majority of the target window's client area resides.

HRESULT GetContainingOutput(
  IDXGIOutput **ppOutput
);

Parameters

ppOutput
[out] A pointer to the output interface (see IDXGIOutput Interface).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

If ppOutput is filled, then the IDXGIOutput's reference count is incremented. Therefore, once you are done with the returned ppOutput you must call ::Release on it before the pointer is freed.

The output (i.e. the display monitor) is also owned by the adapter on which the swapchain's device was created.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Interfaces


IDXGISwapChain::GetDesc

Get a description of the swap chain.

HRESULT GetDesc(
  DXGI_SWAP_CHAIN_DESC *pDesc
);

Parameters

pDesc
[out] A pointer to the swap-chain description (see DXGI_SWAP_CHAIN_DESC).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISwapChain Interface


IDXGISwapChain::GetFrameStatistics

Get performance statistics about the last render frame.

HRESULT GetFrameStatistics(
  DXGI_FRAME_STATISTICS *pStats
);

Parameters

pStats
[out] A pointer to the frame statistics (see DXGI_FRAME_STATISTICS).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISwapChain Interface


IDXGISwapChain::GetFullscreenState

Get the swap-chain display mode.

HRESULT GetFullscreenState(
  BOOL *pFullscreen,
  IDXGIOutput **ppTarget
);

Parameters

pFullscreen
[out] A pointer to a boolean that indicates the display mode. This parameter is TRUE if the swap chain is in fullscreen mode; otherwise, it is FALSE because the screen is in windowed mode - which means the DXGI output (ppTarget) will also be NULL.
ppTarget
[out] A pointer to the output interface (see IDXGIOutput Interface).

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

IDXGISwapChain::GetFullscreenState returns the swap-chain mode (fullscreen or windowed) and the output (if the mode is windowed). If ppTarget is filled, IDXGIOutput's reference count will be incremented.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISwapChain Interface


IDXGISwapChain::GetLastPresentCount

Get the number of times IDXGISwapChain::Present has been called.

HRESULT GetLastPresentCount(
  UINT *pLastPresentCount
);

Parameters

pLastPresentCount
[out] A pointer to the number of calls.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISwapChain Interface


IDXGISwapChain::Present

Present a rendered image to the user.

HRESULT Present(
  UINT SyncInterval,
  UINT Flags
);

Parameters

SyncInterval

An integer that specifies the how to synchronize presentation of a frame with the vertical blank. Values are:

  • 0 - The presentation occurs immediately, there is no synchronization.
  • 1,2,3,4 - Synchronize presentation after the n'th vertical blank.
[in] If the update region straddles more than one output (each represented by IDXGIOutput Interface), the synchronization will be performed to the output that contains the largest subrectangle of the target window's client area.

Flags
[in] An integer value that contains swap-chain presentation options (see DXGI_PRESENT).

Return Values

Possible return values include:

  • S_OK - if the presentation succeeded and no other occlusion event happened.
  • DXGI_STATUS_OCCLUDED - if the target window or IDXGIOutput has been occluded by another window based on z-order. The caller is requested to enter an idle state and perform no rendering, in order to free up system resources for the other application. Applications can use DXGI_PRESENT_TEST to determine when to resume rendering.

Remarks

Differences between Direct3D 9 and Direct3D 10:

Specifying DXGI_PRESENT_TEST in the Flags parameter is analogous to IDirect3DDevice9::TestCooperativeLevel in D3D9.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISwapChain Interface


IDXGISwapChain::ResizeBuffers

Change the swap chain's back buffer size, format, and number of buffers. This should be called when the application window is resized.

HRESULT ResizeBuffers(
  UINT BufferCount,
  UINT Width,
  UINT Height,
  DXGI_FORMAT NewFormat,
  UINT SwapChainFlags
);

Parameters

BufferCount
[in] The number of buffers in the swap chain (including all back and front buffers). This can be different from the number of buffers the swap chain was created with.
Width
[in] New width of the back buffer. If 0 is specified the width of the client area of the target window will be used.
Height
[in] New height of the back buffer. If 0 is specified the height of the client area of the target window will be used.
NewFormat
[in] The new format of the back buffer. See DXGI_FORMAT.
SwapChainFlags
[in] Flags that indicate how the swap chain will function. See DXGI_SWAP_CHAIN_FLAG.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

The swapchain will refuse to resize itself if there are any outstanding references to any of its back buffers. The application must call Release on all back buffer pointers before calling Resize, and can then re-query those interfaces via IDXGISwapChain::GetBuffer.

This method should be called whenever a client window is resized. It is recommended to call this API when an application receives a WM_SIZE message.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISwapChain Interface


IDXGISwapChain::ResizeTarget

Resize the output destination of the swapchain.

HRESULT ResizeTarget(
  const DXGI_MODE_DESC *pNewTargetParameters
);

Parameters

pNewTargetParameters
[in] Specifies the new width, height, format and refresh rate of the target. If the format is DXGI_FORMAT_UNKNOWN, the existing mode format will be taken. Note that this is not thread-safe, in that the mode might change during the ResizeTarget call. Thus, passing DXGI_FORMAT_UNKNOWN is not recommended unless the swapchain is fullscreen. See DXGI_MODE_DESC.

Return Values

Returns a code that indicates sucess or failure. See Return Values.

Remarks

This function resizes the target window when the swapchain is in windowed mode, and changes display mode on the target IDXGIOutput when the swapchain is in fullscreen mode. Therefore, applications can call this method to resize the target window (rather than a win32 API such as SetWindowPos) without knowledge of the fullscreen or windowed state of the swap chain.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISwapChain Interface


IDXGISwapChain::SetFullscreenState

Set the display mode to windowed or fullscreen for a given IDXGIOutput.

HRESULT SetFullscreenState(
  BOOL Fullscreen,
  IDXGIOutput *pTarget
);

Parameters

Fullscreen
[in] True for fullscreen, false for windowed.
pTarget
[in] The IDXGIOutput Interface that contains the swapchain, if the display mode is currently fullscreen. If NULL, the system will choose the output based on the swapchain's device and the output window's placement. This parameter is ignored if currently in windowed mode.

Return Values

This API always returns S_OK.

Remarks

An application should call SetFullscreenState to change the fullscreen state of a swap chain. DXGI may change the fullscreen preference of a swapchain is response to user or system requests.

Requirements

Header: Declared in DXGI.h.

See Also

IDXGISwapChain Interface


DXGI Functions

This section contains information about the following functions:

Function | Description
CreateDXGIFactory | Create a DXGI Factory, which can be used to enumerate adapters, create swap chains, and associate a window with the alt+enter key sequence for toggling to and from the fullscreen display mode.

See Also

DXGI Reference


CreateDXGIFactory

Create a DXGI Factory, which can be used to enumerate adapters, create swap chains, and associate a window with the alt+enter key sequence for toggling to and from the fullscreen display mode.

HRESULT CreateDXGIFactory(
  REFIID riid,
  void **ppFactory
);

Parameters

riid
[in] The globally unique identifier (GUID) of ppFactory. See remarks.
ppFactory
[out] Address of a pointer to the factory object. See IDXGIFactory Interface.

Return Values

Returns one of the following Direct3D 10 Return Codes.

Remarks

Here is an example of how to call this API:

IDXGIFactory * pFactory;
HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&pFactory) );

The __uuidof() macro is used to obtain the REFIID, or GUID, of the IDXGIFactory interface.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Functions


DXGI Structures

This section contains information about the following DXGI structures.

Structure | Description
DXGI_ADAPTER_DESC | An adapter (video card) description.
DXGI_FRAME_STATISTICS | Frame performance statistics.
DXGI_GAMMA_CONTROL | Gamma control settings.
DXGI_GAMMA_CONTROL_CAPABILITIES | The properties for controlling gamma correction.
DXGI_MAPPED_RECT | A mapped rectangle, used for accessing a surface.
DXGI_MODE_DESC | A display-mode description.
DXGI_OUTPUT_DESC | An output description.
DXGI_RATIONAL | A rational number.
DXGI_RGB | An RGB color.
DXGI_SAMPLE_DESC | How to sample a surface.
DXGI_SHARED_RESOURCE | A handle to a shared resource.
DXGI_SURFACE_DESC | A surface description.
DXGI_SWAP_CHAIN_DESC | A swap-chain description.

See Also

DXGI Reference


DXGI_ADAPTER_DESC

Description of a video card (or adapter), usually returned by IDXGIAdapter::GetDesc.

typedef struct DXGI_ADAPTER_DESC {
    WCHAR Description[128];
    UINT VendorId;
    UINT DeviceId;
    UINT SubSysId;
    UINT Revision;
    SIZE_T DedicatedVideoMemory;
    SIZE_T DedicatedSystemMemory;
    SIZE_T SharedSystemMemory;
    LUID AdapterLuid;
} DXGI_ADAPTER_DESC, *LPDXGI_ADAPTER_DESC;

Members

Description
Description of the adapter.
VendorId
PCI ID of the hardware vendor.
DeviceId
PCI ID of the hardware device.
SubSysId
PCI ID of the sub system.
Revision
PCI ID of the revision number of the adapter.
DedicatedVideoMemory
The number of bytes of dedicated video memory that are not shared with the CPU.
DedicatedSystemMemory
The number of bytes of dedicated system memory that are not shared with the GPU. This memory is allocated from available system memory at boot time.
SharedSystemMemory
The number of bytes of shared system memory. This is the maximum value of system memory that may be consumed by the adapter during operation. Any incidental memory consumed by the driver as it manages and uses video memory is additional.
AdapterLuid
A unique value that identifies the adapter. See LUID for a definition of the structure. LUID is defined in dxgi.h.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_FRAME_STATISTICS

Frame statistics, usually returned by IDXGIOutput::GetFrameStatistics or IDXGISwapChain::GetFrameStatistics.

typedef struct DXGI_FRAME_STATISTICS {
    UINT PresentCount;
    UINT PresentRefreshCount;
    UINT SyncRefreshCount;
    LARGE_INTEGER SyncQPCTime;
    LARGE_INTEGER SyncGPUTime;
} DXGI_FRAME_STATISTICS, *LPDXGI_FRAME_STATISTICS;

Members

PresentCount
The running total of times an image has been retired to the monitor since the machine booted. Note that the number of time an image has been retired to the monitor is not necessarily the same as the number of times IDXGISwapChain::Present has been called.
PresentRefreshCount
The running total of v-blanks that have happened since the machine booted.
SyncRefreshCount
The running total of v-blanks that have happened since the machine booted.
SyncQPCTime
Same as the value returned by QueryPerformanceCounter.
SyncGPUTime
Reserved. Always returns 0.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_GAMMA_CONTROL

Gamma control settings, usually passed into IDXGIOutput::SetGammaControl.

typedef struct DXGI_GAMMA_CONTROL {
    DXGI_RGB Scale;
    DXGI_RGB Offset;
    DXGI_RGB GammaCurve[1025];
} DXGI_GAMMA_CONTROL, *LPDXGI_GAMMA_CONTROL;

Members

Scale
A scalar value to be applied to the rgb values before being sent to the gamma look up table.
Offset
A offset value to be applied to the rgb values before being sent to the gamma look up table.
GammaCurve
Array of control points that make up the gamma curve.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_GAMMA_CONTROL_CAPABILITIES

A structure that contains gamma controls.

typedef struct DXGI_GAMMA_CONTROL_CAPABILITIES {
    BOOL ScaleAndOffsetSupported;
    float MaxConvertedValue;
    float MinConvertedValue;
    UINT NumGammaControlPoints;
    float ControlPointPositions[1025];
} DXGI_GAMMA_CONTROL_CAPABILITIES, *LPDXGI_GAMMA_CONTROL_CAPABILITIES;

Members

ScaleAndOffsetSupported
True if scaling and offset operations are supported during gamma correction; false otherwise.
MaxConvertedValue
The maximum range of the control-point positions.
MinConvertedValue
The minimum range of the control-point positions.
NumGammaControlPoints
The number of control points in the array.
ControlPointPositions
An array of control points; the maximum number allowed is 1025.

Remarks

To get a list of the capabilities for controlling gamma correction, call IDXGIOutput::GetGammaControlCapabilities.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_MAPPED_RECT

Access surface data, usually returned by IDXGISurface::Map.

typedef struct DXGI_MAPPED_RECT {
    INT Pitch;
    BYTE *pBits;
} DXGI_MAPPED_RECT, *LPDXGI_MAPPED_RECT;

Members

Pitch
The width of the surface.
pBits
Pointer to the surface's image bits.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_MODE_DESC

Description of a display mode.

typedef struct DXGI_MODE_DESC {
    UINT Width;
    UINT Height;
    DXGI_RATIONAL RefreshRate;
    DXGI_FORMAT Format;
    DXGI_MODE_SCANLINE_ORDER ScanlineOrdering;
    DXGI_MODE_SCALING Scaling;
} DXGI_MODE_DESC, *LPDXGI_MODE_DESC;

Members

Width
Resolution width.
Height
Resolution height.
RefreshRate
Refresh rate in Hz. See DXGI_RATIONAL.
Format
Display format. See DXGI_FORMAT.
ScanlineOrdering
The scaline drawing mode. See DXGI_MODE_SCANLINE_ORDER.
Scaling
The scaling mode. See DXGI_MODE_SCALING.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_OUTPUT_DESC

Description of an output, returned by IDXGIOutput::GetDesc. An output is a physical connection between the graphics card and a display device.

typedef struct DXGI_OUTPUT_DESC {
    WCHAR DeviceName[32];
    RECT DesktopCoordinates;
    BOOL AttachedToDesktop;
    DXGI_MODE_ROTATION Rotation;
    HMONITOR Monitor;
} DXGI_OUTPUT_DESC, *LPDXGI_OUTPUT_DESC;

Members

DeviceName
Name of the output device.
DesktopCoordinates
The bounds of the output in desktop coordinates.
AttachedToDesktop
Whether or not the output is attached to the desktop.
Rotation
A rotation on an image that is performed by the Output. See DXGI_MODE_ROTATION.
Monitor
Handle to the display monitor. See HMONITOR and the Device Context.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_RATIONAL

A rational number.

typedef struct DXGI_RATIONAL {
    UINT Numerator;
    UINT Denominator;
} DXGI_RATIONAL, *LPDXGI_RATIONAL;

Members

Numerator
Unsigned integer value on the top.
Denominator
Unsigned integer value on the bottom.

Remarks

0/0 is legal and will be interpreted as 0/1.

0/anything is interpreted as zero.

One implication of the above is that if you are representing a whole number, the denominator should be 1.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_RGB

A Red, Green, and Blue color.

typedef struct DXGI_RGB {
    float Red;
    float Green;
    float Blue;
} DXGI_RGB, *LPDXGI_RGB;

Members

Red
Color of the red component. Ranges from 0 to 1.
Green
Color of the green component. Ranges from 0 to 1.
Blue
Color of the blue component. Ranges from 0 to 1.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_SAMPLE_DESC

Describes multi-sampling parameters for a resource.

typedef struct DXGI_SAMPLE_DESC {
    UINT Count;
    UINT Quality;
} DXGI_SAMPLE_DESC, *LPDXGI_SAMPLE_DESC;

Members

Count
The number of multisamples per pixel.
Quality
The image quality level. The higher the quality, the lower the performance. The valid range is between zero and one less than the level returned by ID3D10Device::CheckMultisampleQualityLevels.

Remarks

The default sampler mode, with no anti-aliasing, has a count of 1 and a quality level of 0.

If multi-sample antialiasing is being used, all bound render targets and depth buffers must have the same sample counts and quality levels.

For an explanation of multisampling, see Instancing10 Sample.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_SHARED_RESOURCE

A pointer to a shared resource.

typedef struct DXGI_SHARED_RESOURCE {
    HANDLE Handle;
} DXGI_SHARED_RESOURCE, *LPDXGI_ADAPTER_DESC;

Members

Handle
A handle.

Remarks

To create a shared surface, pass a shared-resource handle into IDXGIDevice::CreateSurface.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_SURFACE_DESC

Description of a surface.

typedef struct DXGI_SURFACE_DESC {
    UINT Width;
    UINT Height;
    DXGI_FORMAT Format;
    DXGI_SAMPLE_DESC SampleDesc;
} DXGI_SURFACE_DESC, *LPDXGI_SURFACE_DESC;

Members

Width
Surface width.
Height
Surface height.
Format
Surface format. See DXGI_FORMAT.
SampleDesc
See DXGI_SAMPLE_DESC.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI_SWAP_CHAIN_DESC

Description of a swap chain.

typedef struct DXGI_SWAP_CHAIN_DESC {
    DXGI_MODE_DESC BufferDesc;
    DXGI_SAMPLE_DESC SampleDesc;
    DXGI_USAGE BufferUsage;
    UINT BufferCount;
    HWND OutputWindow;
    BOOL Windowed;
    DXGI_SWAP_EFFECT SwapEffect;
    UINT Flags;
} DXGI_SWAP_CHAIN_DESC;

Members

BufferDesc
The backbuffer's display mode. See DXGI_MODE_DESC.
SampleDesc
See DXGI_SAMPLE_DESC.
BufferUsage
Back-buffer usage flag identifying expected surface usage and CPU access options. For Direct3D 10, the back-buffer can be used as a shader input or a render-target output; these usages can be combined with any CPU access flags. See DXGI_USAGE for the specific flags.
BufferCount
The number of buffers in the swapchain (including the front buffer).
OutputWindow
Handle to the output window. If the parent IDXGIFactory Interface already exists and has an associated window, this parameter can be NULL and the associated window will be used. See IDXGIFactory::MakeWindowAssociation.
Windowed
TRUE for a windowed output, FALSE is the output is full screen. See IDXGIFactory::CreateSwapChain for more information.
SwapEffect
Specifies the effect of IDXGISwapChain::Present on the buffer contents. See DXGI_SWAP_EFFECT.
Flags
Flags that indicate how the swap chain will function. See DXGI_SWAP_CHAIN_FLAG.

Remarks

In fullscreen mode, there is a dedicated front buffer; in windowed mode, the desktop will be the front buffer.

If you create a swap chain with one buffer, specifying DXGI_SWAP_EFFECT_SEQUENTIAL does NOT cause the contents of the single buffer to be swapped with the front buffer.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Structures


DXGI Enumerations

This section contains information about the following enumerations:

Enumeration | Description
DXGI_FORMAT | The memory layouts for each pixel in an image.
DXGI_RESIDENCY | Memory location options.
DXGI_MODE_ROTATION | Rotation options.
DXGI_MODE_SCALING | Scaling options.
DXGI_MODE_SCANLINE_ORDER |
DXGI_SWAP_CHAIN_FLAG |
DXGI_SWAP_EFFECT | Flags indicating how a swap is performed.
DXGI_USAGE | Resource creation options.

See Also

DXGI Reference


DXGI_FORMAT

Resource data formats; includes fully-typed and typeless formats.

typedef enum DXGI_FORMAT
{
    DXGI_FORMAT_UNKNOWN = 0,
    DXGI_FORMAT_R32G32B32A32_TYPELESS = 1,
    DXGI_FORMAT_R32G32B32A32_FLOAT = 2,
    DXGI_FORMAT_R32G32B32A32_UINT = 3,
    DXGI_FORMAT_R32G32B32A32_SINT = 4,
    DXGI_FORMAT_R32G32B32_TYPELESS = 5,
    DXGI_FORMAT_R32G32B32_FLOAT = 6,
    DXGI_FORMAT_R32G32B32_UINT = 7,
    DXGI_FORMAT_R32G32B32_SINT = 8,
    DXGI_FORMAT_R16G16B16A16_TYPELESS = 9,
    DXGI_FORMAT_R16G16B16A16_FLOAT = 10,
    DXGI_FORMAT_R16G16B16A16_UNORM = 11,
    DXGI_FORMAT_R16G16B16A16_UINT = 12,
    DXGI_FORMAT_R16G16B16A16_SNORM = 13,
    DXGI_FORMAT_R16G16B16A16_SINT = 14,
    DXGI_FORMAT_R32G32_TYPELESS = 15,
    DXGI_FORMAT_R32G32_FLOAT = 16,
    DXGI_FORMAT_R32G32_UINT = 17,
    DXGI_FORMAT_R32G32_SINT = 18,
    DXGI_FORMAT_R32G8X24_TYPELESS = 19,
    DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20,
    DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21,
    DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22,
    DXGI_FORMAT_R10G10B10A2_TYPELESS = 23,
    DXGI_FORMAT_R10G10B10A2_UNORM = 24,
    DXGI_FORMAT_R10G10B10A2_UINT = 25,
    DXGI_FORMAT_R11G11B10_FLOAT = 26,
    DXGI_FORMAT_R8G8B8A8_TYPELESS = 27,
    DXGI_FORMAT_R8G8B8A8_UNORM = 28,
    DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29,
    DXGI_FORMAT_R8G8B8A8_UINT = 30,
    DXGI_FORMAT_R8G8B8A8_SNORM = 31,
    DXGI_FORMAT_R8G8B8A8_SINT = 32,
    DXGI_FORMAT_R16G16_TYPELESS = 33,
    DXGI_FORMAT_R16G16_FLOAT = 34,
    DXGI_FORMAT_R16G16_UNORM = 35,
    DXGI_FORMAT_R16G16_UINT = 36,
    DXGI_FORMAT_R16G16_SNORM = 37,
    DXGI_FORMAT_R16G16_SINT = 38,
    DXGI_FORMAT_R32_TYPELESS = 39,
    DXGI_FORMAT_D32_FLOAT = 40,
    DXGI_FORMAT_R32_FLOAT = 41,
    DXGI_FORMAT_R32_UINT = 42,
    DXGI_FORMAT_R32_SINT = 43,
    DXGI_FORMAT_R24G8_TYPELESS = 44,
    DXGI_FORMAT_D24_UNORM_S8_UINT = 45,
    DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46,
    DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47,
    DXGI_FORMAT_R8G8_TYPELESS = 48,
    DXGI_FORMAT_R8G8_UNORM = 49,
    DXGI_FORMAT_R8G8_UINT = 50,
    DXGI_FORMAT_R8G8_SNORM = 51,
    DXGI_FORMAT_R8G8_SINT = 52,
    DXGI_FORMAT_R16_TYPELESS = 53,
    DXGI_FORMAT_R16_FLOAT = 54,
    DXGI_FORMAT_D16_UNORM = 55,
    DXGI_FORMAT_R16_UNORM = 56,
    DXGI_FORMAT_R16_UINT = 57,
    DXGI_FORMAT_R16_SNORM = 58,
    DXGI_FORMAT_R16_SINT = 59,
    DXGI_FORMAT_R8_TYPELESS = 60,
    DXGI_FORMAT_R8_UNORM = 61,
    DXGI_FORMAT_R8_UINT = 62,
    DXGI_FORMAT_R8_SNORM = 63,
    DXGI_FORMAT_R8_SINT = 64,
    DXGI_FORMAT_A8_UNORM = 65,
    DXGI_FORMAT_R1_UNORM = 66,
    DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67,
    DXGI_FORMAT_R8G8_B8G8_UNORM = 68,
    DXGI_FORMAT_G8R8_G8B8_UNORM = 69,
    DXGI_FORMAT_BC1_TYPELESS = 70,
    DXGI_FORMAT_BC1_UNORM = 71,
    DXGI_FORMAT_BC1_UNORM_SRGB = 72,
    DXGI_FORMAT_BC2_TYPELESS = 73,
    DXGI_FORMAT_BC2_UNORM = 74,
    DXGI_FORMAT_BC2_UNORM_SRGB = 75,
    DXGI_FORMAT_BC3_TYPELESS = 76,
    DXGI_FORMAT_BC3_UNORM = 77,
    DXGI_FORMAT_BC3_UNORM_SRGB = 78,
    DXGI_FORMAT_BC4_TYPELESS = 79,
    DXGI_FORMAT_BC4_UNORM = 80,
    DXGI_FORMAT_BC4_SNORM = 81,
    DXGI_FORMAT_BC5_TYPELESS = 82,
    DXGI_FORMAT_BC5_UNORM = 83,
    DXGI_FORMAT_BC5_SNORM = 84,
    DXGI_FORMAT_B5G6R5_UNORM = 85,
    DXGI_FORMAT_B5G5R5A1_UNORM = 86,
    DXGI_FORMAT_B8G8R8A8_UNORM = 87,
    DXGI_FORMAT_B8G8R8X8_UNORM = 88,
    DXGI_FORMAT_FORCE_UINT = 0xffffffffUL,
} DXGI_FORMAT, *LPDXGI_FORMAT;

Constants

DXGI_FORMAT_UNKNOWN
The format is not known.
DXGI_FORMAT_R32G32B32A32_TYPELESS
A four-component, 128-bit typeless format.
DXGI_FORMAT_R32G32B32A32_FLOAT
A four-component, 128-bit floating-point format.
DXGI_FORMAT_R32G32B32A32_UINT
A four-component, 128-bit unsigned-integer format.
DXGI_FORMAT_R32G32B32A32_SINT
A four-component, 128-bit signed-integer format.
DXGI_FORMAT_R32G32B32_TYPELESS
A three-component, 96-bit typeless format.
DXGI_FORMAT_R32G32B32_FLOAT
A three-component, 96-bit floating-point format.
DXGI_FORMAT_R32G32B32_UINT
A three-component, 96-bit unsigned-integer format.
DXGI_FORMAT_R32G32B32_SINT
A three-component, 96-bit signed-integer format.
DXGI_FORMAT_R16G16B16A16_TYPELESS
A four-component, 64-bit typeless format.
DXGI_FORMAT_R16G16B16A16_FLOAT
A four-component, 64-bit floating-point format.
DXGI_FORMAT_R16G16B16A16_UNORM
A four-component, 64-bit unsigned-integer format with values normalized to be between 0 and 1.
DXGI_FORMAT_R16G16B16A16_UINT
A four-component, 64-bit unsigned-integer format.
DXGI_FORMAT_R16G16B16A16_SNORM
A four-component, 64-bit signed-integer format with values normalized to be between -1 and 1.
DXGI_FORMAT_R16G16B16A16_SINT
A four-component, 64-bit signed-integer format.
DXGI_FORMAT_R32G32_TYPELESS
A two-component, 64-bit typeless format.
DXGI_FORMAT_R32G32_FLOAT
A two-component, 64-bit floating-point format.
DXGI_FORMAT_R32G32_UINT
A two-component, 64-bit unsigned-integer format.
DXGI_FORMAT_R32G32_SINT
A two-component, 64-bit signed-integer format.
DXGI_FORMAT_R32G8X24_TYPELESS
A two-component, 64-bit typeless format.
DXGI_FORMAT_D32_FLOAT_S8X24_UINT
DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS
DXGI_FORMAT_X32_TYPELESS_G8X24_UINT
DXGI_FORMAT_R10G10B10A2_TYPELESS
A four-component, 32-bit typeless format.
DXGI_FORMAT_R10G10B10A2_UNORM
A four-component, 32-bit unsigned-integer format with values normalized to be between 0 and 1.
DXGI_FORMAT_R10G10B10A2_UINT
A four-component, 32-bit unsigned-integer format.
DXGI_FORMAT_R11G11B10_FLOAT
A three-component, 32-bit floating-point format.
DXGI_FORMAT_R8G8B8A8_TYPELESS
A three-component, 32-bit typeless format.
DXGI_FORMAT_R8G8B8A8_UNORM
A four-component, 32-bit unsigned-integer format with values normalized to be between 0 and 1.
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB
DXGI_FORMAT_R8G8B8A8_UINT
A four-component, 32-bit unsigned-integer format.
DXGI_FORMAT_R8G8B8A8_SNORM
A three-component, 32-bit signed-integer format with values normalized to be between -1 and 1.
DXGI_FORMAT_R8G8B8A8_SINT
A three-component, 32-bit signed-integer format.
DXGI_FORMAT_R16G16_TYPELESS
A two-component, 32-bit typeless format.
DXGI_FORMAT_R16G16_FLOAT
A two-component, 32-bit floating-point format.
DXGI_FORMAT_R16G16_UNORM
A two-component, 32-bit unsigned-integer format.
DXGI_FORMAT_R16G16_UINT
A two-component, 32-bit unsigned-integer format.
DXGI_FORMAT_R16G16_SNORM
A two-component, 32-bit signed-integer format with values normalized to be between -1 and 1.
DXGI_FORMAT_R16G16_SINT
A two-component, 32-bit signed-integer format.
DXGI_FORMAT_R32_TYPELESS
A single-component, 32-bit typeless format.
DXGI_FORMAT_D32_FLOAT
DXGI_FORMAT_R32_FLOAT
A single-component, 32-bit floating-point format.
DXGI_FORMAT_R32_UINT
A single-component, 32-bit unsigned-integer format.
DXGI_FORMAT_R32_SINT
A single-component, 32-bit signed-integer format.
DXGI_FORMAT_R24G8_TYPELESS
A two-component, 32-bit typeless format.
DXGI_FORMAT_D24_UNORM_S8_UINT
DXGI_FORMAT_R24_UNORM_X8_TYPELESS
DXGI_FORMAT_X24_TYPELESS_G8_UINT
DXGI_FORMAT_R8G8_TYPELESS
A two-component, 16-bit typeless format.
DXGI_FORMAT_R8G8_UNORM
A two-component, 16-bit unsigned-integer format with values normalized to be between 0 and 1.
DXGI_FORMAT_R8G8_UINT
A two-component, 16-bit unsigned-integer format.
DXGI_FORMAT_R8G8_SNORM
A two-component, 16-bit signed-integer format with values normalized to be between -1 and 1.
DXGI_FORMAT_R8G8_SINT
A two-component, 16-bit signed-integer format.
DXGI_FORMAT_R16_TYPELESS
A single-component, 16-bit typeless format.
DXGI_FORMAT_R16_FLOAT
A single-component, 16-bit floating-point format.
DXGI_FORMAT_D16_UNORM
DXGI_FORMAT_R16_UNORM
A single-component, 16-bit unsigned-integer format with values normalized to be between 0 and 1.
DXGI_FORMAT_R16_UINT
A single-component, 16-bit unsigned-integer format.
DXGI_FORMAT_R16_SNORM
A single-component, 16-bit signed-integer format with values normalized to be between -1 and 1.
DXGI_FORMAT_R16_SINT
A single-component, 16-bit signed-integer format.
DXGI_FORMAT_R8_TYPELESS
A single-component, 8-bit typeless format.
DXGI_FORMAT_R8_UNORM
A single-component, 8-bit unsigned-integer format with values normalized to be between 0 and 1.
DXGI_FORMAT_R8_UINT
A single-component, 8-bit unsigned-integer format.
DXGI_FORMAT_R8_SNORM
A single-component, 8-bit signed-integer format with values normalized to be between -1 and 1.
DXGI_FORMAT_R8_SINT
A single-component, 8-bit signed-integer format.
DXGI_FORMAT_A8_UNORM
A single-component, 8-bit unsigned-integer format with values normalized to be between 0 and 1.
DXGI_FORMAT_R1_UNORM
DXGI_FORMAT_R9G9B9E5_SHAREDEXP
DXGI_FORMAT_R8G8_B8G8_UNORM
DXGI_FORMAT_G8R8_G8B8_UNORM
DXGI_FORMAT_BC1_TYPELESS
Typeless block-compression format. See remarks.
DXGI_FORMAT_BC1_UNORM
Block-compression format with values normalized to be between 0 and 1. See remarks.
DXGI_FORMAT_BC1_UNORM_SRGB
Block-compression format with values normalized to be between 0 and 1 in sRGB space. See remarks.
DXGI_FORMAT_BC2_TYPELESS
Typeless block-compression format. See remarks.
DXGI_FORMAT_BC2_UNORM
Block-compression format with values normalized to be between 0 and 1. See remarks.
DXGI_FORMAT_BC2_UNORM_SRGB
Block-compression format with values normalized to be between 0 and 1 in sRGB space. See remarks.
DXGI_FORMAT_BC3_TYPELESS
Typeless block-compression format. See remarks.
DXGI_FORMAT_BC3_UNORM
Block-compression format with values normalized to be between 0 and 1. See remarks.
DXGI_FORMAT_BC3_UNORM_SRGB
Block-compression format with values normalized to be between 0 and 1 in sRGB space. See remarks.
DXGI_FORMAT_BC4_TYPELESS
Typeless block-compression format. See remarks.
DXGI_FORMAT_BC4_UNORM
Block-compression format with values normalized to be between 0 and 1. See remarks.
DXGI_FORMAT_BC4_SNORM
Block-compression format with values normalized to be between -1 and 1. See remarks.
DXGI_FORMAT_BC5_TYPELESS
Typeless block-compression format. See remarks.
DXGI_FORMAT_BC5_UNORM
Block-compression format with values normalized to be between 0 and 1. See remarks.
DXGI_FORMAT_BC5_SNORM
Block-compression format with values normalized to be between -1 and 1. See remarks.
DXGI_FORMAT_B5G6R5_UNORM
DXGI_FORMAT_B5G5R5A1_UNORM
DXGI_FORMAT_B8G8R8A8_UNORM
DXGI_FORMAT_B8G8R8X8_UNORM
DXGI_FORMAT_FORCE_UINT
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Typeless Formats and Subformats

A typeless format identifies the number of components and the size of the format for an element, but leaves the data type unresolved. A typeless format is a group of subformats; each subformat fully resolves the data type. For example, this is the R32G32B32 group of formats:

    DXGI_FORMAT_R32G32B32_TYPELESS = 5,
    DXGI_FORMAT_R32G32B32_FLOAT = 6,
    DXGI_FORMAT_R32G32B32_UINT = 7,
    DXGI_FORMAT_R32G32B32_SINT = 8,

This group contains the typeless format, and three fully-typed subformats. This format group defines a data type for three-component 96-bit data. The three subformats support floating point, unsigned integer, or signed integer data.

Typeless formats are designed for creating typeless resources; that is, a resource whose size is known, but whose data type is not yet fully defined. Typeless resources must be fully typed when they are bound to the pipeline.

New Resource Formats

Direct3D 10 offers new data compression formats for compressing high-dynamic range (HDR) lighting data, normal maps and heightfields to a fraction of their original size. These compression types include:

  • Shared-Exponent high-dynamic range (HDR) format (RGBE)
  • New Block-Compressed 1-2 channel UNORM/SNORM formats

The block compression formats can be used for any of the 2D or 3D texture types ( Texture2D, Texture2DArray, Texture3D, or TextureCube) including mipmap surfaces. The block compression techniques require texture dimensions to be a multiple of 4 (since the implementation compresses on blocks of 4x4 texels). In the texture sampler, compressed formats are always decompressed before texture filtering.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Enumerations


DXGI_RESIDENCY

Flags indicating the memory location of a resource.

typedef enum DXGI_RESIDENCY
{
    DXGI_RESIDENCY_FULLY_RESIDENT = 1,
    DXGI_RESIDENCY_RESIDENT_IN_SHARED_MEMORY = 2,
    DXGI_RESIDENCY_EVICTED_TO_DISK = 3,
} DXGI_RESIDENCY, *LPDXGI_RESIDENCY;

Constants

DXGI_RESIDENCY_FULLY_RESIDENT
The resource is located in video memory.
DXGI_RESIDENCY_RESIDENT_IN_SHARED_MEMORY
At least some of the resource is located in CPU memory.
DXGI_RESIDENCY_EVICTED_TO_DISK
At least some of the resource has been paged out to the hard drive.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Enumerations


DXGI_MODE_ROTATION

Flags that indicate how the back buffers should be rotate to fit the physical rotation of a monitor.

typedef enum DXGI_MODE_ROTATION
{
    DXGI_MODE_ROTATION_UNSPECIFIED = 0,
    DXGI_MODE_ROTATION_IDENTITY = 1,
    DXGI_MODE_ROTATION_ROTATE90 = 2,
    DXGI_MODE_ROTATION_ROTATE180 = 3,
    DXGI_MODE_ROTATION_ROTATE270 = 4,
} DXGI_MODE_ROTATION, *LPDXGI_MODE_ROTATION;

Constants

DXGI_MODE_ROTATION_UNSPECIFIED
Unspecified rotation.
DXGI_MODE_ROTATION_IDENTITY
No rotation.
DXGI_MODE_ROTATION_ROTATE90
90 degrees of rotation.
DXGI_MODE_ROTATION_ROTATE180
180 degrees of rotation.
DXGI_MODE_ROTATION_ROTATE270
270 degrees of rotation.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Enumerations


DXGI_MODE_SCALING

Flags indicating how an image is stretched to fit a given monitor's resolution.

typedef enum DXGI_MODE_SCALING
{
    DXGI_MODE_SCALING_UNSPECIFIED = 0,
    DXGI_MODE_SCALING_CENTERED = 1,
    DXGI_MODE_SCALING_STRETCHED = 2,
} DXGI_MODE_SCALING, *LPDXGI_MODE_SCALING;

Constants

DXGI_MODE_SCALING_UNSPECIFIED
Unspecified scaling.
DXGI_MODE_SCALING_CENTERED
No scaling. The image is centered on the display. Typically used for a fixed-dot-pitch display (such as an LED display).
DXGI_MODE_SCALING_STRETCHED
Stretched scaling.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Enumerations


DXGI_MODE_SCANLINE_ORDER

Flags indicating the method the raster uses to create an image on a surface.

typedef enum DXGI_MODE_SCANLINE_ORDER
{
    DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED = 0,
    DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE = 1,
    DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST = 2,
    DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST = 3,
} DXGI_MODE_SCANLINE_ORDER, *LPDXGI_MODE_SCANLINE_ORDER;

Constants

DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED
Scanline order is unspecified.
DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE
The image is created from the first scanline to the last without skipping any.
DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST
The image is created beginning with the upper field.
DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST
The image is created beginning with the lower field.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Enumerations


DXGI_SWAP_CHAIN_FLAG

Swap chain creation flags that define how a swap chain will behave.

typedef enum DXGI_SWAP_CHAIN_FLAG
{
    DXGI_SWAP_CHAIN_FLAG_NONPREROTATED = 1,
    DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH = 2,
} DXGI_SWAP_CHAIN_FLAG, *LPDXGI_SWAP_CHAIN_FLAG;

Constants

DXGI_SWAP_CHAIN_FLAG_NONPREROTATED
Turns off automatic image rotation, such that when the front buffer is sent to the monitor, the image will not be automatically rotated to match the orientation of the monitor. This only applies to applications that are running in fullscreen mode. If this flag is specified, the application will need to handle image rotation on its own.
DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH
When switching to fullscreen mode, make the application automatically change the display mode (or monitor resolution) to be close to matching the dimensions of the application window. Without this flag fullscreen will use the desktop display mode.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Enumerations


DXGI_SWAP_EFFECT

Flags indicating how a swap chain's buffers behave after a call to IDXGISwapChain::Present.

typedef enum DXGI_SWAP_EFFECT
{
    DXGI_SWAP_EFFECT_DISCARD = 0,
    DXGI_SWAP_EFFECT_SEQUENTIAL = 1,
} DXGI_SWAP_EFFECT, *LPDXGI_SWAP_EFFECT;

Constants

DXGI_SWAP_EFFECT_DISCARD
Do not make any assumptions about the contents of a discarded back buffer; update the entire back buffer before calling IDXGISwapChain::Present. Use this flag to enable the display driver to select the most efficient presentation for the swap chain. This flag may be used on a swap chain with a single back buffer.
DXGI_SWAP_EFFECT_SEQUENTIAL
Do not change the content in any of the back buffers when calling IDXGISwapChain::Present. Sequential swap chains do not allow for multisampled anti-aliasing.

Requirements

Header: Declared in DXGI.h.

See Also

DXGI Enumerations


DXGI_USAGE

DXGI surface and resource creation options; these are #defines in the header.

Flag | Description
DXGI_USAGE_SHADER_INPUT | Use the surface or resource as an input to a shader.
DXGI_USAGE_RENDER_TARGET_OUTPUT | Use the surface or resource as an output render target.
DXGI_USAGE_BACK_BUFFER | Use the surface or resource as a back buffer.
DXGI_USAGE_SHARED | Share the surface or resource.
DXGI_USAGE_READ_ONLY | Use the surface or resource for reading only.

Each flag is defined as an unsigned integer in dxgi.h.

typedef UINT DXGI_USAGE;

Remarks

Specify how a surface is expected to be used with DXGI_USAGE when calling IDXGIDevice::CreateSurface.

See Also

DXGI Reference


DXGI Constants

This section contains information about the following constants:

Enumeration | Description
DXGI_ERROR | Error codes returned by DXGI functions.
DXGI_PRESENT | Options for presenting swap-chain buffers.

See Also

DXGI Reference


DXGI_ERROR

This page list the errors codes that can be returned in an HRESULT when calling a DXGI function.

HRESULT | Description
DXGI_ERROR_INVALID_CALL | Means the application provided invalid parameter data to a method call. This indicates an issue must be debugged and fixed before the application is released.
DXGI_ERROR_NOT_FOUND | Could not find the item in question. In IDXGIObject::GetPrivateData, this is returned if the GUID is not recognized as one previously passed to IDXGIObject::SetPrivateData or IDXGIObject::SetPrivateDataInterface. This is also returned from IDXGIFactory::EnumAdapters, and IDXGIAdapter::EnumOutputs if the enum ordinal is out of range.
DXGI_ERROR_MORE_DATA | The buffer supplied by the application is not big enough to hold the requested data.
DXGI_ERROR_UNSUPPORTED | The requested functionality is not supported by the device or driver.
DXGI_ERROR_DEVICE_REMOVED | The video card has been physically removed from the system, or a driver upgrade for the video card has occurred. The application should destroy and recreate the device in question.
DXGI_ERROR_DEVICE_HUNG | The application's device failed due to badly formed commands sent by the application itself. This is an author-time issue that should be investigated and fixed.
DXGI_ERROR_DEVICE_RESET | The application's device failed due to badly formed commands sent by some other application. This is a run-time issue for which the response should be to destroy and recreate the device.
DXGI_ERROR_WAS_STILL_DRAWING | The device was busy, and did not schedule the requested task. Relevant to asynchronous queries in D3D10. See ID3D10Asynchronous Interface.
DXGI_ERROR_DRIVER_INTERNAL_ERROR | The driver encountered an unspecified and unforeseen problem and was the device was put into the device removed state.
DXGI_ERROR_NONEXCLUSIVE | The application attempted to acquire exclusive ownership of an output, but failed because some other application (or device within the application) has already acquired ownership.

You may be interested only in whether the method succeeded or failed. The best way to test whether an HRESULT value indicates success or failure is to pass the value to the one of the following macros, defined in Winerror.h:

  • The SUCCEEDED macro returns TRUE for a success code and FALSE for a failure code.
  • The FAILED macro returns TRUE for a failure code and FALSE for a success code.

See Also

Direct3D 10 Reference


DXGI_PRESENT

Options for presenting frames to the output.

#define | Description
0 | Present a frame from each buffer (starting with the current buffer) to the output.
DXGI_PRESENT_DO_NOT_SEQUENCE | Present a frame from the current buffer to the output.
DXGI_PRESENT_RESTART | Present a frame from each buffer (starting with the first buffer) to the output.
DXGI_PRESENT_TEST | Do not present the frame to the output. The status of the swapchain will be tested and appropriate errors returned. DXGI_PRESENT_TEST is only intended for use when switching from the idle state; do not use it to determine when to switch to the idle state as doing so can leave the swapchain unable to exit fullscreen mode.

Remarks

Presentation options are supplied during the IDXGISwapChain::Present call. The buffers are specified in the swap chain description (see DXGI_SWAP_CHAIN_DESC).

See Also

DXGI Constants


DXGI Return Values

This page has been deprecated. See DXGI_ERROR.


DXUT Reference

This section contains reference information for the elements provided by DXUT in the DXUT.h header file. DXUT makes Direct3D samples, prototypes, and tools as well as professional games more robust and easier to build. It simplifies the Windows and Direct3D APIs for typical usage.

DXUT supports applications that render using either Direct3D 9 or Direct3D 10. DXUT will only use one Direct3D device at a time so if Direct3D 9 and Direct3D 10 devices are both available and supported by application then only one will be chosen and used.

Reference material is divided into the following sections:

  • DXUT Functions
  • Callback Functions
  • DXUT Structures
  • DXUT Enumerations
  • DXUT Constants
  • Overview of the SDK Mesh File Format


DXUT Functions

This section contains reference information for the functions that you need to implement when you work with DXUT. The following categories of functions are implemented:

  • Initialization Functions
  • Common Task Functions
  • State Retrieval Functions


Initialization Functions

DXUT supplies the following initialization functions that can be used by an application:

  • DXUTCreateDevice
  • DXUTCreateDeviceFromSettings
  • DXUTCreateWindow
  • DXUTInit
  • DXUTMainLoop
  • DXUTRender3DEnvironment
  • DXUTSetCallbackD3D9DeviceAcceptable
  • DXUTSetCallbackD3D9DeviceCreated
  • DXUTSetCallbackD3D9DeviceDestroyed
  • DXUTSetCallbackD3D9DeviceLost
  • DXUTSetCallbackD3D9DeviceReset
  • DXUTSetCallbackD3D9FrameRender
  • DXUTSetCallbackD3D10DeviceAcceptable
  • DXUTSetCallbackD3D10DeviceCreated
  • DXUTSetCallbackD3D10DeviceDestroyed
  • DXUTSetCallbackD3D10FrameRender
  • DXUTSetCallbackD3D10SwapChainReleasing
  • DXUTSetCallbackD3D10SwapChainResized
  • DXUTSetCallbackDeviceChanging
  • DXUTSetCallbackFrameMove
  • DXUTSetCallbackKeyboard
  • DXUTSetCallbackMouse
  • DXUTSetCallbackMsgProc
  • DXUTSetD3D9Device
  • DXUTSetD3D10Device
  • DXUTSetWindow
  • DXUTStaticWndProc


DXUTCreateDevice

Creates a Direct3D 9 or Direct3D 10 device.

HRESULT DXUTCreateDevice(
  bool bWindowed,
  INT nSuggestedWidth,
  INT nSuggestedHeight
);

Parameters

bWindowed
[in] If TRUE, the application will start in windowed mode; if FALSE, the application will start in full-screen mode. The default value is TRUE.
nSuggestedWidth
[in] The requested initial width of the application's back buffer. The actual width may be adjusted to fit device and operating system constraints. The default value is 0.
nSuggestedHeight
[in] The requested initial height of the application's back buffer. The actual height may be adjusted to fit device and operating system constraints. The default value is 0. If both nSuggestedWidth and nSuggestedHeight are zero, the dimension of the client area of the window is used.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function creates a new Direct3D 9 or Direct3D 10 device for the application. DXUT will pick the best device for the application based upon what is availble on the system and which Direct3D API version(s) the application supports. The API version(s) that the application supports is detrimined by which device callbacks are set. This logic can be overridden by calling DXUTSetD3DVersionSupport. If both Direct3D 9 and Direct3D 10 are availble on the system and both are supported by the application, then DXUT will favor Direct3D 10.

Alternately, the application can use the DXUTCreateDeviceFromSettings or handle device creation and pass the desired device to DXUT by using the DXUTSetD3D9Device or DXUTSetD3D10Device function. If neither DXUTCreateDevice, DXUTCreateDeviceFromSettings, nor DXUTSetD3D9Device or DXUTSetD3D10Device have been called before calling DXUTMainLoop, DXUT will automatically call DXUTCreateDevice using the default parameter values.

The application can call this method after a device has already been created to change the current device.

If a device is successfully found, the LPDXUTCALLBACKMODIFYDEVICESETTINGS callback will be called to allow the application to examine or change the device settings before the device is created. This allows an application to modify the device creation settings as it sees fit.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTCreateDeviceFromSettings, DXUTSetD3D10Device, DXUTSetD3D9Device


DXUTCreateDeviceFromSettings

Creates a Direct3D 9 or Direct3D 10 device based on a device described by a DXUTDeviceSettings structure.

HRESULT DXUTCreateDeviceFromSettings(
  DXUTDeviceSettings * pDeviceSettings,
  BOOL bPreserveInput,
  BOOL bClipWindowToSingleAdapter
);

Parameters

pDeviceSettings
[in] Pointer to a DXUTDeviceSettings structure that contains the settings for the new device.
bPreserveInput
[in] Indicates whether the input device settings are to be preserved. If TRUE, the device settings in the pDeviceSettings structure will be used without change; however, it is possible that no valid device will be found, causing this function to return a failure code. If FALSE, a valid device will be created with device settings that are as near as possible to the original device settings in pDeviceSettings. The default value is FALSE.
bClipWindowToSingleAdapter
[in] In a multiple monitor configuration, setting this to TRUE will cause DXUT to move and resize the window if necessary to keep the window positioned on a single adapter. If FALSE, the window is unchanged. The default value is TRUE.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

To alter the settings of a current device, the application can call DXUTGetDeviceSettings to get the device settings structure, change it, and then call DXUTCreateDeviceFromSettings. The application can use DXUTFindValidDeviceSettings to ensure that the device settings are valid before calling DXUTCreateDeviceFromSettings.

This function creates a new Direct3D 9 or Direct3D 10 device for the application based on the settings; alternately, the application can use the DXUTCreateDeviceFromSettings or handle device creation and pass the desired device to DXUT by using the DXUTSetD3D9Device or DXUTSetD3D10Device function. If neither DXUTCreateDevice, DXUTCreateDeviceFromSettings, nor DXUTSetD3D9Device or DXUTSetD3D10Device have been called before calling DXUTMainLoop, DXUT will automatically call DXUTCreateDevice using the default parameter values.

The application can call this method to change the current device that has already been created.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTCreateDevice, DXUTSetD3D10Device, DXUTSetD3D9Device, , DXUTFindValidDeviceSettings


DXUTCreateWindow

Creates the window for the application.

HRESULT DXUTCreateWindow(
  CONST const WCHAR * strWindowTitle,
  HINSTANCE hInstance,
  HICON hIcon,
  HMENU hMenu,
  INT x,
  INT y
);

Parameters

strWindowTitle
[in] Title bar caption for the window. The default value is L"Direct3D Window".
hInstance
[in] Handle of the application's instance, or NULL to retrieve the handle of the current module. The default value is NULL.
hIcon
[in] Handle to the application's icon, or NULL to use the first icon embedded in the application's executable. The default value is NULL.
hMenu
[in] Handle to the application's menu resource, or NULL to indicate no menu. The default value is NULL.
x
[in] Horizontal coordinate of the window's upper left corner, in screen coordinates. Using a value of CW_USEDEFAULT allows Windows to choose an appropriate location. The default value is CW_USEDEFAULT.
y
[in] Vertical coordinate of the window's upper left corner, in screen coordinates. Using a value of CW_USEDEFAULT allows Windows to choose an appropriate location. The default value is CW_USEDEFAULT.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function creates a new window for the application; alternately, the application can handle window creation and pass the desired window handle to DXUT by using the DXUTSetWindow function. If neither DXUTCreateWindow nor DXUTSetWindow has been called before calling a device creation method, DXUT will call DXUTCreateWindow using the default parameter values. The window width and height are set later using the device settings.

All parameters are optional.

If both x and y are CW_USEDEFAULT and a windowed non-primary Direct3D device is created, the window will automatically be moved to the adapter's monitor to ensure maximum performance.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetWindow


DXUTInit

Initializes DXUT.

HRESULT DXUTInit(
  BOOL bParseCommandLine,
  BOOL bShowMsgBoxOnError,
  WCHAR * strExtraCommandLineParams
);

Parameters

bParseCommandLine
[in] If TRUE, DXUT checks for command-line arguments. The application performs the following actions based upon the entered command-line arguments.
Command-line Argument | Action
-forceapi:# | Forces the application to use the specified Direct3D API version. Fails if the application doesn't support this API or if no device is found.
-adapter:# | Forces the application to use this adapter ordinal. Fails if the adapter ordinal does not exist.
-output:# | Applies to Direct3D 10 only. Forces the application to use a particular output on the adapter. Fails if the output does not exist.
-windowed | Forces the application to start in windowed mode.
-fullscreen | Forces the application to start in full-screen mode.
-forcehal | Forces the application to use a HAL device type. Fails if a HAL device does not exist.
-forceref | Forces the application to use a reference device type. Fails if a reference device does not exist.
-forcehwvp | Applies to Direct3D 9 only. Forces the application to use hardware vertex processing. Fails if the device does not support this mode.
-forcepurehwvp | Applies to Direct3D 9 only. Forces the application to use pure hardware vertex processing. Fails if the device does not support this mode.
-forceswvp | Applies to Direct3D 9 only. Forces the application to use software vertex processing.
-forcevsync:# | If # is 0, then vertical sync is disabled. Otherwise, it is enabled.
-width:# | Forces the application to use the window width #. For full-screen mode, DXUT picks the closest possible supported mode.
-height:# | Forces the application to use the window height #. For full-screen mode, DXUT picks the closest possible supported mode.
-startx:# | For windowed mode, forces the application to use the x-coordinate of the window position to the value of #.
-starty:# | For windowed mode, forces the application to use the y-coordinate of the window position to the value of #.
-constantframetime | Forces the application to into a mode where DXUT reports that a constant amount of time has passed between each frame, where # is the time/frame in seconds. This is useful for such scenarios as rendering an movie that can not render in real time
-quitafterframe:# | Forces the application to quit after frame #.
-noerrormsgboxes | Prevents the display of message boxes generated by DXUT, allowing the application to be run without user interaction.
-nostats | Prevents the display of device and frame statistics by always returning blank strings for DXUTGetDeviceStats and DXUTGetFrameStats.
-automation | This is a simple hint to other components that automation is active. The DXUT GUI uses this to enable UI navigation with keyboard by default.
Command-line arguments take precedence over options set by the application when a Direct3D device is first created, but they are ignored afterward to allow the user to interactively change the settings. The default value of this parameter is TRUE.
bShowMsgBoxOnError
[in] If TRUE, DXUT displays a message box if there is an error condition. The default value of this parameter is TRUE.
strExtraCommandLineParams
[in] A string of extra command parameters that will be parsed in addition to the actual command line. It is recommended that be used sparingly. Most the command line options above can be implemented in the application's ModifyDeviceSettings callback or set by using one of DXUT functions. The default value is NULL.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

If this function has not been called before DXUTCreateWindow or DXUTSetWindow, DXUT will automatically call this function using the default parameter values.

Requirements

Header: Declared in DXUT.h.


DXUTMainLoop

Starts the main execution loop of DXUT.

HRESULT DXUTMainLoop(
  HACCEL hAccel
);

Parameters

hAccel
[in] Handle to an accelerator table to use in translating keyboard messages from the Windows message queue, or NULL if not using an accelerator table. The default value is NULL.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function starts the message loop that will run for the lifetime of the application. During execution, DXUTMainLoop calls the registered callback functions to ask the application to update and render the frame, as well as handle any device or input events.

Requirements

Header: Declared in DXUT.h.


DXUTRender3DEnvironment

Renders the 3D environment.

VOID DXUTRender3DEnvironment();

Parameters

None.

Return Values

No return value.

Remarks

This method does not normally need to be called. It is useful only when the application does not use DXUTMainLoop but still wants DXUT to assist with rendering.

This method checks whether the device is lost. If so, the method attempts to reset the device and then calls the LPDXUTCALLBACKFRAMEMOVE and LPDXUTCALLBACKD3D10FRAMERENDER callback functions.

If the application window is minimized or the application is paused, CPU time is yielded to other processes.

Requirements

Header: Declared in DXUT.h.


DXUTSetCallbackD3D9DeviceAcceptable

Sets the Direct3D 9 device acceptable callback function.

VOID DXUTSetCallbackD3D9DeviceAcceptable(
  LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE callback function. If the callback function is supplied, it will be called after the Direct3D 9 device .
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 9 device.

The LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE callback function is the appropriate location for the application to .

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE


DXUTSetCallbackD3D9DeviceCreated

Sets the Direct3D 9 device created callback function.

VOID DXUTSetCallbackD3D9DeviceCreated(
  LPDXUTCALLBACKD3D9DEVICECREATED pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKD3D9DEVICECREATED callback function. If the callback function is supplied, it will be called after the Direct3D 9 device has been created. Device creation will happen during application initialization and if the device is changed. If NULL, DXUT will not notify the application about device creation.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 9 device.

The LPDXUTCALLBACKD3D9DEVICECREATED callback function is the appropriate location for the application to create Direct3D 9 device resources that will live through a device reset such as D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory and that aren't tied to the back buffer size. Resources created in the LPDXUTCALLBACKD3D9DEVICECREATED callback function should be released in the LPDXUTCALLBACKD3D9DEVICEDESTROYED callback function.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKD3D9DEVICECREATED


DXUTSetCallbackD3D9DeviceDestroyed

Sets the Direct3D 9 device destroyed callback function.

VOID DXUTSetCallbackD3D9DeviceDestroyed(
  LPDXUTCALLBACKD3D9DEVICEDESTROYED pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKD3D9DEVICEDESTROYED callback function. If the callback function is supplied, it will be called when the Direct3D device has been destroyed. Device destruction will happen as a result of program termination and if the Direct3D device changes. If NULL, DXUT will not notify the application about device destroyed events.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 9 device.

The LPDXUTCALLBACKD3D9DEVICEDESTROYED callback function is the appropriate location for the application release Direct3D 9 device resources that were created in the LPDXUTCALLBACKD3D9DEVICECREATED callback function.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKD3D9DEVICEDESTROYED


DXUTSetCallbackD3D9DeviceLost

Sets the Direct3D 9 device lost callback function.

VOID DXUTSetCallbackD3D9DeviceLost(
  LPDXUTCALLBACKD3D9DEVICELOST pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKD3D9DEVICELOST callback function. If the callback function is supplied, it will be called after the Direct3D device has been lost. Typical examples when a device is lost include loss of focus, such as when the user presses ALT+TAB or when a system dialog is initialized or during a power management event. If NULL, DXUT will not notify the application about device lost events.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 9 device.

The LPDXUTCALLBACKD3D9DEVICELOST callback function is the appropriate location for the application release Direct3D 9 device resources that were created in the LPDXUTCALLBACKD3D9DEVICERESET callback function.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKD3D9DEVICELOST


DXUTSetCallbackD3D9DeviceReset

Sets the Direct3D 9 device reset callback function.

VOID DXUTSetCallbackD3D9DeviceReset(
  LPDXUTCALLBACKD3D9DEVICERESET pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKD3D9DEVICERESET callback function. If the callback function is supplied, it will be called after the Direct3D device has been reset. Device reset will happen after a lost device is availble again. If NULL, DXUT will not notify the application about device reset events.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 9 device.

The LPDXUTCALLBACKD3D9DEVICERESET callback function is the appropriate location for the application to create Direct3D 9 device resources that won't live through a device reset such as D3DPOOL_DEFAULT or that are tied to the back buffer size. Resources created in the LPDXUTCALLBACKD3D9DEVICERESET callback function should be released in the LPDXUTCALLBACKD3D9DEVICELOST callback function.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKD3D9DEVICERESET


DXUTSetCallbackD3D9FrameRender

Sets the Direct3D 9 frame render callback function.

VOID DXUTSetCallbackD3D9FrameRender(
  LPDXUTCALLBACKD3D9FRAMERENDER pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKD3D9FRAMERENDER callback function. If the callback function is supplied, it will be called once per frame for the application to render the current scene using the Direct3D 9 device. If NULL, DXUT will not prompt the application to render the scene.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 9 device.

The LPDXUTCALLBACKD3D9FRAMERENDER callback function is the appropriate location for the application to render the current scene using the Direct3D 9 device. The LPDXUTCALLBACKFRAMEMOVE callback function will be called once per frame, while LPDXUTCALLBACKD3D9FRAMERENDER will be called when the scene needs to be rendered, which might be more than once per frame.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKD3D9FRAMERENDER


DXUTSetCallbackD3D10DeviceAcceptable

Sets the Direct3D 10 device acceptable callback function.

VOID DXUTSetCallbackD3D10DeviceAcceptable(
  LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE callback function. If the callback function is supplied, it will be called after the Direct3D 10 device .
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 10 device.

The LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE callback function is the appropriate location for the application to .

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE


DXUTSetCallbackD3D10DeviceCreated

Sets the Direct3D 10 device created callback function.

VOID DXUTSetCallbackD3D10DeviceCreated(
  LPDXUTCALLBACKD3D10DEVICECREATED pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKD3D10DEVICECREATED callback function. If the callback function is supplied, it will be called after the Direct3D 10 device has been created. Device creation will happen during application initialization and if the device is changed. If NULL, DXUT will not notify the application about device creation.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The LPDXUTCALLBACKD3D10DEVICECREATED callback function is the appropriate location for the application to create resources in D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory, because these resources do not need to be reloaded whenever the device is reset. Resources created in the LPDXUTCALLBACKD3D10DEVICECREATED callback function should be deleted in the LPDXUTCALLBACKD3D10DEVICEDESTROYED callback function.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKD3D10DEVICECREATED


DXUTSetCallbackD3D10DeviceDestroyed

Sets the Direct3D 10 device destroyed callback function.

VOID DXUTSetCallbackD3D10DeviceDestroyed(
  LPDXUTCALLBACKD3D10DEVICEDESTROYED pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKD3D10DEVICEDESTROYED callback function. If the callback function is supplied, it will be called when the Direct3D 10 device has been destroyed. Device destruction will happen as a result of program termination and if the Direct3D device changes. If NULL, DXUT will not notify the application about device destroyed events.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 10 device.

The LPDXUTCALLBACKD3D10DEVICEDESTROYED callback function is the appropriate location for the application release Direct3D 10 device resources that were created in the LPDXUTCALLBACKD3D10DEVICECREATED callback function.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKD3D10DEVICEDESTROYED


DXUTSetCallbackD3D10FrameRender

Sets the Direct3D 10 frame render callback function.

VOID DXUTSetCallbackD3D10FrameRender(
  LPDXUTCALLBACKD3D10FRAMERENDER pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKD3D10FRAMERENDER callback function. If the callback function is supplied, it will be called at the end of every frame to facilitate rendering of the scene. If NULL, DXUT will not prompt the application to render the scene.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 10 device.

The LPDXUTCALLBACKD3D10FRAMERENDER callback function is the appropriate location for the application to render the current scene. The LPDXUTCALLBACKFRAMEMOVE callback function will be called once per frame, while LPDXUTCALLBACKD3D10FRAMERENDER will be called when the scene needs to be rendered, which might be more than once per frame.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKD3D10FRAMERENDER


DXUTSetCallbackD3D10SwapChainReleasing

Sets the Direct3D 10 swap chain releasing callback function.

HRESULT DXUTSetCallbackD3D10SwapChainReleasing(
  LPDXUTCALLBACKD3D10SWAPCHAINRELEASING pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKD3D10SWAPCHAINRELEASING callback function. If the callback function is supplied, it will be called when the Direct3D 10 swap chain is about to be released. The swap chain will release when the window is resized or the resolution changes. If NULL, DXUT will not notify the application about swap chain events.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 10 device.

The LPDXUTCALLBACKD3D10SWAPCHAINRELEASING callback function is the appropriate location for the application release Direct3D 10 device resources that were created in the LPDXUTCALLBACKD3D10SWAPCHAINRESIZED callback function.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKD3D10SWAPCHAINRELEASING


DXUTSetCallbackD3D10SwapChainResized

Sets the Direct3D 10 swap chain resized callback function.

HRESULT DXUTSetCallbackD3D10SwapChainResized(
  LPDXUTCALLBACKD3D10SWAPCHAINRESIZED pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKD3D10SWAPCHAINRESIZED callback function. If the callback function is supplied, it will be called when the Direct3D 10 swap chain is about to be resized and created. The swap chain will be resized when the window is resized or the resolution changes. If NULL, DXUT will not notify the application about swap chain events.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function only needs to be called if the application supports rendering with Direct3D 10 device.

The LPDXUTCALLBACKD3D10SWAPCHAINRESIZED callback function is the appropriate location for the application to create Direct3D 10 device resources that depend on the back buffer such as a render target that needs to match the size of the back buffer. Resources created in the LPDXUTCALLBACKD3D10SWAPCHAINRESIZED callback function should be released in the LPDXUTCALLBACKD3D10SWAPCHAINRELEASING callback function.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKD3D10SWAPCHAINRESIZED


DXUTSetCallbackDeviceChanging

Sets a callback function that allow the application to change the device settings before the device is created.

VOID DXUTSetCallbackDeviceChanging(
  LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallbackModifyDeviceSettings,
  void* pUserContext
);

Parameters

pCallbackModifyDeviceSettings
[in] Pointer to a LPDXUTCALLBACKMODIFYDEVICESETTINGS callback function. If the callback function is supplied, it will be called before the Direct3D device is created. If NULL, DXUT will not notify the application about device changes.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

Before a device is created by DXUT, the LPDXUTCALLBACKMODIFYDEVICESETTINGS callback will be called to allow the application to examine or change the device settings before the device is created. This allows an application to modify the device creation settings as it sees fit.

This callback also allows applications to reject changing the device altogether. Returning false from inside this callback will notify DXUT to keep using the current device instead of changing to the new device.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKMODIFYDEVICESETTINGS


DXUTSetCallbackDeviceRemoved

Sets a callback function that allows the application to respond to a Direct3D device removed event.

VOID DXUTSetCallbackDeviceRemoved(
  LPDXUTCALLBACKDEVICEREMOVED pCallback,
  void* pUserContext
);

Parameters

pCallback
[in] Pointer to a LPDXUTCALLBACKDEVICEREMOVED callback function. If the callback function is supplied, it will be called after the Direct3D device is removed. If NULL, DXUT will not notify the application about device changes.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

If the Direct3D device is removed such as when a laptop undocks from a docking station, DXUT notifies that application with the LPDXUTCALLBACKDEVICEREMOVED callback. This allows the application to respond to this event. If the application returns false from within the callback, DXUT will not try to find a new device and will shutdown.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKDEVICEREMOVED


DXUTSetCallbackFrameMove

Sets the frame update callback function.

VOID DXUTSetCallbackFrameMove(
  LPDXUTCALLBACKFRAMEMOVE pCallbackFrameMove,
  void* pUserContext
);

Parameters

pCallbackFrameMove
[in] Pointer to a LPDXUTCALLBACKFRAMEMOVE callback function. If the callback function is supplied, it will be called at the beginning of every frame to facilitate updates to the scene. If NULL, DXUT will not notify the application about new frames.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The LPDXUTCALLBACKFRAMEMOVE callback function is the appropriate location for the application to handle updates to the scene. However, LPDXUTCALLBACKFRAMEMOVE is not intended to contain actual rendering calls, which should instead be placed in the LPDXUTCALLBACKD3D9FRAMERENDER or LPDXUTCALLBACKD3D10FRAMERENDER callback function. These callbacks is called when rendering with either Direct3D 9 or Direct3D 10 respectively.

The LPDXUTCALLBACKFRAMEMOVE callback function will be called once per frame, while the render callback function will be called whenever the scene needs to be rendered, which might be more than once per frame on rare occasion if a WM_PAINT message occurs.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKFRAMEMOVE


DXUTSetCallbackKeyboard

Sets the keyboard event callback function.

VOID DXUTSetCallbackKeyboard(
  LPDXUTCALLBACKKEYBOARD pCallbackKeyboard,
  void* pUserContext
);

Parameters

pCallbackKeyboard
[in] Pointer to a LPDXUTCALLBACKKEYBOARD keyboard event callback function. If supplied, the callback function will be called for keyboard events. If NULL, DXUT will not notify the application about keyboard events.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The pCallbackKeyboard keyboard event callback function will be called when any keyboard event occurs.

This callback mechanism is provided to simplify handling keyboard messages through the windows message pump, but does not preclude the application from handling those messages directly through the LPDXUTCALLBACKMSGPROC callback.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKKEYBOARD


DXUTSetCallbackMouse

Sets the mouse event callback function.

VOID DXUTSetCallbackMouse(
  LPDXUTCALLBACKMOUSE pCallbackMouse,
  BOOL bIncludeMouseMove,
  void* pUserContext
);

Parameters

pCallbackMouse
[in] Pointer to an LPDXUTCALLBACKMOUSE mouse event callback function. If supplied, the callback function will be called for mouse events. If NULL, DXUT will not notify the application about mouse events.
bIncludeMouseMove
[in] If TRUE, the mouse movement events are passed to the pCallbackMouse callback function. Default value is FALSE.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The pCallbackMouse mouse event callback function will be called when any mouse events occurs

This callback mechanism is provided to simplify handling mouse messages through the Windows message pump, but does not preclude the application from handling those messages directly in the LPDXUTCALLBACKMSGPROC callback function.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKMOUSE


DXUTSetCallbackMsgProc

Sets the window message callback function.

VOID DXUTSetCallbackMsgProc(
  LPDXUTCALLBACKMSGPROC pCallbackMsgProc,
  void* pUserContext
);

Parameters

pCallbackMsgProc
[in] Pointer to a LPDXUTCALLBACKMSGPROC callback function. If supplied, DXUT will call this function when it receives window messages. If NULL, DXUT will not notify the application about window messages.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The LPDXUTCALLBACKMSGPROC callback function allows the application to respond to any Windows messages as it sees fit.

With the use of the LPDXUTCALLBACKMSGPROC pbNoFurtherProcessing parameter, the application can contol the DXUT's level of involvement in processing window messages. If the application sets the pbNoFurtherProcessing parameter to TRUE in the call to LPDXUTCALLBACKMSGPROC, DXUT will not process the message and will immediately return with the value returned by LPDXUTCALLBACKMSGPROC. If the application sets pbNoFurtherProcessing to FALSE, DXUT will handle window management events.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKMSGPROC, WindowProc


DXUTSetD3D9Device

Sets an existing Direct3D 9 device for use by DXUT.

HRESULT DXUTSetD3D9Device(
  IDirect3DDevice9 * pd3dDevice
);

Parameters

pd3dDevice
[in] Pointer to a IDirect3DDevice9 object to use for rendering.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function relies on an existing Direct3D 9 device object created by the application. Alternately, the application can call DXUTCreateDevice or DXUTCreateDeviceFromSettings to have DXUT create a device. If neither DXUTCreateDevice, DXUTCreateDeviceFromSettings, DXUTSetD3D9Device, nor DXUTSetD3D10Device have been called before a DXUT method that relies on a device, DXUT will automatically call DXUTCreateDevice using the default parameter values.

The application can call this function after a device has already been created to change the current device.

DXUT only allows one active device at a time, so calling this will cause any previous Direct3D device to be released.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTCreateDevice, DXUTCreateDeviceFromSettings, DXUTSetD3D10Device


DXUTSetD3D10Device

Sets an existing Direct3D 10 device for use by DXUT.

HRESULT DXUTSetD3D10Device(
  ID3D10Device * pd3dDevice
);

Parameters

pd3dDevice
[in] Pointer to a ID3D10Device Interface to use for rendering.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function relies on an existing Direct3D 10 device object created by the application. Alternately, the application can call DXUTCreateDevice or DXUTCreateDeviceFromSettings to have DXUT create a device. If neither DXUTCreateDevice, DXUTCreateDeviceFromSettings, DXUTSetD3D9Device, nor DXUTSetD3D10Device have been called before a DXUT method that relies on a device, DXUT will automatically call DXUTCreateDevice using the default parameter values.

The application can call this function after a device has already been created to change the current device.

DXUT only allows one active device at a time, so calling this will cause any previous Direct3D device to be released.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTCreateDevice, DXUTCreateDeviceFromSettings, DXUTSetD3D9Device


DXUTSetWindow

Sets a previously created window for use by DXUT.

HRESULT DXUTSetWindow(
  HWND hWndFocus,
  HWND hWndDeviceFullScreen,
  HWND hWndDeviceWindowed,
  BOOL bHandleMessages
);

Parameters

hWndFocus
[in] Handle of the Direct3D focus window. Must not be NULL.
hWndDeviceFullScreen
[in] Handle of the Direct3D device window when in full-screen mode. Must not be NULL.
hWndDeviceWindowed
[in] Handle of the Direct3D device window when in windowed mode. Must not be NULL.
bHandleMessages
[in] If TRUE, DXUT will handle and respond to messages for the window. If FALSE, DXUT will not handle messages for the window, giving the application full responsibility for responding to messages. The default value is TRUE.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function relies on an existing window object created by the application. Alternately, the application can call DXUTCreateWindow to have DXUT create a window. If neither DXUTCreateWindow nor DXUTSetWindow has been called before calling a device creation method, DXUT will automatically call DXUTCreateWindow using the default parameter values.

The same Window handle may be used for more than one parameter.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTCreateWindow


DXUTStaticWndProc

Processes messages sent to a window.

LRESULT_CALLBACK DXUTStaticWndProc(
  HWND hWnd,
  UINT uMsg,
  WPARAM wParam,
  LPARAM lParam
);

Parameters

hWnd
[in] Handle to the window.
uMsg
[in] Specifies the message.
wParam
[in] Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.
lParam
[in] Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.

Return Values

If the function has processed window messages successfully, returns zero; otherwise, returns a nonzero value.

Remarks

This method does not normally need to be called. It is useful only when the application use DXUTSetWindow with bHandleMessages set to FALSE but still wants DXUT to assist with handling Windows messages. If this is the case, this function can be called from inside the application's window procedure, or it can be used directly as the window procedure.

Requirements

Header: Declared in DXUT.h.


Common Task Functions

DXUT supplies the following common task functions that can be used by an application:

  • DXUTKillTimer
  • DXUTPause
  • DXUTResetFrameworkState
  • DXUTSetConstantFrameTime
  • DXUTSetCursorSettings
  • DXUTSetD3DVersionSupport
  • DXUTSetHotkeyHandling
  • DXUTSetMultimonSettings
  • DXUTSetShortcutKeySettings
  • DXUTSetTimer
  • DXUTSetWindowSettings
  • DXUTShutdown
  • DXUTToggleFullscreen
  • DXUTToggleREF


DXUTFindValidDeviceSettings

Finds valid device settings to be used to create a new device.

HRESULT DXUTFindValidDeviceSettings(
  DXUTDeviceSettings * pOut,
  DXUTDeviceSettings * pIn,
  DXUTMatchOptions * pMatchOptions
);

Parameters

pOut
[out] Pointer to a DXUTDeviceSettings structure that contains valid settings for the new device.
pIn
[in] Pointer to a DXUTDeviceSettings structure that contains desired settings for the new device. The default value is NULL.
pMatchOptions
[in] Pointer to a DXUTMatchOptions structure that contains flags describing how to use the device settings when choosing valid output device settings. Optimal device settings will be created based upon the match values in DXUTMatchOptions. If NULL, the function acts as if all members of this structure were DXUTMT_IGNORE_INPUT, meaning that the function will return valid device settings as close as possible to default device settings. See Remarks. The default value is NULL.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function attempts to find valid device settings based upon the input device settings, given by pIn. For each device setting, a match option in the DXUTDeviceSettings structure specifies how the function makes decisions. The function works for both Direct3D 9 and Direct3D 10 device settings.

This function is internally by DXUT used when toggling between full screen and windowed modes, when selecting between HAL and REF device types, and inside DXUTCreateDevice.

Requirements

Header: Declared in DXUTenum.h.

See Also

DXUTMatchOptions, DXUTCreateDeviceFromSettings


DXUTKillTimer

Uninstalls an existing timer.

HRESULT DXUTKillTimer(
  UINT nIDEvent
);

Parameters

nIDEvent
[in] The event ID for the timer being destroyed. This ID is provided to the application by the DXUTSetTimer method.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

Timers created with DXUTSetTimer can be destroyed with DXUTKillTimer.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKTIMER, DXUTSetTimer


DXUTPause

Sets the paused state of DXUT internal timer and/or rendering process.

VOID DXUTPause(
  BOOL bPauseTime,
  BOOL bPauseRendering
);

Parameters

bPauseTime
[in] If TRUE, DXUT internal timer is paused. If FALSE, the timer is resumed from a paused state. See Remarks.
bPauseRendering
[in] If TRUE, DXUT will not call the LPDXUTCALLBACKD3D10FRAMERENDER callback function; DXUT will continue to call the LPDXUTCALLBACKFRAMEMOVE callback function. If FALSE, rendering will resume from a paused state. See Remarks.

Return Values

No return value.

Remarks

The timer controls the fTime and fElapsedTime parameters passed to the LPDXUTCALLBACKFRAMEMOVE or render callback functions.

When time is paused, fTime will remain unchanged and fElapsedTime will be 0.0f. The LPDXUTCALLBACKFRAMEMOVE and the render callback functions will still be called. This allows a camera to still move while time is paused.

When rendering is paused, the render callback function and the Direct3D Present method will not be called, and DXUT will periodically yield time to other processes by calling Sleep.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTGetElapsedTime, DXUTGetTime, DXUTIsTimePaused, DXUTIsRenderingPaused


DXUTResetFrameworkState

Resets DXUT state to its initial default state. All previous DXUT state changes are lost.

VOID DXUTResetFrameworkState();

Parameters

None.

Return Values

No return value.

Remarks

This function does not normally need to be called. It is useful for testing purposes because the application process does not have to be restarted to reset DXUT back to its initial state.

Requirements

Header: Declared in DXUT.h.


DXUTSetConstantFrameTime

Enables or disables a constant frame time.

HRESULT DXUTSetConstantFrameTime(
  BOOL bEnabled,
  FLOAT fTimePerFrame
);

Parameters

bEnabled
[in] If TRUE, a constant frame time will be enabled.
fTimePerFrame
[in] Time per frame, in seconds. The default value is 0.0333f, so the fTime parameter of LPDXUTCALLBACKFRAMEMOVE and the render callback functions will advance one second for every 30 frames.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function simulates a fixed-frame rate render loop by sending a constant value for elapsed time to the LPDXUTCALLBACKFRAMEMOVE and render callback functions. The default rate is one second for every 30 frames. The application itself will continue to render at an unregulated rate (which may be far higher than the specified frame rate).

This function is useful for saving the rendered output to a video format for playback, allowing animation at a rate independent of the actual rate at which frames were rendered.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTGetElapsedTime, DXUTGetTime


DXUTSetCursorSettings

Sets options for cursor usage in full-screen mode.

HRESULT DXUTSetCursorSettings(
  bool bShowCursorWhenFullScreen,
  bool bClipCursorWhenFullScreen
);

Parameters

bShowCursorWhenFullScreen
[in] Cursor visibility flag. If true, the cursor will be visible when the application is running in full-screen mode.
bClipCursorWhenFullScreen
[in] Cursor clipping flag. If true, the cursor will be restricted from exiting the screen boundaries when the application is running in full screen mode.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Requirements

Header: Declared in DXUT.h.


DXUTSetD3DVersionSupport

Sets if the application can use Direct3D 9 and/or Direct3D 10.

void DXUTSetD3DVersionSupport(
  bool bAppCanUseD3D9,
  bool bAppCanUseD3D10
);

Parameters

bAppCanUseD3D9
[in] If set to false, DXUT will not make any Direct3D 9 calls or enumerate Direct3D 9 devices.
bAppCanUseD3D10
[in] If set to false, DXUT will not make any Direct3D 10 calls or enumerate Direct3D 10 devices.

Return Values

No return value.

Remarks

This function does not normally need to be called. DXUT typically infers which API the application can support from the device callbacks the application has set. For example, if the application has set Direct3D 9 device callbacks, DXUT assumes that application supports Direct3D 9. However, if the application needs to override this logic, it can use this function to explicitly tell DXUT.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTDoesAppSupportD3D9, DXUTDoesAppSupportD3D10


DXUTSetHotkeyHandling

Sets certain hotkeys to active or inactive

void DXUTSetHotkeyHandling(
  bool bAltEnterToToggleFullscreen,
  bool bEscapeToQuit,
  bool bPauseToToggleTimePause
);

Parameters

bAltEnterToToggleFullscreen
[in] If TRUE, pressing alt-enter will toggle the application between windowed mode and full screen mode. Default value is TRUE.
bEscapeToQuit
[in] If TRUE, pressing escape will exit the the application. Default value is TRUE.
bPauseToToggleTimePause
[in] If TRUE, pressing pause will pause the application timer. Default value is TRUE.

Return Values

No return value.

Remarks

Professional applications will typically want to pass TRUE for bAltEnterToToggleFullscreen, and FALSE for bEscapeToQuit and bPauseToToggleTimePause while simple graphics demos will typically want to keep these all TRUE.

Requirements

Header: Declared in DXUT.h.


DXUTSetMultimonSettings

Sets options for how DXUT functions on multiple monitors.

VOID DXUTSetMultimonSettings(
  BOOL bAutoChangeAdapter
);

Parameters

bAutoChangeAdapter
[in] If TRUE and the application window is relocated to a different monitor, DXUT will automatically change to use the new monitor's adapter, and device callback functions will be called to recreate the scene.

Return Values

No return value.

Requirements

Header: Declared in DXUT.h.


DXUTSetShortcutKeySettings

This functions controls if DXUT enables or disables Windows shortcut keys, specifically the Windows keys, the StickyKeys shortcuts, the ToggleKeys shortcut, and the FilterKeys shortcut.

void DXUTSetShortcutKeySettings(
  bool bAllowWhenFullscreen,
  bool bAllowWhenWindowed
);

Parameters

bAllowWhenFullscreen
[in] If TRUE, shortcut keys will be allowed in fullscreen mode. Default value is FALSE.
bAllowWhenWindowed
[in] If TRUE, shortcut keys will be allowed in windowed mode. Default value is TRUE.

Return Values

No return value.

Remarks

By default, DXUT allows Windows shortcuts (the Windows keys, the StickyKeys shortcuts, the ToggleKeys shortcut, and the FilterKeys shortcut) to remain active when application is windowed but disables the shortscuts when fullscreen. This function allows the application to change this behavior. For more information about how DXUT disables these shortcuts, see the article in the DirectX SDK titled "Disabling Shortcut Keys in Games".

Requirements

Header: Declared in DXUT.h.


DXUTSetTimer

Starts a DXUT timer that will trigger a callback function at regular intervals.

HRESULT DXUTSetTimer(
  LPDXUTCALLBACKTIMER pCallbackTimer,
  FLOAT fTimeoutInSecs,
  UINT * pnIDEvent,
  void * pCallbackUserContext
);

Parameters

pCallbackTimer
[in] Pointer to a timer callback function. The callback function is to be called at the specified fTimeoutInSecs timeout intervals. May not be NULL.
fTimeoutInSecs
[in] Interval, in seconds, between successive calls to the timer callback function. The default value is 1.0f.
pnIDEvent
[in] Optional pointer to a variable to receive the event ID for the new timer. This event ID will be passed to the timer callback function to indicate which timer generated the event, allowing the application to use a single callback function for multiple timers. The default value is NULL.
pCallbackUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

Timers created with DXUTSetTimer can be destroyed with DXUTKillTimer.

Requirements

Header: Declared in DXUT.h.

See Also

LPDXUTCALLBACKTIMER, DXUTKillTimer


DXUTSetWindowSettings

Sets DXUT window settings

void DXUTSetWindowSettings(
  bool bCallDefWindowProc
);

Parameters

bCallDefWindowProc
[in] If TRUE, DXUT will call the default window proc. Otherwise it will not. The default value is TRUE.

Return Values

No return value.

Remarks

This function does not typically need to be called. It allows advanced applications which use a dialog window to work with DXUT message processing. Messages sent to dialog window should not be passed to the default window proc so this function can be called to turn this behavior off in this case.

Requirements

Header: Declared in DXUT.h.


DXUTShutdown

Triggers program termination and DXUT cleanup.

VOID DXUTShutdown(
  int nExitCode
);

Parameters

nExitCode
[in] The exit code returned via the DXUTGetExitCode function. The default value is 0

Return Values

No return value.

Remarks

It is not necessary for the application to call this function, since the application lifespan is handled by DXUT. However, the application can call this function to cleanly terminate the application process.

Requirements

Header: Declared in DXUT.h.


DXUTToggleFullscreen

Switches the application between windowed and full-screen modes.

HRESULT DXUTToggleFullscreen();

Parameters

None.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function works regardless of which Direct3D API version the application is using.

Toggling between windowed and full-screen modes will result in swap chain being resized if using Direct3D 10, or the device being reset or recreated if using Direct3D 9.

Requirements

Header: Declared in DXUT.h.


DXUTToggleREF

Switches the application between HAL and reference device types.

HRESULT DXUTToggleREF();

Parameters

None.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function works regardless of which Direct3D API version the application is using.

Requirements

Header: Declared in DXUT.h.


State Retrieval Functions

DXUT supplies the following state retrieval functions that can be used by an application:

  • DXUTDoesAppSupportD3D9
  • DXUTDoesAppSupportD3D10
  • DXUTFindValidDeviceSettings
  • DXUTGetAutomation
  • DXUTGetD3D10GetDepthStencilView
  • DXUTGetD3D10Device
  • DXUTGetRenderTargetView
  • DXUTGetD3D9BackBufferSurfaceDesc
  • DXUTGetD3D9Device
  • DXUTGetD3D9DeviceCaps
  • DXUTGetD3DObject
  • DXUTGetPresentParameters
  • DXUTGetDeviceSettings
  • DXUTGetDeviceStats
  • DXUTGetDXGIBackBufferSurfaceDesc
  • DXUTGetDXGIFactory
  • DXUTGetDXGISwapChain
  • DXUTGetElapsedTime
  • DXUTGetExitCode
  • DXUTGetFPS
  • DXUTGetFrameStats
  • DXUTGetFullsceenClientRectAtModeChange
  • DXUTGetHINSTANCE
  • DXUTGetHWND
  • DXUTGetHWNDDeviceFullScreen
  • DXUTGetHWNDDeviceWindowed
  • DXUTGetHWNDFocus
  • DXUTGetShowMsgBoxOnError
  • DXUTGetTime
  • DXUTGetWindowClientRect
  • DXUTGetWindowClientRectAtModeChange
  • DXUTGetWindowTitle
  • DXUTIsActive
  • DXUTIsAppRenderingWithD3D9
  • DXUTIsAppRenderingWithD3D10
  • DXUTIsD3D10Available
  • DXUTIsKeyDown
  • DXUTIsMouseButtonDown
  • DXUTIsRenderingPaused
  • DXUTIsTimePaused
  • DXUTIsWindowed


DXUTDoesAppSupportD3D9

Indicates whether the application supports Direct3D 9 device calls.

bool DXUTDoesAppSupportD3D9();

Parameters

None.

Return Values

TRUE if the application supports Direct3D 9 device calls; FALSE otherwise.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTDoesAppSupportD3D10, DXUTSetD3DVersionSupport


DXUTDoesAppSupportD3D10

Indicates whether the application supports Direct3D 10 device calls.

bool DXUTDoesAppSupportD3D10();

Parameters

None.

Return Values

TRUE if the application supports Direct3D 10 device calls; FALSE otherwise.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTDoesAppSupportD3D9, DXUTSetD3DVersionSupport


DXUTGetAutomation

Indicates whether the automation command line parameter was used to launch the application.

bool DXUTGetAutomation();

Parameters

None.

Return Values

TRUE if the automation command line parameter was used to launch the application; FALSE otherwise.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTInit


DXUTGetD3D9BackBufferSurfaceDesc

Get a pointer to a D3DSURFACE_DESC surface description of the current Direct3D 9 back buffer.

CONST D3DSURFACE_DESC * DXUTGetD3D9BackBufferSurfaceDesc();

Parameters

None.

Return Values

Pointer to a D3DSURFACE_DESC surface description of the current Direct3D 9 back buffer.

Remarks

If no Direct3D 9 device exists, then the D3DSURFACE_DESC structure is filled with zeros.

Requirements

Header: Declared in DXUT.h.


DXUTGetD3D9Device

Get a pointer to the IDirect3DDevice9 interface that represents the current device.

IDirect3DDevice9 * DXUTGetD3D9Device();

Parameters

None.

Return Values

Pointer to the IDirect3DDevice9 interface that represents the current Direct3D 9 device. NULL is returned if no Direct3D 9 device has been created.

Remarks

Only one device can be active in DXUT at a time so either this function or DXUTGetD3D10Device will return NULL.

This function exposes access to a global IDirect3DDevice9 object. The reference count on this device interface is not incremented, so a calling function should not release the IDirect3DDevice9 interface pointer returned by this function.

Requirements

Header: Declared in DXUT.h.


DXUTGetD3D9DeviceCaps

Get a pointer to the D3DCAPS9 capabilities of the current device.

CONST D3DCAPS9 * DXUTGetD3D9DeviceCaps();

Parameters

None.

Return Values

Pointer to the D3DCAPS9 capabilities of the Direct3D 9 device.

Remarks

If no Direct3D 9 device exists, then the D3DCAPS9 structure is filled with zeros.

Requirements

Header: Declared in DXUT.h.


DXUTGetD3DObject

Get a pointer to the IDirect3D9 object.

IDirect3D9 * DXUTGetD3DObject();

Parameters

None.

Return Values

Pointer to the IDirect3D9 object. NULL is returned if no IDirect3D9 object has been created. See Remarks.

Remarks

This function exposes access to a global IDirect3D9 object. The reference count on this object interface is not incremented, so a calling function should not release the IDirect3D9 interface pointer returned by this function.

Requirements

Header: Declared in DXUT.h.


DXUTGetPresentParameters

Get the presentation parameters of the Direct3D 9 device.

D3DPRESENT_PARAMETERS DXUTGetPresentParameters();

Parameters

None.

Return Values

The presentation parameters of the Direct3D 9 device.

Remarks

If no Direct3D 9 device exists, then the D3DPRESENT_PARAMETERS structure is filled with zeros.

Requirements

Header: Declared in DXUT.h.


DXUTGetD3D10GetDepthStencilView

Get a pointer to the ID3D10DepthStencilView Interface interface for the current Direct3D 10 device.

ID3D10DepthStencilView * DXUTGetD3D10GetDepthStencilView();

Parameters

None.

Return Values

Pointer to the ID3D10DepthStencilView Interface for the current device. NULL is returned if no Direct3D 10 device has been created.

Remarks

This function exposes access to a global ID3D10DepthStencilView Interface object. The reference count on this interface is not incremented, so a calling function should not release the ID3D10DepthStencilView Interface interface pointer returned by this function.

Requirements

Header: Declared in DXUT.h.


DXUTGetD3D10Device

Get a pointer to the ID3D10Device Interface interface that represents the current device.

ID3D10Device * DXUTGetD3D10Device();

Parameters

None.

Return Values

Pointer to the ID3D10Device Interface that represents the current Direct3D 10 device. NULL is returned if no Direct3D 10 device has been created.

Remarks

Only one device can be active in DXUT at a time so either this function or DXUTGetD3D9Device will return NULL.

This function exposes access to a global ID3D10Device Interface object. The reference count on this device interface is not incremented, so a calling function should not release the ID3D10Device Interface interface pointer returned by this function.

Requirements

Header: Declared in DXUT.h.


DXUTGetRenderTargetView

Get a pointer to the ID3D10RenderTargetView Interface interface for the current Direct3D 10 device.

ID3D10RenderTargetView * DXUTGetRenderTargetView();

Parameters

None.

Return Values

Pointer to a ID3D10RenderTargetView Interface for the current device. NULL is returned if no Direct3D 10 device has been created.

Remarks

This function exposes access to a global ID3D10RenderTargetView Interface object. The reference count on this interface is not incremented, so a calling function should not release the ID3D10RenderTargetView Interface interface pointer returned by this function.

Requirements

Header: Declared in DXUT.h.


DXUTGetDeviceSettings

Get the DXUTDeviceSettings structure used to create the current device.

DXUTDeviceSettings DXUTGetDeviceSettings();

Parameters

None.

Return Values

DXUTDeviceSettings structure used to create the current device.

Remarks

This settings structure can describe either a Direct3D 9 device or a Direct3D 10 device as defined the the structure's DXUTDeviceVersion member.

If no device exists, then the DXUTDeviceSettings structure is filled with zeros.

Requirements

Header: Declared in DXUT.h.


DXUTGetDeviceStats

Get a pointer to a string containing the current device type, vertex processing behavior, and device name.

LPCWSTR DXUTGetDeviceStats();

Parameters

None.

Return Values

Pointer to a string containing the current device type, vertex processing behavior, and device name.

Requirements

Header: Declared in DXUT.h.


DXUTGetDXGIBackBufferSurfaceDesc

Get a pointer to a DXGI_SURFACE_DESC surface description of the back buffer on the current adapter.

CONST DXGI_SURFACE_DESC * DXUTGetDXGIBackBufferSurfaceDesc();

Parameters

None.

Return Values

Pointer to a DXGI_SURFACE_DESC surface description of the back buffer on the current adapter.

Remarks

If no device exists, then the DXGI_SURFACE_DESC structure is filled with zeros.

Requirements

Header: Declared in DXUT.h.


DXUTGetDXGIFactory

Get a pointer to a IDXGIFactory Interface interface.

IDXGIFactory * DXUTGetDXGIFactory();

Parameters

None.

Return Values

Pointer to a IDXGIFactory Interface interface. NULL is returned if no Direct3D 10 device has been created.

Remarks

This function exposes access to a global IDXGIFactory Interface object. The reference count on this interface is not incremented, so a calling function should not release the IDXGIFactory Interface interface pointer returned by this function.

Requirements

Header: Declared in DXUT.h.


DXUTGetDXGISwapChain

Get a pointer to a IDXGISwapChain Interface interface for the current Direct3D 10 device.

IDXGISwapChain * DXUTGetDXGISwapChain();

Parameters

None.

Return Values

Pointer to a IDXGISwapChain Interface interface for the current Direct3D 10 device. NULL is returned if no Direct3D 10 device has been created.

Remarks

This function exposes access to a global IDXGISwapChain Interface object. The reference count on this interface is not incremented, so a calling function should not release the IDXGISwapChain Interface interface pointer returned by this function.

Requirements

Header: Declared in DXUT.h.


DXUTGetElapsedTime

Get the time elapsed since the last frame.

FLOAT DXUTGetElapsedTime();

Parameters

None.

Return Values

Time elapsed, in seconds, since the last frame.

Remarks

DXUT internally uses the best practices for high resolution timing information as described in the "Game Timing and Multicore Processors" article in the DirectX SDK.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTGetTime, DXUTPause


DXUTGetExitCode

Get DXUT exit code.

INT DXUTGetExitCode();

Parameters

None.

Return Values

A DXUT exit code, which will be one of the following possible values.
Value | Description
0 | Successful execution.
1 | An undetermined error occurred.
2 | No Direct3D device could be found with the specified device settings.
3 | A media file could not be found.
4 | The Direct3D device has a non-zero reference count, meaning that some objects were not released.
5 | An error occurred when attempting to create an Direct3D device.
6 | An error occurred when attempting to reset an Direct3D device.
7 | An error occurred in the device creation callback function.
8 | An error occurred in the device creation callback function.
9 | The incorrect version of Direct3D or D3DX is installed.
10 | The last device used upon exit was a REF device type.
11 | The device was removed.

Remarks

The return value of this function is typically used in the application as the return code of the application's WinMain function. Command-line tests can then be performed on applications using this return code.

The following is an example of command-line usage that uses DXUT exit code:

start /wait BasicHLSL.exe
echo %errorlevel%

Requirements

Header: Declared in DXUT.h.


DXUTGetFPS

Get the current number of frames being presented per second.

FLOAT DXUTGetFPS();

Parameters

None.

Return Values

The current number of frames being presented per second.

Requirements

Header: Declared in DXUT.h.


DXUTGetFrameStats

Get a pointer to a string containing the current number of frames per second (optionally), resolution, back buffer format, and depth stencil format.

LPCWSTR DXUTGetFrameStats(
  bool bIncludeFPS
);

Parameters

bIncludeFPS
[in] If true, the string returned will contain the frames per second. Otherwise, it will not.

Return Values

Pointer to a string containing the current number of frames per second (optionally), resolution, back buffer format, and depth stencil format.

Requirements

Header: Declared in DXUT.h.


DXUTGetFullsceenClientRectAtModeChange

Get the client rectangle of the application window when it was in fullscreen mode.

CONST RECT * DXUTGetFullsceenClientRectAtModeChange();

Parameters

None.

Return Values

If the application is full screen, it returns the current client RECT of the application window. Otherwise, DXUT returns the RECT when the application was fullscreen mode last.

Remarks

This function is used by DXUT to return itself to the resolution or window size when toggling between windowed and full-screen modes

Requirements

Header: Declared in DXUT.h.


DXUTGetHINSTANCE

Get a handle to the application instance.

HINSTANCE DXUTGetHINSTANCE();

Parameters

None.

Return Values

A handle to the application instance.

Requirements

Header: Declared in DXUT.h.


DXUTGetHWND

Get a handle to the current device window.

HWND DXUTGetHWND();

Parameters

None.

Return Values

A handle to the current device window.

Requirements

Header: Declared in DXUT.h.


DXUTGetHWNDFocus

Get the handle of the focus window.

HWND DXUTGetHWNDFocus();

Parameters

None.

Return Values

Handle to the focus window.

Remarks

The focus window informs Direct3D when the application is switched to a background window with an ALT+TAB key entry, a mouse click, or by other means. It is typically the same window as the device window.

Requirements

Header: Declared in DXUT.h.


DXUTGetHWNDDeviceFullScreen

Get the handle of the device window used when the application is fullscreen.

HWND DXUTGetHWNDDeviceFullScreen();

Parameters

None.

Return Values

Returns a handle of the device window used when the application is fullscreen.

Requirements

Header: Declared in DXUT.h.


DXUTGetHWNDDeviceWindowed

Get the handle of the device window used when the application is windowed.

HWND DXUTGetHWNDDeviceWindowed();

Parameters

None.

Return Values

Returns a handle of the device window used when the application is windowed.

Requirements

Header: Declared in DXUT.h.


DXUTGetShowMsgBoxOnError

Indicates whether DXUT will pop a message box upon an errors.

BOOL DXUTGetShowMsgBoxOnError();

Parameters

None.

Return Values

TRUE if DXUT will pop a message box upon an errors.

Requirements

Header: Declared in DXUT.h.


DXUTGetTime

Get the current time, in seconds.

DOUBLE DXUTGetTime();

Parameters

None.

Return Values

The current time, in seconds.

Remarks

DXUT internally uses the best practices for high resolution timing information as described in the "Game Timing and Multicore Processors" article in the DirectX SDK.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTGetElapsedTime, DXUTPause


DXUTGetWindowClientRect

Get the current client RECT of the application window.

CONST RECT * DXUTGetWindowClientRect();

Parameters

None.

Return Values

Returns the current client RECT of the application window.

Requirements

Header: Declared in DXUT.h.


DXUTGetWindowClientRectAtModeChange

Get the client rectangle of the application window when it was in windowed mode.

CONST RECT * DXUTGetWindowClientRectAtModeChange();

Parameters

None.

Return Values

If the application is windowed, it returns the current client RECT of the application window. Otherwise, DXUT returns the RECT when the application was windowed mode last.

Remarks

This function is used by DXUT to return itself to the resolution or window size when toggling between windowed and full-screen modes

Requirements

Header: Declared in DXUT.h.


DXUTGetWindowTitle

Get a pointer to a string containing the application window title.

LPCWSTR DXUTGetWindowTitle();

Parameters

None.

Return Values

Pointer to a string containing the application window title.

Requirements

Header: Declared in DXUT.h.


DXUTIsActive

Indicates whether the application is active.

BOOL DXUTIsActive();

Parameters

None.

Return Values

TRUE if the application is active; FALSE otherwise.

Remarks

DXUT is not active when the application window loses focus. If DXUT is not active, time is yielded to other processes. Additionally if it not active while in fullscreen mode, DXUT stops rendering while the window is minimized.

Requirements

Header: Declared in DXUT.h.


DXUTIsAppRenderingWithD3D9

Indicates whether the application is rendering with a Direct3D 9 device.

BOOL DXUTIsAppRenderingWithD3D9();

Parameters

None.

Return Values

TRUE if the application is redndering with a Direct3D 9 device; FALSE otherwise.

Requirements

Header: Declared in DXUT.h.


DXUTIsAppRenderingWithD3D10

Indicates whether the application is rendering with a Direct3D 10 device.

BOOL DXUTIsAppRenderingWithD3D10();

Parameters

None.

Return Values

TRUE if the application is redndering with a Direct3D 10 device; FALSE otherwise.

Requirements

Header: Declared in DXUT.h.


DXUTIsD3D10Available

Indicates whether a Direct3D 10 APIs are available to use on the system.

BOOL DXUTIsD3D10Available();

Parameters

None.

Return Values

TRUE if a Direct3D 10 APIs are available to use on the system. However, this does guarantee that a Direct3D 10 device is available.

Remarks

Direct3D 10 is only available on Windows Vista or later.

Requirements

Header: Declared in DXUT.h.


DXUTIsKeyDown

Indicates whether a specified keyboard key is up or down at the time the function is called.

BOOL DXUTIsKeyDown(
  BYTE vKey
);

Parameters

vKey
[in] Virtual key code of a keyboard key. For example VK_F1, VK_LSHIFT, VK_RCONTROL, VK_RMENU, and 41 (representing the 'A' key).

Return Values

TRUE if the specified vKey keyboard key is down; FALSE otherwise.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTIsMouseButtonDown


DXUTIsMouseButtonDown

Indicates whether a specified mouse button is up or down at the time the function is called.

BOOL DXUTIsMouseButtonDown(
  BYTE vButton
);

Parameters

vButton
[in] Virtual key code of a mouse button. Allowed values are VK_LBUTTON, VK_RBUTTON, VK_MBUTTON, VK_XBUTTON1, and VK_XBUTTON2.

Return Values

TRUE if the specified vButton mouse button is down; FALSE otherwise.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTIsKeyDown


DXUTIsRenderingPaused

Indicates whether rendering has been paused in DXUT.

BOOL DXUTIsRenderingPaused();

Parameters

None.

Return Values

TRUE if rendering has been paused in DXUT.

Requirements

Header: Declared in DXUT.h.


DXUTIsTimePaused

Indicates whether time has been paused in DXUT.

BOOL DXUTIsTimePaused();

Parameters

None.

Return Values

TRUE if time has been paused in DXUT.

Requirements

Header: Declared in DXUT.h.


DXUTIsWindowed

Indicates whether the application is in windowed mode.

BOOL DXUTIsWindowed();

Parameters

None.

Return Values

If TRUE, the application is in windowed mode. If the application is not in windowed mode, or no device exists, then FALSE is returned.

Requirements

Header: Declared in DXUT.h.


Callback Functions

DXUT supplies the following callback functions that may be implemented by an application:

  • LPDXUTCALLBACKD3D9DEVICECREATED
  • LPDXUTCALLBACKD3D9DEVICEDESTROYED
  • LPDXUTCALLBACKD3D9DEVICELOST
  • LPDXUTCALLBACKD3D9DEVICERESET
  • LPDXUTCALLBACKD3D9FRAMERENDER
  • LPDXUTCALLBACKD3D10DEVICECREATED
  • LPDXUTCALLBACKD3D10DEVICEDESTROYED
  • LPDXUTCALLBACKD3D10FRAMERENDER
  • LPDXUTCALLBACKD3D10SWAPCHAINRELEASING
  • LPDXUTCALLBACKD3D10SWAPCHAINRESIZED
  • LPDXUTCALLBACKFRAMEMOVE
  • LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE
  • LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE
  • LPDXUTCALLBACKKEYBOARD
  • LPDXUTCALLBACKMODIFYDEVICESETTINGS
  • LPDXUTCALLBACKMOUSE
  • LPDXUTCALLBACKMSGPROC
  • LPDXUTCALLBACKTIMER


LPDXUTCALLBACKD3D9DEVICECREATED

Application-defined resource creation callback function, called by DXUT after the Direct3D 9 device is created. Passes a pointer to the newly created Direct3D 9 device.

HRESULT LPDXUTCALLBACKD3D9DEVICECREATED(
  IDirect3DDevice9 * pd3dDevice,
  CONST D3DSURFACE_DESC * pBackBufferSurfaceDesc,
  void* pUserContext
);

Parameters

pd3dDevice
[out] Pointer to the newly created Direct3D 9 device.
pBackBufferSurfaceDesc
[out] Pointer to the back buffer surface description
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

In general, if no error occurs, program the function to return S_OK. Program the function to return an HRESULT failure code if the function fails. If DXUT receives a failure HRESULT code, it shuts down the application.

Remarks

The LPDXUTCALLBACKD3D9DEVICECREATED callback function is the appropriate location for the application to create Direct3D 9 device resources that will live through a device reset such as D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory and that aren't tied to the back buffer size. Resources created in the LPDXUTCALLBACKD3D9DEVICECREATED callback function should be released in the LPDXUTCALLBACKD3D9DEVICEDESTROYED callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D9DeviceCreated


LPDXUTCALLBACKD3D9DEVICEDESTROYED

Application-defined resource deletion callback function, to be called by DXUT immediately after the Direct3D 9 device is destroyed.

VOID LPDXUTCALLBACKD3D9DEVICEDESTROYED(
  void* pUserContext
);

Parameters

pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The LPDXUTCALLBACKD3D9DEVICEDESTROYED callback function is the appropriate location for the application release Direct3D 9 device resources that were created in the LPDXUTCALLBACKD3D9DEVICECREATED callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D9DeviceDestroyed


LPDXUTCALLBACKD3D9DEVICELOST

Application-defined callback function, to be called by DXUT immediately after the Direct3D 9 device is lost.

VOID LPDXUTCALLBACKD3D9DEVICELOST(
  void* pUserContext
);

Parameters

pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The LPDXUTCALLBACKD3D9DEVICELOST callback function is the appropriate location for the application release Direct3D 9 device resources that were created in the LPDXUTCALLBACKD3D9DEVICERESET callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D9DeviceLost


LPDXUTCALLBACKD3D9DEVICERESET

Application-defined callback function, called by DXUT after the Direct3D 9 device has been reset. Passes a pointer to the newly created Direct3D 9 device.

HRESULT LPDXUTCALLBACKD3D9DEVICERESET(
  IDirect3DDevice9 * pd3dDevice,
  CONST D3DSURFACE_DESC * pBackBufferSurfaceDesc,
  void* pUserContext
);

Parameters

pd3dDevice
[out] Pointer to the newly created Direct3D 9 device.
pBackBufferSurfaceDesc
[out] Pointer to the back buffer surface description
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

In general, if no error occurs, program the function to return S_OK. Program the function to return an HRESULT error code if the function fails. If DXUT receives a failure HRESULT code, it shuts down the application.

Remarks

The LPDXUTCALLBACKD3D9DEVICERESET callback function is the appropriate location for the application to create Direct3D 9 device resources that won't live through a device reset such as D3DPOOL_DEFAULT or that are tied to the back buffer size. Resources created in the LPDXUTCALLBACKD3D9DEVICERESET callback function should be released in the LPDXUTCALLBACKD3D9DEVICELOST callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D9DeviceReset


LPDXUTCALLBACKD3D9FRAMERENDER

Application-defined callback function that allows for rendering the scene using a Direct3D 9 device. This function is called by DXUT at the end of every frame, and whenever the application needs to paint the scene.

VOID LPDXUTCALLBACKD3D9FRAMERENDER(
  IDirect3DDevice9 * pd3dDevice,
  DOUBLE fTime,
  FLOAT fElapsedTime,
  void* pUserContext
);

Parameters

pd3dDevice
[in] Pointer to the Direct3D 9 device used for rendering.
fTime
[in] Time elapsed since the application started, in seconds.
fElapsedTime
[in] Time elapsed since the last frame, in seconds.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The LPDXUTCALLBACKD3D9FRAMERENDER callback function is the appropriate location for the application to render the current scene using the Direct3D 9 device. The LPDXUTCALLBACKFRAMEMOVE callback function will be called once per frame, while LPDXUTCALLBACKD3D9FRAMERENDER will be called when the scene needs to be rendered, which might be more than once per frame.

DXUT will call this function after the LPDXUTCALLBACKFRAMEMOVE callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D9FrameRender


LPDXUTCALLBACKD3D10DEVICECREATED

Application-defined resource creation callback function, called by DXUT after the Direct3D 10 device is created. Passes a pointer to the newly created Direct3D 10 device.

HRESULT LPDXUTCALLBACKD3D10DEVICECREATED(
  ID3D10Device * pd3dDevice,
  CONST DXGI_SURFACE_DESC * pBackBufferSurfaceDesc,
  void* pUserContext
);

Parameters

pd3dDevice
[out] Pointer to the newly created ID3D10Device Interface device.
pBackBufferSurfaceDesc
[out] Pointer to the backbuffer surface description.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

In general, if no error occurs, program the function to return S_OK. Program the function to return an HRESULT failure code if the function fails. If DXUT receives a failure HRESULT code, it shuts down the application.

Remarks

This callback function is the appropriate location for the application to create resources in D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory, since these resources do not need to be reloaded whenever the device is reset. Resources created in this callback function should be deleted in the LPDXUTCALLBACKD3D10DEVICEDESTROYED callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D10DeviceCreated


LPDXUTCALLBACKD3D10DEVICEDESTROYED

Application-defined resource deletion callback function, to be called by DXUT immediately after the Direct3D 10 device is destroyed.

VOID LPDXUTCALLBACKD3D10DEVICEDESTROYED(
  void* pUserContext
);

Parameters

pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The LPDXUTCALLBACKD3D10DEVICEDESTROYED callback function is the appropriate location for the application release Direct3D 10 device resources that were created in the LPDXUTCALLBACKD3D10DEVICECREATED callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D10DeviceDestroyed


LPDXUTCALLBACKD3D10FRAMERENDER

Application-defined callback function that allows for rendering the scene using the Direct3D 10 device. This function is called by DXUT at the end of every frame, and whenever the application needs to paint the scene.

VOID LPDXUTCALLBACKD3D10FRAMERENDER(
  ID3D10Device * pd3dDevice,
  DOUBLE fTime,
  FLOAT fElapsedTime,
  void* pUserContext
);

Parameters

pd3dDevice
[in] Pointer to the ID3D10Device Interface device used for rendering.
fTime
[in] Time elapsed since the application started, in seconds.
fElapsedTime
[in] Time elapsed since the last frame, in seconds.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The LPDXUTCALLBACKD3D10FRAMERENDER callback function is the appropriate location for the application to render the current scene. The LPDXUTCALLBACKFRAMEMOVE callback function will be called once per frame, while LPDXUTCALLBACKD3D10FRAMERENDER will be called when the scene needs to be rendered, which might be more than once per frame.

DXUT will call this function after the LPDXUTCALLBACKFRAMEMOVE callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D10FrameRender


LPDXUTCALLBACKD3D10SWAPCHAINRELEASING

Application-defined callback function called when the Direct3D 10 swap chain is being released.

VOID LPDXUTCALLBACKD3D10SWAPCHAINRELEASING(
  void* pUserContext
);

Parameters

pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The LPDXUTCALLBACKD3D10SWAPCHAINRELEASING callback function is the appropriate location for the application release Direct3D 10 device resources that were created in the LPDXUTCALLBACKD3D10SWAPCHAINRESIZED callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D10SwapChainReleasing


LPDXUTCALLBACKD3D10SWAPCHAINRESIZED

Application-defined callback function that is called when the Direct3D 10 swap chain is resized.

HRESULT LPDXUTCALLBACKD3D10SWAPCHAINRESIZED(
  ID3D10Device * pd3dDevice,
  IDXGISwapChain * pSwapChain,
  CONST D3DSURFACE_DESC * pBackBufferSurfaceDesc,
  void* pUserContext
);

Parameters

pd3dDevice
[out] Pointer to the newly created ID3D10Device Interface device.
pSwapChain
[out] Pointer to a IDXGISwapChain Interface.
pBackBufferSurfaceDesc
[out] Pointer to the back buffer surface description.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

In general, if no error occurs, program the function to return S_OK. Program the function to return an HRESULT error code if the function fails. If DXUT receives a failure HRESULT code, it shuts down the application.

Remarks

The LPDXUTCALLBACKD3D10SWAPCHAINRESIZED callback function is the appropriate location for the application to create Direct3D 10 device resources that depend on the back buffer such as a render target that needs to match the size of the back buffer. Resources created in the LPDXUTCALLBACKD3D10SWAPCHAINRESIZED callback function should be released in the LPDXUTCALLBACKD3D10SWAPCHAINRELEASING callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D10SwapChainResized


LPDXUTCALLBACKDEVICEREMOVED

Application-defined callback function, called by DXUT to allow the application to respond to a Direct3D device removed event.

bool LPDXUTCALLBACKDEVICEREMOVED(
  void* pUserContext
);

Parameters

pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

Program the application to return true to search for a new device. If the application returns false, DXUT will not try to find a new device and will shutdown.

Remarks

If the Direct3D device is removed such as when a laptop undocks from a docking station, DXUT notifies that application with the LPDXUTCALLBACKDEVICEREMOVED callback. This allows the application to respond to this event. If the application returns false from within the callback, DXUT will not try to find a new device and will shutdown.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackDeviceRemoved


LPDXUTCALLBACKFRAMEMOVE

Application-defined callback function that allows for updating the scene. This function is called by DXUT once each frame, before the application renders the scene.

VOID LPDXUTCALLBACKFRAMEMOVE(
  DOUBLE fTime,
  FLOAT fElapsedTime,
  void* pUserContext
);

Parameters

fTime
[in] Time elapsed since the application started, in seconds.
fElapsedTime
[in] Time elapsed since the last frame, in seconds.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The LPDXUTCALLBACKFRAMEMOVE callback function is the appropriate location for the application to handle updates to the scene. However, LPDXUTCALLBACKFRAMEMOVE is not intended to contain actual rendering calls, which should instead be placed in the LPDXUTCALLBACKD3D9FRAMERENDER or LPDXUTCALLBACKD3D10FRAMERENDER callback function. These callbacks is called when rendering with either Direct3D 9 or Direct3D 10 respectively.

The LPDXUTCALLBACKFRAMEMOVE callback function will be called once per frame, while the render callback function will be called whenever the scene needs to be rendered, which might be more than once per frame on rare occasion if a WM_PAINT message occurs.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackFrameMove


LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE

Application-defined callback function, called by DXUT to build an enumerated list of all possible Direct3D 9 devices. DXUT then selects the best device for creation among this list. This callback function allows the application to prevent unwanted devices from being added to the list.

bool LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE(
  D3DCAPS9* pCaps,
  D3DFORMAT AdapterFormat,
  D3DFORMAT BackBufferFormat,
  bool bWindowed,
  void* pUserContext
);

Parameters

pCaps
[in] Pointer to the D3DCAPS9 capabilities of the Direct3D 9 device
AdapterFormat
[in] Format of the Direct3D 9 adapter
BackBufferFormat
[in] Format of the Direct3D 9 backbuffer
bWindowed
[in] Indicates windowed mode. TRUE if the application runs windowed; FALSE if the application runs full-screen.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

Program the application to return TRUE if the device settings are acceptable. If not, the application should return FALSE.

Remarks

This function's parameters describe a set of unique valid device settings that could be used to create a device. The application can examine and reject this set if desired.

All possible unique valid combinations of the following device settings are sent to this callback function:

  • pCaps
  • AdapterFormat
  • BackBufferFormat
  • bWindowed

After the application rejects the unwanted device settings combinations, DXUT picks the best of the remaining combinations and uses that best combination to create the device. Before creating the device, DXUT calls LPDXUTCALLBACKMODIFYDEVICESETTINGS to allow the application to change any of the device creation settings.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D9DeviceAcceptable


LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE

Application-defined callback function, called by DXUT to build an enumerated list of all possible Direct3D 10 devices. DXUT then selects the best device for creation among this list. This callback function allows the application to prevent unwanted devices from being added to the list.

bool LPDXUTCALLBACKISD3D10DEVICEACCEPTABLE(
  UINT Adapter,
  UINT Output,
  D3D10_DRIVER_TYPE DeviceType,
  DXGI_FORMAT BackBufferFormat,
  bool bWindowed,
  void* pUserContext
);

Parameters

Adapter
[in] Adapter ordinal of the Direct3D 10 device. See IDXGIFactory::EnumAdapters.
Output
[in] Output ordinal of the Direct3D 10 device. See IDXGIAdapter::EnumOutputs.
DeviceType
[in] Driver type of the Direct3D 10 device. See D3D10_DRIVER_TYPE.
BackBufferFormat
[in] Back buffer format of the Direct3D 10 device. See DXGI_FORMAT.
bWindowed
[in] Indicates windowed mode. TRUE if the application runs windowed; FALSE if the application runs full-screen.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

Program the application to return TRUE if the device settings are acceptable. If not, the application should return FALSE.

Remarks

This function's parameters describe a set of unique valid device settings that could be used to create a device. The application can examine and reject this set if desired.

All possible unique valid combinations of the following device settings are sent to this callback function:

  • Adapter
  • Output
  • DeviceType
  • BackBufferFormat
  • bWindowed

After the application rejects the unwanted device settings combinations, DXUT picks the best of the remaining combinations and uses that best combination to create the device. Before creating the device, DXUT calls LPDXUTCALLBACKMODIFYDEVICESETTINGS to allow the application to change any of the device creation settings.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackD3D10DeviceAcceptable


LPDXUTCALLBACKKEYBOARD

Application-defined keyboard event callback function, called by DXUT.

VOID LPDXUTCALLBACKKEYBOARD(
  UINT nChar,
  bool bKeyDown,
  bool bAltDown,
  void* pUserContext
);

Parameters

nChar
[in] A virtual-key code for the key. See Virtual-Key Codes for a listing.
bKeyDown
[in] TRUE if key is down. FALSE if the key is up
bAltDown
[in] TRUE if the ALT key is also down.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The pCallbackKeyboard keyboard event callback function will be called when any keyboard event occurs.

This callback mechanism is provided to simplify handling keyboard messages through the windows message pump, but does not preclude the application from handling those messages directly through the LPDXUTCALLBACKMSGPROC callback.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackKeyboard


LPDXUTCALLBACKMODIFYDEVICESETTINGS

Application-defined callback function, called by DXUT to allow changes in device settings before the device is created.

bool LPDXUTCALLBACKMODIFYDEVICESETTINGS(
  DXUTDeviceSettings * pDeviceSettings,
  void* pUserContext
);

Parameters

pDeviceSettings
[in] Pointer to a DXUTDeviceSettings structure that contains the settings for the new device.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

Program the application to return true to continue creating the device. If not, the application should return false to continue using the current device if one exists.

Remarks

Before a device is created by DXUT, the LPDXUTCALLBACKMODIFYDEVICESETTINGS callback will be called to allow the application to examine or change the device settings before the device is created. This allows an application to modify the device creation settings as it sees fit.

This callback also allows applications to reject changing the device altogether. Returning false from inside this callback will notify DXUT to keep using the current device instead of changing to the new device.

Anything in pDeviceSettings can be changed by the application. DXUT will not prevent the failure of device creation caused by changes to device settings.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackDeviceChanging


LPDXUTCALLBACKMOUSE

Application-defined mouse event callback function, called by DXUT when it receives mouse events.

VOID LPDXUTCALLBACKMOUSE(
  bool bLeftButtonDown,
  bool bRightButtonDown,
  bool bMiddleButtonDown,
  bool bSideButton1Down,
  bool bSideButton2Down,
  INT nMouseWheelDelta,
  INT xPos,
  INT yPos,
  void* pUserContext
);

Parameters

bLeftButtonDown
[in] The left mouse button is down.
bRightButtonDown
[in] The right mouse button is down.
bMiddleButtonDown
[in] The middle mouse button is down.
bSideButton1Down
[in] Windows 2000/Windows XP: The first side button is down.
bSideButton2Down
[in] Windows 2000/Windows XP: The second side button is down.
nMouseWheelDelta
[in] The distance and direction the mouse wheel has rolled, expressed in multiples or divisions of WHEEL_DELTA, which is 120. A positive value indicates that the wheel was rotated forward, away from the user; a negative value indicates that the wheel was rotated backward, toward the user.
xPos
[in] x-coordinate of the pointer, relative to the upper-left corner of the client area.
yPos
[in] y-coordinate of the pointer, relative to the upper-left corner of the client area.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

The pCallbackMouse mouse event callback function will be called when any mouse events occurs

This callback mechanism is provided to simplify handling mouse messages through the Windows message pump, but does not preclude the application from handling those messages directly in the LPDXUTCALLBACKMSGPROC callback function.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackMouse


LPDXUTCALLBACKMSGPROC

Application-defined function that processes messages from DXUT message pump.

LRESULT LPDXUTCALLBACKMSGPROC(
  HWND hWnd,
  UINT uMsg,
  WPARAM wParam,
  LPARAM lParam,
  bool * pbNoFurtherProcessing,
  void* pUserContext
);

Parameters

hWnd
[in] Handle to the window.
uMsg
[in] Specifies the message. See WindowProc for details.
wParam
[in] Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.
lParam
[in] Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.
pbNoFurtherProcessing
[out] If TRUE, prevents DXUT from futher handling the message.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

Returns zero if the function has processed window messages successfully; otherwise, returns a nonzero value.

Remarks

This function and its parameters are similar to to the Windows WindowProc function.

With the use of the pbNoFurtherProcessing parameter, the application can control DXUT's level of involvement in processing window messages. If the application sets pbNoFurtherProcessing to TRUE in the call to LPDXUTCALLBACKMSGPROC, DXUT will not process the message and will immediately return with the value returned by LPDXUTCALLBACKMSGPROC. If the application sets pbNoFurtherProcessing to FALSE, DXUT will handle window management events.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetCallbackMsgProc, WindowProc


LPDXUTCALLBACKTIMER

A timer to be called at specified time intervals by DXUT.

VOID LPDXUTCALLBACKTIMER(
  UINT idEvent,
  void* pUserContext
);

Parameters

idEvent
[in] Specifies a nonzero timer event ID. Indicates which timer generated the event, allowing the application to use a single callback function for multiple timers.
pUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. The default value is NULL

Return Values

No return value.

Remarks

DXUT will call this function at the start of the frame, before calling LPDXUTCALLBACKFRAMEMOVE or LPDXUTCALLBACKD3D10FRAMERENDER.

Requirements

Header: Declared in DXUT.h.

See Also

DXUTSetTimer, DXUTKillTimer


DXUT Structures

DXUT supplies the following structures:

  • DXUTD3D10DeviceSettings
  • DXUTD3D9DeviceSettings
  • DXUTDeviceSettings
  • DXUTMatchOptions


DXUTD3D9DeviceSettings

Describes the settings used to create a Direct3D 9 device.

typedef struct DXUTD3D9DeviceSettings {
    UINT AdapterOrdinal;
    D3DDEVTYPE DeviceType;
    D3DFORMAT AdapterFormat;
    DWORD BehaviorFlags;
    D3DPRESENT_PARAMETERS pp;
} DXUTD3D9DeviceSettings, *LPDXUTD3D9DeviceSettings;

Members

AdapterOrdinal
Ordinal number that denotes the display adapter.
DeviceType
Enumerated type of the device.
AdapterFormat
Adapter surface format.
BehaviorFlags
Behavior flags. This member can be a combination of one or more of the D3DCREATE values.
pp
Presentation parameters structure.

See Also

DXUTDeviceSettings


DXUTD3D10DeviceSettings

Describes the settings used to create/use the Direct3D 10 device.

typedef struct DXUTD3D10DeviceSettings {
    UINT AdapterOrdinal;
    D3D10_DRIVER_TYPE DriverType;
    UINT Output;
    DXGI_SWAP_CHAIN_DESC sd;
    UINT32 CreateFlags;
    UINT32 SyncInterval;
    DWORD PresentFlags;
    BOOL AutoCreateDepthStencil;
    DXGI_FORMAT AutoDepthStencilFormat;
} DXUTD3D10DeviceSettings, *LPDXUTD3D10DeviceSettings;

Members

AdapterOrdinal
Adapter ordinal of the Direct3D 10 device. See IDXGIFactory::EnumAdapters.
DriverType
Driver type of the Direct3D 10 device. See D3D10_DRIVER_TYPE.
Output
Output ordinal of the Direct3D 10 device. See IDXGIAdapter::EnumOutputs.
sd
Description of the swap chain. See IDXGIAdapter::EnumOutputs.
CreateFlags
Flags used to create the Direct3D 10 device. See D3D10_CREATE_DEVICE_FLAG.
SyncInterval
Internal used for vertical sync. See IDXGISwapChain::Present.
PresentFlags
Present flags. See IDXGISwapChain::Present.
AutoCreateDepthStencil
DXUT will create the depth stencil resource and view if TRUE.
AutoDepthStencilFormat
Format of the depth stencil. See DXGI_FORMAT.

See Also

DXUTDeviceSettings


DXUTDeviceSettings

A union of settings describing how to create the Direct3D 9 or Direct3D 10 device.

typedef struct DXUTDeviceSettings {
    DXUTDeviceVersion ver;
    union {
        DXUTD3D9DeviceSettings d3d9;
        DXUTD3D10DeviceSettings d3d10;
    };
} DXUTDeviceSettings, *LPDXUTDeviceSettings;

Members

ver
Indicates whether the settings structure is for a Direct3D 9 or Direct3D 10 device.
d3d9
Device settings for Direct3D 9 device. Only valid if ver is DXUT_D3D9_DEVICE.
d3d10
Device settings for Direct3D 10 device. Only valid if ver is DXUT_D3D10_DEVICE.

Remarks

The DXUTDeviceSettings can only describe a single device because the DXUTD3D9DeviceSettings and DXUTD3D10DeviceSettings member variables are unioned together. The DXUTDeviceVersion indicates which of these structures is valid.

See Also

DXUTDeviceVersion, DXUTD3D10DeviceSettings, DXUTD3D9DeviceSettings


DXUTMatchOptions

Describes match options for finding valid device settings using the DXUTFindValidDeviceSettings function. Each member of this structure corresponds to a setting described by the DXUTDeviceSettings structure.

Default values are used when a member is set to DXUTMT_IGNORE_INPUT. See Remarks.

typedef struct DXUTMatchOptions {
    DXUT_MATCH_TYPE eAPIVersion;
    DXUT_MATCH_TYPE eAdapterOrdinal;
    DXUT_MATCH_TYPE eOutput;
    DXUT_MATCH_TYPE eDeviceType;
    DXUT_MATCH_TYPE eWindowed;
    DXUT_MATCH_TYPE eAdapterFormat;
    DXUT_MATCH_TYPE eVertexProcessing;
    DXUT_MATCH_TYPE eResolution;
    DXUT_MATCH_TYPE eBackBufferFormat;
    DXUT_MATCH_TYPE eBackBufferCount;
    DXUT_MATCH_TYPE eMultiSample;
    DXUT_MATCH_TYPE eSwapEffect;
    DXUT_MATCH_TYPE eDepthFormat;
    DXUT_MATCH_TYPE eStencilFormat;
    DXUT_MATCH_TYPE ePresentFlags;
    DXUT_MATCH_TYPE eRefreshRate;
    DXUT_MATCH_TYPE ePresentInterval;
} DXUTMatchOptions, *LPDXUTMatchOptions;

Members

eAPIVersion
Match type for the API version.
eAdapterOrdinal
Match type for the display adapter ordinal.
eOutput
Match type for the adapter output ordinal.
eDeviceType
Match type for the enumerated type of the device. If set to DXUTMT_IGNORE_INPUT, then the default value is D3DDEVTYPE_HAL.
eWindowed
Match type for the windowed or full-screen mode. if set to DXUTMT_IGNORE_INPUT, then the default value is windowed mode (TRUE).
eAdapterFormat
Match type for the adapter surface format. If set to DXUTMT_IGNORE_INPUT, then the default value is the desktop display mode, or D3DFMT_X8R8G8B8 if the desktop display mode is less than 32 bits.
eVertexProcessing
Match type for the vertex processing flags D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, or D3DCREATE_SOFTWARE_VERTEXPROCESSING. if set to DXUTMT_IGNORE_INPUT, then the default value is D3DCREATE_HARDWARE_VERTEXPROCESSING.
eResolution
Match type for the display mode resolution. if set to DXUTMT_IGNORE_INPUT, then the default value is 640 x 480 pixels for windowed mode, or the desktop resolution for full-screen mode.
eBackBufferFormat
Match type for the back buffer format. if BackBufferFormat is set to DXUTMT_IGNORE_INPUT, then the default value is to match the adapter format.
eBackBufferCount
Match type for the number of back buffers. if BackBufferCount is set to DXUTMT_IGNORE_INPUT, then the default value is 2 for triple buffering.
eMultiSample
Match type for the quality level. if set to DXUTMT_IGNORE_INPUT, then the default value is to disable multisampling (MultiSampleQuality = 0).
eSwapEffect
Match type for the swap effect. if set to DXUTMT_IGNORE_INPUT, then the default value is D3DSWAPEFFECT_DISCARD.
eDepthFormat
Match type for the depth format of the automatic depth-stencil surface that the device will create. If both eDepthFormat and eStencilFormat are set to DXUTMT_IGNORE_INPUT, then the default value is D3DFMT_D16 if the backbuffer format is 16 bits or less, or D3DFMT_D32 otherwise.
eStencilFormat
Match type for the stencil format of the automatic depth-stencil surface that the device will create. if both eDepthFormat and eStencilFormat are set to DXUTMT_IGNORE_INPUT, then the default value is D3DFMT_D16 if the backbuffer format is 16 bits or less, or D3DFMT_D32 otherwise.
ePresentFlags
Match type for the presentation parameters flags. if set to DXUTMT_IGNORE_INPUT, then the default value is D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL.
eRefreshRate
Match type for the rate at which the display adapter refreshes the screen. If set to DXUTMT_IGNORE_INPUT, then the default value is 0, indicating windowed mode.
ePresentInterval
Match type for the presentation interval. if set to DXUTMT_IGNORE_INPUT, then the default value is D3DPRESENT_INTERVAL_IMMEDIATE for windowed mode, or D3DPRESENT_INTERVAL_DEFAULT for full-screen mode.

Remarks

For each member of this structure, match options are specified using the constant values of the DXUT_MATCH_TYPE enumeration, as in the following code example.

matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT;

To use default device settings instead, use the DXUTMT_IGNORE_INPUT flag as follows:

matchOptions.eResolution = DXUTMT_IGNORE_INPUT;

See Also

DXUT_MATCH_TYPE, DXUTDeviceSettings, DXUTFindValidDeviceSettings


DXUT Enumerations

DXUT supplies the following enumerated type:

  • DXUT_MATCH_TYPE
  • DXUTDeviceVersion


DXUTDeviceVersion

Indicates the version of Direct3D device.

typedef enum DXUTDeviceVersion
{
    DXUT_D3D9_DEVICE,
    DXUT_D3D10_DEVICE,
} DXUTDeviceVersion;

Constants

DXUT_D3D9_DEVICE
Indicates that this is a Direct3D 9 device
DXUT_D3D10_DEVICE
Indicates that this is a Direct3D 10 device

See Also

DXUTDeviceSettings


DXUT_MATCH_TYPE

Describes how to match input device settings when creating a new device with a function.

typedef enum DXUT_MATCH_TYPE
{
    DXUTMT_IGNORE_INPUT = 0,
    DXUTMT_PRESERVE_INPUT,
    DXUTMT_CLOSEST_TO_INPUT,
} DXUT_MATCH_TYPE, *LPDXUT_MATCH_TYPE;

Constants

DXUTMT_IGNORE_INPUT
Ignore the device setting input, and return a device setting as close as possible to a default device setting.
DXUTMT_PRESERVE_INPUT
Return without changing the device setting that was given as input to the function.
DXUTMT_CLOSEST_TO_INPUT
Return a device setting as close as possible to the device setting that was given as input to the function.

See Also

DXUTCreateDeviceFromSettings


DXUT Constants

DXUT supplies the following constant values:

Constants

  • DXUTERR


DXUTERR

The following table lists the values that can be returned by functions in DXUT.

#define | Description
DXUTERR_NODIRECT3D | Could not initialize Direct3D.
DXUTERR_NOCOMPATIBLEDEVICES | Could not find any compatible Direct3D devices.
DXUTERR_MEDIANOTFOUND | Could not find required media.
DXUTERR_NONZEROREFCOUNT | The Direct3D device has a non-zero reference count, meaning some objects were not released.
DXUTERR_CREATINGDEVICE | An error occurred when attempting to create an Direct3D device.
DXUTERR_RESETTINGDEVICE | An error occurred when attempting to reset an Direct3D device.
DXUTERR_CREATINGDEVICEOBJECTS | An error occurred in the device create callback function.
DXUTERR_RESETTINGDEVICEOBJECTS | An error occurred in the device reset callback function.
DXUTERR_DEVICEREMOVED | The Direct3D device was removed.

Requirements

Header: Declared in DXUT.h.


Overview of the SDK Mesh File Format

Disclaimer:

The DXUT Mesh format (.sdkmesh) is not a recommended file format for shipping titles. It was designed to meet the specific needs of the SDK samples. Any real-world application should avoid this file format in favor of a destination format that meets the specific needs of the application.

Overview of the SDK Mesh File Format

The SDK mesh format used in the samples is a binary format created for the sole purpose of providing an easy way to get mesh data into the SDK sample and tutorial applications. Because of this, it is a very simple format that will not meet the needs of most game developers.

The file consists of multiple fixed sized structures that contain offsets to any variable sized data that may be associated with the structure. For example, the main file header contains a count for the number of materials stored in the file as well as an offset from the beginning of the file to the first material.

File Layout

The mesh file format is layed out as follows:

The SDK mesh format contains two main sections of data.

  • Static Data
  • Buffer Data

Static Data

The static data is first in the file. This contains the overall file header as well as vertex buffer, index buffer, mesh, subset, frame, and material information. The mesh class loads all of this into memory as one giant chunk of data an sets some internal pointers to various parts of the data in order to reduce load times. Note, that this technically may load more information into memory than is absolutely necessary. Real-world applications should ensure their file format meets their needs perfectly in order to avoid loading unneccessary information into memory.

For the SDK samples, it was best to lay out the data in the following order.

  • Main file header
  • A Vertex Buffer description structure for each VB
    • This structure contains an offset to the actual vertex data
    • Vertex buffers can be shared between meshes
  • An Index Buffer description structure for each IB
    • This structure contains an offset to the actual index data
    • Index buffers can be shared between meshes
  • A Mesh structure for each mesh in the file
    • This structure contains a list of vertex buffers references and one index buffer references
    • This structure contains an offset to a subset index list
    • This structure contains an offset to a frame/bone influence list
  • A Subset structure for each subset in the file
    • Subsets can be shared between meshes in this format
  • A heirarchical list of Frames
  • A list of Materials
  • Subset index data: pointed to by the Mesh structures
  • Influence index data: pointed to by the Mesh structures

Buffer Data

The remaining information in the file is the vertex and index data. In the mesh class in DXUt, this buffer data is loaded into memory and consumed by the vertex and index buffer creation calls before being discarded.

Supplemental Animation File Format

In addition to the SD mesh format, some samples will also use a supplemental animation file format to load animation data. The layout of this format is simply a header followed by a list of frame references that should match up with the frames in the mesh file. Each frame reference contains an offset to a list of keyframes. For the purposes of the samples, all frame references have the same number of keyframes.


Direct3D 9 Graphics

Discover the features of Direct3D 9 in one of these sections:

  • Programming Guide (Direct3D 9) - This section contains architecture descriptions, functional block diagrams, descriptions of the building blocks in the pipeline, code snippets, and sample applications.
  • Direct3D 9 Tools - This section contains tools such as the Shader Debugger for debugging DirectX applications.
  • Tutorials and Samples - This section contains tutorials and sample applications for using DirectX graphics.
  • Reference - This section contains the reference pages for the Direct3D and D3DX API. This includes the syntax for the API methods, functions, instructions, and data structures. It includes an explanation of how each API method works and often includes code snippets.

See Also

DirectX Graphics


Converting to Direct3D 9

The following features were changed in Microsoft Direct3D 9. If you are using these features, see the changes listed below to help you port your application to Direct3D 9.

  • BaseVertexIndex Changes
  • CreateImageSurface Changes
  • D3DENUM_NO_WHQL_LEVEL Changes
  • Create Resource Changes
  • EnumAdapterModes Changes
  • Get/SetStreamSource_Changes
  • Multisampling Quality Changes
  • ResourceManagerDiscardBytes Changes
  • SetSoftwareVertexProcessing Changes
  • Texture Sampler Changes
  • Vertex Declaration Changes
  • Intervals,_and_SwapEffects_Changes

BaseVertexIndex Changes

In DirectX 8.x, IDirect3DDevice8::SetIndices required a pointer to the index buffer and a BaseVertexIndex for the starting position in the vertex buffer. An application batching different objects into the vertex buffer had to switch the index buffer (or make a call to IDirect3DDevice8::SetIndices) before calling IDirect3DDevice8::DrawIndexedPrimitive.

In Direct3D 9, the starting position in the vertex buffer, BaseVertexIndex, has been moved to IDirect3DDevice9::DrawIndexedPrimitive, and its data type changed from a DWORD to an INT.

HRESULT IDirect3DDevice9::DrawIndexedPrimitive(
    D3DPRIMITIVETYPE PrimType,
    INT BaseVertexIndex,
    UINT minIndex,
    UINT NumVertices,
    UINT startIndex,
    UINT primCount);

HRESULT SetIndices(IDirect3DIndexBuffer9* pIndexData);

CreateImageSurface Changes

IDirect3DDevice8::CreateImageSurface was renamed IDirect3DDevice9::CreateOffscreenPlainSurface. An additional parameter that takes a D3DPOOL type was added. D3DPOOL_SCRATCH will return a surface that has identical characteristics to a surface created by IDirect3DDevice8::CreateImageSurface. D3DPOOL_DEFAULT is the appropriate pool for use with IDirect3DDevice9::StretchRect and IDirect3DDevice9::ColorFill.

D3DENUM_NO_WHQL_LEVEL Changes

Applications now have to explicitly ask for the Microsoft Windows Hardware Quality Labs (WHQL) because the response takes relatively long (a few seconds). D3DENUM_NO_WHQL_LEVEL has been removed and D3DENUM_WHQL_LEVEL has been added.

Create Resource Changes

A handle has been added to several methods and should be set to NULL. The methods affected include:

  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVolumeTexture
  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateVertexBuffer
  • IDirect3DDevice9::CreateIndexBuffer
  • IDirect3DDevice9::CreateRenderTarget
  • IDirect3DDevice9::CreateDepthStencilSurface
  • IDirect3DDevice9::CreateOffscreenPlainSurface

EnumAdapterModes Changes

The IDirect3D9::EnumAdapterModes now takes a D3DFORMAT.

HRESULT IDirect3D9::EnumAdapterModes(
       UINT Adapter,
       D3DFORMAT Format,
       UINT Mode,
       D3DDISPLAYMODE *pMode);

The format supports an expanding set of display modes. To protect applications from enumerating formats that were not invented when the application shipped, the application must tell Direct3D the format for the display modes that should be enumerated. The resulting array of display modes will differ only by width, height, and refresh rate.

The application specifies a pixel format and the enumeration is restricted to those display modes that exactly match the format. The following is a list of the allowed formats:

  • D3DFMT_A1R5G5B5
  • D3DFMT_A2B10G10R10
  • D3DFMT_A8R8G8B8
  • D3DFMT_R5G6B5
  • D3DFMT_X1R5G5B5
  • D3DFMT_X8R8G8B8

Enumeration is equivalent for alpha and nonalpha versions of the same format. The returned Format will always be filled with the same format supplied by the application.

This method treats 565 and 555 as equivalent, and returns the correct version in the Format. The difference comes into play only when the application locks the back buffer, and there is an explicit flag that the application must set in order to accomplish this.

Get/SetStreamSource Changes

One parameter has been added to the IDirect3DDevice9::GetStreamSource and IDirect3DDevice9::SetStreamSource methods. The offset is the number of bytes between the beginning of the stream and the beginning of the vertex data. It is measured in bytes. This enables the pipeline to support stream offsets. To find out if the device supports stream offsets, see D3DDEVCAPS2_STREAMOFFSET.

HRESULT GetStreamSource(
    UINT StreamNumber,
    IDirect3DVertexBuffer9 **ppStreamData,
    UINT *pOffsetInBytes,
    UINT *pStride);

Multisampling Quality Changes

Previously, there was only the D3DMULTISAMPLE_TYPE enumeration. Direct3D 9 retains this enumeration and adds the idea of a quality level for each element of the enumeration. The quality level indicates a trade-off between visual quality and performance by indicating the number of maskable samples (in the sense of D3DRS_MULTISAMPLEMASK).

An application should choose how many maskable samples it requires, and then consult pQualityLevels. If nonzero, this value indicates the number of quality levels the application can pass to the various creation functions through MultiSampleQuality. Because drivers expose all their multisample schemes as quality levels at D3DMULTISAMPLE_NONMASKABLE, you can enumerate all available multisampling schemes through this one type if your application does not need to mask samples.

The D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE caps bit has been retired. This bit used to mean that the multisampling method did not support write masks, and could not be toggled on and off between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene. Such nonmaskable methods are now exposed through D3DMULTISAMPLE_NONMASKABLE.

HRESULT CheckDeviceMultiSampleType(
       UINT Adapter,
       D3DDEVTYPE DeviceType,
       D3DFORMAT SurfaceFormat,
       BOOL Windowed,
       D3DMULTISAMPLE_TYPE MultiSampleType,
       DWORD * pQualityLevels);

There is a different maximum for each number of maskable samples. For example, D3DMULTISAMPLE_4_SAMPLES might have three levels of quality, while D3DMULTISAMPLE_2_SAMPLES might have only one. There are at most eight levels of quality for each number of maskable samples (the driver is not allowed to express more). The quality ranges from zero to (*pQualityLevels - 1).

ResourceManagerDiscardBytes Changes

ResourceManagerDiscardBytes has been replaced by IDirect3DDevice9::EvictManagedResources. It can evict all resources, both Direct3D and driver resources.

The resource manager is now consulted when a resource (whether managed or nonmanaged) fails creation because there is insufficient video memory. The manager will automatically be asked to free enough resources for the creation to succeed. In DirectX 8.0, this was not an automated process.

SetSoftwareVertexProcessing Changes

An application can create a mixed-mode device to use software and hardware vertex processing.

To switch between the two vertex processing modes in DirectX 8.x, call IDirect3DDevice8::SetRenderState. This has been replaced with IDirect3DDevice9::SetSoftwareVertexProcessing to ease problems caused by state blocks. This new method is not recorded by state blocks.

Texture Sampler Changes

Direct3D 9 supports up to sixteen texture surfaces in one pass using the pixel shader 2_0 model; however, the number of texture coordinates remains limited to eight. Texture stage state is associated with surfaces, coordinate sets, vertex processing, and pixel processing. To manage these differences at compile time, IDirect3DDevice9::SetTextureStageState has been broken into two methods:

  • IDirect3DDevice9::SetTextureStageState will still be used for texture coordinate state, such as wrap modes and texture coordinate generation.
  • IDirect3DDevice9::SetSamplerState has been added and will now be used for filtering, tiling, clamping, MIPLOD, and so forth. This will work for up to sixteen samplers.

SetTextureStageState Changes

IDirect3DDevice9::SetTextureStageState now sets the following states:

  • Fixed function vertex processing state. This state controls the manipulation of texture coordinates D3DTSS_TEXTURETRANSFORMFLAGS and D3DTSS_TEXCOORDINDEX. Up to eight of each can be set (because eight texture coordinates are always supported). D3DTSS_TEXCOORDINDEX is a fixed function vertex processing state. If a programmable vertex shader is used, this state is ignored.
  • Fixed function pixel shader state (the legacy TextureStageState).
    • D3DTSS_ALPHAARG0
    • D3DTSS_ALPHAARG1
    • D3DTSS_ALPHAARG2
    • D3DTSS_ALPHAOP
    • D3DTSS_BUMPENVLOFFSET
    • D3DTSS_BUMPENVLSCALE
    • D3DTSS_BUMPENVMAT00
    • D3DTSS_BUMPENVMAT01
    • D3DTSS_BUMPENVMAT10
    • D3DTSS_BUMPENVMAT11
    • D3DTSS_COLORARG0
    • D3DTSS_COLORARG1
    • D3DTSS_COLORARG2
    • D3DTSS_COLOROP
    • D3DTSS_RESULTARG

    The number of fixed function pixel shader states that can be set is less than or equal to the number represented by MaxTextureBlendStages.

The number of texture samplers available to the application is determined by the pixel shader version, as indicated in the following table.

Name | Number
ps_1_1 to ps_1_3 | 4 texture samplers
ps_1_4 | 6 texture samplers
ps_2_0 | 16 texture samplers
fixed function pipeline | MaxTextureBlendStages/MaxSimultaneousTextures texture samplers

Devices that support displacement mapping in Direct3D 9 will support an additional sampler (D3DDMAPSAMPLER), which samples the displacement maps in the tessellator unit.

SetSamplerState Changes

IDirect3DDevice9::SetSamplerState sets the sampler state (including the one used in the tessellator unit to sample displacement maps). These have been renamed with a D3DSAMP_ prefix to enable compile-time error detection when porting from DirectX 8.x. The states include:

  • D3DSAMP_ADDRESSU
  • D3DSAMP_ADDRESSV
  • D3DSAMP_ADDRESSW
  • D3DSAMP_BORDERCOLOR
  • D3DSAMP_MAGFILTER
  • D3DSAMP_MAXANISOTROPY
  • D3DSAMP_MAXMIPLEVEL
  • D3DSAMP_MINFILTER
  • D3DSAMP_MIPFILTER
  • D3DSAMP_MIPMAPLODBIAS

Vertex Declaration Changes

Vertex declarations are now decoupled from vertex shader creation. Vertex declarations now use a Component Object Model (COM) interface.

For DirectX 8.x, vertex declarations are tied to vertex shaders.

  • For the fixed function pipeline, call IDirect3DDevice9::SetVertexShader with the flexible vertex format (FVF) code of the vertex buffer.
  • For vertex shaders, call IDirect3DDevice9::SetVertexShader with a handle to a previously create vertex shader. The shader includes a vertex declaration.

For Direct3D 9, vertex declarations are decoupled from vertex shaders and they can be used with either the fixed function pipeline or with shaders.

  • For the fixed function pipeline, there is no need to call IDirect3DDevice9::SetVertexShader. If, however, you want to switch to the fixed function pipeline and have previously used a vertex shader, call IDirect3DDevice9::SetVertexShader(NULL). When this is done, you will still need to call IDirect3DDevice9::SetFVF to declare the FVF code.
  • When using vertex shaders, call IDirect3DDevice9::SetVertexShader with the vertex shader object. Additionally, call IDirect3DDevice9::SetFVF to set up a vertex declaration. This uses the information implicit in the FVF. IDirect3DDevice9::SetVertexDeclaration can be called in place of IDirect3DDevice9::SetFVF because it supports vertex declarations that cannot be expressed with an FVF.

Intervals, and SwapEffects Changes

Several changes were made to give the user more control over monitor refresh rate, presentation rate, and front-buffer versus back-buffer drawing. They are as follows:

  • Removed one swap effect, D3DSWAPEFFECT_COPY_VSYNC, and one presentation rate, D3DPRESENT_RATE_UNLIMITED.
  • Renamed D3DPRESENT_PARAMETERS.FullScreen_PresentationInterval to PresentationIntervals.
  • Added D3DPRESENT_INTERVAL_IMMEDIATE, which means that the presentation is not synchronized with the vertical sync. As in DirectX 8.x, D3DPRESENT_INTERVAL_DEFAULT is defined as zero and is equivalent to D3DPRESENT_INTERVAL_ONE. D3DPRESENT_INTERVAL_DEFAULT is a convenience for initializing D3DPRESENT_PARAMETERS to zero.

For a detailed explanation of the modes and the intervals that are supported, see D3DPRESENT.


Programming Guide (Direct3D 9)

This guide contains a description of the graphics pipeline implemented by Microsoft Direct3D. It is a guide for developers who implement Direct3D graphics functionality into their applications. The guide contains architecture descriptions, functional block diagrams, and descriptions of the building blocks in the pipeline, as well as code snippets and sample applications. The information is divided into the following sections:

  • Getting Started - This section contains both an overview of the pipeline and tutorials that can help you get a simple graphics application running in a few minutes.
  • HLSL Shaders - This section covers programmable high-level shader language (HLSL) shaders. Included here are details about using vertex shaders for manipulating object geometry and pixel shaders for controlling pixel shading.
  • Effects - This section covers effects and effect files for building applications that can run on a variety of hardware platforms.
  • Advanced Topics - This section contains examples of different types of special effects you can implement. Topics such as environment and bump mapping, antialiasing, vertex blending, tweening, high dynamic range (HDR) lighting, and precomputed radiance transfer (PRT) show how to apply leading-edge special effects to your application.
  • Programming Tips - This section contains information to help you develop Direct3D graphics applications efficiently.

For more information about specific API methods, see the Reference pages.


Getting Started (Direct3D 9)

This section provides a brief introduction to the Direct3D graphics functionality in the Direct3D API. Here you will find an overview of the graphics pipeline and tutorials to help you get basic Direct3D functionality up and running quickly.

  • Architecture
  • Devices
  • Resources
  • Coordinate Systems and Geometry
  • Transforms
  • Viewports and Clipping
  • Lights and Materials
  • Rendering
  • Surfaces
  • Textures
  • D3DX
  • X Files (Legacy)

See Also

Further Information


Direct3D Architecture (Direct3D 9)

This topic provides two high-level views of the architecture of Direct3D:

  • Direct3D Graphics Pipeline - A view of the internal processing architecture of the Direct3D rendering system.
  • Direct3D System Integration - A view of how Direct3D mediates between an application and the graphics hardware.

Direct3D Graphics Pipeline

The graphics pipeline provides the horsepower to efficiently process and render Direct3D scenes to a display, taking advantage of available hardware. This figure conceptually illustrates the building blocks of the pipeline:

Direct3D graphics pipeline diagram

Pipeline Component | Description | Related Topics
Vertex Data | Untransformed model vertices are stored in vertex memory buffers. | Vertex Buffers (Direct3D 9), IDirect3DVertexBuffer9
Primitive Data | Geometric primitives, including points, lines, triangles, and polygons, are referenced in the vertex data with index buffers. | Index Buffers (Direct3D 9), IDirect3DIndexBuffer9, Primitives (Direct3D 9), Higher-Order Primitives (Direct3D 9)
Tessellation | The tesselator unit converts higher-order primitives, displacement maps, and mesh patches to vertex locations and stores those locations in vertex buffers. | Tessellation (Direct3D 9)
Vertex Processing | Direct3D transformations are applied to vertices stored in the vertex buffer. | Vertex Pipeline (Direct3D 9), Vertex Shader Basics (Direct3D 9)
Geometry Processing | Clipping, back face culling, attribute evaluation, and rasterization are applied to the transformed vertices. | Pixel Pipeline (Direct3D 9)
Textured Surface | Texture coordinates for Direct3D surfaces are supplied to Direct3D through the IDirect3DTexture9 interface. | Direct3D Textures (Direct3D 9), IDirect3DTexture9
Texture Sampler | Texture level-of-detail filtering is applied to input texture values. | Direct3D Textures (Direct3D 9)
Pixel Processing | Pixel shader operations use geometry data to modify input vertex and texture data, yielding output pixel color values. | Pixel Shader Basics (Direct3D 9)
Pixel Rendering | Final rendering processes modify pixel color values with alpha, depth, or stencil testing, or by applying alpha blending or fog. All resulting pixel values are presented to the output display. | Pixel Pipeline (Direct3D 9)

Direct3D System Integration

This figure shows the relationships between a Window application, Direct3D,GDI, and the hardware:

Direct3D system relationship diagram

Direct3D exposes a device-independent interface to an application. Direct3D applications can exist alongsideGDI applications, and both have access to the computer's graphics hardware through the device driver for the graphics card. UnlikeGDI, Direct3D can take advantage of hardware features by creating a hal device.

A hal device provides hardware acceleration to graphics pipeline functions, based upon the feature set supported by the graphics card. Direct3D methods are provided to retrieve device display capabilities at run time. (See IDirect3D9::GetDeviceCaps and IDirect3DDevice9::GetDeviceCaps.) If a capability is not provided by the hardware, the hal does not report it as a hardware capability.

For more information about hal and reference devices supported by Direct3D, see Device Types (Direct3D 9).


Direct3D Devices (Direct3D 9)

A Direct3D device is the rendering component of Direct3D. It encapsulates and stores the rendering state. In addition, a Direct3D device performs transformations and lighting operations and rasterizes an image to a surface.

  • Device Types (Direct3D 9)
  • Creating a Device (Direct3D 9)
  • Windowed vs Full-Screen Mode (Direct3D 9)
  • Selecting a Device (Direct3D 9)
  • Lost Devices (Direct3D 9)
  • Determining Hardware Support (Direct3D 9)
  • Processing Vertex Data (Direct3D 9)
  • Primitives (Direct3D 9)

Architecturally, Direct3D devices contain a transformation module, a lighting module, and a rasterizing module, as the following illustration shows.

Direct3D device architecture

Direct3D currently supports two main types of Direct3D devices:

  • A hal device with hardware-accelerated rasterization and shading with both hardware and software vertex processing
  • A reference device

You can think of these devices as two separate drivers. Software and reference devices are represented by software drivers, and the hal device is represented by a hardware driver. The most common way to take advantage of these devices is to use the hal device for shipping applications, and the reference device for feature testing. These are provided by third parties to emulate particular devices - for example, developmental hardware that has not yet been released.

The Direct3D device that an application creates must correspond to the capabilities of the hardware on which the application is running. Direct3D provides rendering capabilities, either by accessing 3D hardware that is installed in the computer or by emulating the capabilities of 3D hardware in software. Therefore, Direct3D provides devices for both hardware access and software emulation.

Hardware-accelerated devices give much better performance than software devices. The hal device type is available on all Direct3D supported graphic adapters. In most cases, applications target computers that have hardware acceleration and rely on software emulation to accommodate lower-end computers.

With the exception of the reference device, software devices do not always support the same features as a hardware device. Applications should always query for device capabilities to determine which features are supported.

Because the behavior of the software and reference devices provided with Direct3D 9 is identical to that of the hal device, application code authored to work with the hal device will work with the software or reference devices without modifications. Note that while the provided software or reference device behavior is identical to that of the hal device, the device capabilities do vary, and a particular software device may implement a much smaller set of capabilities.

Behaviors

Direct3D enables you to specify the behavior of a device, as well the device's type. The IDirect3D9::CreateDevice method enables a combination of one or more of the behavior flags to control the global behaviors of the Direct3D device. These behaviors specify what is and is not maintained in the run-time portion of Direct3D, and the device types specify which driver to use. Although some combinations of device behaviors are not valid, it is possible to use all device behaviors with all device types. For example, it is valid to specify D3DDEVTYPE_SW on a device created with D3DCREATE_PUREDEVICE.


Device Types (Direct3D 9)

HAL Device

The primary device type is the hal device, which supports hardware accelerated rasterization and both hardware and software vertex processing. If the computer on which your application is running is equipped with a display adapter that supports Direct3D, your application should use it for Direct3D operations. Direct3D hal devices implement all or part of the transformation, lighting, and rasterizing modules in hardware.

Applications do not access graphics adapters directly. They call Direct3D functions and methods. Direct3D accesses the hardware through the hal. If the computer that your application is running on supports the hal, it will gain the best performance by using a hal device.

To create a hal device, call IDirect3D9::CreateDevice using D3DDEVTYPE_HAL as the device type.

Reference Device

Direct3D supports an additional device type called a reference device or reference rasterizer. Unlike a software device, the reference rasterizer supports every Direct3D feature. This device is intended to be used for debugging purposes and is therefore only available on machines where the DirectX SDK has been installed. Because these features are implemented for accuracy rather than speed and are implemented in software, the results are not very fast. The reference rasterizer does make use of special CPU instructions whenever it can, but it is not intended for retail applications. Use the reference rasterizer only for feature testing or demonstration purposes. To create a reference device, call IDirect3D9::CreateDevice method using D3DDEVTYPE_REF as the device type.

HAL vs. REF Devices

HAL (Hardware Abstraction Layer) devices and REF (REFerence rasterizer) devices are the two main types of D3D device; the first is based around the hardware support, and is very fast but might not support everything; while the second uses no hardware acceleration, so is very slow, but is guaranteed to support the entire set of D3D features, in the correct way. In general you'll only ever need to use HAL devices, but if you're using some advanced feature that your graphics card does not support then you might need to fall back to REF.

The other time you might want to use REF is if the HAL device is producing strange results - that is, you're sure your code is correct, but the result is not what you're expecting. The REF device is guaranteed to behave correctly, so you may wish to test your application on the REF device and see if the strange behaviour continues. If it doesn't, it means that either (a) your application is assuming that the graphics card supports something that it doesn't, or (b) it's a driver bug. If it still doesn't work with the REF device, then it's an application bug.

Hardware vs. Software Vertex Processing

Hardware versus Software vertex processing only really applies to HAL devices. When you push vertices through the pipeline, they need to be transformed (by the world, view, and projection matrices in turn) and lit (by D3D's built-in lights) - this processing stage is known as T&L (for Transformation & Lighting). Hardware vertex processing means this is done in hardware, if the hardware supports it; ergo, Software vertex processing is done is software. The general practice is to try creating a Hardware T&L device first, and if that fails try Mixed, and if that fails try Software. (If software fails, give up and exit with an error).


Creating a Device (Direct3D 9)

To create a Direct3D device, first create a Direct3D object (see Direct3DCreate9). All rendering devices created by a Direct3D object share the same physical resources. If you create multiple rendering devices from a single Direct3D object, extreme performance penalties will be incurred because they share the same hardware.

First, initialize values for the D3DPRESENT_PARAMETERS structure that is used to create the Direct3D device. The following code example specifies a windowed application where the back buffer is flipped to the front buffer during a vertical sync operation only.

LPDIRECT3DDEVICE9 pDevice = NULL;

D3DPRESENT_PARAMETERS d3dpp;

ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed   = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;

Next, create the Direct3D device. The following IDirect3D9::CreateDevice call specifies the default adapter, a hardware abstraction layer (HAL) device, and software vertex processing.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                    D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                    &d3dpp, &d3dDevice ) ) )
    return E_FAIL;

Note that a call to create, release, or reset the device should happen only on the same thread as the window procedure of the focus window.

After creating the device, set its state.


Windowed vs Full-Screen Mode (Direct3D 9)

Direct3D applications can run in either of two modes: full-screen or windowed.

Full-screen mode means the window that the application runs in covers the entire desktop, hiding all running applications (including your development environment). Games typically default to full-screen mode to fully immerse the user in the game by hiding all running applications. An application running in windowed-mode shares the desktop with all running applications. Code differences between full-screen mode and windowed mode are very small.

Because an application running in full-screen mode takes over the screen, debugging the application requires either a separate monitor or the use of a remote debugger. Use the DirectX Control Panel Tool to enable multiple-monitor debugging. One advantage of a windowed-mode application is that you can step through the code in a debugger without multiple monitors or a remote debugger.


Selecting a Device (Direct3D 9)

Applications can query hardware to detect the supported Direct3D device types. This section contains information about the primary tasks involved in enumerating display adapters and selecting Direct3D devices.

An application must perform a series of tasks to select an appropriate Direct3D device. Note that the following steps are intended for a full-screen application and that, in most cases, a windowed application can skip most of these steps.

  1. Initially, the application must enumerate the display adapters on the system. An adapter is a physical piece of hardware. Note that the graphics card might contain more than a single adapter, as is the case with a dual-headed display. Applications that are not concerned with multi-monitor support can disregard this step, and pass D3DADAPTER_DEFAULT to the IDirect3D9::EnumAdapterModes method in step 2.
  2. For each adapter, the application enumerates the supported display modes by calling IDirect3D9::EnumAdapterModes.
  3. If required, the application checks for the presence of hardware acceleration in each enumerated display mode by calling IDirect3D9::CheckDeviceType, as shown in the following code example. Note that this is only one of the possible uses for IDirect3D9::CheckDeviceType; for details, see Determining Hardware Support (Direct3D 9).
    D3DPRESENT_PARAMETERS Params;
// Initialize values for D3DPRESENT_PARAMETERS members.

Params.BackBufferFormat = D3DFMT_X1R5G5B5;

if(FAILED(m_pD3D->CheckDeviceType(Device.m_uAdapter,
                  Device.m_DevType,
                  Params.BackBufferFormat, Params.BackBufferFormat,
                  FALSE)))
    return E_FAIL;
  4. The application checks for the desired level of functionality for the device on this adapter by calling the IDirect3D9::GetDeviceCaps method. The capability returned by this method is guaranteed to be constant for a device across all display modes, verified by IDirect3D9::CheckDeviceType.
  5. Devices can always render to surfaces of the format of an enumerated display mode that is supported by the device. If the application is required to render to a surface of a different format, it can call IDirect3D9::CheckDeviceFormat. If the device can render to the format, then it is guaranteed that all capabilities returned by IDirect3D9::GetDeviceCaps are applicable.
  6. Lastly, the application can determine if multisampling techniques, such as full-scene antialiasing, are supported for a render format by using the IDirect3D9::CheckDeviceMultiSampleType method.

After completing the preceding steps, the application should have a list of display modes in which it can operate. The final step is to verify that enough device-accessible memory is available to accommodate the required number of buffers and antialiasing. This test is necessary because the memory consumption for the mode and multisample combination is impossible to predict without verifying it. Moreover, some display adapter architectures might not have a constant amount of device-accessible memory. This means that an application should be able to report out-of-video-memory failures when going into full-screen mode. Typically, an application should remove full-screen mode from the list of modes that it offers to a user, or it should attempt to consume less memory by reducing the number of back buffers or by using a less complex multisampling technique.

A windowed application performs a similar set of tasks.

  1. It determines the desktop rectangle covered by the client area of the window.
  2. It enumerates adapters, looking for the adapter whose monitor covers the client area. If the client area is owned by more than one adapter, then the application can choose to drive each adapter independently, or to drive a single adapter and have Direct3D transfer pixels from one device to another at presentation. The application can also disregard two preceding steps and use the D3DADAPTER_DEFAULT adapter. Note that this might result in slower operation when the window is placed on a secondary monitor.
  3. The application should call IDirect3D9::CheckDeviceType to determine if the device can support rendering to a back buffer of the specified format while in desktop mode. IDirect3D9::GetAdapterDisplayMode can be used to determine the desktop display format, as shown in the following code example.
    D3DPRESENT_PARAMETERS Params;
// Initialize values for D3DPRESENT_PARAMETERS members.

// Use the current display mode.
D3DDISPLAYMODE mode;

if(FAILED(m_pD3D->GetAdapterDisplayMode(Device.m_uAdapter , &mode)))
    return E_FAIL;

Params.BackBufferFormat = mode.Format;

if(FAILED(m_pD3D->CheckDeviceType(Device.m_uAdapter, Device.m_DevType,
Params.BackBufferFormat, Params.BackBufferFormat, FALSE)))
    return E_FAIL;


Lost Devices (Direct3D 9)

A Direct3D device can be in either an operational state or a lost state. The operational state is the normal state of the device in which the device runs and presents all rendering as expected. The device makes a transition to the lost state when an event, such as the loss of keyboard focus in a full-screen application, causes rendering to become impossible. The lost state is characterized by the silent failure of all rendering operations, which means that the rendering methods can return success codes even though the rendering operations fail. In this situation, the error code D3DERR_DEVICELOST is returned by IDirect3DDevice9::Present.

By design, the full set of scenarios that can cause a device to become lost is not specified. Some typical examples include loss of focus, such as when the user presses ALT+TAB or when a system dialog is initialized. Devices can also be lost due to a power management event, or when another application assumes full-screen operation. In addition, any failure from IDirect3DDevice9::Reset puts the device into a lost state.

All methods that derive from IUnknown Are guaranteed to work after a device is lost. After device loss, each function generally has the following three options:

  • Fail with D3DERR_DEVICELOST - This means that the application needs to recognize that the device was lost, so that the application identifies that something isn't happening as expected.
  • Silently fail, returning S_OK or any other return codes - If a function silently fails, the application generally can't distinguish between the result of "success" and a "silent failure."
  • The function returns a return code.

Responding to a Lost Device

A lost device must re-create resources (including video memory resources) after it has been reset. If a device is lost, the application queries the device to see if it can be restored to the operational state. If not, the application waits until the device can be restored.

If the device can be restored, the application prepares the device by destroying all video-memory resources and any swap chains. Then, the application calls the IDirect3DDevice9::Reset method. Reset is the only method that has an effect when a device is lost, and is the only method by which an application can change the device from a lost to an operational state. Reset will fail unless the application releases all resources that are allocated in D3DPOOL_DEFAULT, including those created by the IDirect3DDevice9::CreateRenderTarget and IDirect3DDevice9::CreateDepthStencilSurface methods.

For the most part, the high-frequency calls of Direct3D do not return any information about whether the device has been lost. The application can continue to call rendering methods, such as IDirect3DDevice9::DrawPrimitive, without receiving notification of a lost device. Internally, these operations are discarded until the device is reset to the operational state.

The application can determine what to do on encountering a lost device by querying the return value of the IDirect3DDevice9::TestCooperativeLevel method.

Locking Operations

Internally, Direct3D does enough work to ensure that a lock operation will succeed after a device is lost. However, it is not guaranteed that the video-memory resource's data will be accurate during the lock operation. It is guaranteed that no error code will be returned. This allows applications to be written without concern for device loss during a lock operation.

Resources

Resources can consume video memory. Because a lost device is disconnected from the video memory owned by the adapter, it is not possible to guarantee allocation of video memory when the device is lost. As a result, all resource creation methods are implemented to succeed by returning D3D_OK, but do in fact allocate only dummy system memory. Because any video-memory resource must be destroyed before the device is resized, there is no issue of over-allocating video memory. These dummy surfaces allow lock and copy operations to appear to function normally until the application calls IDirect3DDevice9::Present and discovers that the device has been lost.

All video memory must be released before a device can be reset from a lost state to an operational state. This means that the application should release any swap chains created with IDirect3DDevice9::CreateAdditionalSwapChain and any resources placed in the D3DPOOL_DEFAULT memory class. The application need not release resources in the D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory classes. Other state data is automatically destroyed by the transition to an operational state.

You are encouraged to develop applications with a single code path to respond to device loss. This code path is likely to be similar, if not identical, to the code path taken to initialize the device at startup.

Retrieved Data

Direct3D allows applications to validate texture and render states against single pass rendering by the hardware using IDirect3DDevice9::ValidateDevice. This method, which is typically invoked during initialization of the application, will return D3DERR_DEVICELOST if the device has been lost.

Direct3D also allows applications to copy generated or previously written images from video-memory resources to nonvolatile system-memory resources. Because the source images of such transfers might be lost at any time, Direct3D allows such copy operations to fail when the device is lost.

Regarding asynchronous queries, IDirect3DQuery9::GetData returns D3DERR_DEVICELOST if the FLUSH flag is specified, in order to indicate to the application that IDirect3DQuery9::GetData will never return S_OK.

The copy operation, IDirect3DDevice9::GetFrontBufferData, can fail with D3DERR_DEVICELOST since there is no primary surface when the device is lost. IDirect3DDevice9::CreateAdditionalSwapChain can also fail with D3DERR_DEVICELOST because a back buffer can't be created when the device is lost. Note that these cases are the only instance of D3DERR_DEVICELOST outside of the IDirect3DDevice9::Present, IDirect3DDevice9::TestCooperativeLevel, and IDirect3DDevice9::Reset methods.

Programmable Shaders

In Direct3D 9, vertex shaders and pixel shaders don't need to be re-created after reset. They will be remembered. In previous versions of DirectX, a lost device required shaders to be re-created.


Determining Hardware Support (Direct3D 9)

Direct3D provides the following functions to determine hardware support.

  • IDirect3D9::CheckDeviceFormat

    Used to verify whether a surface format can be used as a texture, whether a surface format can be used as a texture and a render target, or whether a surface format can be used as a depth-stencil buffer. In addition, this method is used to verify depth buffer format support and depth-stencil buffer format support.

  • IDirect3D9::CheckDeviceType

    Used to verify a device's ability to perform hardware acceleration, a device's ability to build a swap chain for presentation, or a device's ability to render to the current display format.

  • IDirect3D9::CheckDepthStencilMatch

    Used to verify whether a depth-stencil buffer format is compatible with a render-target format. Note that before calling this method, the application should call IDirect3D9::CheckDeviceFormat on both the depth-stencil and render-target formats.


Processing Vertex Data (Direct3D 9)

The IDirect3DDevice9 interface supports vertex processing in both software and hardware. In general, the device capabilities for software and hardware vertex processing are not identical. Hardware capabilities are variable, depending on the display adapter and driver, while software capabilities are fixed.

The following flags control vertex processing behavior for the hardware abstraction layer (HAL) and reference devices.

  • D3DCREATE_SOFTWARE_VERTEXPROCESSING
  • D3DCREATE_HARDWARE_VERTEXPROCESSING
  • D3DCREATE_MIXED_VERTEXPROCESSING

Specify one of the vertex processing behavior flags when calling IDirect3D9::CreateDevice. The mixed-mode flag enables the device to perform both software and hardware vertex processing. Only one vertex processing flag may be set for a device at any one time. Note that the D3DCREATE_HARDWARE_VERTEXPROCESSING flag is required to be set when creating a pure device (D3DCREATE_PUREDEVICE).

To avoid dual vertex processing capabilities on a single device, only the hardware vertex processing capabilities can be queried at run time. Software vertex processing capabilities are fixed and cannot be queried at run time.

The VertexProcessingCaps member of the D3DCAPS9 structure determines the hardware vertex processing capabilities of the device.

For software vertex processing the following capabilities are supported.

  • the D3DVTXPCAPS_DIRECTIONALLIGHTS member of D3DVTXPCAPS
  • the D3DVTXPCAPS_LOCALVIEWER member of D3DVTXPCAPS
  • the D3DVTXPCAPS_MATERIALSOURCE7 member of D3DVTXPCAPS
  • the D3DVTXPCAPS_POSITIONALLIGHTS member of D3DVTXPCAPS
  • the D3DVTXPCAPS_TEXGEN member of D3DVTXPCAPS
  • the D3DVTXPCAPS_TWEENING member of D3DVTXPCAPS

In addition, the following table lists the values that are set for members of the D3DCAPS9 structure for a device in software vertex processing mode.

Member | Software vertex processing capabilities
MaxActiveLights | Unlimited
MaxUserClipPlanes | 6
MaxVertexBlendMatrices | 4
MaxStreams | 16
MaxVertexIndex | 0xFFFFFFFF

In general, any application that is vertex processing bound should use a HAL device. Software vertex processing provides a guaranteed set of vertex processing capabilities, including an unbounded number of lights and full support for programmable vertex shaders. You can toggle between software and hardware vertex processing at any time when using the HAL device (which is the only device type that supports both hardware and software vertex processing). The only requirement is that vertex buffers used for software vertex processing must be allocated in system memory.


Primitives (Direct3D 9)

A 3D primitive is a collection of vertices that form a single 3D entity. The simplest primitive is a collection of points in a 3D coordinate system, which is called a point list.

Often, 3D primitives are polygons. A polygon is a closed 3D figure delineated by at least three vertices. The simplest polygon is a triangle. Microsoft Direct3D uses triangles to compose most of its polygons because all three vertices in a triangle are guaranteed to be coplanar. Rendering nonplanar vertices is inefficient. You can combine triangles to form large, complex polygons and meshes.

The following illustration shows a cube. Two triangles form each face of the cube. The entire set of triangles forms one cubic primitive. You can apply textures and materials to the surfaces of primitives to make them appear to be a single solid form. For details, see Materials (Direct3D 9) and Direct3D Textures (Direct3D 9).

You can also use triangles to create primitives whose surfaces appear to be smooth curves. The following illustration shows how a sphere can be simulated with triangles. After a material is applied, the sphere looks curved when it is rendered. This is especially true if you use Gouraud shading. For details, see Gouraud Shading.

Direct3D devices can create and manipulate the following types of primitives.

  • Point Lists (Direct3D 9)
  • Line Lists (Direct3D 9)
  • Line Strips (Direct3D 9)
  • Triangle Lists (Direct3D 9)
  • Triangle Strips (Direct3D 9)
  • Triangle Fans (Direct3D 9)

You can render primitive types from a C++ application with any of the rendering methods of the IDirect3DDevice9 interface.


Point Lists (Direct3D 9)

A point list is a collection of vertices that are rendered as isolated points. Your application can use them in 3D scenes for star fields, or dotted lines on the surface of a polygon.

The following illustration depicts a rendered point list.

Your application can apply materials and textures to a point list. The colors in the material or texture appear only at the points drawn, and not anywhere between the points.

The following code shows how to create vertices for this point list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};


Line Lists (Direct3D 9)

A line list is a list of isolated, straight line segments. Line lists are useful for such tasks as adding sleet or heavy rain to a 3D scene. Applications create a line list by filling an array of vertices. Note that the number of vertices in a line list must be an even number greater than or equal to two.

The following illustration shows a rendered line list.

You can apply materials and textures to a line list. The colors in the material or texture appear only along the lines drawn, not at any point in between the lines.

The following code shows how to create vertices for this line list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this line list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_LINELIST, 0, 3 );


Line Strips (Direct3D 9)

A line strip is a primitive that is composed of connected line segments. Your application can use line strips for creating polygons that are not closed. A closed polygon is a polygon whose last vertex is connected to its first vertex by a line segment. If your application makes polygons based on line strips, the vertices are not guaranteed to be coplanar.

The following illustration depicts a rendered line strip.

The following code shows how to create vertices for this line strip.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this line strip.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_LINESTRIP, 0, 5 );


Triangle Lists (Direct3D 9)

A triangle list is a list of isolated triangles. They might or might not be near each other. A triangle list must have at least three vertices and the total number of vertices must be divisible by three.

Use triangle lists to create an object that is composed of disjoint pieces. For instance, one way to create a force-field wall in a 3D game is to specify a large list of small, unconnected triangles. Then apply a material and texture that appears to emit light to the triangle list. Each triangle in the wall appears to glow. The scene behind the wall becomes partially visible through the gaps between the triangles, as a player might expect when looking at a force field.

Triangle lists are also useful for creating primitives that have sharp edges and are shaded with Gouraud shading. See Face and Vertex Normal Vectors (Direct3D 9).

The following illustration depicts a rendered triangle list.

Rendered triangle list

The following code shows how to create vertices for this triangle list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}

};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this triangle list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 2 );


Triangle Strips (Direct3D 9)

A triangle strip is a series of connected triangles. Because the triangles are connected, the application does not need to repeatedly specify all three vertices for each triangle. For example, you need only seven vertices to define the following triangle strip:

The system uses vertices v1, v2, and v3 to draw the first triangle; v2, v4, and v3 to draw the second triangle; v3, v4, and v5 to draw the third; v4, v6, and v5 to draw the fourth; and so on. Notice that the vertices of the second and fourth triangles are out of order; this is required to make sure that all the triangles are drawn in a clockwise orientation.

Most objects in 3D scenes are composed of triangle strips. This is because triangle strips can be used to specify complex objects in a way that makes efficient use of memory and processing time.

The following illustration depicts a rendered triangle strip.

Rendered triangle strip

The following code shows how to create vertices for this triangle strip.

struct CUSTOMVERTEX
{
float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
{-5.0, -5.0, 0.0},
{ 0.0,  5.0, 0.0},
{ 5.0, -5.0, 0.0},
{10.0,  5.0, 0.0},
{15.0, -5.0, 0.0},
{20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this triangle strip.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 4);


Triangle Fans (Direct3D 9)

A triangle fan is similar to a triangle strip, except that all the triangles share one vertex. This is shown in the following illustration:

The system uses vertices v2, v3, and v1 to draw the first triangle; v3, v4, and v1 to draw the second triangle; v4, v5, and v1 to draw the third triangle; and so on. When flat shading is enabled, the system shades the triangle with the color from its first vertex.

This illustration depicts a rendered triangle fan.

Rendered triangle fan

The following code shows how to create vertices for this triangle fan.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    { 0.0, 0.0, 0.0},
    {-5.0, 5.0, 0.0},
    {-3.0,  7.0, 0.0},
    { 0.0, 10.0, 0.0},
    { 3.0,  7.0, 0.0},
    { 5.0,  5.0, 0.0},
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this triangle fan.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 4 );


States (Direct3D 9)

A Direct3D device uses states to set-up all of the pipeline processing. Sampler states control the set-up of the texture samplers by defining texture addressing and filter modes for example. Texture states set-up the multi-texture blender which controls how textures are combined and blended with each other. Render states control most of the pipeline state.

State blocks are a convenient mechanism for saving and restoring state. See State Blocks Save and Restore State (Direct3D 9)


State Blocks Save and Restore State (Direct3D 9)

A state block is a group of device states. Device state is made up of render state, vertex state, pixel state, or all of the above. A state block contains a snapshot of a device's current state, or you can create a state block that records each state change that your application makes.

  • Create a State Block
  • Capture State Information

Create a State Block

Choose the type of state that you want to capture, and create a state block like this:

  IDirect3DStateBlock9* pStateBlock = NULL;
  pd3dDevice->CreateStateBlock( D3DSBT_ALL, &pStateBlock );
);

IDirect3DDevice9::CreateStateBlock creates a state block, and captures the device state. The device state is specified by the state block type in the first argument. This state can be one of the following:

  • All device state (see Saving All Device States with a StateBlock (Direct3D 9)).
  • All pixel state (see Saving Pixel State With a StateBlock (Direct3D 9)).
  • All vertex state (see Saving Vertex States With a StateBlock (Direct3D 9)).

Capture State Information

Creating a state block automatically captures the current device state. The effect system uses a state block to save state. After ID3DXEffect::Begin is called, a state block is created and state is captured. When ID3DXEffect::End is called, the state block state is reapplied to the device.

To save a custom state sequence, wrap the state that you want to save in a IDirect3DDevice9::BeginStateBlock and IDirect3DDevice9::EndStateBlock pair. IDirect3DDevice9::BeginStateBlock tells the current device to set up a state block and add to it every state change that occurs until IDirect3DDevice9::EndStateBlock is called. Here's an example:

  IDirect3DStateBlock9* pStateBlock = NULL;
  pd3dDevice->BeginStateBlock();

  // Any number of state changes can occur here
  // SetRenderState, SetSamplerState, SetTextureStageState ...

  pd3dDevice->EndStateBlock( &pStateBlock );

This will save any number of state changes in any sequence to a custom stateblock. Later, when you want to use the stateblock to reset the device state, call IDirect3DStateBlock9::Apply. This will overwrite only the device state that has been captured in the state block. Any other device state that was not captured with the custom stateblock will not be changed. Once again, since the stateblock object is an interface, you will need to release it when you are done with it.


Saving All Device States with a StateBlock (Direct3D 9)

A state block can be used to capture all device states (see State Blocks Save and Restore State (Direct3D 9)). The following state elements are included in the device state:

  • Vertex state (see Saving Vertex States With a StateBlock (Direct3D 9)).
  • Pixel state (see Saving Pixel State With a StateBlock (Direct3D 9)).
  • Each texture assigned to a sampler.
  • Each vertex texture.
  • Each displacement map texture.
  • The current texture palette.
  • For each vertex stream: a pointer to the vertex buffer, each argument from IDirect3DDevice9::SetStreamSource, and the divider (if any) from IDirect3DDevice9::SetStreamSourceFreq.
  • A pointer to the index buffer.
  • The viewport.
  • The scissors rectangle.
  • The world, view, and projection matrices.
  • The texture transforms.
  • The clipping planes (if any).
  • The current material.

To capture all device states with a state block, specify D3DSBT_ALL when calling IDirect3DDevice9::CreateStateBlock.


Saving Vertex States With a StateBlock (Direct3D 9)

A state block can be used to capture only vertex state (see State Blocks Save and Restore State (Direct3D 9)). The following state is vertex state:

  • Vertex render state (see Vertex Pipeline: Render State).
  • Vertex sampler state (see Vertex Pipeline: Sampler State).
  • Vertex texture state (see Vertex Pipeline: Texture State).
  • The NPatch mode segments from IDirect3DDevice9::SetNPatchMode.
  • Each light from IDirect3DDevice9::SetLight, as well as whether or not the light is enabled with IDirect3DDevice9::LightEnable.
  • The current vertex shader and each of the vertex shader constants.
  • For each vertex stream, store the divider value from IDirect3DDevice9::SetStreamSourceFreq.
  • The current vertex declaration.

To capture vertex state with a state block, specify D3DSBT_VERTEXSTATE when calling IDirect3DDevice9::CreateStateBlock.

Vertex Pipeline: Render State

Device render states affect the behavior of almost every part of the pipeline. Render states are set by calling IDirect3DDevice9::SetRenderState.

The following table includes all render states that set-up vertex state:

Render States | Default Value
D3DRS_CULLMODE | D3DCULL_CCW
D3DRS_FOGCOLOR | 0
D3DRS_FOGTABLEMODE | D3DFOG_NONE
D3DRS_FOGSTART | 0
D3DRS_FOGEND | 1
D3DRS_FOGDENSITY | 1
D3DRS_RANGEFOGENABLE | FALSE
D3DRS_AMBIENT | 0
D3DRS_COLORVERTEX | TRUE
D3DRS_FOGVERTEXMODE | D3DFOG_NONE
D3DRS_CLIPPING | TRUE
D3DRS_LIGHTING | TRUE
D3DRS_LOCALVIEWER | TRUE
D3DRS_EMISSIVEMATERIALSOURCE | D3DMCS_MATERIAL
D3DRS_AMBIENTMATERIALSOURCE | D3DMCS_MATERIAL
D3DRS_DIFFUSEMATERIALSOURCE | D3DMCS_COLOR1
D3DRS_SPECULARMATERIALSOURCE | D3DMCS_COLOR2
D3DRS_VERTEXBLEND | D3DVBF_DISABLE
D3DRS_CLIPPLANEENABLE | 0
D3DRS_POINTSIZE | Driver dependent
D3DRS_POINTSIZE_MIN | 1
D3DRS_POINTSPRITEENABLE | FALSE
D3DRS_POINTSCALEENABLE | FALSE
D3DRS_POINTSCALE_A | 1
D3DRS_POINTSCALE_B | 0
D3DRS_POINTSCALE_C | 0
D3DRS_MULTISAMPLEANTIALIAS | TRUE
D3DRS_MULTISAMPLEMASK | 0xffffffff
D3DRS_PATCHEDGESTYLE | D3DPATCHEDGE_DISCRETE
D3DRS_POINTSIZE_MAX | 1
D3DRS_INDEXEDVERTEXBLENDENABLE | FALSE
D3DRS_TWEENFACTOR | 0
D3DRS_POSITIONDEGREE | D3DDEGREE_CUBIC
D3DRS_NORMALDEGREE | D3DDEGREE_LINEAR
D3DRS_MINTESSELLATIONLEVEL | 1
D3DRS_MAXTESSELLATIONLEVEL | 1
D3DRS_ADAPTIVETESS_X | 0
D3DRS_ADAPTIVETESS_Y | 0
D3DRS_ADAPTIVETESS_Z | 1
D3DRS_ADAPTIVETESS_W | 0
D3DRS_ENABLEADAPTIVETESSELLATION"/> | FALSE

Vertex Pipeline: Sampler State

Sampler states control sampling related topics such as filtering, tiling, and texture coordinate address modes. Use IDirect3DDevice9::SetSamplerState to set up the sampler state (including the one used in the tessellator unit to sample displacement maps). The sampler states have been renamed with a "D3DSAMP_" prefix to enable compile time error detection when porting from DirectX 8.

The following table includes all sampler states that set-up vertex state:

Sampler States | Default Value
D3DSAMP_DMAPOFFSET | 256

Vertex Pipeline: Texture State

Texture states control texture blending operations of the multi-texture blender. Use IDirect3DDevice9::SetTextureStageState to set-up texture states. Use IDirect3DDevice9::SetTexture to associate a texture with a sampler stage.

The following table includes all the texture states that set-up vertex state:

Texture States | Default Value
D3DTSS_TEXCOORDINDEX | 0
D3DTSS_TEXTURETRANSFORMFLAGS | D3DTTFF_DISABLE

D3DTSS_TEXCOORDINDEX is a fixed function vertex processing state. If a programmable vertex shader is used, this state is ignored.


Saving Pixel State With a StateBlock (Direct3D 9)

A state block can be used to capture only pixel state (see State Blocks Save and Restore State (Direct3D 9)). The following state is pixel state:

  • Pixel render state (see Pixel Pipeline: Render State).
  • Pixel texture state (see Pixel Pipeline: Texture State).
  • Pixel sampler state (see Pixel Pipeline: Sampler State).
  • The current pixel shader and each of the pixel shader constants.

To capture pixel state with a state block, specify D3DSBT_PIXELSTATE when calling IDirect3DDevice9::CreateStateBlock.

Pixel Pipeline: Render State

Device render states affect the behavior of almost every part of the pipeline. Render states are set by calling IDirect3DDevice9::SetRenderState.

The following table includes all render states that set-up pixel state:

Render States | Default Value
D3DRS_ZENABLE | D3DZB_FALSE
D3DRS_SPECULARENABLE | FALSE
D3DFILLMODE | D3DFILL_SOLID
D3DSHADEMODE | D3DSHADE_GOURAUD
D3DRS_ZWRITEENABLE | TRUE
D3DRS_ALPHATESTENABLE | FALSE
D3DRS_LASTPIXEL | TRUE
D3DRS_SRCBLEND | D3DBLEND_ONE
D3DRS_DESTBLEND | D3DBLEND_ZERO
D3DRS_ZFUNC | D3DCMP_LESSEQUAL
D3DRS_ALPHAREF | 0
D3DRS_ALPHAFUNC | D3DCMP_ALWAYS
D3DRS_DITHERENABLE | FALSE
D3DRS_FOGSTART | 0
D3DRS_FOGEND | 1
D3DRS_FOGDENSITY | 1
D3DRS_ALPHABLENDENABLE | FALSE
D3DRS_DEPTHBIAS | 0
D3DRS_STENCILENABLE | FALSE
D3DRS_STENCILFAIL | D3DSTENCILOP_KEEP
D3DRS_STENCILZFAIL | D3DSTENCILOP_KEEP
D3DRS_STENCILPASS | D3DSTENCILOP_KEEP
D3DRS_STENCILFUNC | D3DCMP_ALWAYS
D3DRS_STENCILREF | 0
D3DRS_STENCILMASK | 0xffffffff
D3DRS_STENCILWRITEMASK | 0xffffffff
D3DRS_TEXTUREFACTOR | 0xffffffff
D3DRS_WRAP0 | 0
D3DRS_WRAP1 | 0
D3DRS_WRAP2 | 0
D3DRS_WRAP3 | 0
D3DRS_WRAP4 | 0
D3DRS_WRAP5 | 0
D3DRS_WRAP6 | 0
D3DRS_WRAP7 | 0
D3DRS_WRAP8 | 0
D3DRS_WRAP9 | 0
D3DRS_WRAP10 | 0
D3DRS_WRAP11 | 0
D3DRS_WRAP12 | 0
D3DRS_WRAP13 | 0
D3DRS_WRAP14 | 0
D3DRS_WRAP15 | 0
D3DRS_LOCALVIEWER | TRUE
D3DRS_EMISSIVEMATERIALSOURCE | D3DMCS_MATERIAL
D3DRS_AMBIENTMATERIALSOURCE | D3DMCS_MATERIAL
D3DRS_DIFFUSEMATERIALSOURCE | D3DMCS_COLOR1
D3DRS_SPECULARMATERIALSOURCE | D3DMCS_COLOR2
D3DRS_COLORWRITEENABLE | 0x0000000f
D3DBLENDOP | D3DBLENDOP_ADD
D3DRS_SCISSORTESTENABLE | FALSE
D3DRS_SLOPESCALEDEPTHBIAS | 0
D3DRS_ANTIALIASEDLINEENABLE | FALSE
D3DRS_Two_Sided_StencilMODE | FALSE
D3DRS_CCW_STENCILFAIL | D3DSTENCILOP_KEEP
D3DRS_CCW_STENCILZFAIL | D3DSTENCILOP_KEEP
D3DRS_CCW_STENCILPASS | D3DSTENCILOP_KEEP
D3DRS_CCW_STENCILFUNC | D3DCMP_ALWAYS
D3DRS_COLORWRITEENABLE1 | 0x0000000f
D3DRS_COLORWRITEENABLE2 | 0x0000000f
D3DRS_COLORWRITEENABLE3 | 0x0000000f
D3DRS_BLENDFACTOR | 0xffffffff
D3DRS_SRGBWRITEENABLE | 0
D3DRS_SEPARATEALPHABLENDENABLE | FALSE
D3DRS_SRCBLENDALPHA | D3DBLEND_ONE
D3DRS_DESTBLENDALPHA | D3DBLEND_ZERO
D3DRS_BLENDOPALPHA | D3DBLENDOP_ADD

Pixel Pipeline: Sampler State

Sampler states control sampling related topics such as filtering, tiling, and texture coordinate address modes. Use IDirect3DDevice9::SetSamplerState to set up the sampler state (including the one used in the tessellator unit to sample displacement maps). The sampler states have been renamed with a "D3DSAMP_" prefix to enable compile time error detection when porting from DirectX 8.

The following table includes all sampler states that set-up pixel state:

Sampler States | Default Value
D3DSAMP_ADDRESSU | D3DTADDRESS_WRAP
D3DSAMP_ADDRESSV | D3DTADDRESS_WRAP
D3DSAMP_ADDRESSW | D3DTADDRESS_WRAP
D3DSAMP_BORDERCOLOR | 0x00000000
D3DSAMP_MAGFILTER | D3DTEXF_POINT
D3DSAMP_MINFILTER | D3DTEXF_POINT
D3DSAMP_MIPFILTER | D3DTEXF_NONE
D3DSAMP_MIPMAPLODBIAS | 0
D3DSAMP_MAXMIPLEVEL | 0
D3DSAMP_MAXANISOTROPY | 1
D3DSAMP_SRGBTEXTURE | 0
D3DSAMP_ELEMENTINDEX | 0

Pixel Pipeline: Texture State

Texture states control texture blending operations of the multi-texture blender. Use IDirect3DDevice9::SetTextureStageState to set-up texture stage states. Use IDirect3DDevice9::SetTexture to associate a texture with a sampler stage.

The following table includes all the texture states that set-up pixel state:

Texture States | Default Value
D3DTSS_COLOROP | D3DTOP_DISABLE
D3DTSS_COLORARG1 | D3DTA_TEXTURE
D3DTSS_COLORARG2 | D3DTA_CURRENT
D3DTSS_ALPHAOP | D3DTOP_DISABLE
D3DTSS_ALPHAARG1 | D3DTA_TEXTURE
D3DTSS_ALPHAARG2 | D3DTA_CURRENT
D3DTSS_BUMPENVMAT00 | 0
D3DTSS_BUMPENVMAT01 | 0
D3DTSS_BUMPENVMAT10 | 0
D3DTSS_BUMPENVMAT11 | 0
D3DTSS_TEXCOORDINDEX | 0
D3DTSS_BUMPENVLSCALE | 0
D3DTSS_BUMPENVLOFFSET | 0
D3DTSS_TEXTURETRANSFORMFLAGS | D3DTTFF_DISABLE
D3DTSS_COLORARG0 | D3DTA_CURRENT
D3DTSS_ALPHAARG0 | D3DTA_CURRENT
D3DTSS_RESULTARG | D3DTA_CURRENT


Render States (Direct3D 9)

Device render states affect the behavior of almost every part of the pipeline. Render states are set by calling IDirect3DDevice9::SetRenderState.

Additional information is contained in the following topics:

  • Alpha Blending State (Direct3D 9)
  • Alpha Testing State (Direct3D 9)
  • Ambient Lighting State (Direct3D 9)
  • Antialiasing State (Direct3D 9)
  • Culling State (Direct3D 9)
  • Depth Buffering State (Direct3D 9)
  • Fog State (Direct3D 9)
  • Lighting State (Direct3D 9)
  • Outline and Fill State (Direct3D 9)
  • Per-Vertex Color State (Direct3D 9)
  • Primitive Clipping State (Direct3D 9)
  • Shading State (Direct3D 9)
  • Stencil Buffer State (Direct3D 9)
  • Texture Wrapping State (Direct3D 9)


Alpha Blending State (Direct3D 9)

The alpha value of a color controls its transparency. Enabling alpha blending allows colors, materials, and textures on a surface to be blended with transparency onto another surface.

For more information, see Alpha Texture Blending (Direct3D 9) and Texture Blending (Direct3D 9).

Applications written in C++ use the D3DRS_ALPHABLENDENABLE render state to enable alpha transparency blending. The Direct3D API allows many types of alpha blending. However, it is important to note the user's 3D hardware might not support all the blending states allowed by Direct3D.

The type of alpha blending that is done depends on the D3DRS_SRCBLEND And D3DRS_DESTBLEND render states. Source and destination blend states are used in pairs. The following code example demonstrates how the source blend state is set to D3DBLEND_SRCCOLOR and the destination blend state is set to D3DBLEND_INVSRCCOLOR.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice9 interface.

// Set the source blend state.
d3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR);

// Set the destination blend state.

d3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);

Altering the source and destination blend states can give the appearance of emissive objects in a foggy or dusty atmosphere. For instance, if your application models flames, force fields, plasma beams, or similarly radiant objects in a foggy environment, set the source and destination blend states to D3DBLEND_ONE.

Another application of alpha blending is to control the lighting in a 3D scene, also called light mapping. Setting the source blend state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCALPHA darkens a scene according to the source alpha information. The source primitive is used as a light map that scales the contents of the frame buffer to darken it when appropriate. This produces monochrome light mapping.

You can achieve color light mapping by setting the source alpha blending state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCCOLOR.


Alpha Testing State (Direct3D 9)

C++ applications can use alpha testing to control when pixels are written to the render-target surface. By using the D3DRS_ALPHATESTENABLE render state, your application sets the current Direct3D device so that it tests each pixel according to an alpha test function. If the test succeeds, the pixel is written to the surface. If it does not, Direct3D ignores the pixel. Select the alpha test function with the D3DRS_ALPHAFUNC render state. Your application can set a reference alpha value for all pixels to compare against by using the D3DRS_ALPHAREF render state.

The most common use for alpha testing is to improve performance when rasterizing objects that are nearly transparent. If the color data being rasterized is more opaque than the color at a given pixel (D3DPCMPCAPS_GREATEREQUAL), then the pixel is written. Otherwise, the rasterizer ignores the pixel altogether, saving the processing required to blend the two colors. The following code example checks if a given comparison function is supported and, if so, it sets the comparison function parameters required to improve performance during rendering.

// This code example assumes that pCaps is a
// D3DCAPS9 structure that was filled with a
// previous call to IDirect3D9::GetDeviceCaps.

if (pCaps.AlphaCmpCaps & D3DPCMPCAPS_GREATEREQUAL)
{
    dev->SetRenderState(D3DRS_ALPHAREF, (DWORD)0x00000001);
    dev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
    dev->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
}

// If the comparison is not supported, render anyway.
// The only drawback is no performance gain.

Not all hardware supports all alpha-testing features. You can check the device capabilities by calling the IDirect3D9::GetDeviceCaps method. After retrieving the device capabilities, check the associated D3DCAPS9 structure's AlphaCmpCaps member for the desired comparison function. If the AlphaCmpCaps member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests.


Ambient Lighting State (Direct3D 9)

Ambient light is surrounding light that radiates from all directions. For information about how Direct3D uses ambient light, see Mathematics of Lighting (Direct3D 9).

A C++ application sets the color of ambient lighting by invoking the IDirect3DDevice9::SetRenderState method and passing the enumerated value D3DRS_AMBIENT as the first parameter. The second parameter is a color value. The default value is zero.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice9 interface.

// Set the ambient light.

d3dDevice->SetRenderState(D3DRS_AMBIENT, 0x00202020);


Antialiasing State (Direct3D 9)

Antialiasing (Direct3D 9) is a method of making lines and edges appear smoother on the screen. By default, Direct3D does not perform antialiasing. To enable full-scene antialiasing, set the D3DRS_MULTISAMPLEANTIALIAS render state to TRUE. To disable it, set D3DRS_MULTISAMPLEANTIALIAS to FALSE.


Culling State (Direct3D 9)

To improve rendering performance, you can cull out (or remove) a primitive that faces away from the camera. For single-sided primitives, this saves rendering time because a back-face is not visible. To enable culling, you need to know the winding order of the vertices (typically counter-clockwise). This example will remove any primitive whose back face is facing forward (given a counter-clockwise winding order):

SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);


Depth Buffering State (Direct3D 9)

Depth buffering is a method of removing hidden lines and surfaces. By default, Direct3D does not use depth buffering.

For a conceptual overview of depth buffers, see Depth Buffers (Direct3D 9).

C++ applications update the depth-buffering state with the D3DRS_ZENABLE render state, using a member of the D3DZBUFFERTYPE enumeration to specify the new state value.

If your application needs to prevent Direct3D from writing to the depth buffer, it can use the D3DRS_ZWRITEENABLE enumerated value, specifying D3DZB_FALSE as the second parameter for the call to IDirect3DDevice9::SetRenderState.

The following code example shows how the depth-buffer state is set to enable z-buffering.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice9 interface.
// Enable z-buffering.
d3dDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);

Your application can also use the D3DRS_ZFUNC render state to control the comparison function that Direct3D uses when performing depth buffering.

Z-biasing is a method of displaying one surface in front of another, even if their depth values are the same. You can use this technique for a variety of effects. A common example is rendering shadows on walls. Both the shadow and the wall have the same depth value. However, you want your application to show the shadow on the wall. Giving a z-bias to the shadow makes Direct3D display them properly (see D3DRS_DEPTHBIAS).


Fog State (Direct3D 9)

Fog effects can give a 3D scene greater realism. You can use fog effects for more than simulating fog. They can also decrease the clarity of a scene with distance. This mirrors what happens in the real world; as objects become more distant from the user, their detail is less distinct.

For more information about using fog in your application, see Fog (Direct3D 9).

A C++ application controls fog through device rendering states. The D3DRENDERSTATETYPE enumerated type includes states to control whether pixel (table) or vertex fog is used, what color it is, the fog formula the system applies, and the parameters of the formula.

You enable fog by setting the D3DRS_FOGENABLE render state to TRUE. The fog color can be set to any color value by using the D3DRS_FOGCOLOR render state; the alpha component of the fog color is ignored.

The D3DRS_FOGTABLEMODE and D3DRS_FOGVERTEXMODE render states control the fog formula applied for fog calculations, and they indirectly control which type of fog is applied. Both render states can be set to a member of the D3DFOGMODE enumerated type. Setting either render state to D3DFOG_NONE disables pixel or vertex fog, respectively. If both render states are set to valid modes, the system applies only pixel fog effects.

The D3DRS_FOGSTART and D3DRS_FOGEND render states control fog formula parameters for the D3DFOG_LINEAR mode. The D3DRS_FOGDENSITY render state controls fog density in the exponential fog modes.

For more information, see Fog Parameters (Direct3D 9).


Lighting State (Direct3D 9)

If you do not light with a vertex shader or a pixel shader, you may choose to use the lighting engine in the runtime. The lighting engine requires that the vertex data contains per-vertex normals; vertices without normal data will generate a dot product of zero in all lighting computations. The lighting calculations are covered in more detail in Mathematics of Lighting (Direct3D 9).

To enable the lighting engine, use:

SetRenderState(D3DRS_LIGHTING, TRUE);


Outline and Fill State (Direct3D 9)

Primitives that have no textures are rendered with the color specified by their material, or with the colors specified for the vertices, if any. You can select the method to fill them by specifying a value defined by the D3DFILLMODE enumerated type for the D3DRS_FILLMODE render state.

To enable dithering, your application must pass the D3DRS_DITHERENABLE enumerated value as the first parameter to IDirect3DDevice9::SetRenderState. It must set the second parameter to TRUE to enable dithering, and FALSE to disable it.

At times, drawing the last pixel in a line can cause unsightly overlap with surrounding primitives. You can control this using the D3DRS_LASTPIXEL enumerated value. However, do not alter this setting without some forethought. Under some conditions, suppressing the rendering of the last pixel can cause unsightly gaps between primitives.

Object outlines can be drawn by setting the appropriate line drawing pattern. The default line drawing state is to draw solid lines. For more information, see Line Drawing Support in D3DX (Direct3D 9) render state.


Per-Vertex Color State (Direct3D 9)

The Direct3D lighting engine can use per-vertex color data when performing lighting if you tell the runtime the data is present. This is done by turning on the following render state:

// disable per-vertex color
SetRenderState(D3DRS_COLORVERTEX, FALSE);

// enable per-vertex color
SetRenderState(D3DRS_COLORVERTEX, TRUE);

If per-vertex color is enabled, applications can configure the source from which the system retrieves color information for a vertex. The D3DRS_AMBIENTMATERIALSOURCE, D3DRS_DIFFUSEMATERIALSOURCE, D3DRS_EMISSIVEMATERIALSOURCE, and D3DRS_SPECULARMATERIALSOURCE render states control the ambient, diffuse, emissive, and specular color component sources, respectively. Each state can be set to members of the D3DMATERIALCOLORSOURCE enumerated type, which defines constants that instruct the system to use the current material, diffuse color, or specular color as the source for the specified color component.


Primitive Clipping State (Direct3D 9)

Primitives that lie partially inside (or completely outside) the view frustum can be clipped so that only the visible portion of the primitive will be rendered. Clipping reduces the amount of work that is done to only those primitives or portions of a primitive that will be visible.

To use the pipeline for clipping, set the D3DRS_CLIPPING render state to TRUE (the default value) to enable clipping, or to FALSE to disable Direct3D clipping.


Shading State (Direct3D 9)

Direct3D supports both flat and Gouraud shading. The default is Gouraud shading. To control the current shading mode, your C++ application specifies a member of the D3DSHADEMODE enumerated type for the D3DRS_SHADEMODE render state.

The following C++ code example demonstrates the process of setting the shading state to flat shading mode.

// This code example assumes that d3dDevice is a
// valid pointer to a IDirect3DDevice9 interface.
// Set the shading state.
d3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);


Stencil Buffer State (Direct3D 9)

Applications use the stencil buffer to determine whether a pixel is written to the rendering target surface. For details, see Stencil Buffer Techniques (Direct3D 9).


Texture Wrapping State (Direct3D 9)

The D3DRS_WRAP0 thru D3DRS_WRAP7 render states enable and disable u- and v-wrapping for various textures in the device's multitexture cascade. You can set these render states to a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags to enable wrapping in first, second, third, and fourth directions of the texture. Use a value of zero to disable wrapping altogether. Texture wrapping is disabled in all directions for all texture stages by default.

For a conceptual overview, see Texture Wrapping (Direct3D 9).


Direct3D Resources (Direct3D 9)

Resources are the textures and buffers that are used to render a scene. Applications need to create, load, copy, and use resources. This section gives a brief introduction to resources and the steps and methods used by applications when working with resources.

All resources, including the geometry resources IDirect3DIndexBuffer9 and IDirect3DVertexBuffer9, inherit from the IDirect3DResource9 interface. The texture resources, IDirect3DCubeTexture9, IDirect3DTexture9, and IDirect3DVolumeTexture9, also inherit from the IDirect3DBaseTexture9 interface.

  • Resource Properties (Direct3D 9)
  • Manipulating Resources (Direct3D 9)
  • Locking Resources (Direct3D 9)
  • Resource Relationships (Direct3D 9)
  • Managing Resources (Direct3D 9)
  • Application-Managed Resources and Allocation Strategies (Direct3D 9)
  • Index Buffers (Direct3D 9)
  • Vertex Buffers (Direct3D 9)


Resource Properties (Direct3D 9)

All resources share the following properties.

  • Usage. The way a resource is used, for example, as a texture or a render target.
  • Format. The format of the data, for example, the pixel format of a 2D surface.
  • Pool. The type of memory where the resource is allocated.
  • Type. The type of resource, for example, a vertex buffer or render target.

Resource uses are enforced. An application that will use a resource in a certain operation must specify that operation at resource-creation time. For a list of the usage constants defined for resources, see D3DUSAGE.

The D3DUSAGE_RTPATCHES, D3DUSAGE_NPATCHES, and D3DUSAGE_POINTS constants indicate to the driver that the data in these buffers is likely to be used for triangular or grid patches, N-patches, or point sprites, respectively. These flags are provided in case the hardware cannot perform these operations without host processing. Therefore, the driver will want to allocate these surfaces in system memory so that the CPU can access them. If the driver can perform these operations entirely in hardware, it can allocate these surfaces in video or AGP memory to avoid a host copy and improve performance at least twofold. Note that the information provided by these flags is not absolutely required. A driver can detect that such operations are being performed on the data, and it will move the buffer back to system memory for subsequent frames.

For details about the usage flags and how they relate to specific resources, see the reference pages on the individual resource creation methods.

For information about the surface format of resources, see the D3DFORMAT enumerated type.

The class of memory that holds a resource's buffers is called a pool. Pool values are defined by the D3DPOOL enumerated type. A pool cannot be mixed for different objects contained in a single resource - that is, mip levels in a mipmap - and, when a pool is chosen for a resource, the pool cannot be changed.

The resources types are set implicitly at run time when the application calls a resource creation method such as IDirect3DDevice9::CreateCubeTexture. Resource types are defined by the D3DRESOURCETYPE enumerated type. Applications can query these types at run time; however, it is expected that most scenarios will not require run-time type checking.


Manipulating Resources (Direct3D 9)

Your application manipulates resources in order to render a scene. First, an application needs to create a texture resource with one of the following methods:

  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVolumeTexture

A texture resource can instead be created with one of the D3DXCreatexxx texturing functions.

The texture objects returned by the texture creation methods are containers for surfaces or volumes; these containers are generically known as buffers. The buffers owned by the resource inherit the usages, format, and pool of the resource but have their own type. For more information, see Resource Properties (Direct3D 9).

The application gains access to the contained surfaces, for the purpose of loading artwork, by calling the following methods. For details, see Locking Resources (Direct3D 9).

  • IDirect3DCubeTexture9::LockRect
  • IDirect3DTexture9::LockRect
  • IDirect3DVolumeTexture9::LockBox

The lock methods take arguments denoting the contained surface - for example, the mipmap sub-level or cube face of the texture - and return pointers to the pixels. The typical application never uses a surface object directly.

Create geometry-oriented resources by calling IDirect3DDevice9::CreateIndexBuffer or IDirect3DDevice9::CreateVertexBuffer.

Lock and fill the buffer resources by calling either IDirect3DIndexBuffer9::Lock or IDirect3DVertexBuffer9::Lock, depending upon the resource.

For managed texture resources, the resource creation process ends here. For non-managed texture resources, an application promotes system memory resources to device-accessible resources (for hardware acceleration) by calling IDirect3DDevice9::UpdateTexture.

To present images rendered from resources, the application also needs color and depth-stencil buffers. For typical applications, the color buffer is owned by the device's swap chain, which is a collection of back-buffer surfaces, and is implicitly created with the device. Depth-stencil surfaces can be implicitly created, or explicitly created by using the IDirect3DDevice9::CreateDepthStencilSurface method. The application associates a device and its depth and color buffer with a call to IDirect3DDevice9::SetRenderTarget or IDirect3DDevice9::SetDepthStencilSurface.

For details on presenting the final image, see Presenting a Scene (Direct3D 9).


Locking Resources (Direct3D 9)

Locking a resource means granting CPU access to its storage. The following locking options are defined for resources:

  • D3DLOCK_DISCARD
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_NO_DIRTY_UPDATE

For details on locking flags and how they relate to specific resources, see the reference pages on the individual resource locking methods. Application developers should note that the D3DLOCK_DISCARD, D3DLOCK_READONLY, and D3DLOCK_NOOVERWRITE flags are only hints. The run time does not check that applications are following the functionality specified by these flags. An application that specifies D3DLOCK_READONLY but then writes to the resource should expect undefined results. In general, working against locking flags, including the locking usage flags, is not guaranteed to work in later releases and may incur a significant performance penalty.

A lock operation is followed by an unlock operation. For example, after locking a texture, the application subsequently relinquishes direct access to locked textures by unlocking them. In addition to granting processor access, any other operations involving that resource are serialized for the duration of a lock. Only a single lock for a resource is allowed, even for non-overlapping regions, and no accelerator operations on a surface can be ongoing while a lock operation is outstanding on that surface.

Each resource interface has methods for locking the contained buffers. Each texture resource can also lock a sub-portion of that resource. 2D resources (surfaces) allow the locking of sub-rectangles, and volume resources allow the locking of sub-volumes or boxes. Each lock method returns a structure that contains a pointer to the storage backing the resource and values representing the distances between rows or planes of data, depending on the resource type. For details, see the method lists for the resource interfaces. The returned pointer always points to the top-left byte in the locked sub-regions.

When working with index and vertex buffers, you can make multiple lock calls; however, you must ensure that the number of lock calls matches the number of unlock calls.

The DXTn store pixels in encoded 4x4 blocks, and can only be locked on 4x4 boundaries.


Resource Relationships (Direct3D 9)

The following diagram illustrates the operations that are syntactically possible on specific resources and their contents. For more information about how to use resources, see Manipulating Resources (Direct3D 9).

Arrows running from left to right indicate that the target types are created by the given methods, while arrows running from right to left indicate that those resource types can be passed as arguments to the given methods.


Managing Resources (Direct3D 9)

Resource management is the process where resources are promoted from system-memory storage to device-accessible storage and discarded from device-accessible storage. The Direct3D run time has its own management algorithm based on a least-recently-used priority technique. Direct3D switches to a most-recently-used priority technique when it detects that more resources than can coexist in device-accessible memory are used in a single frame - between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene calls.

Use the D3DPOOL_DEFAULT flag at creation time to specify that a resource are placed in the memory pool most appropriate for the set of usages requested for the given resource. This is usually video memory, including both local video memory and accelerated graphics port (AGP) memory. Resources in the default pool do not persist through transitions between the lost and operational states of the device. These resources must be released before calling reset and must then be re-created.

Use the D3DPOOL_MANAGED flag at creation time to specify a managed resource. Managed resources persist through transitions between the lost and operational states of the device. These resources exist both in video and system memory. A managed resource will be copied into video memory when it is needed during rendering. The device can be restored with a call to IDirect3DDevice9::Reset, and such resources continue to function normally without being reloaded with data. However, if the device must be destroyed and re-created, all resources must be re-created.

Resource management is not recommended for resources which change with high frequency. For example, vertex and index buffers which are used to traverse a scene graph every frame rendering only geometry visible to the user changes every frame. Since managed resources are backed by system memory, the constant changes must be updated in system memory, which can cause a severe degradation in performance. For this particular scenario, D3DPOOL_DEFAULT along with D3DUSAGE_DYNAMIC should be used.

Another example for which resource management is not recommended (and explicitly not allowed by the runtime) is management of a texture created with D3DUSAGE_RENDERTARGET. If the memory used by render targets were managed by the runtime, it's contents would have to constantly be copied to system memory during rendering, causing large performance penalties. For this reason, render targets must be created in the default pool. If CPU access of the data contained in a render target is needed, the data must be copied to a resource created in D3DPOOL_SYSTEMMEM using IDirect3DDevice9::UpdateTexture, or IDirect3DDevice9::UpdateSurface

For more information about the lost state of a device, see Lost Devices (Direct3D 9).


Application-Managed Resources and Allocation Strategies (Direct3D 9)

Managed vertex-buffer or index-buffer resources cannot be declared dynamic by specifying D3DUSAGE_DYNAMIC at creation time. This would require an additional copy for every modification to the vertex buffer contents. Dynamic vertex buffers are intended for rendering dynamic geometry and data pulled in from binary space partitioned trees or other visibility data structures. This can be accomplished by pre-allocating buffers of the desired format. These resources are then parceled out to support application needs by a resource manager within the application. The total number of dynamic vertex buffers is small because an application will use simultaneously only a few different vertex strides and because a different vertex buffer is required only for unique strides. When managing dynamic resources in this way, ensure that high-frequency demands on the resources do not significantly decrease the application's performance.

When using resources managed by both Direct3D and applications, allocate application-managed resources in D3DPOOL_DEFAULT memory prior to creating Direct3D-managed resources. This enables the memory manager to maintain an accurate count of available memory.


Vertex Buffers (Direct3D 9)

Vertex buffers, represented by the IDirect3DVertexBuffer9 interface, are memory buffers that contain vertex data. Vertex buffers can contain any vertex type - transformed or untransformed, lit or unlit - that can be rendered through the use of the rendering methods in the IDirect3DDevice9 interface. You can process the vertices in a vertex buffer to perform operations such as transformation, lighting, or generating clipping flags. Transformation is always performed.

The flexibility of vertex buffers make them ideal staging points for reusing transformed geometry. You could create a single vertex buffer, transform, light, and clip the vertices in it, and render the model in the scene as many times as needed without re-transforming it, even with interleaved render state changes. This is useful when rendering models that use multiple textures: the geometry is transformed only once, and then portions of it can be rendered as needed, interleaved with the required texture changes. Render state changes made after vertices are processed take effect the next time the vertices are processed.

  • Description
  • Memory Pool and Usage

Description

A vertex buffer is described in terms of its capabilities: if it can exist only in system memory, if it is only used for write operations, and the type and number of vertices it can contain. All these traits are held in a D3DVERTEXBUFFER_DESC structure.

The Format member is set to D3DFMT_VERTEXDATA to indicate that this is a vertex buffer. The Type identifies the resource type of the vertex buffer. The Usage structure member contains general capability flags. The D3DUSAGE_SOFTWAREPROCESSING flag indicates that the vertex buffer is to be used with software vertex processing. The presence of the D3DUSAGE_WRITEONLY flag in Usage indicates that the vertex buffer memory is used only for write operations. This frees the driver to place the vertex data in the best memory location to enable fast processing and rendering. If the D3DUSAGE_WRITEONLY flag is not used, the driver is less likely to put the data in a location that is inefficient for read operations. This sacrifices some processing and rendering speed. If this flag is not specified, it is assumed that applications perform read and write operations on the data within the vertex buffer.

Pool specifies the memory class that is allocated for the vertex buffer. The D3DPOOL_SYSTEMMEM flag indicates that the system created the vertex buffer in system memory.

The Size member stores the size, in bytes, of the vertex buffer data. The FVF member contains a combination of D3DFVF that identify the type of vertices that the buffer contains.

Memory Pool and Usage

You can create vertex buffers with the IDirect3DDevice9::CreateVertexBuffer method, which takes pool (memory class) and usage parameters. IDirect3DDevice9::CreateVertexBuffer can also be created with a specified FVF code for use in fixed function vertex processing, or as the output of process vertices. For details, see FVF Vertex Buffers (Direct3D 9).

The D3DUSAGE_SOFTWAREPROCESSING flag can be set when mixed-mode or software vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING / D3DCREATE_SOFTWARE_VERTEXPROCESSING) is enabled for that device. D3DUSAGE_SOFTWAREPROCESSING must be set for buffers to be used with software vertex processing in mixed mode, but it should not be set for the best possible performance when using hardware vertex processing in mixed mode.(D3DCREATE_HARDWARE_VERTEXPROCESSING). However, setting D3DUSAGE_SOFTWAREPROCESSING is the only option when a single buffer is to be used with both hardware and software vertex processing. D3DUSAGE_SOFTWAREPROCESSING is allowed for mixed as well as for software devices.

It is possible to force vertex and index buffers into system memory by specifying D3DPOOL_SYSTEMMEM, even when the vertex processing is done in hardware. This is a way to avoid overly large amounts of page-locked memory when a driver is putting these buffers into AGP memory.

This section introduces the concepts necessary to understand and use vertex buffers in a Direct3D application. Information is divided into the following sections.

  • Creating a Vertex Buffer (Direct3D 9)
  • Accessing the Contents of a Vertex Buffer (Direct3D 9)
  • Rendering from a Vertex Buffer (Direct3D 9)
  • FVF Vertex Buffers (Direct3D 9)
  • Fixed Function Vertex Processing (Direct3D 9)
  • Programmable Vertex Processing (Direct3D 9)
  • Device Types and Vertex Processing Requirements (Direct3D 9)

See Also

Rendering from Vertex and Index Buffers (Direct3D 9) | Index Buffers (Direct3D 9)

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


Creating a Vertex Buffer (Direct3D 9)

You create a vertex buffer object by calling the IDirect3DDevice9::CreateVertexBuffer method, which accepts five parameters. The first parameter specifies the vertex buffer length, in bytes. Use the sizeof operator to determine the size of a vertex format, in bytes. Consider the following custom vertex format.

struct CUSTOMVERTEX {
        FLOAT x, y, z;
        FLOAT rhw;
        DWORD color;
        FLOAT tu, tv;   // Texture coordinates
};

// Custom flexible vertex format (FVF) describing the custom vertex structure
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1)

To create a vertex buffer to hold four CUSTOMVERTEX structures, specify [4*sizeof(CUSTOMVERTEX)] for the Length parameter.

The second parameter is a set of usage controls. Among other things, its value determines whether the vertex buffer is capable of containing clipping information - in the form of clip flags - for vertices that exist outside the viewing area. To create a vertex buffer that cannot contain clip flags, include the D3DUSAGE_DONOTCLIP flag for the Usage parameter. The D3DUSAGE_DONOTCLIP flag is applied only if you also indicate that the vertex buffer will contain transformed vertices - the D3DFVF_XYZRHW flag is included in the FVF parameter. The IDirect3DDevice9::CreateVertexBuffer method ignores the D3DUSAGE_DONOTCLIP flag if you indicate that the buffer will contain untransformed vertices (the D3DFVF_XYZ flag). Clipping flags occupy additional memory, making a clipping-capable vertex buffer slightly larger than a vertex buffer incapable of containing clipping flags. Because these resources are allocated when the vertex buffer is created, you must request a clipping-capable vertex buffer ahead of time.

The third parameter, FVF, is a combination of D3DFVF that describe the vertex format of the vertex buffer. If you specify 0 for this parameter, then the vertex buffer is a non-FVF vertex buffer. For more information, see FVF Vertex Buffers (Direct3D 9). The fourth parameter describes the memory class into which to place the vertex buffer.

The final parameter that IDirect3DDevice9::CreateVertexBuffer accepts is the address of a variable that will be filled with a pointer to the new IDirect3DVertexBuffer9 interface of the vertex buffer object, if the call succeeds.

You cannot produce clip flags for a vertex buffer that was created without support for them.

The following C++ code example shows what creating a vertex buffer might look like in code.

// d3dDevice contains the address of an IDirect3DDevice9 interface
// g_pVB is a variable of type LPDIRECT3DVERTEXBUFFER9

// The custom vertex type
struct CUSTOMVERTEX {
    FLOAT x, y, z;
    FLOAT rhw;
    DWORD color;
    FLOAT tu, tv;   // The texture coordinates
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1)

// Create a clipping-capable vertex buffer. Allocate enough memory
// in the default memory pool to hold three CUSTOMVERTEX
// structures

    if( FAILED( d3dDevice->CreateVertexBuffer( 3*sizeof(CUSTOMVERTEX),
            0 /*Usage*/, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )
        return E_FAIL;


Accessing the Contents of a Vertex Buffer (Direct3D 9)

Vertex buffer objects enable applications to directly access the memory allocated for vertex data. You can retrieve a pointer to vertex buffer memory by calling the IDirect3DVertexBuffer9::Lock method, and then accessing the memory as needed to fill the buffer with new vertex data or to read any data it already contains. The IDirect3DVertexBuffer9::Lock method accepts four parameters. The first, OffsetToLock, is the offset into the vertex data. The second parameter is the size, measured in bytes, of the vertex data. The third parameter accepted is the address of a pointer that points to the vertex data, if the call succeeds.

The last parameter, Flags, tells the system how the memory should be locked. Specify constants for the Flags parameter according to the way the vertex data will be accessed. Make sure the value chosen for D3DUSAGE matches the value chosen for D3DLOCK. For example, if you are creating a vertex buffer with write access only, it doesn't make sense to try to read the data by specifying D3DLOCK_READONLY. Wisely using these flags allows the driver to lock the memory and provide the best performance, given the requested access type.

After you finish filling or reading the vertex data, call the IDirect3DVertexBuffer9::Unlock method, as shown in the following code example.

// This code example assumes the g_pVB is a variable of type
//   LPDIRECT3DVERTEXBUFFER9 and that g_Vertices has been
//   properly initialized with vertices

// Lock the buffer to gain access to the vertices
VOID* pVertices;

if(FAILED(g_pVB->Lock(0, sizeof(g_Vertices),
        (BYTE**)&pVertices, 0 ) ) )
    return E_FAIL;

memcpy(pVertices, g_Vertices, sizeof(g_Vertices));
g_pVB->Unlock();

If you create a vertex buffer with the D3DUSAGE_WRITEONLY flag, do not use the D3DLOCK_READONLY locking flag. Use the D3DLOCK_READONLY flag if your application will read only from the vertex buffer memory. Including this flag enables Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

See Using Dynamic Vertex and Index Buffers for information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of IDirect3DVertexBuffer9::Lock.

In C++, because you directly access the memory allocated for the vertex buffer, make sure your application properly accesses the allocated memory. Otherwise, you risk rendering that memory invalid. Use the stride of the vertex format that your application uses to move from one vertex in the allocated buffer to another. The vertex buffer memory is a simple array of vertices specified in FVF. Use the stride of whatever vertex format structure you define. You can calculate the stride of each vertex at run time by examining the D3DFVF contained in the vertex buffer description. The following table shows the size for each vertex component.

Vertex Format Flag | Size
D3DFVF_DIFFUSE | sizeof(DWORD)
D3DFVF_NORMAL | sizeof(float) x 3
D3DFVF_SPECULAR | sizeof(DWORD)
D3DFVF_TEXn | sizeof(float) x n
D3DFVF_XYZ | sizeof(float) x 3
D3DFVF_XYZRHW | sizeof(float) x 4

The number of texture coordinates present in the vertex format is described by the D3DFVF_TEX n flags (where n is a value from 0 to 8). Multiply the number of texture coordinate sets by the size of one set of texture coordinates, which can range from one to four floats, to calculate the memory required for that number of texture coordinates.

Use the total vertex stride to increment and decrement the memory pointer as needed to access particular vertices.

Retrieving Vertex Buffer Descriptions

You can retrieve information about a vertex buffer by calling the IDirect3DVertexBuffer9::GetDesc method. This method fills the members of the D3DVERTEXBUFFER_DESC structure with information about the vertex buffer.


Rendering from a Vertex Buffer (Direct3D 9)

Rendering vertex data from a vertex buffer requires a few steps. First, you need to set the stream source by calling the IDirect3DDevice9::SetStreamSource method, as shown in the following example.

d3dDevice->SetStreamSource( 0, g_pVB, sizeof(CUSTOMVERTEX) );

The first parameter of IDirect3DDevice9::SetStreamSource tells Direct3D the source of the device data stream. The second parameter is the vertex buffer to bind to the data stream. The third parameter is the size of the component, in bytes. In the sample code above, the size of a CUSTOMVERTEX is used for the size of the component.

The next step is to inform Direct3D which vertex shader to use by calling the IDirect3DDevice9::SetVertexShader method. The following sample code sets an FVF code for the vertex shader. This informs Direct3D of the types of vertices it is dealing with.

d3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );

After setting the stream source and vertex shader, any draw methods will use the vertex buffer. The code example below shows how to render vertices from a vertex buffer with the IDirect3DDevice9::DrawPrimitive method.

d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 );

The second parameter that IDirect3DDevice9::DrawPrimitive accepts is the index of the first vector in the vertex buffer to load.

See Also

Rendering from Vertex and Index Buffers (Direct3D 9)


FVF Vertex Buffers (Direct3D 9)

Setting the FVF parameter of the IDirect3DDevice9::CreateVertexBuffer method to a nonzero value, which must be a valid FVF code, indicates that the buffer content is to be characterized by an FVF code. A vertex buffer that is created with an FVF code is referred to as an FVF vertex buffer. Some methods or uses of IDirect3DDevice9 require FVF vertex buffers, and others require non-FVF vertex buffers. FVF vertex buffers are required as the destination vertex buffer argument for IDirect3DDevice9::ProcessVertices.

FVF vertex buffers can be bound to a source data stream for any stream number.

The presence of the D3DFVF_XYZRHW component on FVF vertex buffers indicates that the vertices in that buffer have been processed. Vertex buffers used for IDirect3DDevice9::ProcessVertices destination vertex buffers must be post-processed. Vertex buffers used for fixed function shader inputs can be either preprocessed or postprocessed. If the vertex buffer is post-processed, then the shader is effectively bypassed and the data is passed directly to the primitive clipping and setup module.

FVF vertex buffers can be used with vertex shaders. Also, vertex streams can represent the same vertex formats that non-FVF vertex buffers can. They do not have to be used to input data from separate vertex buffers. The additional flexibility of the new vertex streams enables applications that need to keep their data separate to work better, but it is not required. If the application can maintain interleaved data in advance, then that is a performance boost. If the application will only interleave the data before every rendering call, then it should enable the API or hardware to do this with multiple streams.

The most important things with vertex performance is to use a 32-byte vertex, and to maintain good cache ordering.


Fixed Function Vertex Processing (Direct3D 9)

In the fixed function vertex pipeline, processing the vertices in a vertex buffer applies the current transformation matrices for the device. Vertex operations such as lighting, generating clip flags, and updating extents can also be applied, optionally. When using fixed function vertex processing, modifying the elements in the destination vertex buffer is controlled by the D3DPV_DONOTCOPYDATA flag. This flag applies only to fixed function vertex processing. The IDirect3DDevice9 interface exposes the IDirect3DDevice9::ProcessVertices method to process vertices. You process vertices from a vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer by calling the IDirect3DDevice9::ProcessVertices method. The method accepts five parameters that describe the location and quantity of vertices that the method targets, the destination vertex buffer, and the processing options. After the call, the destination buffer contains the processed vertex data.

The first, second, and third parameters, SrcStartIndex, DestIndex, and VertexCount, reflect the index of the first vertex to load, the index within the destination buffer at which the vertices will be placed, and the total number of vertices to process and place in the destination buffer, respectively. The fourth parameter, pDestBuffer should be set to the address of the IDirect3DVertexBuffer9 interface of the vertex buffer object that will receive the source vertices. The SrcStartIndex parameter specifies the index at which the method should start processing vertices.

The final parameter, Flags, determines special processing options for the method. You can set this parameter to 0 for default vertex processing, or to D3DPV_DONOTCOPYDATA to optimize processing in some situations. You can also combine the D3DPV_DONOTCOPYDATA value with one or more D3DLOCK values appropriate for the destination buffer. When you set Flags to 0, vertex components of the destination vertex buffer's vertex format that are not affected by the vertex operation are still copied from the vertex shader or set to 0. However, when using D3DPV_DONOTCOPYDATA, IDirect3DDevice9::ProcessVertices does not overwrite color and texture coordinate information in the destination buffer unless this data is generated by Direct3D. Diffuse color is generated when lighting is enabled, that is, D3DRS_LIGHTING is set to TRUE. Specular color is generated when lighting is enabled and specular is enabled, that is, D3DRS_SPECULARENABLE and D3DRS_LIGHTING are set to TRUE. Specular color is also generated when fog is enabled. Texture coordinates are generated when texture transform or texture generation is enabled. IDirect3DDevice9::ProcessVertices uses the current render states to determine what vertex processing should be done.

FVF Usage Settings for Destination Vertex Buffers

The IDirect3DDevice9::ProcessVertices method requires specific settings for the D3DFVF of the destination vertex buffer. The FVF usage settings must be compatible with the current settings for vertex processing.

For fixed function vertex processing, IDirect3DDevice9::ProcessVertices requires the following FVF settings:

  • Position type is always D3DFVF_XYZRHW ; therefore, D3DFVF_XYZ And D3DFVF_XYZB1 through D3DFVF_XYZB5 Are invalid.
  • The D3DFVF_NORMAL, D3DFVF_RESERVED0, and D3DFVF_RESERVED2 flags must not be set.
  • The D3DFVF_DIFFUSE flag must be set if an OR operation of the following conditions returns true:
    • Lighting is enabled; that is, D3DRS_LIGHTING is true.
    • Lighting is disabled, diffuse color is present in the input vertex streams, and D3DPV_DONOTCOPYDATA is not set.
  • The D3DFVF_SPECULAR flag must be set if an OR operation of the following conditions returns true:
    • Lighting is enabled and specular color is enabled; that is, D3DRS_SPECULARENABLE is true.
    • Lighting is disabled, specular color is present in the input vertex streams, and D3DPV_DONOTCOPYDATA is not set.
    • Vertex fog is enabled; that is, D3DRS_FOGVERTEXMODE is not set to D3DFOG_NONE.

In addition, the texture coordinate count must be set in the following manner:

  • If texture transform and texture generation are disabled for all active texture stages, and the D3DPV_DONOTCOPYDATA is not set, then the number and type of output texture coordinates are required to match those of the input vertex texture coordinates. If D3DPV_DONOTCOPYDATA is set and texture transform and texture generation are disabled, then the output texture coordinates are ignored.
  • If texture transform or texture generation is enabled for any active texture stages, the output vertex might need to contain more texture coordinate sets than the input vertex. This is due to the proliferation of texture coordinates from those being generated by texture generation or derived by texture transforms. Note that a similar proliferation of texture coordinates occurs during IDirect3DDevice9::DrawPrimitive calls, but is not visible to the application programmer. In this case, Direct3D generates a new set of texture coordinates. The new set of texture coordinates is derived by stepping through the texture stages and analyzing the settings for texture generation, texture transformation, and texture coordinate index to determine if a unique set of texture coordinates is required for that stage. Each time a new set is required it is allocated in increasing order. Note that the maximum, and typical, requirement is one set per stage, although it might be less due to sharing of nontransformed texture coordinates through D3DTSS_TEXCOORDINDEX.

Thus, for each texture stage, a new set of texture coordinates is generated if a texture is bound to that stage and any of the following conditions are true:

  • Texture generation is enabled for that stage.
  • Texture transformation is enabled for that stage.
  • Nontransformed input texture coordinates are referenced through D3DTSS_TEXCOORDINDEX for the first time.

When Direct3D is generating texture coordinates, the application is required to perform the following actions:

  1. Use a destination vertex buffer with the appropriate FVF usage.
  2. Reprogram the D3DTSS_TEXCOORDINDEX of the texture stage according to the placement of the postprocessed texture coordinates. Note that the reprogramming of the D3DTSS_TEXCOORDINDEX setting occurs when the processed vertex buffer is used in subsequent IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive calls.

Finally, texture coordinate dimensionality (D3DFVF_TEX0 through D3DFVF_TEX8 ) must be set in the following manner:

  • For each texture coordinate set, if texture transform and texture generation are disabled, then the output texture coordinate dimensionality must match the input. If the texture transform is enabled, then the output dimensionality must match the count defined by the D3DTTFF_COUNT1, D3DTTFF_COUNT2, D3DTTFF_COUNT3, or D3DTTFF_COUNT4 settings. If the texture transform is disabled and texture generation is enabled, then the output dimensionality must match the settings for the texture generation mode; currently all modes generate three float values.

When IDirect3DDevice9::ProcessVertices fails due to an incompatible destination vertex buffer FVF code, the expected code is printed to the debug output (debug builds only).


Programmable Vertex Processing (Direct3D 9)

When using a programmed vertex shader, the elements updated in the destination vertex buffer are controlled by the shader function program. When the application writes to one of the destination vertex registers, the corresponding element within each vertex of the destination vertex buffer is updated. Elements in the destination vertex buffer that are not written to by the application are not modified. IDirect3DDevice9::ProcessVertices will fail if the application writes to elements that are not present in the destination vertex buffer.


Device Types and Vertex Processing Requirements (Direct3D 9)

The performance of vertex processing operations, including transformation and lighting, depends heavily on where the vertex buffer exists in memory and what type of rendering device is being used. Applications control the memory allocation for vertex buffers when they are created. When the D3DPOOL_SYSTEMMEM memory flag is set, the vertex buffer is created in system memory. When the D3DPOOL_DEFAULT memory flag is used, the device driver determines where the memory for the vertex buffer is best allocated, often referred to as driver-optimal memory. Driver-optimal memory can be local video memory, nonlocal video memory, or system memory.

Setting the D3DUSAGE_SOFTWAREPROCESSING constant with IDirect3DDevice9::CreateVertexBuffer enables software vertex processing on the vertex buffer data. This flag is required for software vertex processing while in mixed mode. The flag may not be used for hardware vertex processing mode. Vertex buffers used with software vertex processing include the following:

  • All input streams for IDirect3DDevice9::ProcessVertices.
  • All input streams for IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive.

The reasoning you use to determine the memory location - system or driver optimal - for vertex buffers is the same as that for textures. Vertex processing, including transformation and lighting, in hardware works best when the vertex buffers are allocated in driver-optimal memory, while software vertex processing works best with vertex buffers allocated in system memory. For textures, hardware rasterization works best when textures are allocated in driver-optimal memory, while software rasterization works best with system-memory textures.

Microsoft Direct3D 9 supports standalone processing of vertices, without rendering any primitive with the IDirect3DDevice9::ProcessVertices method. This standalone vertex processing is always performed in software on the host processor. Because of this, vertex buffers used as sources set with IDirect3DDevice9::SetStreamSource must be created with the D3DUSAGE_SOFTWAREPROCESSING flag. The functionality provided by IDirect3DDevice9::ProcessVertices is identical to that of the IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive methods while using software vertex processing.

If your application performs its own vertex processing and passes transformed, lit, and clipped vertices to rendering methods, then the application can directly write vertices to a vertex buffer allocated in driver-optimal memory. This technique prevents a redundant copy operation later. Note that this technique will not work well if your application reads data back from a vertex buffer, because read operations done by the host from driver-optimal memory can be very slow. Therefore, if your application needs to read during processing or writes data to the buffer erratically, a system-memory vertex buffer is a better choice.

When using the Direct3D vertex processing features (by passing untransformed vertices to vertex-buffer rendering methods), processing can occur in either hardware or software depending on the device type and device creation flags. It is recommended that vertex buffers be allocated in pool D3DPOOL_DEFAULT for best performance in virtually all cases. When a device is using hardware vertex processing, there are a number of additional optimizations that may be done based on the flags D3DUSAGE_DYNAMIC and D3DUSAGE_WRITEONLY. See IDirect3DDevice9::CreateVertexBuffer for more information about using these flags.


Vertex Declaration (Direct3D 9)

A vertex declaration defines the vertex buffer layout and programs the tessellation engine. Starting with Direct3D 9, vertex streams are expressed as an array of D3DVERTEXELEMENT9 structures (instead of using flexible vertex format (FVF) codes). Each array element describes each per-vertex data type. Converting FVF> codes into the new format is covered in the following topics:

  • Mapping FVF Codes to a Direct3D 9 Declaration (Direct3D 9)
  • Fixed Function FVF Codes (Direct3D 9)
  • Mapping between a Direct3D Declaration and FVF Codes (Direct3D 9)
  • Mapping between a Direct3D 9 Declaration and a Direct3D 8 Declaration (Direct3D 9)
  • Programming One or More Streams (Direct3D 9)


Mapping FVF Codes to a Direct3D 9 Declaration (Direct3D 9)

This table maps FVF codes to a D3DVERTEXELEMENT9 structure.

FVF | Data type | Usage | Usage index
D3DFVF_XYZ | D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 0
D3DFVF_XYZRHW | D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITIONT | 0
D3DFVF_XYZW | D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITION | 0
D3DFVF_XYZB5 and D3DFVF_LASTBETA_UBYTE4 | D3DVSDT_FLOAT3, D3DVSDT_FLOAT4, D3DVSDT_UBYTE4 | D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT, D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZB5 and D3DFVF_LASTBETA_D3DCOLOR | D3DVSDT_FLOAT3, D3DVSDT_FLOAT4, D3DVSDT_D3DCOLOR | D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT, D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZB5 | D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT4, D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT, D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZBn (n=1..4) | D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOATn | D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT | 0
D3DFVF_XYZBn (n=1..4) and D3DFVF_LASTBETA_UBYTE4 | D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT(n-1), D3DDECLTYPE_UBYTE4 | D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT, D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZBn (n=1..4) and D3DFVF_LASTBETA_D3DCOLOR | D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT(n-1), D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT, D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_NORMAL | D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 0
D3DFVF_PSIZE | D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_PSIZE | 0
D3DFVF_DIFFUSE | D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 0
D3DFVF_SPECULAR | D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 1
D3DFVF_TEXCOORDSIZEm(n) | D3DDECLTYPE_FLOATm | D3DDECLUSAGE_TEXCOORD | n

Vertex Declarations with D3DDECLUSAGE_POSITIONT

The presence of a vertex element with (D3DUSAGE_POSITIONT, 0) is used to indicate to the device that the vertex data coming in has already been through vertex processing (like an FVF with D3DFVF_XYZRHW bit set). At draw time, if the currently set declaration has an element with the (D3DUSAGE_POSITIONT, 0) semantic, the entire vertex processing is skipped (just as if an FVF with D3DFVF_XYZRHW bit has been set).

There are some restrictions on vertex declarations with (D3DDECLUSAGE_POSITIONT, 0):

  • Only stream zero can be used in such declarations.
  • Vertex elements must be sorted by increasing stream offset.
  • The stream offset must be DWORD aligned.
  • The same (Usage, Usage Index) pair should be listed only once.
  • Only the D3DDECLMETHOD_DEFAULT method can be used.
  • Other vertex elements cannot have the (D3DDECLUSAGE_POSITION, 0) semantic.

In addition, there are some restrictions on such declaration related to the device driver version. These restrictions are in effect because Direct3D sends such declarations directly to the driver without doing any conversion.

Vertex Declarations without D3DDECLUSAGE_POSITIONT

Runtime validates the creation of declarations. Following are the general rules for what declarations are legal.

  • All vertex elements for a stream must be consecutive and sorted by offset.
  • The stream offset must be DWORD aligned.
  • The same (Usage, Usage Index) pair should be listed only once.
  • If the D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET is set then
    • Multiple vertex elements can share the same offset in a stream.
    • The vertex elements can all be of different types which can be of different sizes.
    • The vertex elements can overlap arbitrarily. For example, one element can start at a location of a stream that is, at the same time, in the middle of another element.
    • Vertex elements are allowed to have stream offset in any order.
  • The number of vertex elements cannot be greater than 64.
  • UsageIndex should be in the range [0-15].
  • Declaration, used with the DrawPrimitive API, should not have vertex elements other than D3DDECLMETHOD_DEFAULT, D3DDECLMETHOD_LOOKUPPRESAMPLED, or D3DDECLMETHOD_LOOKUP.
  • Declaration, which contains D3DDECLMETHOD_LOOKUP or LOOKUPPRESAMPLED, should be used only with the programmable vertex pipeline.
  • Declaration, used with the DrawRectPatch/DrawTriPatch API, cannot have vertex elements with D3DDECLMETHOD_LOOKUPPRESAMPLED or D3DDECLMETHOD_LOOKUP.
  • Declaration should have only one element with D3DDECLMETHOD_LOOKUP or D3DDECLMETHOD_LOOKUPPRESAMPLED method.
  • Declaration with D3DDECLMETHOD_LOOKUP or D3DDECLMETHOD_LOOKUPPRESAMPLED should not have elements other than D3DDECLMETHOD_DEFAULT, because displacement mapping is done only for N-patches.
  • Vertex elements with D3DDECLMETHOD_LOOKUP or D3DDECLMETHOD_LOOKUPPRESAMPLED can only be used with the (D3DDECLUSAGE_SAMPLE, n) semantic and vice versa.
  • If a vertex element with D3DDECLMETHOD_LOOKUP method has a stream index and offset of an already existing vertex element, this vertex element should have the same data type.
  • A vertex element with the D3DDECLMETHOD_LOOKUP method should have the D3DDECLTYPE_FLOAT2/3/4 data type
  • Vertex elements with types D3DDECLMETHOD_CROSSUV, D3DDECLMETHOD_PARTIALU, and D3DDECLMETHOD_PARTIALV should have an offset of a vertex element with a compatible data type.
  • A vertex element with the method D3DDECLMETHOD_UV or D3DDECLMETHOD_LOOKUPPRESAMPLED must have type D3DDECLTYPE_UNUSED, stream index zero, and stream offset zero.
  • Declarations with methods D3DDECLMETHOD_UV, D3DDECLMETHOD_PARTIALU, and D3DDECLMETHOD_PARTIALV can only be used with DrawRectPatch.
  • Usage D3DDECLUSAGE_TESSFACTOR should be used only with data type D3DDECLTYPE_FLOAT1 and usage index 0.
  • When a declaration is used for tessellation (DrawRectPatch, DrawTriPatch, N-patches), data type must be less than or equal to D3DDECLTYPE_SHORT4.
  • Declarations that contain methods requiring certain device capabilities (for example, displacement mapping, RT-patches) can only be created if the device supports them.
  • A vertex declaration used to draw points and lines cannot have methods other than D3DDECLMETHOD_DEFAULT.
  • The declarations that can be created also depends on the driver capabilities.

Driver Considerations

Pre-Direct3D 9 Drivers

  • The input declaration must be translatable to a valid FVF (have the same order of vertex elements and their data types).
  • Gaps in texture coordinates are not allowed. This means that if there is a vertex element with (D3DDECLUSAGE_TEXCOORD, n) then there also should be a vertex element with (D3DDECLUSAGE_TEXCOORD, n-1).

Direct3D 9 Drivers without Pixel Shader Version 3 Support

  • The input declaration must be translatable to a valid FVF (have the same order of vertex elements and their data types).
  • Gaps in texture coordinates are allowed.

Direct3D 9 Drivers with Pixel Shader Version 3 Support

More general declarations are allowed.

  • Vertex elements can be in arbitrary order and can have any data types.
  • Multiple vertex elements can share the same stream offset and be of a different type in the same time if D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET is set by device.

Vertex Declaration Usage with the Programmable Vertex Pipeline

  • At draw time, Direct3D looks for the same "usage - usage index" combination in the current vertex declaration and the current vertex shader function. When the combination is found, the register from shader function DCL is used as the destination for the vertex element.
  • When a vertex element in the current vertex declaration has a usage which is not found in the current vertex shader, that vertex element is ignored.
  • When using a vertex shaders version less than 2.0, all semantics mentioned in the shader code need to be present in the declaration bound at draw time. When using vertex shaders 2.0 and above, this restriction that allows applications to use different vertex declarations with the same vertex shader does not exist. This is useful when a vertex shader reads input data based on static conditions. Vertex shader registers not initialized because of this will have undefined values.

There are additional restrictions when using with hardware vertex processing on a DirectX 8 driver:

  • Vertex elements cannot overlap or share the same offset.
  • Data types are limited to what the DirectX 8 driver can understand.

The CreateVertexDeclaration might fail if the declaration provided cannot be converted to a DirectX 8-style declaration. For a mixed mode device, this failure will happen at Draw* time because that is the only time it can be known whether this shader is being used with hardware or software vertex processing.

Vertex Declaration Usage with the Fixed Function Pipeline

Only declarations that adhere to the following rules can be used:

  • There should be no gaps between vertex elements (SKIP was not allowed in a DirectX 8 declaration, which is used for the fixed function pipeline).
  • Semantic (D3DDECLUSAGE_POSITION, 0) must be specified and should have D3DDECLTYPE_FLOAT3 data type.
  • A vertex element with method D3DDECLMETHOD_UV must specify usage D3DDECLUSAGE_TEXCOORD or D3DDECLUSAGE_BLENDWEIGHT.
  • A vertex element with method D3DDECLMETHOD_PARTIALU, _PARTIALV, or _CROSSUV can only be used with D3DDECLUSAGE_POSITION, _NORMAL, _BLENDWEIGHT, or _TEXCOORD, and must use input type D3DDECLTYPE_FLOAT3.

When a declaration is used with hardware vertex processing on a DirectX 8 driver, the Direct3D runtime converts it to a DirectX 8-style declaration with the following rules:

  • Vertex elements cannot share the same offset in a stream and they cannot overlap.
  • Data type must be less or equal D3DDECLTYPE_SHORT4.
  • Only the following methods are allowed: D3DDECLMETHOD_DEFAULT, D3DDECLMETHOD_CROSSUV, and D3DDECLMETHOD_UV
  • Mapping between a Direct3D 9 Declaration and a Direct3D 8 Declaration (Direct3D 9) shows which Direct3D 9 semantics could be converted to DirectX 8-style declaration. Usage and UsageIndex are converted to a register value.
  • If there are n vertex elements in a declaration and 0 - m (m < n) maps to an FVF (elements described in the Mapping between a Direct3D Declaration and FVF Codes (Direct3D 9)), but m + 1 does not, then:
    • If any of m + 2 until n - 1 vertex elements map to FVF/dx8decl, the declaration is invalid.
    • The elements 0 to m are converted (by the runtime for DirectX 8 and older drivers, and by the Direct3D 9 drivers) using the Mapping between a Direct3D Declaration and FVF Codes (Direct3D 9), m + 1, m + 2 until n - 1 become mapped to contiguous texcoord(k), texcoord(k+1), starting from any texcoord in elements 0 - m.
    • The data type at a mapped texcoord is assumed to be float[1234] replacing whatever data type the current element contains (but the same size). Therefore, the existing data type can be something that is not in Mapping between a Direct3D Declaration and FVF Codes (Direct3D 9).
    • If k reaches 8, the declaration is invalid for FVF/dx8decl.
    • If any mappings to texcoords have occurred, the entire declaration is required to have no elements with generation method other than DEFAULT or the declaration is invalid for FVF/dx8decl.

Using Vertex Declarations with ProcessVertices

A vertex declaration could be used to describe the output of ProcessVertices. Such declaration should adhere to the following rules:

  • Only stream 0 must be used.
  • Only D3DDECLMETHOD_DEFAULT methods are allowed.
  • Only D3DDECLTYPE_FLOATn or D3DDECLTYPE_D3DCOLOR data types can be used.
  • Vertex elements cannot share the same offset or overlap with each other.
  • Vertex elements with (D3DDECLUSAGE_POSITION, 0) or (D3DDECLUSAGE_POSITIONT,0) are not required.
  • Vertex elements with (D3DDECLUSAGE_POSITION, 0) and (D3DDECLUSAGE_POSITIONT,0) cannot be present in the same declaration.
  • The current vertex shader must be version 3.0 or higher when such declaration is used.


Fixed Function FVF Codes (Direct3D 9)

A FVF code describes the contents of vertices stored interleaved in a single data stream. It generally specifies data to be processed by the fixed function vertex processing pipeline. This is an older-style vertex declaration; to see the current vertex declaration style, see D3DVERTEXELEMENT9.

Direct3D applications can define model vertices in several different ways. Support for flexible vertex definitions, also known as flexible vertex formats or flexible vertex format codes, makes it possible for your application to use only the vertex components it needs, eliminating those components that aren't used. By using only the needed vertex components, your application can conserve memory and minimize the processing bandwidth required to render models. You describe how your vertices are formatted by using a combination of D3DFVF codes.

The FVF specification includes formats for point size, specified by D3DFVF_PSIZE. This size is expressed in camera space units for non-transformed and lit (TL) vertices, and in device-space units for TL vertices.

The rendering methods of the IDirect3DDevice9 interface provide C++ applications with methods that accept a combination of these flags, and use them to determine how to render primitives. Basically, these flags tell the system which vertex components - position, vertex blending weights, normal, colors, and the number and format of texture coordinates - your application uses and, indirectly, which parts of the rendering pipeline you want Direct3D to apply to them. In addition, the presence or absence of a particular vertex format flag communicates to the system which vertex component fields are present in memory and which you've omitted.

To determine device limitations, you can query a device for the values of D3DFVFCAPS_DONOTSTRIPELEMENTS and D3DFVFCAPS_TEXCOORDCOUNTMASK in the FVFCaps member of D3DCAPS9.

Texture coordinates can be declared in different formats, allowing textures to be addressed using as few as one coordinate or as many as four texture coordinates (for 2D projected texture coordinates). For more information, see Texture Coordinate Formats (Direct3D 9). Use the D3DFVF_TEXCOORDSIZEN set of macros to create bit patterns that identify the texture coordinate formats that your vertex format uses.

No application will use every component. The reciprocal homogeneous W (RHW) and vertex normal fields are mutually exclusive. Nor will most applications try to use all eight sets of texture coordinates, but Direct3D has this capacity. There are several restrictions on which flags you can use with other flags. For example, you cannot use the D3DFVF_XYZ and D3DFVF_XYZRHW flags together, as this would indicate that your application is describing a vertex's position with both untransformed and transformed vertices.

To use indexed vertex blending, the D3DFVF_LASTBETA_UBYTE4 flag should appear at the end of the FVF declaration. The presence of this flag indicates that the fifth blending weight will be treated as a DWORD instead of float. For more information, see Indexed Vertex Blending (Direct3D 9).

The following code samples shows the difference between an FVF code that uses the D3DFVF_LASTBETA_UBYTE4 flag and one that doesn't. The flag D3DFVF_XYZB3 is present when four blending indices are used because you always subtract the sum of the first three from the number one to obtain the fourth (blend4 = 1 - (blend1 + blend2 + blend3)).

#define D3DFVF_BLENDVERTEX (D3DFVF_XYZB3|D3DFVF_NORMAL|D3DFVF_TEX1)

struct BLENDVERTEX
{
    D3DXVECTOR3 v;       // Referenced as v0 in the vertex shader
    FLOAT       blend1;  // Referenced as v1.x in the vertex shader
    FLOAT       blend2;  // Referenced as v1.y in the vertex shader
    FLOAT       blend3;  // Referenced as v1.z in the vertex shader
                         // v1.w = 1.0 - (v1.x + v1.y + v1.z)
    D3DXVECTOR3 n;       // Referenced as v3 in the vertex shader
    FLOAT       tu, tv;  // Referenced as v7 in the vertex shader
};

The FVF defined below uses the D3DFVF_LAST_UBYTE4 flag.

#define D3DFVF_BLENDVERTEX (D3DFVF_XYZB4 | D3DFVF_LASTBETA_UBYTE4 |D3DFVF_NORMAL|D3DFVF_TEX1)

struct BLENDVERTEX
{
    D3DXVECTOR3 v;       // Referenced as v0 in the vertex shader
    FLOAT       blend1;  // Referenced as v1.x in the vertex shader
    FLOAT       blend2;  // Referenced as v1.y in the vertex shader
    FLOAT       blend3;  // Referenced as v1.z in the vertex shader
                         // v1.w = 1.0 - (v1.x + v1.y + v1.z)
    DWORD       indices; // Referenced as v2.xyzw in the vertex shader
    D3DXVECTOR3 n;       // Referenced as v3 in the vertex shader
    FLOAT       tu, tv;  // Referenced as v7 in the vertex shader
};


Mapping between a Direct3D 9 Declaration and a Direct3D 8 Declaration (Direct3D 9)

This table maps members of a D3DVERTEXELEMENT9 declaration to a Direct3D 8 declaration.

Direct3D 9 Usage | Direct3D 9 Usage index | Direct3D 8
D3DDECLUSAGE_POSITION | 0 | D3DVSDE_POSITION
D3DDECLUSAGE_POSITION | 1 | D3DVSDE_POSITION2
D3DDECLUSAGE_NORMAL | 0 | D3DVSDE_NORMAL
D3DDECLUSAGE_NORMAL | 1 | D3DVSDE_NORMAL2
D3DDECLUSAGE_BLENDWEIGHT | 0 | D3DVSDE_BLENDWEIGHT
D3DDECLUSAGE_BLENDINDICES | 0 | D3DVSDE_BLENDINDICES
D3DDECLUSAGE_PSIZE | 0 | D3DVSDE_PSIZE
D3DDECLUSAGE_COLOR | 0 | D3DVSDE_DIFFUSE
D3DDECLUSAGE_COLOR | 1 | D3DVSDE_SPECULAR
D3DDECLUSAGE_TEXCOORD | n | D3DVSDE_TEXCOORDn

When a declaration is used with hardware vertex processing on a Direct3D 7 driver, the Direct3D runtime converts it to a FVF with the following rules:

  • Only stream 0 should be used (evident from the MaxStreams cap).
  • The order of vertex elements should be the same as order of FVF bits.
  • Gaps in texture coordinates are not allowed.
  • Any vertex element not described the table cannot be converted into a valid FVF for all pre-DirectX 8 drivers and, hence, cannot be used on those drivers.
  • Only D3DDECLTYPE_FLOAT2 is allowed for vertex elements with D3DDECLUSAGE_TEXCOORD if device does not set either of the D3DPTEXTURECAPS_PROJECTED or D3DPTEXTURECAPS_CUBEMAP caps.


Mapping between a Direct3D Declaration and FVF Codes (Direct3D 9)

This table maps members of a D3DVERTEXELEMENT9 declaration to a FVF code.

Data type | Usage | Usage index | FVF
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 0 | D3DFVF_XYZ
D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITIONT | 0 | D3DFVF_XYZRHW
D3DDECLTYPE_FLOATn | D3DDECLUSAGE_BLENDWEIGHT | 0 | D3DFVF_XYZBn
D3DDECLTYPE_UBYTE4 | D3DDECLUSAGE_BLENDINDICES | 0 | D3DFVF_XYZB (nWeights+1)
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 0 | D3DFVF_NORMAL
D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_PSIZE | 0 | D3DFVF_PSIZE
D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 0 | D3DFVF_DIFFUSE
D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 1 | D3DFVF_SPECULAR
D3DDECLTYPE_FLOATm | D3DDECLUSAGE_TEXCOORD | n | D3DFVF_TEXCOORDSIZEm(n)
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 1 | N/A
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 1 | N/A


Programming One or More Streams (Direct3D 9)

This section describes shaders that can be used for the programmable stream model.

Using Streams

DirectX 8 introduced the notion of a stream to bind data to input registers for use by shaders. A stream is a uniform array of component data, where each component consists of one or more elements that represent a single entity such as position, normal, color, and so on. Streams enable graphic chips to perform a direct memory access from multiple vertex buffers in parallel and also provide a more natural mapping from application data. They also enable trivial multitexture versus multipass. Think of it like this:

  • A vertex is composed of n streams.
  • A stream is composed of m elements.
  • An element is [position, color, normal, texture coordinate].

The IDirect3DDevice9::SetStreamSource method binds a vertex buffer to a device data stream, creating an association between the vertex data and one of several data stream ports that feed the primitive processing functions. The actual references to the stream data do not occur until a drawing method, such as IDirect3DDevice9::DrawPrimitive, is called.

The mapping of the input vertex elements to the vertex input registers for programmable vertex shaders is defined in the shader declaration, but the input vertex elements do not have specific semantics about their use. The interpretation of the input vertex elements is programmed using the shader instructions. The vertex shader function is defined by an array of instructions that are applied to each vertex. The vertex output registers are explicitly written to, using instructions in the shader function.

For this discussion, though, be less concerned with the semantic mapping of elements to registers and more concerned with the reason for using streams and what problem is solved by using streams. The main benefit of streams is that they remove the vertex data costs previously associated with multitexturing. Before streams, a user had to either duplicate vertex data sets to handle the single and multitexture case with no unused data elements, or carry data elements that would be unused except in the multitexture case.

Here is an example of using two sets of vertex data, one for single texture and one for multitexturing.

struct CUSTOMVERTEX_TEX1
{
    FLOAT x, y, z;      // The untransformed position for the vertex
    DWORD diffColor;    // The vertex diffuse color
    DWORD specColor;    // The vertex specular color
    float tu_1, tv_1;   // Texture coordinates for a single texture
};

struct CUSTOMVERTEX_TEX2
{
    FLOAT x, y, z;      // The untransformed position for the vertex
    DWORD diffColor;    // The vertex diffuse color
    DWORD specColor;    // The vertex specular color
    float tu_2, tv_2;   // Texture coordinates for multitexturing
};

The alternative was to have a single vertex element that contained both sets of texture coordinates.

struct CUSTOMVERTEX_TEX2
{
    FLOAT x, y, z;      // The untransformed position for the vertex
    DWORD diffColor;    // The vertex diffuse color
    DWORD specColor;    // The vertex specular color
    float tu_1, tv_1;   // Texture coordinates for a single texture
    float tu_2, tv_2;   // Texture coordinates for multitexturing
};

With this vertex data, only one copy of the position and color data are carried in memory, at the expense of carrying both sets of texture coordinates around for rendering even in the single texture case.

Now that the tradeoff is clear, streams provide an elegant fix to this dilemma. Here is a set of vertex definitions to support three streams: one with position and color, one with the first set of texture coordinates, and one with the second set of texture coordinates.

// Multistream vertex
// Stream 0, pos, diffuse, specular
struct POSCOLORVERTEX
{
    FLOAT x, y, z;
    DWORD diffColor, specColor;
};
#define D3DFVF_POSCOLORVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_SPECULAR)
// Stream 1, tex coord 0
struct TEXC0VERTEX
{
    FLOAT tu1, tv1;
};
#define D3DFVF_TEXC0VERTEX (D3DFVF_TEX1)

// Stream 2, tex coord 1
struct TEXC1VERTEX
{
    FLOAT tu2, tv2;
};
#define D3DFVF_TEXC1VERTEX (D3DFVF_TEX0)

The vertex declaration would be as follows:

// Multitexture - multistream

D3DVERTEXELEMENT9 dwDecl3[] =
{
    {0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0},
    {0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 0},
    {0, 16, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 1},
    {1,  0, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0},
    {2,  0, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 1},
    D3DDECL_END()
};

Now create the vertex declaration object and set it as shown:

LPDIRECT3DVERTEXDECLARATION9 m_pVertexDeclaration;
g_d3dDevice->CreateVertexDeclaration(dwDecl3, &m_pVertexDeclaration);

m_pd3dDevice->SetVertexDeclaration(m_pVertexDeclaration);

Examples of Combinations

One Stream Diffuse Color

The vertex declaration and stream settings for diffuse color rendering would look like this:

D3DVERTEXELEMENT9 dwDecl3[] =
{
    {0,  0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0},
    {0, 12,  D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 0 ,
    {0, 16,  D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 1},
    D3DDECL_END()
};
   m_pd3dDevice->SetStreamSource(0, m_pVBVertexShader0, 0,
                                      sizeof(CUSTOMVERTEX));
   m_pd3dDevice->SetStreamSource(1, NULL, 0, 0);
   m_pd3dDevice->SetStreamSource(2, NULL, 0, 0);

Two Streams with Color and Texture

The vertex declaration and stream settings for single texture rendering would look like this:

D3DVERTEXELEMENT9 dwDecl3[] =
{
    {0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0},
    {0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 0},
    {0, 16, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 1},

    {1,  0, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0},

    D3DDECL_END()
};
   m_pd3dDevice->SetStreamSource(0, m_pVBPosColor, 0,
                                           sizeof(POSCOLORVERTEX));
   m_pd3dDevice->SetStreamSource(1, m_pVBTexC0, 0,
                                           sizeof(TEXC0VERTEX));
   m_pd3dDevice->SetStreamSource(2, NULL, 0, 0);

Two Streams with Color and two Textures

The vertex declaration and stream settings for two-texture multi-texture rendering would look like this:

D3DVERTEXELEMENT9 dwDecl3[] =
{
    {0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0},
    {0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 0},
    {0, 16, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 1},

    {1,  0, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0},

    {2,  0, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 1},

    D3DDECL_END()
};

m_pd3dDevice->SetStreamSource(0, m_pVBPosColor, 0,
                                          sizeof(POSCOLORVERTEX));
m_pd3dDevice->SetStreamSource(1, m_pVBTexC0, 0,
                                          sizeof(TEXC0VERTEX));
m_pd3dDevice->SetStreamSource(2, m_pVBTexC1, 0,
                                          sizeof(TEXC1VERTEX));

In every case, the following IDirect3DDevice9::DrawPrimitive invocation suffices.

       m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, NUM_TRIS);

This shows the flexibility of streams in solving the problem of data duplication/redundant data transmission across the bus (that is, of wasting bandwidth).


Index Buffers (Direct3D 9)

Index buffers, represented by the IDirect3DIndexBuffer9 interface, are memory buffers that contain index data. Index data, or indices, are integer offsets into vertex buffers and are used to render primitives using the IDirect3DDevice9::DrawIndexedPrimitive method.

A vertex buffer contains vertices; therefore, you can draw a vertex buffer either with or without indexed primitives. However, because an index buffer contains indices, you cannot use an index buffer without a corresponding vertex buffer. (As a side note, IDirect3DDevice9::DrawIndexedPrimitiveUP and IDirect3DDevice9::DrawPrimitiveUP are the only draw methods that draw without an index or a vertex buffer.)

Index Buffer Description

An index buffer is described in terms of its capabilities, such as where it exists in memory, whether it supports reading and writing, and the type and number of indices it can contain. These traits are held in a D3DINDEXBUFFER_DESC structure.

Index buffer descriptions tell your application how an existing buffer was created. You provide an empty description structure for the system to fill with the capabilities of a previously created index buffer.

  • The Format member describes the surface format of the index buffer data.
  • The Type identifies the resource type of the index buffer.
  • The Usage structure member contains general capability flags. The D3DUSAGE_SOFTWAREPROCESSING flag indicates that the index buffer is to be used with software vertex processing. The presence of the D3DUSAGE_WRITEONLY flag in Usage indicates that the index buffer memory is used only for write operations. This frees the driver to place the index data in the best memory location to enable fast processing and rendering. If the D3DUSAGE_WRITEONLY flag is not used, the driver is less likely to put the data in a location that is inefficient for read operations. This sacrifices some processing and rendering speed. If this flag is not specified, it is assumed that applications perform read and write operations on the data in the index buffer.
  • Pool specifies the memory class allocated for the index buffer. The D3DPOOL_SYSTEMMEM flag indicates that the system created the index buffer in system memory.
  • The Size member stores the size, in bytes, of the vertex buffer data.
  • The last parameter pSharedHandle is not used. Set it to NULL.

Index Processing Requirements

The performance of index processing operations depends heavily on where the index buffer exists in memory and what type of rendering device is being used. Applications control the memory allocation for index buffers when they are created. When the D3DPOOL_SYSTEMMEM memory flag is set, the index buffer is created in system memory. When the D3DPOOL_DEFAULT memory flag is used, the device driver determines where the memory for the index buffer is best allocated, often referred to as driver-optimal memory. Driver-optimal memory can be local video memory, non-local video memory, or system memory.

Setting the D3DUSAGE_SOFTWAREPROCESSING behavior flag when calling the IDirect3DDevice9::CreateIndexBuffer method specifies that the index buffer is to be used with software vertex processing. This flag is required in mixed mode vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING) when software vertex processing is used.

The application can directly write indices to a index buffer allocated in driver-optimal memory. This technique prevents a redundant copy operation later. This technique does not work well if your application reads data back from an index buffer, because read operations done by the host from driver-optimal memory can be very slow. Therefore, if your application needs to read during processing or writes data to the buffer erratically, a system-memory index buffer is a better choice.

Note Always use D3DPOOL_DEFAULT, except when you don't want to use video memory or use large amounts of page-locked RAM when the driver is putting vertex or index buffers into AGP memory.

Create an Index Buffer

Create an index buffer object by calling the IDirect3DDevice9::CreateIndexBuffer method, which accepts six parameters.

  • The first parameter specifies the index buffer length, in bytes.

  • The second parameter is a set of usage controls. Among other things, its value determines whether the vertices being referred to by the indices are capable of containing clipping information. To improve performance, specify D3DUSAGE_DONOTCLIP when clipping is not required.

    The D3DUSAGE_SOFTWAREPROCESSING flag can be set when mixed-mode or software vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING / D3DCREATE_SOFTWARE_VERTEXPROCESSING) is enabled for that device. D3DUSAGE_SOFTWAREPROCESSING must be set for buffers to be used with software vertex processing in mixed mode, but it should not be set for the best possible performance when using hardware index processing in mixed mode (D3DCREATE_HARDWARE_VERTEXPROCESSING). However, setting D3DUSAGE_SOFTWAREPROCESSING is the only option when a single buffer is used with both hardware and software vertex processing. D3DUSAGE_SOFTWAREPROCESSING is allowed for mixed and software devices.

    It is possible to force vertex and index buffers into system memory by specifying D3DPOOL_SYSTEMMEM, even when the index processing is being done in hardware. This is a way to avoid overly large amounts of page-locked memory when a driver is putting these buffers into AGP memory.

  • The third parameter is either the D3DFMT_INDEX16 or D3DFMT_INDEX32 member of the D3DFORMAT enumerated type that specifies the size of each index.

  • The fourth parameter is a member of the D3DPOOL enumerated type that tells the system where in memory to place the new index buffer.

  • The final parameter that IDirect3DDevice9::CreateIndexBuffer accepts is the address of a variable that is filled with a pointer to the new IDirect3DIndexBuffer9 interface of the vertex buffer object, if the call succeeds.

The following C++ code example shows what creating an index buffer might look like in code.

/*
 * For the purposes of this example, the d3dDevice variable is the
 * address of an IDirect3DDevice9 interface exposed by a
 * Direct3DDevice object, g_IB is a variable of type
 * LPDIRECT3DINDEXBUFFER9.
 */

if( FAILED( d3dDevice->CreateIndexBuffer( 16384 *sizeof(WORD),
           D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT,
           &g_IB, NULL ) ) )
    return E_FAIL;

Access an Index Buffer

Index buffer objects enable applications to directly access the memory allocated for index data. You can retrieve a pointer to index buffer memory by calling the IDirect3DIndexBuffer9::Lock method, and then accessing the memory as needed to fill the buffer with new index data or to read any data it contains. The Lock method accepts four parameters. The first, OffsetToLock, is the offset into the index data. The second parameter is the size, measured in bytes, of the index data. The third parameter accepted by the IDirect3DIndexBuffer9::Lock method, ppbData, is the address of a BYTE pointer filled with a pointer to the index data, if the call succeeds.

The last parameter, Flags, tells the system how the memory should be locked. You can use it to indicate how the application accesses the data in the buffer. Specify constants for the Flags parameter according to the way the index data will be accessed by your application. This allows the driver to lock the memory and provide the best performance given the requested access type. Use D3DLOCK_READONLY flag if your application will read only from the index buffer memory. Including this flag enables Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

After you fill or read the index data, call the IDirect3DIndexBuffer9::Unlock method, as shown in the following code example.

// This code example assumes the m_pIndexBuffer is a variable of type
// LPDIRECT3DINDEXBUFFER9 and that g_Indices has been properly
// initialized with indices.

// To fill the index buffer, you must lock the buffer to gain
// access to the indices. This mechanism is required because index
// buffers may be in device memory.

VOID* pIndices;

if( FAILED( m_pIndexBuffer->Lock(
      0,                 // Fill from start of the buffer
      sizeof(g_Indices), // Size of the data to load
      BYTE**)&pIndices,  // Returned index data
      0 ) ) )            // Send default flags to the lock
{
    SAFE_RELEASE(m_pIndexBuffer);
    return E_FAIL;
}

memcpy( pIndices, g_Indices, sizeof(g_Indices) );
m_pIndexBuffer->Unlock();

Note

If you create an index buffer with the D3DUSAGE_WRITEONLY flag, do not use the D3DLOCK_READONLY locking flag. Use the D3DLOCK_READONLY flag if your application will read only from the index buffer memory. Including this flag enables Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

For information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the IDirect3DIndexBuffer9::Lock method, see Performance Optimizations (Direct3D 9).

In C++, because you directly access the memory allocated for the index buffer, make sure your application properly accesses the allocated memory. Otherwise, you risk rendering that memory invalid. Use the stride of the index format your application uses to move from one index in the allocated buffer to another.

Retrieve information about an index buffer by calling the IDirect3DIndexBuffer9::GetDesc method. This method fills the members of the D3DINDEXBUFFER_DESC structure with information about the index buffer.

See Also

Rendering from Vertex and Index Buffers (Direct3D 9), Vertex Buffers (Direct3D 9)


Coordinate Systems and Geometry (Direct3D 9)

Programming Direct3D applications requires a working familiarity with 3D geometric principles. This section introduces the most important geometric concepts for creating 3D scenes. The following topics are covered.

  • Coordinate Systems (Direct3D 9)
  • Primitives (Direct3D 9)
  • Face and Vertex Normal Vectors (Direct3D 9)
  • Rasterization Rules (Direct3D 9)
  • Rectangles (Direct3D 9)
  • Triangle Interpolation (Direct3D 9)
  • Vectors, Vertices, and Quaternions (Direct3D 9)

These topics provide high-level descriptions of the basic concepts employed by a Direct3D application. For more information about these topics, see Further Information.


Coordinate Systems (Direct3D 9)

Typically 3D graphics applications use two types of Cartesian coordinate systems: left-handed and right-handed. In both coordinate systems, the positive x-axis points to the right, and the positive y-axis points up. You can remember which direction the positive z-axis points by pointing the fingers of either your left or right hand in the positive x-direction and curling them into the positive y-direction. The direction your thumb points, either toward or away from you, is the direction that the positive z-axis points for that coordinate system. The following illustration shows these two coordinate systems.

Two coordinate systems

Direct3D uses a left-handed coordinate system. If you are porting an application that is based on a right-handed coordinate system, you must make two changes to the data passed to Direct3D.

  • Flip the order of triangle vertices so that the system traverses them clockwise from the front. In other words, if the vertices are v0, v1, v2, pass them to Direct3D as v0, v2, v1.
  • Use the view matrix to scale world space by -1 in the z-direction. To do this, flip the sign of the _31, _32, _33, and _34 member of the D3DMATRIX structure that you use for your view matrix.

To obtain what amounts to a right-handed world, use the D3DXMatrixPerspectiveRH and D3DXMatrixOrthoRH functions to define the projection transform. However, be careful to use the corresponding D3DXMatrixLookAtRH function, reverse the backface-culling order, and lay out the cube maps accordingly.

Although left-handed and right-handed coordinates are the most common systems, there is a variety of other coordinate systems used in 3D software. For example, it is not unusual for 3D modeling applications to use a coordinate system in which the y-axis points toward or away from the viewer, and the z-axis points up.

Formally, the orientation of a set of basis vectors (i.e. a coordinate system) can be found by the computing the determinant of the matrix defined by the particular set of basis vectors. If the determinant is positive, the basis is said to be "positively" oriented (or right-handed). If the determinant is negative, the basis is said to be "negatively" oriented (or left-handed). For an explanation of what a determinant is, see any linear algebra resource.

Informally, you can use the "right/left hand rule" to determine if a given set of basis vectors form either a right or left handed coordinate system.

The essential operations performed on objects defined in a 3D coordinate system are translation, rotation, and scaling. You can combine these basic transformations to create a transform matrix. For details, see Transforms (Direct3D 9).

When you combine these operations, the results are not commutative; the order in which you multiply matrices is important.


Face and Vertex Normal Vectors (Direct3D 9)

Each face in a mesh has a perpendicular unit normal vector. The vector's direction is determined by the order in which the vertices are defined and by whether the coordinate system is right- or left-handed. The face normal points away from the front side of the face. In Direct3D, only the front of a face is visible. A front face is one in which vertices are defined in clockwise order.

Any face that is not a front face is a back face. Direct3D does not always render back faces; therefore, back faces are said to be culled. You can change the culling mode to render back faces if you want. See Culling State (Direct3D 9) for more information.

Direct3D uses the vertex unit normals for Gouraud shading, lighting, and texturing effects.

When applying Gouraud shading to a polygon, Direct3D uses the vertex normals to calculate the angle between the light source and the surface. It calculates the color and intensity values for the vertices and interpolates them for every point across all the primitive's surfaces. Direct3D calculates the light intensity value by using the angle. The greater the angle, the less light is shining on the surface.

If you are creating an object that is flat, set the vertex normals to point perpendicular to the surface, as shown in the following illustration. A flat surface composed of two triangles is defined.

It is more likely, however, that your object is made up of triangle strips and the triangles are not coplanar. One simple way to achieve smooth shading across all the triangles in the strip is to first calculate the surface normal vector for each polygonal face with which the vertex is associated. The vertex normal can be set to make an equal angle with each surface normal. However, this method might not be efficient enough for complex primitives.

This method is illustrated by the following figure, which shows two surfaces, S1 and S2 seen edge-on from above. The normal vectors for S1 and S2 are shown in blue. The vertex normal vector is shown in red. The angle that the vertex normal vector makes with the surface normal of S1 is the same as the angle between the vertex normal and the surface normal of S2. When these two surfaces are lit and shaded with Gouraud shading, the result is a smoothly shaded, smoothly rounded edge between them.

If the vertex normal leans toward one of the faces with which it is associated, it causes the light intensity to increase or decrease for points on that surface, depending on the angle it makes with the light source. An example is shown in the following figure. Again, these surfaces are seen edge-on. The vertex normal leans toward S1, causing it to have a smaller angle with the light source than if the vertex normal had equal angles with the surface normals.

You can use Gouraud shading to display some objects in a 3D scene with sharp edges. To do so, duplicate the vertex normal vectors at any intersection of faces where a sharp edge is required, as shown in the following illustration.

If you use the DrawPrimitive methods to render your scene, define the object with sharp edges as a triangle list, rather than a triangle strip. When you define an object as a triangle strip, Direct3D treats it as a single polygon composed of multiple triangular faces. Gouraud shading is applied both across each face of the polygon and between adjacent faces. The result is an object that is smoothly shaded from face to face. Because a triangle list is a polygon composed of a series of disjoint triangular faces, Direct3D applies Gouraud shading across each face of the polygon. However, it is not applied from face to face. If two or more triangles of a triangle list are adjacent, they appear to have a sharp edge between them.

Another alternative is to change to flat shading when rendering objects with sharp edges. This is computationally the most efficient method, but it may result in objects in the scene that are not rendered as realistically as the objects that are Gouraud-shaded.


Rasterization Rules (Direct3D 9)

Often, the points specified for vertices do not precisely match the pixels on the screen. When this happens, Direct3D applies triangle rasterization rules to decide which pixels apply to a given triangle.

  • Triangle Rasterization Rules
  • Point and Line Rules
  • Point Sprite Rules

Triangle Rasterization Rules

Direct3D uses a top-left filling convention for filling geometry. This is the same convention that is used for rectangles in GDI and OpenGL. In Direct3D, the center of the pixel is the decisive point. If the center is inside a triangle, the pixel is part of the triangle. Pixel centers are at integer coordinates.

This description of triangle-rasterization rules used by Direct3D does not necessarily apply to all available hardware. Your testing may uncover minor variations in the implementation of these rules.

The following illustration shows a rectangle whose upper-left corner is at (0, 0) and whose lower-right corner is at (5, 5). This rectangle fills 25 pixels, just as you would expect. The width of the rectangle is defined as right minus left. The height is defined as bottom minus top.

Numbered square divided into six rows and columns

In the top-left filling convention, top refers to the vertical location of horizontal spans, and left refers to the horizontal location of pixels within a span. An edge cannot be a top edge unless it is horizontal. In general, most triangles have only left and right edges.

Numbered square containing two triangles

The top-left filling convention determines the action taken by Direct3D when a triangle passes through the center of a pixel. The following illustration shows two triangles, one at (0, 0), (5, 0), and (5, 5), and the other at (0, 5), (0, 0), and (5, 5). The first triangle in this case gets 15 pixels (shown in black), whereas the second gets only 10 pixels (shown in gray) because the shared edge is the left edge of the first triangle.

Numbered square containing diagonal line

If you define a rectangle with its upper-left corner at (0.5, 0.5) and its lower-right corner at (2.5, 4.5), the center point of this rectangle is at (1.5, 2.5). When the Direct3D rasterizer tessellates this rectangle, the center of each pixel is unambiguously inside each of the four triangles, and the top-left filling convention is not needed. The following illustration shows this. The pixels in the rectangle are labeled according to the triangle in which Direct3D includes them.

Numbered square containing rectangle divided into four triangles

If you move the rectangle in the previous example so that its upper-left corner is at (1.0, 1.0), its lower-right corner at (3.0, 5.0), and its center point at (2.0, 3.0), Direct3D applies the top-left filling convention. Most pixels in this rectangle straddle the border between two or more triangles, as the next illustration shows.

Numbered square containing rectangle divided into four triangles

For both rectangles, the same pixels are affected.

Numbered square containing rectangle divided into four triangles

Point and Line Rules

Points are rendered the same as point sprites, which are both rendered as screen-aligned quadrilaterals and thus adhere to the same rules as polygon rendering.

Non-antialiased line rendering rules are exactly the same as those forGDI.

For information about antialiased line rendering, see ID3DXLine.

Point Sprite Rules

Point sprites and patch primitives are rasterized as if the primitives were first tessellated into triangles and the resulting triangles rasterized. For more information, see Point Sprites (Direct3D 9).


Rectangles (Direct3D 9)

Throughout Direct3D and Window programming, objects on the screen are referred to in terms of bounding rectangles. The sides of a bounding rectangle are always parallel to the sides of the screen, so the rectangle can be described by two points, the upper-left corner and lower-right corner. Most applications use the RECT structure to carry information about a bounding rectangle to use when blitting to the screen or performing hit detection.

In C++, the RECT structure has the following definition.

typedef struct tagRECT {
    LONG    left;    // This is the upper-left corner x-coordinate.
    LONG    top;     // The upper-left corner y-coordinate.
    LONG    right;   // The lower-right corner x-coordinate.
    LONG    bottom;  // The lower-right corner y-coordinate.
} RECT, *PRECT, NEAR *NPRECT, FAR *LPRECT;

In the preceding example, the left and top members are the x- and y-coordinates of a bounding rectangle's upper-left corner. Similarly, the right and bottom members make up the coordinates of the lower-right corner. The following diagram illustrates how you can visualize these values.

The column of pixels at the right edge and the row of pixels at the bottom edge are not included in the RECT. For example, locking a RECT with members {10, 10, 138, 138} results in an object 128 pixels in width and height.

In the interest of efficiency, consistency, and ease of use, all Direct3D presentation functions work with rectangles.


Triangle Interpolation (Direct3D 9)

During rendering, the pipeline interpolates vertex data across each triangle. Vertex data can be a broad variety of data and can include (but is not limited to): diffuse color, specular color, diffuse alpha (triangle opacity), specular alpha, and a fog factor (taken from specular alpha for fixed function vertex pipeline and from fog register for programmable vertex pipeline). The vertex data is defined by the Vertex Declaration (Direct3D 9).

For some vertex data, the interpolation is dependent on the current shading mode, as shown in the following table.

Shading mode | Description
Flat | Only the fog factor is interpolated in flat shade mode. For all other interpolated values, the color of the first vertex in the triangle is applied across the entire face.
Gouraud | Linear interpolation is performed between all three vertices.

The diffuse color and specular color are treated differently, depending on the color model. In the RGB color model, the system uses the red, green, and blue color components in the interpolation.

The alpha component of a color is treated as a separate interpolated value because device drivers can implement transparency in two different ways: by using texture blending or by using stippling.

Use the ShadeCaps member of the D3DCAPS9 structure to determine what forms of interpolation the current device driver supports.


Vectors, Vertices, and Quaternions (Direct3D 9)

Throughout Direct3D, vertices describe position and orientation. Each vertex in a primitive is described by a vector that gives its position, color, texture coordinates, and a normal vector that gives its orientation.

Quaternions add a fourth element to the [x, y, z] values that define a three-component-vector. Quaternions are an alternative to the matrix methods that are typically used for 3D rotations. A quaternion represents an axis in 3D space and a rotation around that axis. For example, a quaternion might represent a (1,1,2) axis and a rotation of 1 radian. Quaternions carry valuable information, but their true power comes from the two operations that you can perform on them: composition and interpolation.

Performing composition on quaternions is similar to combining them. The composition of two quaternions is notated as follows:

The composition of two quaternions applied to a geometry means "rotate the geometry around axis2 by rotation2, then rotate it around axis1 by rotation1." In this case, Q represents a rotation around a single axis that is the result of applying q2, then q1 to the geometry.

Using quaternion interpolation, an application can calculate a smooth and reasonable path from one axis and orientation to another. Therefore, interpolation between q1 and q2 provides a simple way to animate from one orientation to another.

When you use composition and interpolation together, they provide you with a simple way to manipulate a geometry in a manner that appears complex. For example, imagine that you have a geometry that you want to rotate to a given orientation. You know that you want to rotate it r2 degrees around axis2, then rotate it r1 degrees around axis1, but you don't know the final quaternion. By using composition, you could combine the two rotations on the geometry to get a single quaternion that is the result. Then, you could interpolate from the original to the composed quaternion to achieve a smooth transition from one to the other.

The D3DX utility library includes functions that help you work with quaternions. For example, the D3DXQuaternionRotationAxis function adds a rotation value to a vector that defines an axis of rotation, and returns the result in a quaternion defined by a D3DXQUATERNION structure. Additionally, the D3DXQuaternionMultiply function composes quaternions and the D3DXQuaternionSlerp performs spherical linear interpolation between two quaternions.

Direct3D applications can use the following functions to simplify the task of working with quaternions.

  • D3DXQuaternionBaryCentric
  • D3DXQuaternionConjugate
  • D3DXQuaternionDot
  • D3DXQuaternionExp
  • D3DXQuaternionIdentity
  • D3DXQuaternionInverse
  • D3DXQuaternionIsIdentity
  • D3DXQuaternionLength
  • D3DXQuaternionLengthSq
  • D3DXQuaternionLn
  • D3DXQuaternionMultiply
  • D3DXQuaternionNormalize
  • D3DXQuaternionRotationAxis
  • D3DXQuaternionRotationMatrix
  • D3DXQuaternionRotationYawPitchRoll
  • D3DXQuaternionSlerp
  • D3DXQuaternionSquad
  • D3DXQuaternionToAxisAngle

Direct3D applications can use the following functions to simplify the task of working with three-component-vectors.

  • D3DXVec3Add
  • D3DXVec3BaryCentric
  • D3DXVec3CatmullRom
  • D3DXVec3Cross
  • D3DXVec3Dot
  • D3DXVec3Hermite
  • D3DXVec3Length
  • D3DXVec3LengthSq
  • D3DXVec3Lerp
  • D3DXVec3Maximize
  • D3DXVec3Minimize
  • D3DXVec3Normalize
  • D3DXVec3Project
  • D3DXVec3Scale
  • D3DXVec3Subtract
  • D3DXVec3Transform
  • D3DXVec3TransformCoord
  • D3DXVec3TransformNormal
  • D3DXVec3Unproject

Many additional functions that simplify tasks using two- and four-component-vectors are included among the Math Functions supplied by the D3DX utility library.


Transforms (Direct3D 9)

The part of Direct3D that pushes geometry through the fixed function geometry pipeline is the transform engine. It locates the model and viewer in the world, projects vertices for display on the screen, and clips vertices to the viewport. The transform engine also performs lighting computations to determine diffuse and specular components at each vertex.

The geometry pipeline takes vertices as input. The transform engine applies the world, view, and projection transforms to the vertices, clips the result, and passes everything to the rasterizer.

At the head of the pipeline, a model's vertices are declared relative to a local coordinate system. This is a local origin and an orientation. This orientation of coordinates is often referred to as model space, and individual coordinates are called model coordinates.

The first stage of the geometry pipeline transforms a model's vertices from their local coordinate system to a coordinate system that is used by all the objects in a scene. The process of reorienting the vertices is called the world transform. This new orientation is commonly referred to as world space, and each vertex in world space is declared using world coordinates.

In the next stage, the vertices that describe your 3D world are oriented with respect to a camera. That is, your application chooses a point-of-view for the scene, and world space coordinates are relocated and rotated around the camera's view, turning world space into camera space. This is the view transform.

The next stage is the projection transform. In this part of the pipeline, objects are usually scaled with relation to their distance from the viewer in order to give the illusion of depth to a scene; close objects are made to appear larger than distant objects, and so on. For simplicity, this documentation refers to the space in which vertices exist after the projection transform as projection space. Some graphics books might refer to projection space as post-perspective homogeneous space. Not all projection transforms scale the size of objects in a scene. A projection such as this is sometimes called an affine or orthogonal projection.

In the final part of the pipeline, any vertices that will not be visible on the screen are removed, so that the rasterizer doesn't take the time to calculate the colors and shading for something that will never be seen. This process is called clipping. After clipping, the remaining vertices are scaled according to the viewport parameters and converted into screen coordinates. The resulting vertices, seen on the screen when the scene is rasterized, exist in screen space.

Transforms are used to convert object geometry from one coordinate space to another. Direct3D uses matrices to perform 3D transforms. This section explains how matrices create 3D transforms, describes some common uses for transforms, and details how you can combine matrices to produce a single matrix that encompasses multiple transforms.

  • World Transform (Direct3D 9) - convert from model space to world space
  • View Transform (Direct3D 9) - convert from world space to view space
  • Projection Transform (Direct3D 9) - convert from view space to projection space

Matrix Transforms

In applications that work with 3D graphics, you can use geometrical transforms to do the following:

  • Express the location of an object relative to another object.
  • Rotate and size objects.
  • Change viewing positions, directions, and perspectives.

You can transform any point (x,y,z) into another point (x', y', z') using a 4 by 4 matrix.

Perform the following operations on (x, y, z) and the matrix to produce the point (x', y', z').

The most common transforms are translation, rotation, and scaling. You can combine the matrices that produce these effects into a single matrix to calculate several transforms at once. For example, you can build a single matrix to translate and rotate a series of points.

Matrices are written in row-column order. A matrix that evenly scales vertices along each axis, known as uniform scaling, is represented by the following matrix using mathematical notation.

In C++, Direct3D declares matrices as a two-dimensional array, using the D3DMATRIX structure. The following example shows how to initialize a D3DMATRIX structure to act as a uniform scaling matrix.

// In this example, s is a variable of type float.

D3DMATRIX scale = {
    s,               0.0f,            0.0f,            0.0f,
    0.0f,            s,               0.0f,            0.0f,
    0.0f,            0.0f,            s,               0.0f,
    0.0f,            0.0f,            0.0f,            1.0f
};

Translate

The following transform translates the point (x, y, z) to a new point (x', y', z').

You can manually create a translation matrix in C++. The following example shows the source code for a function that creates a matrix to translate vertices.

D3DXMATRIX Translate(const float dx, const float dy, const float dz) {
    D3DXMATRIX ret;

    D3DXMatrixIdentity(&ret);
    ret(3, 0) = dx;
    ret(3, 1) = dy;
    ret(3, 2) = dz;
    return ret;
}    // End of Translate

For convenience, the D3DX utility library supplies the D3DXMatrixTranslation function.

Scale

The following transform scales the point (x, y, z) by arbitrary values in the x-, y-, and z-directions to a new point (x', y', z').

Rotate

The transforms described here are for left-handed coordinate systems, and so may be different from transform matrices that you have seen elsewhere.

The following matrix rotates the point (x, y, z) around the x-axis, producing a new point (x', y', z').

x rotation matrix

The following matrix rotates the point around the y-axis.

y rotation matrix

The following matrix rotates the point around the z-axis.

z rotation matrix

In these example matrices, the Greek letter theta stands for the angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

?

In a C++ application, use the D3DXMatrixRotationX, D3DXMatrixRotationY, and D3DXMatrixRotationZ functions supplied by the D3DX utility library to create rotation matrices. The following is the code for the D3DXMatrixRotationX function.

D3DXMATRIX* WINAPI D3DXMatrixRotationX
    ( D3DXMATRIX *pOut, float angle )
{
#if DBG
    if(!pOut)
        return NULL;
#endif

    float sin, cos;
    sincosf(angle, &sin, &cos);  // Determine sin and cos of angle

    pOut->_11 = 1.0f; pOut->_12 =  0.0f;   pOut->_13 = 0.0f; pOut->_14 = 0.0f;
    pOut->_21 = 0.0f; pOut->_22 =  cos;    pOut->_23 = sin;  pOut->_24 = 0.0f;
    pOut->_31 = 0.0f; pOut->_32 = -sin;    pOut->_33 = cos;  pOut->_34 = 0.0f;
    pOut->_41 = 0.0f; pOut->_42 =  0.0f;   pOut->_43 = 0.0f; pOut->_44 = 1.0f;

    return pOut;
}

Concatenating Matrices

One advantage of using matrices is that you can combine the effects of two or more matrices by multiplying them. This means that, to rotate a model and then translate it to some location, you don't need to apply two matrices. Instead, you multiply the rotation and translation matrices to produce a composite matrix that contains all their effects. This process, called matrix concatenation, can be written with the following formula.

Matrix concatenation formula

In this formula, C is the composite matrix being created, and M1 through Mn are the individual matrices. In most cases, only two or three matrices are concatenated, but there is no limit.

Use the D3DXMatrixMultiply function to perform matrix multiplication.

The order in which the matrix multiplication is performed is crucial. The preceding formula reflects the left-to-right rule of matrix concatenation. That is, the visible effects of the matrices that you use to create a composite matrix occur in left-to-right order. A typical world matrix is shown in the following example. Imagine that you are creating the world matrix for a stereotypical flying saucer. You would probably want to spin the flying saucer around its center - the y-axis of model space - and translate it to some other location in your scene. To accomplish this effect, you first create a rotation matrix, and then multiply it by a translation matrix, as shown in the following formula.

In this formula, Ry is a matrix for rotation about the y-axis, and Tw is a translation to some position in world coordinates.

The order in which you multiply the matrices is important because, unlike multiplying two scalar values, matrix multiplication is not commutative. Multiplying the matrices in the opposite order has the visual effect of translating the flying saucer to its world space position, and then rotating it around the world origin.

No matter what type of matrix you are creating, remember the left-to-right rule to ensure that you achieve the expected effects.


World Transform (Direct3D 9)

The discussion of the world transformation introduces basic concepts and provides details on how to set up a world transform.

What Is a World Transform?

A world transform changes coordinates from model space, where vertices are defined relative to a model's local origin, to World Space, where vertices are defined relative to an origin common to all the objects in a scene. In essence, the world transform places a model into the world; hence its name. The following diagram illustrates the relationship between the world coordinate system and a model's local coordinate system.

The world transform can include any combination of translations, rotations, and scalings.

Setting Up a World Matrix

As with any other transform, create the world transform by concatenating a series of matrices into a single matrix that contains the sum total of their effects. In the simplest case, when a model is at the world origin and its local coordinate axes are oriented the same as world space, the world matrix is the identity matrix. More commonly, the world matrix is a combination of a translation into world space and possibly one or more rotations to turn the model as needed.

The following example, from a fictitious 3D model class written in C++, uses the helper functions included in the D3DX utility library to create a world matrix that includes three rotations to orient a model and a translation to relocate it relative to its position in world space.

/*
 * For the purposes of this example, the following variables
 * are assumed to be valid and initialized.
 *
 * The m_xPos, m_yPos, m_zPos variables contain the model's
 * location in world coordinates.
 *
 * The m_fPitch, m_fYaw, and m_fRoll variables are floats that
 * contain the model's orientation in terms of pitch, yaw, and roll
 * angles, in radians.
 */

void C3DModel::MakeWorldMatrix( D3DXMATRIX* pMatWorld )
{
    D3DXMATRIX MatTemp;  // Temp matrix for rotations.
    D3DXMATRIX MatRot;   // Final rotation matrix, applied to
                         // pMatWorld.

    // Using the left-to-right order of matrix concatenation,
    // apply the translation to the object's world position
    // before applying the rotations.
    D3DXMatrixTranslation(pMatWorld, m_xPos, m_yPos, m_zPos);
    D3DXMatrixIdentity(&MatRot);

    // Now, apply the orientation variables to the world matrix
    if(m_fPitch || m_fYaw || m_fRoll) {
        // Produce and combine the rotation matrices.
        D3DXMatrixRotationX(&MatTemp, m_fPitch);         // Pitch
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
        D3DXMatrixRotationY(&MatTemp, m_fYaw);           // Yaw
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
        D3DXMatrixRotationZ(&MatTemp, m_fRoll);          // Roll
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);

        // Apply the rotation matrices to complete the world matrix.
        D3DXMatrixMultiply(pMatWorld, &MatRot, pMatWorld);
    }
}

After you prepare the world matrix, call the IDirect3DDevice9::SetTransform method to set it, specifying the D3DTS_WORLD macro for the first parameter.

Note Direct3D uses the world and view matrices that you set to configure several internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently-for example, thousands of times per frame-is computationally time-consuming. You can minimize the number of required calculations by concatenating your world and view matrices into a world-view matrix that you set as the world matrix, and then setting the view matrix to the identity. Keep cached copies of individual world and view matrices so that you can modify, concatenate, and reset the world matrix as needed. For clarity, in this documentation Direct3D samples rarely employ this optimization.


View Transform (Direct3D 9)

This section introduces the basic concepts of the view transform and provides details on how to set up a view transform matrix in a Direct3D application.

The view transform locates the viewer in world space, transforming vertices into camera space. In camera space, the camera, or viewer, is at the origin, looking in the positive z-direction. Recall that Direct3D uses a left-handed coordinate system, so z is positive into a scene. The view matrix relocates the objects in the world around a camera's position - the origin of camera space - and orientation.

There are many ways to create a view matrix. In all cases, the camera has some logical position and orientation in world space that is used as a starting point to create a view matrix that will be applied to the models in a scene. The view matrix translates and rotates objects to place them in camera space, where the camera is at the origin. One way to create a view matrix is to combine a translation matrix with rotation matrices for each axis. In this approach, the following general matrix formula applies.

In this formula, V is the view matrix being created, T is a translation matrix that repositions objects in the world, and Rx through Rz are rotation matrices that rotate objects along the x-, y-, and z-axis. The translation and rotation matrices are based on the camera's logical position and orientation in world space. So, if the camera's logical position in the world is <10,20,100>, the aim of the translation matrix is to move objects -10 units along the x-axis, -20 units along the y-axis, and -100 units along the z-axis. The rotation matrices in the formula are based on the camera's orientation, in terms of how much the axes of camera space are rotated out of alignment with world space. For example, if the camera mentioned earlier is pointing straight down, its z-axis is 90 degrees (pi/2 radians) out of alignment with the z-axis of world space, as shown in the following illustration.

The rotation matrices apply rotations of equal, but opposite, magnitude to the models in the scene. The view matrix for this camera includes a rotation of -90 degrees around the x-axis. The rotation matrix is combined with the translation matrix to create a view matrix that adjusts the position and orientation of the objects in the scene so that their top is facing the camera, giving the appearance that the camera is above the model.

Setting Up a View Matrix

The D3DXMatrixLookAtLH and D3DXMatrixLookAtRH helper functions create a view matrix based on the camera location and a look-at point.

The following example creates a view matrix for left-handed coordinates.

D3DXMATRIX out;
D3DXVECTOR3 eye(2,3,3);
D3DXVECTOR3 at(0,0,0);
D3DXVECTOR3 up(0,1,0);
D3DXMatrixLookAtLH(&out, &eye, &at, &up);

Direct3D uses the world and view matrices to configure several internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently is computationally time-consuming. You can minimize the number of required calculations by concatenating your world and view matrices into a world-view matrix that you set as the world matrix, and then setting the view matrix to the identity. Keep cached copies of individual world and view matrices that you can modify, concatenate, and reset the world matrix as needed. For clarity, the samples rarely employ this optimization.


Projection Transform (Direct3D 9)

You can think of the projection transformation as controlling the camera's internals; it is analogous to choosing a lens for the camera. This is the most complicated of the three transformation types. This discussion of the projection transformation is organized into the following topics.

The projection matrix is typically a scale and perspective projection. The projection transformation converts the viewing frustum into a cuboid shape. Because the near end of the viewing frustum is smaller than the far end, this has the effect of expanding objects that are near to the camera; this is how perspective is applied to the scene.

In the viewing frustum, the distance between the camera and the origin of the viewing transform space is defined arbitrarily as D, so the projection matrix looks like:

The viewing matrix translates the camera to the origin by translating in the z direction by - D. The translation matrix is as follows:

Multiplying the translation matrix by the projection matrix (T*P) gives the composite projection matrix. It looks like:

The perspective transform converts a viewing frustum into a new coordinate space. Notice that the frustum becomes cuboid and also that the origin moves from the upper-right corner of the scene to the center.

In the perspective transform, the limits of the x- and y-directions are -1 and 1. The limits of the z-direction are 0 for the front plane and 1 for the back plane.

This matrix translates and scales objects based on a specified distance from the camera to the near clipping plane, but it doesn't consider the field of view (fov), and the z-values that it produces for objects in the distance can be nearly identical, making depth comparisons difficult. The following matrix addresses these issues, and it adjusts vertices to account for the aspect ratio of the viewport, making it a good choice for the perspective projection.

In this matrix, Zn is the z-value of the near clipping plane. The variables w, h, and Q have the following meanings. Note that fovw and fovk represent the viewport's horizontal and vertical fields of view, in radians.

For your application, using field-of-view angles to define the x- and y-scaling coefficients might not be as convenient as using the viewport's horizontal and vertical dimensions (in camera space). As the math works out, the following two formulas for w and h use the viewport's dimensions, and are equivalent to the preceding formulas.

In these formulas, Zn represents the position of the near clipping plane, and the Vw and Vh variables represent the width and height of the viewport, in camera space.

For a C++ application, these two dimensions correspond directly to the Width and Height members of the D3DVIEWPORT9 structure.

Whatever formula you decide to use, be sure to set Zn to as large a value as possible, because z-values extremely close to the camera don't vary by much. This makes depth comparisons using 16-bit z-buffers somewhat complicated.

As with the world and view transformations, you call the IDirect3DDevice9::SetTransform method to set the projection transform.

Setting Up a Projection Matrix

The following ProjectionMatrix sample function sets the front and back clipping planes, as well as the horizontal and vertical field of view angles. The fields of view should be less than pi radians.

D3DXMATRIX
ProjectionMatrix(const float near_plane, // Distance to near clipping
                                         // plane
                 const float far_plane,  // Distance to far clipping
                                         // plane
                 const float fov_horiz,  // Horizontal field of view
                                         // angle, in radians
                 const float fov_vert)   // Vertical field of view
                                         // angle, in radians
{
    float    h, w, Q;

    w = (float)1/tan(fov_horiz*0.5);  // 1/tan(x) == cot(x)
    h = (float)1/tan(fov_vert*0.5);   // 1/tan(x) == cot(x)
    Q = far_plane/(far_plane - near_plane);

    D3DXMATRIX ret;
    ZeroMemory(&ret, sizeof(ret));

    ret(0, 0) = w;
    ret(1, 1) = h;
    ret(2, 2) = Q;
    ret(3, 2) = -Q*near_plane;
    ret(2, 3) = 1;
    return ret;
}   // End of ProjectionMatrix

After creating the matrix, set it with IDirect3DDevice9::SetTransform specifying D3DTS_PROJECTION.

The D3DX utility library provides the following functions to help you set up your projection matrix.

  • D3DXMatrixPerspectiveLH
  • D3DXMatrixPerspectiveRH
  • D3DXMatrixPerspectiveFovLH
  • D3DXMatrixPerspectiveFovRH
  • D3DXMatrixPerspectiveOffCenterLH
  • D3DXMatrixPerspectiveOffCenterRH

A W-Friendly Projection Matrix

Direct3D can use the w-component of a vertex that has been transformed by the world, view, and projection matrices to perform depth-based calculations in depth-buffer or fog effects. Computations such as these require that your projection matrix normalize w to be equivalent to world-space z. In short, if your projection matrix includes a (3,4) coefficient that is not 1, you must scale all the coefficients by the inverse of the (3,4) coefficient to make a proper matrix. If you don't provide a compliant matrix, fog effects and depth buffering are not applied correctly.

The following illustration shows a noncompliant projection matrix, and the same matrix scaled so that eye-relative fog will be enabled.

In the preceding matrices, all variables are assumed to be nonzero. For more information about eye-relative fog, see Eye-Relative vs. Z-Based Depth. For information about w-based depth buffering, see Depth Buffers (Direct3D 9).

Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, applications must set a compliant projection matrix to receive the desired w-based features, even if they do not use Direct3D for transforms.


Viewports and Clipping (Direct3D 9)

Conceptually, a viewport is a two-dimensional (2D) rectangle into which a 3D scene is projected. In Direct3D, the rectangle exists as coordinates within a Direct3D surface that the system uses as a rendering target. The projection transformation converts vertices into the coordinate system used for the viewport. A viewport is also used to specify the range of depth values on a render-target surface into which a scene will be rendered (usually 0.0 to 1.0).

The Viewing Frustum

A viewing frustum is 3D volume in a scene positioned relative to the viewport's camera. The shape of the volume affects how models are projected from camera space onto the screen. The most common type of projection, a perspective projection, is responsible for making objects near the camera appear bigger than objects in the distance. For perspective viewing, the viewing frustum can be visualized as a pyramid, with the camera positioned at the tip. This pyramid is intersected by a front and back clipping plane. The volume within the pyramid between the front and back clipping planes is the viewing frustum. Objects are visible only when they are in this volume.

If you imagine that you are standing in a dark room and looking through a square window, you are visualizing a viewing frustum. In this analogy, the near clipping plane is the window, and the back clipping plane is whatever finally interrupts your view - the skyscraper across the street, the mountains in the distance, or nothing at all. You can see everything inside the truncated pyramid that starts at the window and ends with whatever interrupts your view, and you can see nothing else.

The viewing frustum is defined by fov (field of view) and by the distances of the front and back clipping planes, specified in z-coordinates.

In this illustration, the variable D is the distance from the camera to the origin of the space that was defined in the last part of the geometry pipeline - the viewing transformation. This is the space around which you arrange the limits of your viewing frustum. For information about how this D variable is used to build the projection matrix, see the Projection Transform (Direct3D 9)

Viewport Rectangle

You define the viewport rectangle in C++ by using the D3DVIEWPORT9 structure. The D3DVIEWPORT9 structure is used with the following viewport manipulation methods exposed by the IDirect3DDevice9 interface.

  • IDirect3DDevice9::GetViewport
  • IDirect3DDevice9::SetViewport

The D3DVIEWPORT9 structure contains four members - X, Y, Width, Height - that define the area of the render-target surface into which a scene will be rendered. These values correspond to the destination rectangle, or viewport rectangle, as shown in the following illustration.

The values you specify for the X, Y, Width, Height members are screen coordinates relative to the upper-left corner of the render-target surface. The structure defines two additional members (MinZ and MaxZ) that indicate the depth-ranges into which the scene will be rendered.

Direct3D assumes that the viewport clipping volume ranges from -1.0 to 1.0 in X, and from 1.0 to -1.0 in Y. These were the settings used most often by applications in the past. You can adjust the viewport aspect ratio before clipping using the projection transform.

Note MinZ and MaxZ indicate the depth-ranges into which the scene will be rendered and are not used for clipping. Most applications will set these members to 0.0 and 1.0 to enable the system to render to the entire range of depth values in the depth buffer. In some cases, you can achieve special effects by using other depth ranges. For instance, to render a heads-up display in a game, you can set both values to 0.0 to force the system to render objects in a scene in the foreground, or you might set them both to 1.0 to render an object that should always be in the background.

The dimensions used in the X, Y, Width, Height members of the D3DVIEWPORT9 structure for a viewport define the location and dimensions of the viewport on the render-target surface. These values are in screen coordinates, relative to the upper-left corner of the surface.

Direct3D uses the viewport location and dimensions to scale the vertices to fit a rendered scene into the appropriate location on the target surface. Internally, Direct3D inserts these values into a matrix that is applied to each vertex:

This matrix scales vertices according to the viewport dimensions and desired depth range and translates them to the appropriate location on the render-target surface. The matrix also flips the y-coordinate to reflect a screen origin at the top-left corner with y increasing downward. After this matrix is applied, vertices are still homogeneous - that is, they still exist as [x,y,z,w] vertices - and they must be converted to non-homogeneous coordinates before being sent to the rasterizer.

Note The viewport scaling matrix incorporates the MinZ and MaxZ members of the D3DVIEWPORT9 structure to scale vertices to fit the depth range [MinZ, MaxZ]. This represents different semantics from previous releases of DirectX, in which these members were used for clipping.

Note Applications typically set MinZ and MaxZ to 0.0 and 1.0 respectively to cause the system to render to the entire depth range. However, you can use other values to achieve certain affects. For example, you might set both values to 0.0 to force all objects into the foreground, or set both to 1.0 to render all objects into the background.

Clearing a Viewport

Clearing the viewport resets the contents of the viewport rectangle on the render-target surface. It can also clear the rectangle in the depth and stencil buffer surfaces.

Use IDirect3DDevice9::Clear to clear the viewport. The method accepts one or more rectangles that define the areas on the surface being cleared. Setting the Count parameter to 1, and the pRects parameter to the address of a single rectangle that covers the entire viewport area will clear the entire viewport. Another way to clear the entire viewport is to set the pRects parameter to NULL and the Count parameter to 0.

The IDirect3DDevice9::Clear can be used for clearing stencil bits within a depth buffer. Simply set the Flags parameter to determine how IDirect3DDevice9::Clear works with the render target and any associated depth or stencil buffers. The D3DCLEAR_TARGET flag will clear the viewport using an arbitrary RGBA color that you provide in the Color argument (this is not the material color). The D3DCLEAR_ZBUFFER flag will clear the depth buffer to an arbitrary depth you specify in Z: 0.0 is the closest distance, and 1.0 is the farthest. The D3DCLEAR_STENCIL flag will reset the stencil bits to the value you provide in the Stencil argument. You can use integers that range from 0 to 2n-1, where n is the stencil buffer bit depth.

In some situations, you might be rendering only to small portions of the render target and depth buffer surfaces. The clear methods also enable you to clear multiple areas of your surfaces in a single call. Do this by setting the Count parameter to the number of rectangles you want cleared, and specify the address of the first rectangle in an array of rectangles in the pRects parameter.

Set Up the Viewport for Clipping

The results of the projection matrix determine the clipping volume in projection space as:

-wc<= xc<= wc

-wc<= yc<= wc

0 <= zc<= wc

Where: x, y, z, and w represent the vertex coordinates after the projection transformation is applied. Any vertices that have an x-, y-, or z-component outside these ranges are clipped, if clipping is enabled (the default behavior).

With the exception of vertex buffers, applications enable or disable clipping by way of the D3DRS_CLIPPING render state. Clipping information for vertex buffers is generated during processing. For more information, see Fixed Function Vertex Processing (Direct3D 9) and Programmable Vertex Processing (Direct3D 9).

Direct3D does not clip transformed vertices of a primitive from a vertex buffer unless it comes from IDirect3DDevice9::ProcessVertices. If you are doing your own transforms and need Direct3D to do the clipping, you should not use vertex buffers. In this case, the application traverses the data to transform it. Direct3D traverses the data a second time to clip it, and then the driver renders the data, which is inefficient. So, if the application transforms the data, is should also clip the data.

When the device receives pre-transformed and lit vertices (T&L vertices) that need to be clipped, in order to perform the clipping operation the vertices are back-transformed to the clipping space using the vertex's reciprocal homogeneous w (RHW) and the viewport information. Clipping is then performed. Not all devices are capable of performing this back-transform in order to clip T&L vertices.

The D3DPMISCCAPS_CLIPTLVERTS device capability indicates whether the device is capable of clipping T&L vertices. If this capability is not set, the application is responsible for clipping the T&L vertices that it intends to send down to the device to be rendered. The device is always capable of clipping T&L vertices in the software vertex processing mode (regardless of whether the device is created in the software vertex processing mode, or switched to the software vertex processing mode).

The only requirement for configuring the viewport parameters for a rendering device is to set the viewport's clipping volume. To do this, you initialize and set clipping values for the clipping volume and for the render-target surface. Viewports are commonly set up to render to the full area of the render-target surface, but this isn't a requirement.

You can use the following settings for the members of the D3DVIEWPORT9 structure to achieve this in C++.

D3DVIEWPORT9 viewData = { 0, 0, width, height, 0.0f, 1.0f };

After setting values in the D3DVIEWPORT9 structure, apply the viewport parameters to the device by calling its IDirect3DDevice9::SetViewport method. The following code example shows what this call might look like.

HRESULT hr;

hr = pd3dDevice->SetViewport(&viewData);
if(FAILED(hr))
    return hr;

If the call succeeds, the viewport parameters are set and will take effect the next time a rendering method is called. To make changes to the viewport parameters, just update the values in the D3DVIEWPORT9 structure and call IDirect3DDevice9::SetViewport again.

Note The D3DVIEWPORT9 structure members MinZ and MaxZ indicate the depth-ranges into which the scene will be rendered and are not used for clipping. Most applications set these members to 0.0 and 1.0 to enable the system to render to the entire range of depth values in the depth buffer. In some cases, you can achieve special effects by using other depth ranges. For instance, to render a heads-up display in a game, you can set both values to 0.0 to force the system to render objects in a scene in the foreground, or you might set them both to 1.0 to render an object that should always be in the background.


Lights and Materials (Direct3D 9)

Lights are used to illuminate objects in a scene. When lighting is enabled, Direct3D calculates the color of each object vertex based on a combination of:

  • The current material color and the texels in an associated texture map.
  • The diffuse and specular colors at the vertex, if specified.
  • The color and intensity of light produced by light sources in the scene or the scene's ambient light level.

When you use Direct3D lighting and materials, you allow Direct3D to handle the details of illumination for you. Advanced users can perform lighting on their own, if desired.

How you work with lighting and materials makes a big difference in the appearance of the rendered scene. Materials define how light reflects off a surface. Direct light and ambient light levels define the light that is reflected. You must use materials to render a scene if lighting is enabled. Lights are not required to render a scene, but details in a scene rendered without light are not visible. At best, rendering an unlit scene results in a silhouette of the objects in the scene. This is not enough detail for most purposes.

Direct Light vs. Ambient Light

Although both direct and ambient light illuminate objects in a scene, they are independent of one another, they have very different effects, and they require that you work with them in completely different ways.

Direct light is just that: direct. Direct light always has direction and color, and it is a factor for shading algorithms, such as Gouraud shading. Different types of lights emit direct light in different ways, creating special attenuation effects. You create a set of light parameters for direct light by calling the IDirect3DDevice9::SetLight method.

Ambient light is effectively everywhere in a scene. You can think of it as a general level of light that fills an entire scene, regardless of the objects and their locations in that scene. Ambient light has no position or direction, only color and intensity. Each light adds to the overall ambient light in a scene. Set the ambient light level with a call to the IDirect3DDevice9::SetRenderState method, specifying D3DRS_AMBIENT as the State parameter, and the desired RGBA color as the Value parameter.

Ambient light color takes the form of an RGBA value, where each component is an integer value from 0 to 255. This is unlike most color values in Direct3D.

You can use the D3DCOLOR_RGBA macro to generate RGBA values. The red, green, and blue components combine to make the final color of the ambient light. The alpha component controls the transparency of the color. When using hardware acceleration or RGB emulation, the alpha component is ignored.

Direct3D Light Model vs. Nature

In nature, when light is emitted from a source, it is reflected off of hundreds, if not thousands or millions of objects before reaching the user's eye. Each time it is reflected, some light is absorbed by a surface, some is scattered in random directions, and the rest goes on to another surface or to the user's eye. This process continues until the light is reduced to nothing or a user perceives the light.

Obviously, the calculations required to perfectly simulate the natural behavior of light are too time-consuming to use for real-time Direct3D graphics. Therefore, with speed in mind, the Direct3D light model approximates the way light works in the natural world. Direct3D describes light in terms of red, green, and blue components that combine to create a final color.

In Direct3D, when light reflects off a surface, the light color interacts mathematically with the surface itself to create the color eventually displayed on the screen. For specific information about the algorithms Direct3D uses, see Mathematics of Lighting (Direct3D 9).

The Direct3D light model generalizes light into two types: ambient light and direct light. Each has different attributes, and each interacts with the material of a surface in different ways. Ambient light is light that has been scattered so much that its direction and source are indeterminate: it maintains a low level of intensity everywhere. The indirect lighting used by photographers is a good example of ambient light. Ambient light in Direct3D, as in nature, has no real direction or source, only a color and intensity. In fact, the ambient light level is completely independent of any objects in a scene that generate light. Ambient light does not contribute to specular reflection.

Direct light is the light generated by a source within a scene; it always has color and intensity, and it travels in a specified direction. Direct light interacts with the material of a surface to create specular highlights, and its direction is used as a factor in shading algorithms, including Gouraud shading. When direct light is reflected, it does not contribute to the ambient light level in a scene. The sources in a scene that generate direct light have different characteristics that affect how they illuminate a scene.

Additionally, a polygon's material has properties that affect how that polygon reflects the light it receives. You set a single reflectance trait that describes how the material reflects ambient light, and you set individual traits to determine the material's specular and diffuse reflectance. For more information, see Materials (Direct3D 9).

Color Values for Lights and Materials

Direct3D describes color in terms of four components-red, green, blue, and alpha-that combine to make a final color. The D3DCOLORVALUE C++ structure is defined to contain values for each component. Each member is a floating-point value that typically ranges from 0.0 to 1.0, inclusive. Although both lights and materials use the same structure to describe color, the values in the structure are used a little differently by each.

Color values for light sources represent the amount of a particular light component it emits. Because lights don't use an alpha component, only the red, green, and blue components of the color are relevant. You can visualize the three components as the red, green, and blue lenses on a projection television. Each lens might be off (a 0.0 value in the appropriate member), it might be as bright as possible (a 1.0 value), or it might be some level in between. The colors coming through the lenses combine to make the light's final color. A combination like R(1.0), G(1.0), B(1.0) creates a white light, where R(0.0), G(0.0), B(0.0) doesn't emit light at all. You can make a light that emits only one component, resulting in a pure red, green, or blue light; or, the light could use combinations to emit colors like yellow or purple. You can even set negative color component values to create a "dark light" that actually removes light from a scene. Or, you might set the components to some value larger than 1.0 to create an extremely bright light.

With materials, on the other hand, color values represent how much of a light component is reflected by a surface that is rendered with that material. A material whose color components are R(1.0), G(1.0), B(1.0), A(1.0) reflects all the light that comes its way. Likewise, a material with R(0.0), G(1.0), B(0.0), A(1.0) reflects all the green light that is directed at it. Materials have multiple reflectance values to create various types of effects.

Additional information is contained in the following topics.

  • Light Types (Direct3D 9)
  • Light Properties (Direct3D 9)
  • Mathematics of Lighting (Direct3D 9)
  • Materials (Direct3D 9)


Light Types (Direct3D 9)

The light type property defines which type of light source you're using. The light type is set by using a value from the D3DLIGHTTYPE C++ enumeration in the Type member of the light's D3DLIGHT9 structure. There are three types of lights in Direct3D - point lights, spotlights, and directional lights. Each type illuminates objects in a scene differently, with varying levels of computational overhead.

Point Light

Point lights have color and position within a scene, but no single direction. They give off light equally in all directions, as shown in the following illustration.

A light bulb is a good example of a point light. Point lights are affected by attenuation and range, and illuminate a mesh on a vertex-by-vertex basis. During lighting, Direct3D uses the point light's position in world space and the coordinates of the vertex being lit to derive a vector for the direction of the light, and the distance that the light has traveled. Both are used, along with the vertex normal, to calculate the contribution of the light to the illumination of the surface.

Directional Light

Directional lights have only color and direction, not position. They emit parallel light. This means that all light generated by directional lights travels through a scene in the same direction. Imagine a directional light as a light source at near infinite distance, such as the sun. Directional lights are not affected by attenuation or range, so the direction and color you specify are the only factors considered when Direct3D calculates vertex colors. Because of the small number of illumination factors, these are the least computationally intensive lights to use.

SpotLight

Spotlights have color, position, and direction in which they emit light. Light emitted from a spotlight is made up of a bright inner cone and a larger outer cone, with the light intensity diminishing between the two, as shown in the following illustration.

Spotlights are affected by falloff, attenuation, and range. These factors, as well as the distance light travels to each vertex, are figured in when computing lighting effects for objects in a scene. Computing these effects for each vertex makes spotlights the most computationally time-consuming of all lights in Direct3D.

The D3DLIGHT9 C++ structure contains three members that are used only by spotlights. These members - Falloff, Theta, and Phi - control how large or small a spotlight object's inner and outer cones are, and how light decreases between them.

The Theta value is the radian angle of the spotlight's inner cone, and the Phi value is the angle for the outer cone of light. The Falloff value controls how light intensity decreases between the outer edge of the inner cone and the inner edge of the outer cone. Most applications set Falloff to 1.0 to create falloff that occurs evenly between the two cones, but you can set other values as needed.

The following illustration shows the relationship between the values for these members and how they can affect a spotlight's inner and outer cones of light.

Spotlights emit a cone of light that has two parts: a bright inner cone and an outer cone. Light is brightest in the inner cone and isn't present outside the outer cone, with light intensity attenuating between the two areas. This type of attenuation is commonly referred to as falloff.

The amount of light a vertex receives is based on the vertex's location in the inner or outer cones. Direct3D computes the dot product of the spotlight's direction vector (L) and the vector from the light to the vertex (D). This value is equal to the cosine of the angle between the two vectors, and serves as an indicator of the vertex's position that can be compared to the light's cone angles to determine where the vertex might lie in the inner or outer cones. The following illustration provides a graphical representation of the association between these two vectors.

Spotlight direction vector and vector from vertex to spotlight

The system compares this value to the cosine of the spotlight's inner and outer cone angles. In the light's D3DLIGHT9 structure, the Theta and Phi members represent the total cone angles for the inner and outer cones. Because the attenuation occurs as the vertex becomes more distant from the center of illumination (rather than across the total cone angle), the runtime divides these cone angles in half before calculating their cosines.

If the dot product of vectors L and D is less than or equal to the cosine of the outer cone angle, the vertex lies beyond the outer cone and receives no light. If the dot product of L and D is greater than the cosine of the inner cone angle, then the vertex is within the inner cone and receives the maximum amount of light, still considering attenuation over distance. If the vertex is somewhere between the two regions, then falloff is calculated with the following formula:

Formula for light intensity at vertex, after falloff

Where:

  • If is light intensity after falloff
  • Alpha is the angle between vectors L and D
  • Theta is the inner cone angle
  • Phi is the outer cone angle
  • p is the falloff

This formula generates a value between 0.0 and 1.0 that scales the light's intensity at the vertex to account for falloff. Attenuation as a factor of the vertex's distance from the light is also applied. The following illustration shows how different falloff values can affect the falloff curve.

Graph of light intensity versus vertex distance from the light

The effect of various falloff values on the actual lighting is subtle, and a small performance penalty is incurred by shaping the falloff curve with falloff values other than 1.0. For these reasons, this value is typically set to 1.0.


Light Properties (Direct3D 9)

Light properties describe a light source's type and color. Depending on the type of light being used, a light can have properties for attenuation and range, or for spotlight effects. But, not all types of lights use all properties. Direct3D uses the D3DLIGHT9 structure to carry information about light properties for all types of light sources. This section contains information for all light properties. Information is divided into the following groups.

The position, range, and attenuation properties define a light's location in world space and how the light it emits behaves over distance. As with all light properties you use in C++, these are contained in a light's D3DLIGHT9 structure.

  • Light Attenuation
  • Light Color
  • Light Direction
  • Light Position
  • Light Range

Light Attenuation

Attenuation controls how a light's intensity decreases toward the maximum distance specified by the range property. Three D3DLIGHT9 structure members represent light attenuation: Attenuation0, Attenuation1, and Attenuation2. These members contain floating-point values ranging from 0.0 through infinity, controlling a light's attenuation. Some applications set the Attenuation1 member to 1.0 and the others to 0.0, resulting in light intensity that changes as 1 / D, where D is the distance from the light source to the vertex. The maximum light intensity is at the source, decreasing to 1 / (Light Range) at the light's range. Typically, an application sets Attenuation0 to 0.0, Attenuation1 to a constant value, and Attenuation2 to 0.0.

You can combine attenuation values to get more complex attenuation effects. Or, you might set them to values outside the normal range to create even stranger attenuation effects. Negative attenuation values, however, are not allowed. See Attenuation and Spotlight Factor (Direct3D 9).

Light Color

Lights in Direct3D emit three colors that are used independently in the system's lighting computations: a diffuse color, an ambient color, and a specular color. Each is incorporated by the Direct3D lighting module, interacting with a counterpart from the current material, to produce a final color used in rendering. The diffuse color interacts with the diffuse reflectance property of the current material, the specular color with the material's specular reflectance property, and so on. For specifics about how Direct3D applies these colors, see Mathematics of Lighting (Direct3D 9).

In a C++ application, the D3DLIGHT9 structure includes three members for these colors - Diffuse, Ambient, and Specular - each one is a D3DCOLORVALUE structure that defines the color being emitted.

The type of color that applies most heavily to the system's computations is the diffuse color. The most common diffuse color is white (R:1.0 G:1.0 B:1.0), but you can create colors as needed to achieve desired effects. For example, you could use red light for a fireplace, or you could use green light for a traffic signal set to "Go."

Generally, you set the light color components to values between 0.0 and 1.0, inclusive, but this isn't a requirement. For example, you might set all the components to 2.0, creating a light that is "brighter than white." This type of setting can be especially useful when you use attenuation settings other than constant.

Note that although Direct3D uses RGBA values for lights, the alpha color component is not used.

Usually material colors are used for lighting. However, you can specify that material colors-emissive, ambient, diffuse, and specular-are to be overridden by diffuse or specular vertex colors. This is done by calling IDirect3DDevice9::SetRenderState and setting the device state variables listed in the following table.

Device state variable | Meaning | Type | Default
D3DRS_AMBIENTMATERIALSOURCE | Defines where to get ambient material color. | D3DMATERIALCOLORSOURCE | D3DMCS_MATERIAL
D3DRS_DIFFUSEMATERIALSOURCE | Defines where to get diffuse material color. | D3DMATERIALCOLORSOURCE | D3DMCS_COLOR1
D3DRS_SPECULARMATERIALSOURCE | Defines where to get specular material color. | D3DMATERIALCOLORSOURCE | D3DMCS_COLOR2
D3DRS_EMISSIVEMATERIALSOURCE | Defines where to get emissive material color. | D3DMATERIALCOLORSOURCE | D3DMCS_MATERIAL
D3DRS_COLORVERTEX | Disables or enables use of vertex colors. | BOOL | TRUE

The alpha/transparency value always comes only from the diffuse color's alpha channel.

The fog value always comes only from the specular color's alpha channel.

D3DMATERIALCOLORSOURCE can have the following values.

  • D3DMCS_MATERIAL - Material color is used as source.
  • D3DMCS_COLOR1 - Diffuse vertex color is used as source.
  • D3DMCS_COLOR2 - Specular vertex color is used as source.

Light Direction

A light's direction property determines the direction that the light emitted by the object travels, in world space. Direction is used only by directional lights and spotlights, and is described with a vector.

Set the light direction in the Direction member of the light's D3DLIGHT9 structure. Direction member is of type D3DVECTOR. Direction vectors are described as distances from a logical origin, regardless of the light's position in a scene. Therefore, a spotlight that points straight into a scene - along the positive z-axis - has a direction vector of <0,0,1> no matter where its position is defined to be. Similarly, you can simulate sunlight shining directly on a scene by using a directional light whose direction is <0,-1,0>. Obviously, you don't have to create lights that shine along the coordinate axes; you can mix and match values to create lights that shine at more interesting angles.

Note Although you don't need to normalize a light's direction vector, always be sure that it has magnitude. In other words, don't use a <0,0,0> direction vector.

Light Position

Light position is described using a D3DVECTOR structure in the Position member of the D3DLIGHT9 structure. The x-, y-, and z-coordinates are assumed to be in world space. Directional lights are the only type of light that don't use the position property.

Light Range

A light's range property determines the distance, in world space, at which meshes in a scene no longer receive light emitted by that object. The Range member contains a floating-point value that represents the light's maximum range, in world space. Directional lights don't use the range property.


Mathematics of Lighting (Direct3D 9)

The Direct3D Light Model covers ambient, diffuse, specular, and emissive lighting. This is enough flexibility to solve a wide range of lighting situations. You refer to the total amount of light in a scene as the global illumination and compute it using the following equation.

Global Illumination = Ambient Light + Diffuse Light + Specular Light + Emissive Light

Ambient Lighting (Direct3D 9) is constant lighting. It is constant in all directions and it colors all pixels of an object the same. It is fast to calculate but leaves objects looking flat and unrealistic. To see how ambient lighting is calculated by Direct3D, see Ambient Lighting (Direct3D 9).

Diffuse Lighting (Direct3D 9) depends on both the light direction and the object surface normal. It varies across the surface of an object as a result of the changing light direction and the changing surface numeral vector. It takes longer to calculate diffuse lighting because it changes for each object vertex, however the benefit of using it is that it shades objects and gives them three-dimensional (3D) depth. To see how diffuse lighting is calculated in Direct3D, see Diffuse Lighting (Direct3D 9).

Specular Lighting (Direct3D 9) identifies the bright specular highlights that occur when light hits an object surface and reflects back toward the camera. It is more intense than diffuse light and falls off more rapidly across the object surface. It takes longer to calculate specular lighting than diffuse lighting, however the benefit of using it is that it adds significant detail to a surface. To see how specular lighting is calculated in Direct3D, see Specular Lighting (Direct3D 9).

Emissive Lighting (Direct3D 9) is light that is emitted by an object; for example, a glow. To see how emissive lighting is calculated in Direct3D, see Emissive Lighting (Direct3D 9).

Realistic lighting can be accomplished by applying each of these types of lighting to a 3D scene. The values calculated for ambient, emissive, and diffuse components are output as the diffuse vertex color; the value for the specular lighting component is output as the specular vertex color. Ambient, diffuse, and specular light values can be affected by a given light's attenuation and spotlight factor. For more information about how attenuation works, see Attenuation and Spotlight Factor (Direct3D 9).

To achieve a more realistic lighting effect, you add more lights; however, the scene takes longer to render. To achieve all the effects a designer wants, some games use more CPU power than is commonly available. In this case, it is typical to reduce the number of lighting calculations to a minimum by using lighting maps and environment maps to add lighting to a scene while using texture maps.

Lighting is computed in the camera space. To see how lighting transformations are calculated, see Camera Space Transformations (Direct3D 9). Optimized lighting can be computed in model space, when special conditions exist: normal vectors are already normalized (D3DRS_NORMALIZENORMALS is True), vertex blending is not needed, transformation matrices are orthogonal, and so forth.


Ambient Lighting (Direct3D 9)

Ambient lighting provides constant lighting for a scene. It lights all object vertices the same because it is not dependent on any other lighting factors such as vertex normals, light direction, light position, range, or attenuation. It is the fastest type of lighting but it produces the least realistic results. Direct3D contains a single global ambient light property that you can use without creating any light. Alternatively, you can set any light object to provide ambient lighting. The ambient lighting for a scene is described by the following equation.

Ambient Lighting = Ca*[Ga + sum(Atti*Spoti*Lai)]

Where:

Parameter | Default value | Type | Description
Ca | (0,0,0,0) | D3DCOLORVALUE | Material ambient color
Ga | (0,0,0,0) | D3DCOLORVALUE | Global ambient color
Atteni | (0,0,0,0) | D3DCOLORVALUE | Light attenuation of the ith light. See Attenuation and Spotlight Factor (Direct3D 9).
Spoti | (0,0,0,0) | D3DVECTOR | Spotlight factor of the ith light. See Attenuation and Spotlight Factor (Direct3D 9).
sum | N/A | N/A | Sum of the ambient light
Lai | (0,0,0,0) | D3DVECTOR | Light ambient color of the ith light

The value for Ca is either:

  • vertex color1, if AMBIENTMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if AMBIENTMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in vertex declaration.
  • material ambient color.

Note If either AMBIENTMATERIALSOURCE option is used, and the vertex color is not provided, then the material ambient color is used.

To use the material ambient color, use SetMaterial as shown in the example code below.

Ga is the global ambient color. It is set using SetRenderState(D3DRS_AMBIENT). There is one global ambient color in a Direct3D scene. This parameter is not associated with a Direct3D light object.

Lai is the ambient color of the ith light in the scene. Each Direct3D light has a set of properties, one of which is the ambient color. The term, sum(Lai) is a sum of all the ambient colors in the scene.

Example

In this example, the object is colored using the scene ambient light and a material ambient color.

#define GRAY_COLOR	0x00bfbfbf

// create material
D3DMATERIAL9 mtrl;
ZeroMemory(&mtrl, sizeof(mtrl));
mtrl.Ambient.r = 0.75f;
mtrl.Ambient.g = 0.0f;
mtrl.Ambient.b = 0.0f;
mtrl.Ambient.a = 0.0f;
m_pd3dDevice->SetMaterial(&mtrl);
m_pd3dDevice->SetRenderState(D3DRS_AMBIENT, GRAY_COLOR);

According to the equation, the resulting color for the object vertices is a combination of the material color and the light color.

These two images show the material color, which is gray, and the light color, which is bright red.

The resulting scene is shown below. The only object in the scene is a sphere. Ambient light lights all object vertices with the same color. It is not dependent on the vertex normal or the light direction. As a result, the sphere looks like a 2D circle because there is no difference in shading around the surface of the object.

Sphere with ambient lighting

To give objects a more realistic look, apply diffuse or specular lighting in addition to ambient lighting.


Diffuse Lighting (Direct3D 9)

After adjusting the light intensity for any attenuation effects, the lighting engine computes how much of the remaining light reflects from a vertex, given the angle of the vertex normal and the direction of the incident light. The lighting engine skips to this step for directional lights because they do not attenuate over distance. The system considers two reflection types, diffuse and specular, and uses a different formula to determine how much light is reflected for each. After calculating the amounts of light reflected, Direct3D applies these new values to the diffuse and specular reflectance properties of the current material. The resulting color values are the diffuse and specular components that the rasterizer uses to produce Gouraud shading and specular highlighting.

Diffuse lighting is described by the following equation.

Diffuse Lighting = sum[Cd*Ld*(N.Ldir)*Atten*Spot]

Parameter | Default value | Type | Description
sum | N/A | N/A | Summation of each light's diffuse component.
Cd | (0,0,0,0) | D3DCOLORVALUE | Diffuse color.
Ld | (0,0,0,0) | D3DCOLORVALUE | Light diffuse color.
N | N/A | D3DVECTOR | Vertex normal
Ldir | N/A | D3DVECTOR | Direction vector from object vertex to the light.
Atten | N/A | FLOAT | Light attenuation. See Attenuation and Spotlight Factor (Direct3D 9).
Spot | N/A | FLOAT | Spotlight factor. See Attenuation and Spotlight Factor (Direct3D 9).

The value for Cd is either:

  • vertex color1, if DIFFUSEMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if DIFFUSEMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in the vertex declaration.
  • material diffuse color

Note If either DIFFUSEMATERIALSOURCE option is used, and the vertex color is not provided, the material diffuse color is used.

To calculate the attenuation (Atten) or the spotlight characteristics (Spot), see Attenuation and Spotlight Factor (Direct3D 9).

Diffuse components are clamped to be from 0 to 255, after all lights are processed and interpolated separately. The resulting diffuse lighting value is a combination of the ambient, diffuse and emissive light values.

Example

In this example, the object is colored using the light diffuse color and a material diffuse color. The code is shown below.

D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );

D3DLIGHT9 light;
ZeroMemory( &light, sizeof(light) );
light.Type = D3DLIGHT_DIRECTIONAL;

D3DXVECTOR3 vecDir;
vecDir = D3DXVECTOR3(0.5f, 0.0f, -0.5f);
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );

// set directional light diffuse color
light.Diffuse.r = 1.0f;
light.Diffuse.g = 1.0f;
light.Diffuse.b = 1.0f;
light.Diffuse.a = 1.0f;
m_pd3dDevice->SetLight( 0, &light );
m_pd3dDevice->LightEnable( 0, TRUE );

// if a material is used, SetRenderState must be used
// vertex color = light diffuse color * material diffuse color
mtrl.Diffuse.r = 0.75f;
mtrl.Diffuse.g = 0.0f;
mtrl.Diffuse.b = 0.0f;
mtrl.Diffuse.a = 0.0f;
m_pd3dDevice->SetMaterial( &mtrl );
m_pd3dDevice->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);

According to the equation, the resulting color for the object vertices is a combination of the material color and the light color.

These two images show the material color, which is gray, and the light color, which is bright red.

The resulting scene is shown below. The only object in the scene is a sphere. The diffuse lighting calculation takes the material and light diffuse color and modifies it by the angle between the light direction and the vertex normal using the dot product. As a result, the backside of the sphere gets darker as the surface of the sphere curves away from the light.

Diffuse lighting only

Combining the diffuse lighting with the ambient lighting from the previous example shades the entire surface of the object. The ambient light shades the entire surface and the diffuse light helps reveal the object's 3D shape.

Sphere with diffuse lighting

Diffuse lighting is more intensive to calculate than ambient lighting. Because it depends on the vertex normals and light direction, you can see the objects geometry in 3D space, which produces a more realistic lighting than ambient lighting. You can use specular highlights to achieve a more realistic look.


Specular Lighting (Direct3D 9)

Modeling specular reflection requires that the system not only know in what direction light is traveling, but also the direction to the viewer's eye. The system uses a simplified version of the Phong specular-reflection model, which employs a halfway vector to approximate the intensity of specular reflection.

The default lighting state does not calculate specular highlights. To enable specular lighting, be sure to set D3DRS_SPECULARENABLE to TRUE.

Specular Lighting Equation

Specular Lighting is described by the following equation.

Specular Lighting = Cs * sum[Ls * (N • H)P * Atten * Spot]

The following table identifies the variables, their types, and their ranges.

Parameter | Default value | Type | Description
Cs | (0,0,0,0) | D3DCOLORVALUE | Specular color.
sum | N/A | N/A | Summation of each light's specular component.
N | N/A | D3DVECTOR | Vertex normal.
H | N/A | D3DVECTOR | Half way vector. See the section on the halfway vector.
P | 0.0 | FLOAT | Specular reflection power. Range is 0 to +infinity
Ls | (0,0,0,0) | D3DCOLORVALUE | Light specular color.
Atten | N/A | FLOAT | Light attenuation value. See Attenuation and Spotlight Factor (Direct3D 9).
Spot | N/A | FLOAT | Spotlight factor. See Attenuation and Spotlight Factor (Direct3D 9).

The value for Cs is either:

if(SPECULARMATERIALSOURCE == D3DMCS_COLOR1)
  C = color1;
  • vertex color1, if the specular material source is D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if specular material source is D3DMCS_COLOR2, and the second vertex color is supplied in the vertex declaration.
  • material specular color

Note If either specular material source option is used and the vertex color is not provided, then the material specular color is used.

Specular components are clamped to be from 0 to 255, after all lights are processed and interpolated separately.

The Halfway Vector

The halfway vector (H) exists midway between two vectors: the vector from an object vertex to the light source, and the vector from an object vertex to the camera position. Direct3D provides two ways to compute the halfway vector. When D3DRS_LOCALVIEWER is set to TRUE, the system calculates the halfway vector using the position of the camera and the position of the vertex, along with the light's direction vector. The following formula illustrates this.

H = norm(norm(Cp - Vp) + Ldir)
Parameter | Default value | Type | Description
Cp | N/A | D3DVECTOR | Camera position.
Vp | N/A | D3DVECTOR | Vertex position.
Ldir | N/A | D3DVECTOR | Direction vector from vertex position to the light position.

Determining the halfway vector in this manner can be computationally intensive. As an alternative, setting D3DRS_LOCALVIEWER = FALSE instructs the system to act as though the viewpoint is infinitely distant on the z-axis. This is reflected in the following formula.

H = norm((0,0,1) + Ldir)

This setting is less computationally intensive, but much less accurate, so it is best used by applications that use orthogonal projection.

Example

In this example, the object is colored using the scene specular light color and a material specular color. The code is shown below.

D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );

D3DLIGHT9 light;
ZeroMemory( &light, sizeof(light) );
light.Type = D3DLIGHT_DIRECTIONAL;

D3DXVECTOR3 vecDir;
vecDir = D3DXVECTOR3(0.5f, 0.0f, -0.5f);
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );

light.Specular.r = 1.0f;
light.Specular.g = 1.0f;
light.Specular.b = 1.0f;
light.Specular.a = 1.0f;

light.Range = 1000;
light.Falloff = 0;
light.Attenuation0 = 1;
light.Attenuation1 = 0;
light.Attenuation2 = 0;
m_pd3dDevice->SetLight( 0, &light );
m_pd3dDevice->LightEnable( 0, TRUE );
m_pd3dDevice->SetRenderState( D3DRS_SPECULARENABLE, TRUE );

mtrl.Specular.r = 0.5f;
mtrl.Specular.g = 0.5f;
mtrl.Specular.b = 0.5f;
mtrl.Specular.a = 0.5f;
mtrl.Power = 20;
m_pd3dDevice->SetMaterial( &mtrl );
m_pd3dDevice->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);

According to the equation, the resulting color for the object vertices is a combination of the material color and the light color.

These two images show the specular material color, which is gray, and the specular light color, which is white.

The resulting specular highlight is shown below.

Specular highlight only

Combining the specular highlight with the ambient and diffuse lighting produces the following image. With all three types of lighting applied, this more clearly resembles a realistic object.

Specular highligh applied

Specular lighting is more intensive to calculate than diffuse lighting. It is typically used to provide visual clues about the surface material. The specular highlight varies in size and color with the material of the surface.


Emissive Lighting (Direct3D 9)

Emissive lighting is described by a single term.

Emissive Lighting = Ce

Where:

Parameter | Default value | Type | Description
Ce | (0,0,0,0) | D3DCOLORVALUE | Emissive color.

The value for Ce is either:

  • vertex color1, if EMISSIVEMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if EMISSIVEMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in the vertex declaration.
  • material emissive color

Note If either EMISSIVEMATERIALSOURCE option is used, and the vertex color is not provided, the material emissive color is used.

Example

In this example, the object is colored using the scene ambient light and a material ambient color. The code is shown below.

// create material
D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );
mtrl.Emissive.r = 0.0f;
mtrl.Emissive.g = 0.75f;
mtrl.Emissive.b = 0.0f;
mtrl.Emissive.a = 0.0f;
m_pd3dDevice->SetMaterial( &mtrl );
m_pd3dDevice->SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);

According to the equation, the resulting color for the object vertices is the material color.

The image below shows the material color, which is green. Emissive light lights all object vertices with the same color. It is not dependent on the vertex normal or the light direction. As a result, the sphere looks like a 2D circle because there is no difference in shading around the surface of the object.

This image shows how the emissive light blends with the other three types of lights, from the previous examples. On the right side of the sphere, there is a blend of the green emissive and the red ambient light. On the left side of the sphere, the green emissive light blends with red ambient and diffuse light producing a red gradient. The specular highlight is white in the center and creates a yellow ring as the specular light value falls off sharply leaving the ambient, diffuse and emissive light values which blend together to make yellow.

Green sphere with emissive light


Camera Space Transformations (Direct3D 9)

Vertices in the camera space are computed by transforming the object vertices with the world view matrix.

V = V * wvMatrix

Vertex normals, in camera space, are computed by transforming the object normals with the inverse transpose of the world view matrix. The world view matrix may or may not be orthogonal.

N = N * (wvMatrix-1)T

The matrix inversion and matrix transpose operate on a 4x4 matrix. The multiply combines the normal with the 3x3 portion of the resulting 4x4 matrix.

If the render state, D3DRENDERSTATE_NORMALIZENORMALS is set to TRUE, vertex normal vectors are normalized after transformation to camera space as follows:

N = norm(N)

Light position in camera space is computed by transforming the light source position with the view matrix.

Lp = Lp * vMatrix

The direction to the light in camera space for a directional light is computed by multiplying the light source direction by the view matrix, normalizing, and negating the result.

Ldir = -norm(Ldir * wvMatrix)

For the D3DLIGHT_POINT and D3DLIGHT_SPOT the direction to light is computed as follows:

Ldir = norm(V * Lp), where the parameters are defined in the following table.

Parameter | Default value | Type | Description
Ldir | N/A | D3DVECTOR | Direction vector from object vertex to the light
V | N/A | D3DVECTOR | Vertex position in camera space
wvMatrix | Identity | D3DMATRIX | Composite matrix containing the world and view transforms
N | N/A | D3DVECTOR | Vertex normal
Lp | N/A | D3DVECTOR | Light position in camera space
vMatrix | Identity | D3DMATRIX | Matrix containing the view transform


Attenuation and Spotlight Factor (Direct3D 9)

The diffuse and specular lighting components of the global illumination equation contain terms that describe light attenuation and the spotlight cone. These terms are described below.

Attenuation

The attenuation of a light depends on the type of light and the distance between the light and the vertex position. To calculate attenuation, use one of the following equations.

Atten = 1/( att0i + att1i * d + att2i * d2)

Where:

Parameter | Default value | Type | Description | Range
att0i | 0.0 | FLOAT | Constant attenuation factor | 0 to +infinity
att1i | 0.0 | FLOAT | Linear attenuation factor | 0 to +infinity
att2i | 0.0 | FLOAT | Quadratic attenuation factor | 0 to +infinity
d | N/A | FLOAT | Distance from vertex position to light position | N/A
  • Atten = 1, if the light is a directional light.
  • Atten = 0, if the distance between the light and the vertex exceeds the light's range.

The att0, att1, att2 values are specified by the Attenuation0, Attenuation1, and Attenuation2 members of D3DLIGHT9.

The distance between the light and the vertex position is always positive.

d = | Ldir |

Where:

Parameter | Default value | Type | Description
Ldir | N/A | D3DVECTOR | Direction vector from vertex position to the light position

If d is greater than the light's range, that is, the Range member of a D3DLIGHT9 structure, Direct3D makes no further attenuation calculations and applies no effects from the light to the vertex.

The attenuation constants act as coefficients in the formula - you can produce a variety of attenuation curves by making simple adjustments to them. You can set Attenuation1 to 1.0 to create a light that doesn't attenuate but is still limited by range, or you can experiment with different values to achieve various attenuation effects.

The attenuation at the maximum range of the light is not 0.0. To prevent lights from suddenly appearing when they are at the light range, an application can increase the light range. Or, the application can set up attenuation constants so that the attenuation factor is close to 0.0 at the light range. The attenuation value is multiplied by the red, green, and blue components of the light's color to scale the light's intensity as a factor of the distance light travels to a vertex.

Spotlight Factor

Formula for spotlight factor

Parameter | Default value | Type | Description | Range
rhoi | N/A | FLOAT | cosine(angle) for spotlight i | N/A
phii | 0.0 | FLOAT | Penumbra angle of spotlight i in radians | [thetai, pi)
thetai | 0.0 | FLOAT | Umbra angle of spotlight i in radians | [0, pi)
falloff | 0.0 | FLOAT | Falloff factor | (-infinity, +infinity)

Where:

rho = norm(Ldcs).norm(Ldir)

and:

Parameter | Default value | Type | Description
Ldcs | N/A | D3DVECTOR | The negative of the light direction in camera space
Ldir | N/A | D3DVECTOR | Direction vector from vertex position to the light position

After computing the light attenuation, Direct3D also considers spotlight effects if applicable, the angle that the light reflects from a surface, and the reflectance of the current material to calculate the diffuse and specular components for that vertex. For more information, see SpotLight.


Materials (Direct3D 9)

Materials describe how polygons reflect light or appear to emit light in a 3D scene. Material properties detail a material's diffuse reflection, ambient reflection, light emission, and specular highlight characteristics. Direct3D uses the D3DMATERIAL9 structure to carry all material property information. With the exception of the specular property, each property is described as an RGBA color that represents how much of the red, green, and blue parts of a given type of light it reflects, and an alpha blending factor.

Diffuse and Ambient Reflection

The Diffuse and Ambient members of the D3DMATERIAL9 structure describe how a material reflects the ambient and diffuse light in a scene. Because most scenes contain much more diffuse light than ambient light, diffuse reflection plays the largest part in determining color. Additionally, because diffuse light is directional, the angle of incidence for diffuse light affects the overall intensity of the reflection. Diffuse reflection is greatest when the light strikes a vertex parallel to the vertex normal. As the angle increases, the effect of diffuse reflection diminishes. The amount of light reflected is the cosine of the angle between the incoming light and the vertex normal, as shown here.

Ambient reflection, like ambient light, is nondirectional. Ambient reflection has a lesser impact on the apparent color of a rendered object, but it does affect the overall color and is most noticeable when little or no diffuse light reflects off the material. A material's ambient reflection is affected by the ambient light set for a scene by calling the IDirect3DDevice9::SetRenderState method with the D3DRS_AMBIENT flag.

Diffuse and ambient reflection work together to determine the perceived color of an object, and are usually identical values. For example, to render a blue crystalline object, you create a material that reflects only the blue component of diffuse and ambient light. When placed in a room with a white light, the crystal appears to be blue. However, in a room that has only red light, the same crystal would appear to be black, because its material doesn't reflect red light.

Emission

Materials can be used to make a rendered object appear to be self-luminous. The Emissive member of the D3DMATERIAL9 structure is used to describe the color and transparency of the emitted light. Emission affects an object's color and can, for example, make a dark material brighter and take on part of the emitted color.

You can use a material's emissive property to add the illusion that an object is emitting light, without incurring the computational overhead of adding a light to the scene. In the case of the blue crystal, the emissive property is useful if you want to make the crystal appear to light up, but not cast light on other objects in the scene. Remember, materials with emissive properties don't emit light that can be reflected by other objects in a scene. To achieve this reflected light, you need to place an additional light within the scene.

Specular Reflection

Specular reflection creates highlights on objects, making them appear shiny. The D3DMATERIAL9 structure contains two members that describe the specular highlight color as well as the material's overall shininess. You establish the color of the specular highlights by setting the Specular member to the desired RGBA color - the most common colors are white or light gray. The values you set in the Power member control how sharp the specular effects are.

Specular highlights can create dramatic effects. Drawing again on the blue crystal analogy: a larger Power value creates sharper specular highlights, making the crystal appear to be quite shiny. Smaller values increase the area of the effect, creating a dull reflection that make the crystal look frosty. To make an object truly matte, set the Power member to zero and the color in Specular to black. Experiment with different levels of reflection to produce a realistic appearance for your needs. The following illustration shows two identical models. The one on the left uses a specular reflection power of 10; the model on the right has no specular reflection.

Specular reflection models

Setting Material Properties

Direct3D rendering devices can render with one set of material properties at a time.

In a C++ application, you set the material properties that the system uses by preparing a D3DMATERIAL9 structure, and then calling the IDirect3DDevice9::SetMaterial method.

To prepare the D3DMATERIAL9 structure for use, set the property information in the structure to create the desired effect during rendering. The following code example sets up the D3DMATERIAL9 structure for a purple material with sharp white specular highlights.

D3DMATERIAL9 mat;

// Set the RGBA for diffuse reflection.
mat.Diffuse.r = 0.5f;
mat.Diffuse.g = 0.0f;
mat.Diffuse.b = 0.5f;
mat.Diffuse.a = 1.0f;

// Set the RGBA for ambient reflection.
mat.Ambient.r = 0.5f;
mat.Ambient.g = 0.0f;
mat.Ambient.b = 0.5f;
mat.Ambient.a = 1.0f;

// Set the color and sharpness of specular highlights.
mat.Specular.r = 1.0f;
mat.Specular.g = 1.0f;
mat.Specular.b = 1.0f;
mat.Specular.a = 1.0f;
mat.Power = 50.0f;

// Set the RGBA for emissive color.
mat.Emissive.r = 0.0f;
mat.Emissive.g = 0.0f;
mat.Emissive.b = 0.0f;
mat.Emissive.a = 0.0f;

After preparing the D3DMATERIAL9 structure, you apply the properties by calling the IDirect3DDevice9::SetMaterial method of the rendering device. This method accepts the address of a prepared D3DMATERIAL9 structure as its only parameter. You can call IDirect3DDevice9::SetMaterial with new information as needed to update the material properties for the device. The following code example shows how this might look in code.

// This code example uses the material properties defined for
// the mat variable earlier in this topic. The pd3dDev is assumed
// to be a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;
hr = pd3dDev->SetMaterial(&mat);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

When you create a Direct3D device, the current material is automatically set to the default shown in the following table.

Member | Value
Diffuse | (R:1, G:1, B:1, A:0)
Specular | (R:0, G:0, B:0, A:0)
Ambient | (R:0, G:0, B:0, A:0)
Emissive | (R:0, G:0, B:0, A:0)
Power | (0.0)

Retrieving Material Properties

You retrieve the material properties that the rendering device is currently using by calling the IDirect3DDevice9::GetMaterial method for the device. Unlike the IDirect3DDevice9::SetMaterial method, IDirect3DDevice9::GetMaterial doesn't require preparation. The IDirect3DDevice9::GetMaterial method accepts the address of a D3DMATERIAL9 structure, and fills the provided structure with information describing the current material properties before returning.

// For this example, the pd3dDev variable is assumed to
// be a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;
D3DMATERIAL9 mat;

hr = pd3dDev->GetMaterial(&mat);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

Note If your application does not specify material properties for rendering, the system uses a default material. The default material reflects all diffuse light - white, for example - with no ambient or specular reflection, and no emissive color.


Direct3D Rendering (Direct3D 9)

Applications use the DrawPrimitive family of methods to render a 3D scene.

  • Shading (Direct3D 9)
  • Presenting a Scene (Direct3D 9)
  • Rendering Primitives (Direct3D 9)
  • Depth Buffers (Direct3D 9)
  • Fog (Direct3D 9)
  • Alpha Blending (Direct3D 9)
  • Line Drawing Support in D3DX (Direct3D 9)


Shading (Direct3D 9)

This section describes techniques used in Direct3D to control the shading of 3D polygons.

  • Shading Modes (Direct3D 9)
  • Comparing Shading Modes (Direct3D 9)
  • Setting the Shading Mode (Direct3D 9)


Shading Modes (Direct3D 9)

The shading mode used to render a polygon has a profound effect on its appearance. Shading modes determine the intensity of color and lighting at any point on a polygon face. Direct3D supports two shading modes.

  • Flat Shading
  • Gouraud Shading

Flat Shading

In the flat shading mode, the Direct3D rendering pipeline renders a polygon, using the color of the polygon material at its first vertex as the color for the entire polygon. 3D objects that are rendered with flat shading have visibly sharp edges between polygons if they are not coplanar.

The following figure shows a teapot rendered with flat shading. The outline of each polygon is clearly visible. Flat shading is the fastest form of shading.

Rough image of teapot

Gouraud Shading

When Direct3D renders a polygon using Gouraud shading, it computes a color for each vertex by using the vertex normal and lighting parameters. Then, it interpolates the color across the face of the polygons The interpolation is done linearly. For example, if the red component of the color of vertex 1 is 0.8 and the red component of vertex 2 is 0.4, using the Gouraud shading mode and the RGB color model, the Direct3D lighting module assigns a red component of 0.6 to the pixel at the midpoint of the line between these vertices.

The following figure demonstrates Gouraud shading. This teapot is composed of many flat, triangular polygons. However, Gouraud shading makes the surface of the object appear curved and smooth.

Smooth imaage of teapot

Gouraud shading can also be used to display objects with sharp edges.

For more information, see Face and Vertex Normal Vectors (Direct3D 9).


Comparing Shading Modes (Direct3D 9)

In flat shading mode, the pyramid below is displayed with a sharp edge between adjoining faces. In Gouraud shading mode, however, shading values are interpolated across the edge, and the final appearance is of a curved surface.

Automatic face normals

Gouraud shading lights flat surfaces more realistically than flat shading. A face in the flat shading mode is a uniform color, but Gouraud shading enables light to fall across a face more correctly. This effect is particularly obvious if there is a nearby point source.

Gouraud shading smoothes the sharp edges between polygons that are visible with flat shading. However, it can result in mach bands, which are bands of color or light that are not smoothly blended across adjacent polygons. Your application can reduce the appearance of Mach bands by increasing the number of polygons in an object, increasing screen resolution, or increasing the color depth of the application.

Gouraud shading can miss some details. One example is the case shown by the following illustration, in which a spotlight is completely contained within a polygon face.

In this case, Gouraud shading, which interpolates between vertices, would miss the spotlight altogether; the face would be rendered as though the spotlight did not exist.


Setting the Shading Mode (Direct3D 9)

Direct3D enables one shading mode to be selected at a time. By default, Gouraud shading is selected. In C++, you can change the shading mode by calling the IDirect3DDevice9::SetRenderState method. Set the State parameter to D3DRS_SHADEMODE. The State parameter must be set to a member of the D3DSHADEMODE enumeration. The following sample code examples illustrate how the current shading mode of a Direct3D application can be set to flat or Gouraud shading mode.

// Set to flat shading.
// This code example assumes that pDev is a valid pointer to
// an IDirect3DDevice9 interface.
hr = pDev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

// Set to Gouraud shading. This is the default for Direct3D.
hr = pDev->SetRenderState(D3DRS_SHADEMODE,
                            D3DSHADE_GOURAUD);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}


Presenting a Scene (Direct3D 9)

This section introduces the presentation APIs and discusses the issues involved in presenting a scene to the display.

Information is divided into the following topics.

  • Introduction to Presenting a Scene (Direct3D 9)
  • Multiple Views in Windowed Mode (Direct3D 9)
  • Multiple-Monitor Operations (Direct3D 9)
  • Manipulating the Depth Buffer (Direct3D 9)
  • Accessing the Color Front Buffer (Direct3D 9)


Introduction to Presenting a Scene (Direct3D 9)

The presentation APIs are a set of methods that control the state of the device that affects what the user sees on the monitor. These methods include setting display modes and once-per-frame methods that are used to present images to the user.

  • IDirect3DDevice9::Present
  • IDirect3DDevice9::Reset
  • IDirect3DDevice9::GetGammaRamp
  • IDirect3DDevice9::SetGammaRamp
  • IDirect3DDevice9::GetRasterStatus

Familiarity with the following terms is necessary to understand the presentation APIs.

  • front buffer. A rectangle of memory that is translated by the graphics adapter and displayed on the monitor or other output device.
  • back buffer. A surface whose contents can be promoted to the front buffer.
  • swap chain. A collection of back buffers that can be serially presented to the front buffer. Typically, a full-screen swap chain presents subsequent images with the flipping device driver interface (DDI), and a windowed swap chain presents images with the blitting DDI.

Because Direct3D 9 has one swap chain as a property of the device, there is always at least one swap chain per device. The IDirect3DDevice9 interface has a set of methods that manipulate the implicit swap chain and are a copy of the swap chain's own interface. Applications can create additional swap chains; however, this is not necessary for the typical single window or full-screen application.

The front buffer is not directly exposed in Direct3D 9. As a result, applications cannot lock or render to the front buffer. For details, see Accessing the Color Front Buffer (Direct3D 9).

Note DirectX 7 provided a number of presentation APIs that were called together. A good example of this is the IDirectDraw7::SetCooperativeLevel, IDirectDraw7::SetDisplayMode, and IDirectDraw7::CreateSurface sequence. Additionally, the IDirectDrawSurface7::Flip and IDirectDrawSurface7::Blt methods signaled the transport of rendered frames to the monitor. Direct3D 9 collapses these groups of APIs into two main methods, Reset and Present. Reset subsumes SetCooperativeLevel, SetDisplayMode, CreateSurface, and some of the parameters to flip. Present subsumes flip and the presentation uses of blit.

A call to IDirect3D9::CreateDevice represents an implicit reset of the device. The Direct3D 9 API has no notion of a primary surface; you cannot create an object that represents the primary surface. It is considered to be an internal property of the device.

Gamma ramps are associated with a swap chain and are manipulated with the IDirect3DDevice9::GetGammaRamp and IDirect3DDevice9::SetGammaRamp methods.


Multiple Views in Windowed Mode (Direct3D 9)

In addition to the swap chain that is owned and manipulated through the Direct3DDevice object, an application can use the IDirect3DDevice9::CreateAdditionalSwapChain method to create additional swap chains to present multiple views from the same device.

Typically, the application creates one swap chain per view, and it associates each swap chain with a particular view. The application renders images in the back buffers of each swap chain, and then uses the IDirect3DDevice9::Present method to present them individually. Note that only one swap chain at a time can be full-screen on each adapter.


Multiple-Monitor Operations (Direct3D 9)

When a device is successfully reset (IDirect3DDevice9::Reset) or created (IDirect3D9::CreateDevice) in full-screen operations, the Direct3D object that created the device is marked as owning all adapters on that system. This state is known as exclusive mode, and the Direct3D object owns exclusive mode. Exclusive mode means that devices created by any other Direct3D object can neither assume full-screen operations nor allocate video memory. In addition, when a Direct3D object assumes exclusive mode, all devices other than the one that went full-screen are placed in lost state. For details, see Lost Devices (Direct3D 9).

Along with exclusive mode, the Direct3D object is informed of the focus window that the device will use. Exclusive mode is released when the final full-screen device owned by that Direct3D object is either reset to windowed mode or destroyed.

Devices can be divided into two categories when a Direct3D object owns exclusive mode. The first category of devices have the following characteristics.

  • They are created by the same Direct3D object that created the device that is full-screen.
  • They have the same focus window as the device that is full-screen.
  • They represent a different adapter from any full-screen device.

Devices in this category have no restrictions concerning their ability to be reset or created, and they are not placed in lost state. Devices in this category can even be put into full-screen mode.

Devices that do not fall in the first category - devices created by another Direct3D object, created with a different focus window, and created for an adapter with a device that is already full-screen - cannot be reset and remain in lost state until the exclusive mode is lost. As a result, a multiple-monitor application can place several devices in full-screen mode, but only if all these devices are for different adapters, were created by the same Direct3D object, and share the same focus window.


Manipulating the Depth Buffer (Direct3D 9)

Depth buffers are associated with the device. Applications are required to move the depth buffers when they set render targets. The IDirect3DDevice9::GetDepthStencilSurface and IDirect3DDevice9::SetDepthStencilSurface methods are used to manipulate depth buffers.


Accessing the Color Front Buffer (Direct3D 9)

Accessing the front buffer is allowed through the IDirect3DDevice9::GetFrontBufferData method. This method is the only way to get a screen shot of an anti-aliased scene.


Rendering Primitives (Direct3D 9)

The following topics provide information about drawing primitives in your application.

  • Vertex Data Streams (Direct3D 9)
  • Setting the Stream Source (Direct3D 9)
  • Rendering from Vertex and Index Buffers (Direct3D 9)
  • Rendering from User Memory Pointers (Direct3D 9)


Vertex Data Streams (Direct3D 9)

The rendering interfaces for Direct3D consist of methods that render primitives from vertex data stored in one or more data buffers. Vertex data consists of vertex elements combined to form vertex components. Vertex elements, the smallest unit of a vertex, represent entities such as position, normal, or color.

Vertex components are one or more vertex elements stored contiguously (interleaved per vertex) in a single memory buffer. A complete vertex consists of one or more components, where each component is in a separate memory buffer. To render a primitive, multiple vertex components are read and assembled so that complete vertices are available for vertex processing. The illustration below shows the process of rendering primitives using vertex components.

Rendering primitives consists of two steps. First, set up one or more vertex component streams; second, invoke a IDirect3DDevice9::DrawPrimitive method to render from those streams. Identification of vertex elements within these component streams is specified by the vertex shader.

The IDirect3DDevice9::DrawPrimitive methods specify an offset in the vertex data streams so that an arbitrary contiguous subset of the primitives within one set of vertex data can be rendered with each draw invocation. This enables you to change the device rendering state between groups of primitives that are rendered from the same vertex buffers.

Both indexed and nonindexed drawing methods are supported. For more information, see Rendering from Vertex and Index Buffers (Direct3D 9).


Setting the Stream Source (Direct3D 9)

The IDirect3DDevice9::SetStreamSource method binds a vertex buffer to a device data stream, creating an association between the vertex data and one of several data stream ports that feed the primitive processing functions. The actual references to the stream data do not occur until a drawing method, such as IDirect3DDevice9::DrawPrimitive, is called.

A stream is defined as a uniform array of component data, where each component consists of one or more elements representing a single entity such as position, normal, color, and so on. The Stride parameter specifies the size of the component, in bytes.

The following code demonstrates setting the stream source and drawing its contents. The g_pVB variable is a LPDIRECT3DVERTEXBUFFER9 that contains vertex data.

if( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
{
    // Setup the world, view, and projection matrices
    SetupMatrices();

    // Render the vertex buffer contents
    g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof(CUSTOMVERTEX) );
    g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
    g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 1 );

    // End the scene
    g_pd3dDevice->EndScene();
}

For more information about this code see the following tutorial: Tutorial 3: Using Matrices


Rendering from Vertex and Index Buffers (Direct3D 9)

Both indexed and nonindexed drawing methods are supported by Direct3D. The indexed methods use a single set of indices for all vertex components. Vertex data is stored in vertex buffers, and index data is stored in index buffers. Listed below are a few common scenarios for drawing primitives using vertex and index buffers.

These examples compare the use of IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive

Scenario 1: Drawing Two Triangles without Indexing

Let's say you want to draw this quad:

If you use the Triangle List primitive type to render the two triangles, each triangle will be stored as 3 individual vertices, resulting in a similar vertex buffer to this:

The drawing call is very straightforward; starting at location 0 within the vertex buffer, draw two triangles. If culling is enabled, the order of the vertices will be important. This example assumes the default counter-clockwise culling state, so visible triangles must be drawn in clockwise order. The Triangle List primitive type simply reads three vertices in linear order from the buffer for each triangle, so this call will draw triangles (0, 1, 2) and (3, 4, 5):

DrawPrimitive( D3DPT_TRIANGLELIST, // PrimitiveType
               0,                  // StartVertex
               2 );                // PrimitiveCount

Scenario 2: Drawing Two Triangles with Indexing

As you'll notice, the vertex buffer contains duplicate data in locations 0 and 4, 2 and 5. That makes sense because the two triangles share two common vertices. This duplicate data is wasteful, and the vertex buffer can be compressed by using an index buffer. A smaller vertex buffer reduces the amount of vertex data that has to be sent to the graphics adapter. Even more importantly, using an index buffer allows the adapter to store vertices in a vertex cache; if the primitive being drawn contains a recently-used vertex, that vertex can be fetched from the cache instead of reading it from the vertex buffer, which results in a big performance increase.

An index buffer 'indexes' into the vertex buffer so each unique vertex needs to be stored only once in the vertex buffer. Here is an indexed approach to the drawing scenario above:

The index buffer stores VB Index values, which reference a particular vertex within the vertex buffer. A vertex buffer can be thought of as an array of vertices, so the VB Index is simply the index into the vertex buffer for the target vertex. Similarly, an IB Index is an index into the index buffer. This can get very confusing very quickly if you're not careful, so make sure you're clear on the vocabulary being used: VB Index values index into the vertex buffer, IB Index values index into the index buffer, and the index buffer itself stores VB Index values.

The drawing call is shown below. The meanings of all the arguments are discussed at length for the next drawing scenario; for now, just note that this call is again instructing Direct3D to render a triangle list containing two triangles, starting at location 0 within the index buffer. This call will draw the same two triangles in the exact same order as before, ensuring a proper clockwise orientation:

DrawIndexPrimitive( D3DPT_TRIANGLELIST, // PrimitiveType
                    0,                  // BaseVertexIndex
                    0,                  // MinIndex
                    4,                  // NumVertices
                    0,                  // StartIndex
                    2 );                // PrimitiveCount

Scenario 3: Drawing One Triangle with Indexing

Pretend now that you only want to draw the second triangle, but you want to use the same vertex buffer and index buffer used when drawing the entire quad:

For this drawing call, the first IB Index used is 3; this value is called the StartIndex. The lowest VB Index used is 0; this value is called the MinIndex. Even though only three vertices are required to draw the triangle, those three vertices are spread across four adjacent locations in the vertex buffer; the number of locations within the contiguous block of vertex buffer memory required for the drawing call is called NumVertices, and will be set to 4 in this call. The MinIndex and NumVertices values are really just hints to help Direct3D optimize memory access during software vertex processing, and could simply be set to include the entire vertex buffer at the price of performance.

Here is the drawing call for the single triangle case; the meaning of the BaseVertexIndex argument will be explained next:

DrawIndexPrimitive( D3DPT_TRIANGLELIST, // PrimitiveType
                    0,                  // BaseVertexIndex
                    0,                  // MinIndex
                    4,                  // NumVertices
                    3,                  // StartIndex
                    1 );                // PrimitiveCount

Scenario 4: Drawing One Triangle with Offset Indexing

BaseVertexIndex is a value that's effectively added to every VB Index stored in the index buffer. For example, if we had passed in a value of 50 for BaseVertexIndex during the previous call, that would functionally be the same as using the following index buffer for the duration of the DrawIndexedPrimitive call:

This value is rarely set to anything other than 0, but can be useful if you want to decouple the index buffer from the vertex buffer: If when filling in the index buffer for a particular mesh the location of the mesh within the vertex buffer isn't yet known, you can simply pretend the mesh vertices will be located at the start of the vertex buffer; when it comes time to make the draw call, simply pass the actual starting location as the BaseVertexIndex.

This technique can also be used when drawing multiple instances of a mesh using a single index buffer; for example, if the vertex buffer contained two meshes with identical draw order but slightly different vertices (perhaps different diffuse colors or texture coordinates), both meshes could be drawn by using different values for BaseVertexIndex. Taking this concept one step further, you could use one index buffer to draw multiple instances of a mesh, each contained in a different vertex buffer, simply by cycling which vertex buffer is active and adjusting the BaseVertexIndex as needed. Note that the BaseVertexIndex value is also automatically added to the MinIndex argument, which makes sense when you see how it's used:

Pretend now that we again want to draw only the second triangle of the quad using the same index buffer as before; however, a different vertex buffer is being used in which the quad is located at VB Index 50. The relative order of the quad vertices remains unchanged, only the starting location within the vertex buffer is different. The index buffer and vertex buffer would look like this:

Here is the appropriate draw call; note that BaseVertexIndex is the only value which has changed from the previous scenario:

DrawIndexPrimitive( D3DPT_TRIANGLELIST, // PrimitiveType
                    50,                 // BaseVertexIndex
                    0,                  // MinIndex
                    4,                  // NumVertices
                    3,                  // StartIndex
                    1 );                // PrimitiveCount


Rendering from User Memory Pointers (Direct3D 9)

A secondary set of rendering interfaces supports passing vertex and index data directly from user memory pointers. These interfaces support a single stream of vertex data only. For more information, see the following reference topics.

  • IDirect3DDevice9::DrawPrimitiveUP
  • IDirect3DDevice9::DrawIndexedPrimitiveUP

These methods render with data specified by user memory pointers, instead of vertex and index buffers.


Depth Buffers (Direct3D 9)

A depth buffer, often called a z-buffer or a w-buffer, is a property of the device that stores depth information to be used by Direct3D. When Direct3D renders a scene to a target surface, it can use the memory in an associated depth-buffer surface as a workspace to determine how the pixels of rasterized polygons occlude one another. Direct3D uses an off-screen Direct3D surface as the target to which final color values are written. The depth-buffer surface that is associated with the render-target surface is used to store depth information that tells Direct3D how deep each visible pixel is in the scene.

When a scene is rasterized with depth buffering enabled, each point on the rendering surface is tested. The values in the depth buffer can be a point's z-coordinate or its homogeneous w-coordinate - from the point's (x,y,z,w) location in projection space. A depth buffer that uses z values is often called a z-buffer, and one that uses w values is called a w-buffer. Each type of depth buffer has advantages and disadvantages, which are discussed later.

At the beginning of the test, the depth value in the depth buffer is set to the largest possible value for the scene. The color value on the rendering surface is set to either the background color value or the color value of the background texture at that point. Each polygon in the scene is tested to see if it intersects with the current coordinate (x,y) on the rendering surface. If it does, the depth value - which will be the z coordinate in a z-buffer, and the w coordinate in a w-buffer - at the current point is tested to see if it is smaller than the depth value stored in the depth buffer. If the depth of the polygon value is smaller, it is stored in the depth buffer and the color value from the polygon is written to the current point on the rendering surface. If the depth value of the polygon at that point is larger, the next polygon in the list is tested. This process is shown in the following illustration.

Note Although most applications don't use this feature, you can change the comparison that Direct3D uses to determine which values are placed in the depth buffer and subsequently the render-target surface. To do so, change the value for the D3DRS_ZFUNC render state. On some hardware, changing the compare function may disable hierarchical z testing.

Nearly all accelerators on the market support z-buffering, making z-buffers the most common type of depth buffer today. However ubiquitous, z-buffers have their drawbacks. Due to the mathematics involved, the generated z values in a z-buffer tend not to be distributed evenly across the z-buffer range (typically 0.0 to 1.0, inclusive). Specifically, the ratio between the far and near clipping planes strongly affects how unevenly z values are distributed. Using a far-plane distance to near-plane distance ratio of 100, 90 percent of the depth buffer range is spent on the first 10 percent of the scene depth range. Typical applications for entertainment or visual simulations with exterior scenes often require far-plane/near-plane ratios of anywhere between 1,000 to 10,000. At a ratio of 1,000, 98 percent of the range is spent on the first 2 percent of the depth range, and the distribution becomes worse with higher ratios. This can cause hidden surface artifacts in distant objects, especially when using 16-bit depth buffers, the most commonly supported bit-depth.

A w-based depth buffer, on the other hand, is often more evenly distributed between the near and far clip planes than a z-buffer. The key benefit is that the ratio of distances for the far and near clipping planes is no longer an issue. This allows applications to support large maximum ranges, while still getting relatively accurate depth buffering close to the eye point. A w-based depth buffer isn't perfect, and can sometimes exhibit hidden surface artifacts for near objects. Another drawback to the w-buffered approach is related to hardware support: w-buffering isn't supported as widely in hardware as z-buffering.

Using a z-buffer requires overhead during rendering. Various techniques can be used to optimize rendering when using z-buffers. For details, see Z-Buffer Performance.

Note The actual interpretation of a depth value is specific to the renderer.

This section presents information about using depth buffers for hidden line and hidden surface removal.

  • Querying for Depth Buffer Support (Direct3D 9)
  • Creating a Depth Buffer (Direct3D 9)
  • Enabling Depth Buffering (Direct3D 9)
  • Retrieving a Depth Buffer (Direct3D 9)
  • Clearing Depth Buffers (Direct3D 9)
  • Changing Depth Buffer Write Access (Direct3D 9)
  • Changing Depth Buffer Comparison Functions (Direct3D 9)


Querying for Depth Buffer Support (Direct3D 9)

As with any feature, the driver that your application uses might not support all types of depth buffering. Always check the driver's capabilities. Although most drivers support z-based depth buffering, not all will support w-based depth buffering. Drivers do not fail if you attempt to enable an unsupported scheme. They fall back on another depth buffering method instead, or sometimes disable depth buffering altogether, which can result in scenes rendered with extreme depth-sorting artifacts.

You can check for general support for depth buffers by querying Direct3D for the display device that your application will use before you create a Direct3D device. If the Direct3D object reports that it supports depth buffering, any hardware devices you create from this Direct3D object will support z-buffering.

To query for depth buffering support, you can use the IDirect3D9::CheckDeviceFormat method, as shown in the following code example.

// The following example assumes that pCaps is a valid pointer to an
// initialized D3DCAPS9 structure
if(FAILED(m_pD3D->CheckDeviceFormat(pCaps->AdapterOrdinal,
                                    pCaps->DeviceType,
                                    AdapterFormat,
                                    D3DUSAGE_DEPTHSTENCIL,
                                    D3DRTYPE_SURFACE,
                                    D3DFMT_D16)))
    return E_FAIL;

IDirect3D9::CheckDeviceFormat allows you to choose a device to create based on the capabilities of that device. In this case, devices that do not support 16-bit depth buffers are rejected.

Using IDirect3D9::CheckDepthStencilMatch to determine depth-stencil compatibility with a render target is illustrated in the following code example.

// Reject devices that cannot create a render target of RTFormat while
// the back buffer is of RTFormat and the depth-stencil buffer is
// at least 8 bits of stencil
if(FAILED(m_pD3D->CheckDepthStencilMatch(pCaps->AdapterOrdinal,
                                        pCaps->DeviceType,
                                        AdapterFormat,
                                        RTFormat,
                                        D3DFMT_D24S8)))
    return E_FAIL;

When you know that the driver supports depth buffers, you can verify w-buffer support. Although depth buffers are supported for all software rasterizers, w-buffers are supported only by the reference rasterizer, which is not suited for use by real-world applications. Regardless of the type of device your application uses, verify support for w-buffers before you attempt to enable w-based depth buffering.

  1. After creating your device, call the IDirect3DDevice9::GetDeviceCaps method, passing an initialized D3DCAPS9 structure.
  2. After the call, the LineCaps member contains information about the driver's support for rendering primitives.
  3. If the RasterCaps member of this structure contains the D3DPRASTERCAPS_WBUFFER flag, then the driver supports w-based depth buffering for that primitive type.


Creating a Depth Buffer (Direct3D 9)

A depth buffer is a property of the device. To create a depth buffer that is managed by Direct3D, set the appropriate members of the D3DPRESENT_PARAMETERS structure as shown in the following code example.

D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed               = TRUE;
d3dpp.SwapEffect             = D3DSWAPEFFECT_COPY;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

By setting the EnableAutoDepthStencil member to TRUE, you instruct Direct3D to manage depth buffers for the application. Note that AutoDepthStencilFormat must be set to a valid depth buffer format. The D3DFMT_D16 flag specifies a 16-bit depth buffer, if one is available.

The following call to the IDirect3D9::CreateDevice method creates a device that then creates a depth buffer.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                &d3dpp, &d3dDevice ) ) )
return E_FAIL;

The depth buffer is automatically set as the render target of the device. When the device is reset, the depth buffer is automatically destroyed and re-created in the new size.

To create a new depth buffer surface, use the IDirect3DDevice9::CreateDepthStencilSurface method.

To set a new depth-buffer surface for the device, use the IDirect3DDevice9::SetDepthStencilSurface method.

To use the depth buffer in your application, you need to enable the depth buffer. For details, see Enabling Depth Buffering (Direct3D 9).


Enabling Depth Buffering (Direct3D 9)

After you create a depth buffer, as described in Creating a Depth Buffer (Direct3D 9), you enable depth buffering by calling the IDirect3DDevice9::SetRenderState method. Set the D3DRS_ZENABLE render state to enable depth-buffering. Use the D3DZB_TRUE member of the D3DZBUFFERTYPE enumerated type (or TRUE) to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE (or FALSE) to disable depth buffering.

Note To use w-buffering, your application must set a compliant projection matrix even if it doesn't use the Direct3D transformation pipeline. For information about providing an appropriate projection matrix, see A W-Friendly Projection Matrix


Retrieving a Depth Buffer (Direct3D 9)

The following code example shows how to use the IDirect3DDevice9::GetDepthStencilSurface method to retrieve a pointer to the depth-buffer surface owned by the device.

LPDIRECT3DSURFACE9 pZBuffer;

m_d3dDevice->GetDepthStencilSurface( &pZBuffer );


Clearing Depth Buffers (Direct3D 9)

Many C++ applications clear the depth buffer before rendering each new frame. You can explicitly clear the depth buffer through Direct3D by calling IDirect3DDevice9::Clear and specifying D3DCLEAR_ZBUFFER for the Flags parameter. The IDirect3DDevice9::Clear method allows you to specify an arbitrary depth value in the Z parameter.


Changing Depth Buffer Write Access (Direct3D 9)

By default, the Direct3D system is allowed to write to the depth buffer. Most applications leave writing to the depth buffer enabled, but you can achieve some special effects by not allowing the Direct3D system to write to the depth buffer.

You can disable depth buffer writes in C++ by calling the IDirect3DDevice9::SetRenderState method with the State parameter set to D3DRS_ZWRITEENABLE and the Value parameter set to 0.


Changing Depth Buffer Comparison Functions (Direct3D 9)

By default, when depth-testing is performed on a rendering surface, the Direct3D system updates the render-target surface if the corresponding depth value (z or w) for each point is less than the value in the depth buffer. In a C++ application, you change how the system performs comparisons on depth values by calling the IDirect3DDevice9::SetRenderState method with the State parameter set to D3DRS_ZFUNC. The Value parameter should be set to a value in the D3DCMPFUNC enumerated type.


Fog (Direct3D 9)

Adding fog to a 3D scene can enhance realism, provide ambiance or set a mood, and obscure artifacts sometimes caused when distant geometry comes into view. Direct3D supports two fog models, pixel fog and vertex fog, each with its own features and programming interface.

Essentially, fog is implemented by blending the color of objects in a scene with a chosen fog color based on the depth of an object in a scene or its distance from the viewpoint. As objects grow more distant, their original color blends more and more with the chosen fog color, creating the illusion that the object is being increasingly obscured by tiny particles floating in the scene. The following illustration shows a scene rendered without fog, and a similar scene rendered with fog enabled.

In this illustration, the scene on the left has a clear horizon, beyond which no scenery is visible, even though it would be visible in the real world. The scene on the right obscures the horizon by using a fog color identical to the background color, making polygons appear to fade into the distance. By combining discrete fog effects with creative scene design you can add mood and soften the color of objects in a scene.

Direct3D provides two ways to add fog to a scene: pixel fog and vertex fog, named for how the fog effects are applied. For details, see Pixel Fog (Direct3D 9) and Vertex Fog (Direct3D 9). In short, pixel fog - also called table fog - is implemented in the device driver and vertex fog is implemented in the Direct3D lighting engine. An application can implement fog with a vertex shader, and pixel fog simultaneously if desired.

Note Regardless of whether you use pixel or vertex fog, your application must provide a compliant projection matrix to ensure that fog effects are properly applied. This restriction applies even to applications that do not use the Direct3D transformation and lighting engine. For additional details about how you can provide an appropriate matrix, see Projection Transform (Direct3D 9).

The following topics introduce fog and present information about using various fog features in Direct3D applications.

  • Fog Formulas (Direct3D 9)
  • Fog Parameters (Direct3D 9)
  • Fog Blending (Direct3D 9)
  • Fog Color (Direct3D 9)
  • Vertex Fog (Direct3D 9)
  • Pixel Fog (Direct3D 9)

Fog blending is controlled by render states; it is not part of the programmable pixel pipeline.


Alpha Blending (Direct3D 9)

Alpha blending is used to display an image that has transparent or semi-transparent pixels. In addition to a red, green, and blue color channel, each pixel in an alpha bitmap has a transparency component known as its alpha channel. The alpha channel typically contains as many bits as a color channel. For example, an 8-bit alpha channel can represent 256 levels of transparency, from 0 (the entire pixel is transparent) to 255 (the entire pixel is opaque). The list below shows some special effects you can create using alpha blending.

Color can be defined with or without alpha values. Color without alpha is RGB color with alpha is stored as ARGB. Vertex data, material data and texture data can be used to give object's transparency. The frame buffer can also be used to generate transparency effects.

  • Vertex Alpha (Direct3D 9)
  • Material Alpha (Direct3D 9)
  • Texture Alpha (Direct3D 9)
  • Frame Buffer Alpha (Direct3D 9)
  • Render Target Alpha (Direct3D 9)

Samples that demonstrate alpha include:

  • Billboarding (Direct3D 9)
  • Clouds, Smoke, and Vapor Trails (Direct3D 9)
  • Fire, Flares, and Explosions (Direct3D 9)


Vertex Alpha (Direct3D 9)

Alpha data can be supplied in the vertex data. To enable vertex alpha, set the D3DRS_DIFFUSEMATERIALSOURCE to D3DMCS_COLOR1 so that the Direct3D runtime takes the diffuse value from the diffuse color rather than the material.

m_pd3dDevice->SetRenderState( D3DRS_DIFFUSEMATERIALSOURCE,
                                D3DMCS_COLOR1 );

Then, provide alpha values in the diffuse color. The AddAlphaToASphere function, adds alpha to the vertices of a sphere. Here's an example of how to provide the alpha information to the function.

AddAlphaToASphere( m_pObstacleVertices, 12,
                    D3DRGBA(light.dcvDiffuse.r, light.dcvDiffuse.g,
                            light.dcvDiffuse.b, vAlpha ));

This is what the function looks like.

void AddAlphaToASphere(D3DLVERTEX* pVertices, DWORD dwNumRings, D3DCOLOR lightcolor)
{
    WORD x, y;
    // rings around
    for( y=0; y < dwNumRings; y++ )
        for( x=0; x < (dwNumRings*2)+1; x++ )
            (pVertices++)->color = lightcolor;

    // top and bottom
    (pVertices++)->color = lightcolor;
    (pVertices++)->color = lightcolor;
}

AddAlphaToASphere simply modifies the color member of each vertex, which are of type D3DLVERTEX, to include the alpha information.

D3DLVERTEX looks like this.

// Lit vertex
typedef struct {
    D3DVALUE x, y, z;
    DWORD dwReserved;
    D3DCOLOR color, specular;
    D3DVALUE tu, tv;
} D3DLVERTEX, *LPD3DLVERTEX;

Drawing the sphere,

#define D3DFVF_LVERTEX ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_SPECULAR | \
                        D3DFVF_TEX0 )

//...

// Draw the lit sphere
m_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX,
                                    m_pObstacleVertices, m_dwNumObstacleVertices,
                                    m_pObstacleIndices,  m_dwNumObstacleIndices, 0 );

results in a transparent sphere using vertex alpha.


Material Alpha (Direct3D 9)

Alpha can also be supplied in a material. To enable material alpha, set the diffuse material render state so that the runtime will use the material diffuse color components rather than the vertex diffuse color components.

m_pd3dDevice->SetRenderState( D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL );

Initialize the material with an alpha value, and set the material before drawing.

D3DMATERIAL9 mtrl;
mtrl.Diffuse = mtrl.Ambient = mtrl.Specular = mtrl.Emissive =
    D3DCOLORVALUE(255,0,0,0.5f)

m_pd3dDevice->SetMaterial(&mtrl);


Texture Alpha (Direct3D 9)

Alpha values can also be provided by textures. First, the texture must be created. Second, the alpha values must be added to the texture. To render with the texture, set the texture to a texture stage and select the appropriate texture stage operation and operands. When draw is called, the primitive will be rendered with transparency. This example creates a texture resource, and then loads the alpha channel.

LPDIRECT3DTEXTURE9 m_pTexture;

// Create an alpha texture
D3DXCreateTexture(m_d3dDevice, 128, 128, 0, D3DUSAGE_RENDERTARGET,
    D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &m_pTexture);

// Initialize the alpha channel
int  yGrad, xGrad;
D3DLOCKED_RECT lockedRect;

if(SUCCEEDED(pTexture->LockRect(0, &lockedRect, NULL, D3DLOCK_DISCARD ))
{
    m_pRGBAData = new DWORD[128*128];
    if( m_pRGBAData != NULL )
    {
        for( DWORD y=0; y < m_dwHeight; y++ )
        {
            DWORD dwOffset = y*m_dwWidth;
            yGrad = (int)(((float)y/(float)m_dwWidth) * 255.0f);

            for( DWORD x=0; x < m_dwWidth; x )
            {
                xGrad = (int)(((float)x/(float)m_dwWidth) * 255.0f);

                DWORD b = (DWORD)(xGrad + (255 - yGrad))/2 & 0xFF;
                DWORD g = (DWORD)((255 - xGrad) + yGrad)/2 & 0xFF;
                DWORD r = (DWORD)(xGrad + yGrad)/2 & 0xFF;
                DWORD a = (DWORD)(xGrad + yGrad)/2 & 0xFF;

                lockedRect.pBits[dwOffset+x] = ((a<<24L)+(r<<16L)+(g<<8L)+(b));
                x++;
            }

            pTexture->UnlockRect(&lockedRect);
        }
    }
}

The alpha value is calculated based on the current pixel's relative x/y position within the texture size. Next, assign the texture to a texture stage and set up the texture stage.

#define D3DFVF_LVERTEX ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_SPECULAR | \
                        D3DFVF_TEX0 )

// Assign texture
m_pd3dDevice->SetTexture(0, m_pTexture);

// Texture stage states
m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);

m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);

m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);

m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);

This results in a primitive with a transparency gradient. The gradient is transparent where x = 0, and opaque where x is its maximum value.


Frame Buffer Alpha (Direct3D 9)

Frame buffer alpha-blending is a bit different than vertex alpha, material alpha, and texture alpha. Vertex, material, and texture alpha set transparency values that are used only for the current primitive, and by themselves have no effect on other primitives. Frame buffer alpha-blending controls how the current primitive is combined with existing pixels in the frame buffer to yield a final pixel color.

When performing alpha blending, two colors are being combined: a source color and a destination color. The source color is from the transparent object, the destination color is the color already at the pixel location. The destination color is the result of rendering some other object that is behind the transparent object, that is, the object that will be visible through the transparent object. Alpha blending uses a formula to control the ratio between the source and destination objects.

Final Color = ObjectColor * SourceBlendFactor + PixelColor * DestinationBlendFactor

ObjectColor is the contribution from the primitive being rendered at the current pixel location. PixelColor is the contribution from the frame buffer at the current pixel location.

The set of alpha blend factors that can be used are listed below.

Blend mode factor | Description
D3DBLEND_ZERO | (0, 0, 0, 0)
D3DBLEND_ONE | (1, 1, 1, 1)
D3DBLEND_SRCCOLOR | (Rs, Gs, Bs, As)
D3DBLEND_INVSRCCOLOR | (1-Rs, 1-Gs, 1-Bs, 1-As)
D3DBLEND_SRCALPHA | (As, As, As, As)
D3DBLEND_INVSRCALPHA | (1-As, 1-As, 1-As, 1-As)
D3DBLEND_DESTALPHA | (Ad, Ad, Ad, Ad)
D3DBLEND_INVDESTALPHA | (1-Ad, 1-Ad, 1-Ad, 1-Ad)
D3DBLEND_DESTCOLOR | (Rd, Gd, Bd, Ad)
D3DBLEND_INVDESTCOLOR | (1-Rd, 1-Gd, 1-Bd, 1-Ad)
D3DBLEND_SRCALPHASAT | (f, f, f, 1); f = min(As, 1-Ad)
D3DBLEND_BOTHSRCALPHA | Obsolete for DirectX 6 and later. You can achieve the same effect by setting the source and destination blend factors to D3DBLEND_SRCALPHA and D3DBLEND_INVSRCALPHA in separate calls.
D3DBLEND_BOTHINVSRCALPHA | Obsolete for DirectX 6. You can achieve the same effect by setting the source and destination blend factors to D3DBLEND_INVSRCALPHA and D3DBLEND_SRCALPHA in separate calls.
D3DBLEND_BLENDFACTOR | Use color.r, color.g, color.b, and color.a obtained from the D3DRS_BLENDFACTOR setting.
D3DBLEND_INVBLENDFACTOR | Use 1-color.r, 1-color.g, 1-color.b, and 1-color.a obtained from the D3DRS_BLENDFACTOR setting.

Direct3D uses the D3DRS_ALPHABLENDENABLE render state to enable alpha transparency blending. The type of alpha blending that is done depends on the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states. Source and destination blend states are used in pairs. The following code fragment sets the source blend state to D3DBLEND_SRCCOLOR and the destination blend state to D3DBLEND_INVSRCCOLOR.

// This code fragment assumes that lpD3DDevice is a
//   valid pointer to a device.

// Enable alpha blending.
lpD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,
                            TRUE);

// Set the source blend state.
lpD3DDevice->SetRenderState(D3DRS_SRCBLEND,
                            D3DBLEND_SRCCOLOR);

// Set the destination blend state.
lpD3DDevice->SetRenderState(D3DRS_DESTBLEND,
                            D3DBLEND_INVSRCCOLOR);

This code performs a linear blend between the source color (the color of the primitive being rendered at the current location) and the destination color (the color at the current location in the frame buffer). The resulting appearance is similar to tinted glass in that some of the color of the destination object seems to be transmitted through the source object; the rest of it appears to be absorbed.

Many of these blend factors require alpha values in the texture to operate correctly. Thus, when using vertex or material alpha, the application is restricted as to which modes will produce interesting results.


Render Target Alpha (Direct3D 9)

The frame buffer blender can now blend alpha channels independent from color-channel blending on render targets. This control is enabled with a new render state, D3DRS_SEPARATEALPHABLENDENABLE.

When D3DRS_SEPARATEALPHABLENDENABLE is set to FALSE (which is the default condition), the render-target blending factors and operations applied to alpha are the same as those defined for blending color channels. A driver needs to set the D3DPMISCCAPS_SEPARATEALPHABLEND cap to indicate that it can support render-target alpha blending. Be sure to enable D3DRS_ALPHABLEND to tell the pipeline that alpha blending is needed.

To control the factors in the alpha channel of the render-target blenders, two new render states are defined as follows:

D3DRS_SRCBLENDALPHA
D3DRS_DESTBLENDALPHA

Like the D3DRS_SRCBLEND and D3DRS_DESTBLEND, these can be set to one of the values in the D3DBLEND enumeration. The source and destination blend settings can be combined in several ways, depending on the settings in the SrcBlendCaps and DestBlendCaps members of D3DCAPS9.

The alpha blending is done as follows:

renderTargetAlpha = (alphain* srcBlendOp) BlendOp (alphart* destBlendOp)

Where:

  • alphain is the input alpha value.
  • srcBlendOp is one of the blend factors in D3DBLEND.
  • BlendOp is one of the blend factors in D3DBLENDOP.
  • alphart is the render-target alpha value.
  • destBlendOp is one of the blend factors in D3DBLEND.
  • renderTargetAlpha is the final blended alpha value.


Direct3D Surfaces (Direct3D 9)

A surface represents a linear area of display memory and usually resides in the display memory of the display card, although surfaces can exist in system memory. Surfaces are managed by the IDirect3DSurface9 interface.

  • Front Buffer. A rectangle of memory that is translated by the graphics adapter and displayed on the monitor. In Direct3D an application never writes directly to the front buffer.
  • Back Buffer. A rectangle of memory that an application can directly write to. The back buffer is never directly displayed on the monitor.
  • Flipping surfaces. The process of moving the back buffer to the front buffer.
  • Swap chain. A collection of one or more back buffers that can be serially presented to the front buffer.

Getting a Surface

Create a surface by calling any of these methods:

  • IDirect3DDevice9::CreateDepthStencilSurface
  • IDirect3DDevice9::CreateOffscreenPlainSurface
  • IDirect3DDevice9::CreateRenderTarget

Surface formats determine how data for each pixel in surface memory is interpreted. Direct3D uses the D3DFORMAT member of the D3DSURFACE_DESC structure to describe the surface format. You can retrieve the format of an existing surface by calling the IDirect3DSurface9::GetDesc method.

Once a surface is created, you can get a pointer to it by calling any of these methods:

  • IDirect3DCubeTexture9::GetCubeMapSurface
  • IDirect3DDevice9::GetBackBuffer
  • IDirect3DDevice9::GetDepthStencilSurface
  • IDirect3DDevice9::GetFrontBufferData
  • IDirect3DDevice9::GetRenderTarget
  • IDirect3DSwapChain9::GetBackBuffer
  • IDirect3DTexture9::GetSurfaceLevel

The IDirect3DSurface9 interface enables you to indirectly access memory through the IDirect3DDevice9::UpdateSurface method. This method allows you to copy a rectangular region of pixels from one IDirect3DSurface9 interface to another IDirect3DSurface9 interface. The surface interface also has methods to directly access display memory. For example, you can use the IDirect3DSurface9::LockRect method to lock a rectangular region of display memory. It is important to call IDirect3DSurface9::UnlockRect after you are done working with the locked rectangular region on the surface.

Additional Surface Topics

Find out more about how to use surfaces with any of these topics:

  • Surface Formats (Direct3D 9)
  • What Is a Swap Chain? (Direct3D 9)
  • Width vs. Pitch (Direct3D 9)
  • Flipping Surfaces (Direct3D 9)
  • Page Flipping and Back Buffering (Direct3D 9)
  • Copying to Surfaces (Direct3D 9)
  • Copying Surfaces (Direct3D 9)
  • Accessing Surface Memory Directly (Direct3D 9)
  • Private Surface Data (Direct3D 9)
  • Gamma Controls (Direct3D 9)


Surface Formats (Direct3D 9)

In Direct3D, all two-dimensional (2D) images are represented by a linear range of memory called a surface. A surface can be thought of as a 2D array where each element holds a color value representing a small section of the image, called a pixel. An image's detail level is defined by both the number of pixels needed to represent the image, and the number of bits needed for the image's color spectrum. For example, an image that is 800 pixels wide by 600 pixels high with 32 bits of color for each pixel (written as 800x600x32) will be more detailed than an image that is 640 pixels wide by 480 pixels tall with 16 bits of color for each pixel (written as 640x480x16). Likewise, the more detailed image will require a larger surface to store the data. For an 800x600x32 image, the surface's array dimensions will be 800x600, and each element will hold a 32-bit value to represent its color.

All surfaces have a size and store a specific number of bits that represent color. The bits that represent color are separated into individual color elements: red, green, and blue. In Direct3D all color elements are defined by the D3DFORMAT enumerated type. A Direct3D color format is broken down into the number of byes reserved for each color. For example, a 16-bit color format in Direct3D is defined as D3DFMT_R5G6B5, where 5 bits are reserved for red (R), 6 bits for green (G), and 5 bits for blue (B).


What Is a Swap Chain? (Direct3D 9)

A graphics adapter holds a pointer to a surface that represents the image being displayed on the monitor, called a front buffer. As the monitor is refreshed, the graphics card sends the contents of the front buffer to the monitor to be displayed. However, this leads to a problem when rendering real-time graphics. The heart of the problem is that monitor refresh rates are very slow in comparison to the rest of the computer. Common refresh rates range from 60 Hz (60 times per second) to 100 Hz. If your application is updating the front buffer while the monitor is in the middle of a refresh, the image that is displayed will be cut in half with the upper half of the display containing the old image and the lower half containing the new image. This problem is referred to as tearing.

Direct3D implements two options to avoid tearing:

  • An option to only allow updates of the monitor on the vertical retrace (or vertical sync) operation. A monitor typically refreshes its image by moving a light pin horizontally, zigzagging from the top left of the monitor and ending at the bottom right. When the light pin reaches the bottom, the monitor recalibrates the light pin by moving it back to the upper left so that the process can start again. This recalibration is called a vertical sync. During a vertical sync, the monitor is not drawing anything, so any update to the front buffer will not be seen until the monitor starts to draw again. The vertical sync is relatively slow; however, not slow enough to render a complex scene while waiting. What is needed to avoid tearing and be able to render complex scenes is a process called back buffering.
  • An option to use a technique called back buffering. Back buffering is the process of drawing a scene to an off-screen surface, called a back buffer. Note that any surface other than the front buffer is called an off-screen surface because it is never directly viewed by the monitor. By using a back buffer, an application has the freedom to render a scene whenever the system is idle (that is, no windows messages are waiting) without having to consider the monitor's refresh rate. Back buffering brings in an additional complication of how and when to move the back buffer to the front buffer.

The process of moving the back buffer to the front buffer is called surface flipping. Because the graphics card simply uses a pointer to a surface to represent the front buffer, a simple pointer change is all that is needed to set the back buffer to the front buffer. When an application asks Direct3D to present the back buffer to the front buffer, Direct3D simply "flips" the two surface pointers. The result is that the back buffer is now the new front buffer, and the old front buffer is the new back buffer. A surface flip is invoked whenever an application asks the Direct3D device to present the back buffer; however, Direct3D can be set up to queue the requests until a vertical sync occurs. This option is referred to as the Direct3D device's presentation interval. Note that the data in the new back buffer may not be reusable, depending on how an application specifies how Direct3D should handle surface flipping. Surface flipping is key in multimedia, animation, and game software; it is equivalent to the way you can do animation with a pad of paper. On each page, the artist changes the figures slightly, so that when you flip rapidly between sheets, the drawing appears animated.

See Also

Flipping Surfaces (Direct3D 9)


Width vs. Pitch (Direct3D 9)

Although the terms width and pitch are often used informally, they have very important, and distinctly different, meanings. As a result, you should understand the meanings for each, and how to interpret the values that Direct3D uses to describe them.

Direct3D uses the D3DSURFACE_DESC structure to carry information describing a surface. Among other things, this structure is defined to contain information about a surface's dimensions, as well as how those dimensions are represented in memory. The structure uses the Height and Width members to describe the logical dimensions of the surface. Both members are measured in pixels. Therefore, the Height and Width values for a 640 x 480 surface are the same whether it is an 8-bit surface or a 24-bit RGB surface.

When you lock a surface using the IDirect3DSurface9::LockRect method, the method fills in a D3DLOCKED_RECT structure that contains the pitch of the surface and a pointer to the locked bits. The value in the Pitch member describes the surface's memory pitch, also called stride. Pitch is the distance, in bytes, between two memory addresses that represent the beginning of one bitmap line and the beginning of the next bitmap line. Because pitch is measured in bytes rather than pixels, a 640x480x8 surface has a very different pitch value than a surface with the same dimensions but a different pixel format. Additionally, the pitch value sometimes reflects bytes that Direct3D has reserved as a cache, so it is not safe to assume that pitch is just the width multiplied by the number of bytes per pixel. Rather, visualize the difference between width and pitch as shown in the following illustration.

Pitch and width difference

In this figure, the front buffer and back buffer are both 640x480x8, and the cache is 384x480x8.

When accessing surfaces directly, take care to stay within the memory allocated for the dimensions of the surface and stay out of any memory reserved for cache. Additionally, when you lock only a portion of a surface, you must stay within the rectangle you specify when locking the surface. Failing to follow these guidelines will have unpredictable results. When rendering directly into surface memory, always use the pitch returned by the IDirect3DSurface9::LockRect method. Do not assume a pitch based solely on the display mode. If your application works on some display adapters but looks garbled on others, this may be the cause of the problem.

For more information, see Accessing Surface Memory Directly (Direct3D 9).


Flipping Surfaces (Direct3D 9)

A Direct3D application typically displays an animated sequence by generating the frames of the animation in back buffers and presenting them in sequence. Back buffers are organized into swap chains. A swap chain is a series of buffers that "flip" to the screen one after another. This can be used to render one scene in memory and then flip the scene to the screen when rendering is complete. This avoids the phenomenon known as tearing and allows for smoother animation.

Each device created in Direct3D has at least one swap chain. When you initialize the first Direct3D device, you set the BackBufferCount member of D3DPRESENT_PARAMETERS, which tells Direct3D the number of back buffers that will be in the swap chain. The call to IDirect3D9::CreateDevice then creates the Direct3D device and corresponding swap chain.

When you use IDirect3DDevice9::Present to request a surface flip operation, the pointers to surface memory for the front buffer and back buffers are swapped. Flipping is performed by switching pointers that the display device uses for referencing memory, not by copying surface memory. When a flipping chain contains a front buffer and more than one back buffer, the pointers are switched in a circular pattern, as shown in the following illustration.

You can create addition swap chains for a device by calling IDirect3DDevice9::CreateAdditionalSwapChain. An application can create one swap chain per view and associate each swap chain with a particular window. The application renders images in the back buffers of each swap chain, and then presents them individually. The two parameters that IDirect3DDevice9::CreateAdditionalSwapChain takes are a pointer to a D3DPRESENT_PARAMETERS structure and the address of a pointer to an IDirect3DSwapChain9 interface. You can then use IDirect3DSwapChain9::Present to display the contents of the next back buffer to the front buffer. Note that a device can only have one full-screen swap chain.

You can gain access to a specific back buffer by calling the IDirect3DDevice9::GetBackBuffer or IDirect3DSwapChain9::GetBackBuffer methods, which return a pointer to an IDirect3DSurface9 interface that represents the returned back buffer surface. Note that calling this method increases the internal reference count on the IDirect3DDevice9 interface so be sure to call IUnknown when you are done using this surface or you will have a memory leak.

Remember, Direct3D flips surfaces by swapping surface memory pointers within the swap chain, not by swapping the surfaces themselves. This means that you will always render to the back buffer that will be displayed next.

It is important to note the distinction between a "flipping operation," as performed by a display adapter driver, and a "Present" operation applied to a swap chain created with D3DSWAPEFFECT_FLIP.

The term "flip" conventionally denotes an operation that alters the range of video memory addresses that a display adapter uses to generate its output signal, thus causing the contents of a previously hidden back buffer to be displayed. In Direct3D 9, the term is often used more generally to describe the presentation of a back buffer in any swap chain created with the D3DSWAPEFFECT_FLIP swap effect.

While such "Present" operations are almost invariably implemented by flip operations when the swap chain is a full-screen one, they are necessarily implemented by copy operations when the swap chain is windowed. Furthermore, a display adapter driver may use flipping to implement Present operations against full-screen swap chains based on the D3DSWAPEFFECT_DISCARD and D3DSWAPEFFECT_COPY.

The discussion above applies to the commonly used case of a full-screen swap chain created with D3DSWAPEFFECT_FLIP.

For a more general discussion of the different swap effects for both windowed and full-screen swap chains, see D3DSWAPEFFECT.


Page Flipping and Back Buffering (Direct3D 9)

Page flipping is key in multimedia, animation, and game software; it is analogous to the way you can do animation with a pad of paper. On each page, the artist changes the figure slightly, so that when you flip rapidly between sheets, the drawing appears animated.

Page flipping in software is similar to this process. Direct3D implements page flipping functionality through a swap chain, which is a property of the device. Initially, you set up a series of Direct3D buffers that flip to the screen in the way that the artist's paper flips to the next page. The first buffer is referred to as the color front buffer. The buffers behind it are called back buffers. Your application writes to a back buffer and then flips the color front buffer so that the back buffer appears on screen. While the system displays the image, your software is again writing to a back buffer. The process continues as long as you are animating, enabling you to animate images efficiently.

Direct3D makes it easy to set up page flipping schemes - from a simple double-buffered scheme (a color front buffer with one back buffer) to more sophisticated schemes with additional back buffers.

See Also

What Is a Swap Chain? (Direct3D 9)


Copying to Surfaces (Direct3D 9)

When using IDirect3DDevice9::UpdateSurface, pass a rectangle on the source surface, or use NULL to specify the entire surface. You also pass a point on the destination surface to which the upper left position of the rectangle on the source image is copied. This method does not support clipping. The operation will fail unless the source rectangle and the corresponding destination rectangle are completely contained within the source and destination surfaces respectively. This method does not support alpha blending, color keys, or format conversion. Note that the destination and source surfaces must be distinct.

For other restrictions when using UpdateSurface, see IDirect3DDevice9::UpdateSurface.

The following methods are also available in C++/C for copying images to a Direct3D surface.

  • D3DXLoadSurfaceFromFile
  • D3DXLoadSurfaceFromFileInMemory
  • D3DXLoadSurfaceFromMemory
  • D3DXLoadSurfaceFromResource
  • D3DXLoadSurfaceFromSurface
  • IDirect3DDevice9::UpdateSurface

UpdateSurface Example

The following example copies two rectangles from the source surface to a destination surface. The first rectangle is copied from (0, 0, 50, 50) on the source surface to the same location on the destination surface, and the second rectangle is copied from (50, 50, 100, 100) on the source surface to (150, 150, 200, 200) on the destination surface.

//The following assumptions are made:
// -d3dDevice is a valid Direct3DDevice9 object.
// -pSource and pDest are valid IDirect3DSurface9 pointers.

RECT  rcSource[] = {  0,  0,  50,  50,
                     50, 50, 100, 100 };
POINT ptDest[]   = {  0,  0, 150, 150 };

d3dDevice->UpdateSurface( pSource, rcSource, 2, pDest, ptDest);

See Also

IDirect3DDevice9::StretchRect


Copying Surfaces (Direct3D 9)

The term blit is shorthand for "bit block transfer," which is the process of transferring blocks of data from one place in memory to another. The blitting device driver interface (DDI) continues to be used in Direct3D 9 as the primary mechanism for moving large rectangles of pixels on a per-frame basis, the mechanism behind the copy-oriented IDirect3DDevice9::Present method. The transportation of artwork in the blit operation is performed by the IDirect3DDevice9::UpdateTexture method. Artwork can also be copied in Direct3D 9 by using the IDirect3DDevice9::UpdateSurface method, which copies a rectangular subset of pixels.

Note Direct3D 9 provides D3DX functions that enable you to load artwork from files, apply color conversion, and resize artwork. For more information about the available functions see Texturing Functions.

See Also

IDirect3DDevice9::StretchRect, IDirect3DDevice9::StretchRect


Accessing Surface Memory Directly (Direct3D 9)

You can directly access the surface memory by using the IDirect3DSurface9::LockRect method. When you call this method, the pRect parameter is a pointer to a RECT structure that describes the rectangle on the surface to access directly. To request that the entire surface be locked, set pRect to NULL. Also, you can specify a RECT that covers only a portion of the surface. Providing that no two rectangles overlap, two threads or processes can simultaneously lock multiple rectangles in a surface. Note that a multisample back buffer cannot be locked.

The IDirect3DSurface9::LockRect method fills a D3DLOCKED_RECT structure with all the information to properly access the surface memory. The structure includes information about the pitch and has a pointer to the locked bits. When you finish accessing the surface memory, call the IDirect3DSurface9::UnlockRect method to unlock it.

While you have a surface locked, you can directly manipulate the contents. The following list describes some tips for avoiding common problems with directly rendering surface memory.

  • Never assume a constant display pitch. Always examine the pitch information returned by the IDirect3DSurface9::LockRect method. This pitch can vary for a number of reasons, including the location of the surface memory, the display card type, or even the version of the Direct3D driver. For more information, see Width vs. Pitch (Direct3D 9).
  • Make certain you copy to unlocked surfaces. Direct3D copy methods will fail if called on a locked surface.
  • Limit your application's activity while a surface is locked.
  • Always copy data aligned to display memory. Windows 98 uses a page fault handler, Vflatd.386, to implement a virtual flat-frame buffer for display cards with bank-switched memory. The handler allows these display devices to present a linear frame buffer to Direct3D. Copying data unaligned to display memory can cause the system to suspend operations if the copy spans memory banks.
  • A surface may not be locked if it belongs to a resource assigned to the D3DPOOL_DEFAULT memory pool unless it is a dynamic texture or a surface created using IDirect3DDevice9::CreateOffscreenPlainSurface. Back buffer surfaces, which may be accessed using the IDirect3DDevice9::GetBackBuffer and IDirect3DSwapChain9::GetBackBuffer methods, may be locked only if the swap chain was created with the Flags member of D3DPRESENT_PARAMETERS to include D3DPRESENTFLAG_LOCKABLE_BACKBUFFER.


Private Surface Data (Direct3D 9)

You can store any kind of application-specific data with a surface. For example, a surface representing a map in a game might contain information about terrain.

A surface can have more than one private data buffer. Each buffer is identified by a GUID that you supply when attaching the data to the surface.

To store private surface data, use SetPrivateData, passing a pointer to the source buffer, the size of the data, and an application-defined GUID for the data. Optionally, the source data can exist in the form of a COM object; in this case, you pass a pointer to the object's IUnknown interface pointer and you set the D3DSPD_IUNKNOWNPOINTER flag.

SetPrivateData allocates an internal buffer for the data and copies it. You can then safely free the source buffer or object. The internal buffer or interface reference is released when FreePrivateData is called. This happens automatically when the surface is freed.

To retrieve private data for a surface, you must allocate a buffer of the correct size and then call the GetPrivateData method, passing the GUID that was assigned to the data. You are responsible for freeing any dynamic memory you use for this buffer. If the data is a COM object, this method retrieves the IUnknown pointer.

If you don't know how big a buffer to allocate, first call GetPrivateData with zero in pSizeOfData. If the method fails with D3DERR_MOREDATA, it returns the necessary number of bytes for the buffer.


Gamma Controls (Direct3D 9)

Gamma controls allow you to change how the system displays the contents of the surface, without affecting the contents of the surface itself. Think of these controls as very simple filters that Direct3D applies to data as it leaves a surface and before it is rendered on the screen.

Gamma controls are a property of a swap chain. Gamma controls make it possible to dynamically change how a surface's red, green, and blue levels map to the actual levels that the system displays. By setting gamma levels, you can cause the user's screen to flash colors - red when the user's character is shot, green when the character picks up a new item, and so on - without copying new images to the frame buffer to achieve the effect. Or, you might adjust color levels to apply a color bias to the images in the back buffer.

There is always at least one swap chain (the implicit swap chain) for each device because Direct3D 9 has one swap chain as a property of the device. Because the gamma ramp is a property of the swap chain, the gamma ramp can be applied when the swap chain is windowed. The gamma ramp takes effect immediately. There is no waiting for a vertical sync operation.

The IDirect3DDevice9::SetGammaRamp and IDirect3DDevice9::GetGammaRamp methods allow you to manipulate ramp levels that affect the red, green, and blue color components of pixels from the surface before they are sent to the digital-to-analog converter (DAC) for display.

Gamma Ramp Levels

In Direct3D, the term gamma ramp describes a set of values that map the level of a particular color component - red, green, blue - for all pixels in the frame buffer to new levels that are received by the DAC for display. The remapping is performed by way of three look-up tables, one for each color component.

Here's how it works: Direct3D takes a pixel from the frame buffer and evaluates its individual red, green, and blue color components. Each component is represented by a value from 0 to 65535. Direct3D takes the original value and uses it to index a 256-element array (the ramp), where each element contains a value that replaces the original one. Direct3D performs this look-up and replace process for each color component of each pixel in the frame buffer, thereby changing the final colors for all the on-screen pixels.

It's handy to visualize the ramp values by graphing them. The left graph of the two following graphs shows a ramp that doesn't modify colors at all. The right graph shows a ramp that imposes a negative bias to the color component to which it is applied.

The array elements for the graph on the left contain values identical to their index - 0 in the element at index 0, and 65535 at index 255. This type of ramp is the default, as it doesn't change the input values before they're displayed. The right graph provides more variation; its ramp contains values that range from 0 in the first element to 32768 in the last element, with values ranging uniformly in between. The effect is that the color component that uses this ramp appears muted on the display. You are not limited to using linear graphs; if your application can assign arbitrary mapping if needed. You can even set the entries to all zeroes to remove a color component completely from the display.

Setting and Retrieving Gamma Ramp Levels

Gamma ramp levels are effectively look-up tables that Direct3D uses to map the frame buffer color components to new levels that will be displayed. You can set and retrieve ramp levels for the primary surface by calling the IDirect3DDevice9::SetGammaRamp and IDirect3DDevice9::GetGammaRamp methods. IDirect3DDevice9::SetGammaRamp accepts two parameters and IDirect3DDevice9::GetGammaRamp accepts one parameter. For IDirect3DDevice9::SetGammaRamp, the first parameter is either D3DSGR_CALIBRATE or D3DSGR_NO_CALIBRATION. The second parameter, pRamp, is a pointer to a D3DGAMMARAMP structure. The D3DGAMMARAMP structure contains three 256-element arrays of WORDs, one array each to contain the red, green, and blue gamma ramps. IDirect3DDevice9::GetGammaRamp has one parameter that takes a pointer to a D3DGAMMARAMP type that will be filled with the current gamma ramp.

You can include the DDSGR_CALIBRATE value for the first parameter of IDirect3DDevice9::SetGammaRamp to invoke the calibrator when setting new gamma levels. Calibrating gamma ramps incurs some processing overhead, and should not be used frequently. Setting a calibrated gamma ramp provides a consistent and absolute gamma value for the user, regardless of the display adapter and monitor.

Not all systems support gamma calibration. To determine if gamma calibration is supported, call IDirect3DDevice9::GetDeviceCaps, and examine the Caps2 member of the associated D3DCAPS9 structure after the method returns. If the D3DCAPS2_CANCALIBRATEGAMMA capability flag is present, then gamma calibration is supported.

When setting new ramp levels, keep in mind that that the levels you set in the arrays are only used when your application is in full-screen, exclusive mode. Whenever your application changes to normal mode, the ramp levels are set aside, taking effect again when the application reinstates full-screen mode.

If the device does not support gamma ramps in the swap chain's current presentation mode (full-screen or windowed), no error value is returned. Applications can check the D3DCAPS2_FULLSCREENGAMMA and D3DCAPS2_CANCALIBRATEGAMMA capability bits in the Caps2 member of the D3DCAPS9 type to determine the capabilities of the device and whether a calibrator is installed.


Direct3D Textures (Direct3D 9)

Textures are a powerful tool in creating realism in computer-generated 3D images. Direct3D supports an extensive texturing feature set, providing developers with easy access to advanced texturing techniques.

This section will get you started using textures.

  • Basic Texturing Concepts (Direct3D 9)
  • Texture Coordinates (Direct3D 9)
  • Texture Filtering (Direct3D 9)
  • Texture Resources (Direct3D 9)
  • Texture Wrapping (Direct3D 9)
  • Texture Blending (Direct3D 9)

These topics will go into more detail about additional texturing functionality.

  • Automatic Generation of Mipmaps (Direct3D 9)
  • Automatic Texture Management (Direct3D 9)
  • Compressed Texture Resources (Direct3D 9)
  • Hardware Considerations for Texturing (Direct3D 9)
  • Volume Texture Resources (Direct3D 9)

For improved performance, consider using dynamic textures. A dynamic texture can be locked, written to, and unlocked each frame. See Using Dynamic Textures.


Basic Texturing Concepts (Direct3D 9)

Early computer-generated 3D images, although generally advanced for their time, tended to have a shiny plastic look. They lacked the types of markings-such as scuffs, cracks, fingerprints, and smudges-that give 3D objects realistic visual complexity. In recent years, textures have gained popularity among developers as a tool for enhancing the realism of computer-generated 3D images.

In its everyday use, the word texture refers to an object's smoothness or roughness. In computer graphics, however, a texture is a bitmap of pixel colors that give an object the appearance of texture.

Because Direct3D textures are bitmaps, any bitmap can be applied to a Direct3D primitive. For instance, applications can create and manipulate objects that appear to have a wood grain pattern in them. Grass, dirt, and rocks can be applied to a set of 3D primitives that form a hill. The result is a realistic-looking hillside. You can also use texturing to create effects such as signs along a roadside, rock strata in a cliff, or the appearance of marble on a floor.

In addition, Direct3D supports more advanced texturing techniques such as texture blending-with or without transparency-and light mapping. For more information, see Texture Blending (Direct3D 9) and Light Mapping with Textures (Direct3D 9).

If your application creates a hardware abstraction layer (HAL) device or a software device, it can use 8, 16, 24, 32, 64, or 128-bit textures.

Additional information is contained in the following topics.

  • Texture Addressing Modes (Direct3D 9)
  • Texture Dirty Regions (Direct3D 9)
  • Texture Palettes (Direct3D 9)


Texture Addressing Modes (Direct3D 9)

Your Direct3D application can assign texture coordinates to any vertex of any primitive. For details, see Texture Coordinates (Direct3D 9). Typically, the u- and v-texture coordinates that you assign to a vertex are in the range of 0.0 to 1.0 inclusive. However, by assigning texture coordinates outside that range, you can create certain special texturing effects.

You control what Direct3D does with texture coordinates that are outside the [0.0, 1.0] range by setting the texture addressing mode. For instance, you can have your application set the texture addressing mode so that a texture is tiled across a primitive.

Direct3D enables applications to perform texture wrapping. It is important to note that setting the texture addressing mode to D3DTADDRESS_WRAP is not the same as performing texture wrapping. Setting the texture addressing mode to D3DTADDRESS_WRAP results in multiple copies of the source texture being applied to the current primitive, and enabling texture wrapping changes how the system rasterizes textured polygons. For details, see Texture Wrapping (Direct3D 9).

Enabling texture wrapping effectively makes texture coordinates outside the [0.0, 1.0] range invalid, and the behavior for rasterizing such delinquent texture coordinates is undefined in this case. When texture wrapping is enabled, texture addressing modes are not used. Take care that your application does not specify texture coordinates lower than 0.0 or higher than 1.0 when texture wrapping is enabled.

Setting the Addressing Mode

You can set texture addressing modes for individual texture stages by calling the IDirect3DDevice9::SetSamplerState method. Specify the desired texture stage identifier in the first parameter. Set the second parameter to D3DSAMP_ADDRESSU, D3DSAMP_ADDRESSV, or D3DSAMP_ADDRESSW values to update the u-, v-, or w-addressing modes individually. The third parameter you pass to IDirect3DDevice9::SetSamplerState determines which mode is being set. This can be any member of the D3DTEXTUREADDRESS enumerated type. To retrieve the current texture address mode for a texture stage, call IDirect3DDevice9::GetSamplerState, using the D3DSAMP_ADDRESSU, D3DSAMP_ADDRESSV, or D3DSAMP_ADDRESSW members of the D3DSAMPLERSTATETYPE enumeration to identify the address mode about which you want information.

Device Limitations

Although the system generally allows texture coordinates outside the range of 0.0 and 1.0, inclusive, hardware limitations often affect how far outside that range texture coordinates can be. A rendering device communicates this limit in the MaxTextureRepeat member of the D3DCAPS9 structure when you retrieve device capabilities. The value in this member describes the full range of texture coordinates allowed by the device. For instance, if this value is 128, then the input texture coordinates must be kept in the range -128.0 to +128.0. Passing vertices with texture coordinates outside this range is invalid. The same restriction applies to the texture coordinates generated as a result of automatic texture coordinate generation and texture coordinate transformations.

The interpretation of MaxTextureRepeat is also affected by the D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE capability bit. When this bit is set, the value in the MaxTextureRepeat member is used precisely as described. However, when D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is not set, texture repeating limitations depend on the size of the texture indexed by the texture coordinates. In this case, MaxTextureRepeat must be scaled by the current texture size at the largest level of detail to compute the valid texture coordinate range. For example, given a texture dimension of 32 and MaxTextureRepeat of 512, the actual valid texture coordinate range is 512/32 = 16, so the texture coordinates for this device must be within the range of -16.0 to +16.0.

Additional information about the texture addressing modes is contained in the following topics.

  • Wrap Texture Address Mode (Direct3D 9)
  • Mirror Texture Address Mode (Direct3D 9)
  • Clamp Texture Address Mode (Direct3D 9)
  • Border Color Texture Address Mode (Direct3D 9)


Wrap Texture Address Mode (Direct3D 9)

The wrap texture address mode, identified by the D3DTADDRESS_WRAP member of the D3DTEXTUREADDRESS enumerated type, makes Direct3D repeat the texture on every integer junction. Suppose, for example, your application creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_WRAP results in the texture being applied three times in both the u-and v-directions.

The effects of this texture address mode are similar to, but distinct from, those of the mirror mode. For more information, see Mirror Texture Address Mode (Direct3D 9).


Mirror Texture Address Mode (Direct3D 9)

The mirror texture address mode, identified by the D3DTADDRESS_MIRROR member of the D3DTEXTUREADDRESS enumerated type, causes Direct3D to mirror the texture at every integer boundary. Suppose, for example, your application creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_MIRROR results in the texture being applied three times in both the u- and v-directions. Every other row and column that it is applied to is a mirror image of the preceding row or column.

The effects of this texture address mode are similar to, but distinct from, those of the wrap mode. For more information, see Wrap Texture Address Mode (Direct3D 9).


Clamp Texture Address Mode (Direct3D 9)

The clamp texture address mode, identified by the D3DTADDRESS_CLAMP member of the D3DTEXTUREADDRESS enumerated type, causes Direct3D to clamp your texture coordinates to the [0.0, 1.0] range. That is, it applies the texture once, then smears the color of edge pixels. For example, suppose that your application creates a square primitive and assigns texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0) to the primitive's vertices. Setting the texture addressing mode to D3DTADDRESS_CLAMP results in the texture being applied once. The pixel colors at the top of the columns and the end of the rows are extended to the top and right of the primitive respectively.

This is illustrated in the following figure.


Border Color Texture Address Mode (Direct3D 9)

The border color texture address mode, identified by the D3DTADDRESS_BORDER member of the D3DTEXTUREADDRESS enumerated type, causes Direct3D to use an arbitrary color, known as the border color, for any texture coordinates outside the range of 0.0 through 1.0, inclusive.

This is shown in the following figure in which the application specifies that the texture be applied to the primitive using a red border.

Applications set the border color by calling IDirect3DDevice9::SetSamplerState. Set the first parameter for the call to the desired texture stage identifier, the second parameter to the D3DSAMP_BORDERCOLOR stage state value, and the third parameter to the new RGBA border color.


Texture Dirty Regions (Direct3D 9)

Applications can optimize which subset of a texture is copied by specifying "dirty" regions on textures. Only those regions marked as dirty are copied by a call to IDirect3DDevice9::UpdateTexture. However, the dirty regions may be expanded to optimize alignment. When a texture is created, the entire texture is considered dirty. Only the following operations affect the dirty state of a texture:

  • Adding a dirty region to a texture.
  • Locking some buffer in the texture. This operation adds the locked region as a dirty region. The application can turn off this automatic dirty region update if it has better knowledge of the actual dirty regions.
  • Using a surface level of the texture as a destination in IDirect3DDevice9::UpdateSurface marks the entire texture as dirty.
  • Using the texture as a source in IDirect3DDevice9::UpdateTexture clears all the dirty regions on the source texture.
  • Using IDirect3DSurface9::GetDC to return a device context.
  • Calling IDirect3DBaseTexture9::GenerateMipSubLevels marks the entire texture as dirty.
  • Calling IDirect3DBaseTexture9::SetAutoGenFilterType marks the entire texture as dirty.

Dirty regions are set on the top level of a mipmapped texture, and IDirect3DDevice9::UpdateTexture can expand the dirty region down the mip chain in order to minimize the number of bytes copied for each sublevel. Note that the sublevel dirty region coordinates are rounded outward, that is, their fractional parts are rounded toward the nearest edge of the texture.

Because each type of texture has different types of dirty regions, there are methods on each texture type. 2D textures use dirty rectangle, and volume textures use boxes.

  • IDirect3DCubeTexture9::AddDirtyRect
  • IDirect3DTexture9::AddDirtyRect
  • IDirect3DVolumeTexture9::AddDirtyBox

Passing NULL for the pDirtyRect or pDirtyBox parameters for the above methods expands the dirty region to cover the entire texture.

Each lock method can take D3DLOCK_NO_DIRTY_UPDATE, which prevents any changes to the dirty state of the texture. For more information, see Locking Resources (Direct3D 9).

When more information about the true set of regions that are changed during a lock operation is available, applications should use D3DLOCK_NO_DIRTY_UPDATE. Note that a lock or a copy to a texture sublevel only (that is, without locking or copying to the top level) does not update the dirty regions for that texture. Applications assume the same responsibility for updating dirty regions when they lock lower levels without locking the topmost level.


Texture Palettes (Direct3D 9)

Direct3D 9 supports paletted textures through a set of 256 entry palettes associated with the IDirect3DDevice9 object. A palette is made current by calling the IDirect3DDevice9::SetCurrentTexturePalette method. The current palette is used for translating all paletted textures for all active texture stages. IDirect3DDevice9::SetPaletteEntries updates all of a palette's 256 entries. Each entry is a PALETTEENTRY structure of the format D3DFMT_A8R8G8B8. All entries default to 0xFFFFFFFF.

The IDirect3DDevice9 palettes contain an alpha channel. This alpha channel can be used when the D3DPTEXTURECAPS_ALPHAPALETTE device capability flag is set, indicating that the device supports alpha from the palette. The palette alpha channel is used when the texture format does not have an alpha channel. If the device does not support alpha from the palette and the texture format does not have an alpha channel, then a value of 0xFF is used for alpha.

There is a maximum of 65,536 (0x0000FFFF) palettes. Because memory resources associated with the set of palettes are proportional to the maximum palette number that an application references, use contiguous palette numbers starting at zero.


Texture Coordinates (Direct3D 9)

Most textures, like bitmaps, are a two-dimensional array of color values. Cubic environment map textures are an exception. For details, see Cubic Environment Mapping (Direct3D 9). The individual color values are called a texture element, or texel. Each texel has a unique address in the texture. The address can be thought of as a column and row number, which are labeled u and v respectively.

Texture coordinates are in texture space. That is, they are relative to the location (0,0) in the texture. When a texture is applied to a primitive in 3D space, its texel addresses must be mapped into object coordinates. They must then be translated into screen coordinates, or pixel locations.

Mapping Texels to Screen Space

Direct3D maps texels in texture space directly to pixels in screen space, skipping the intermediate step for greater efficiency. This mapping process is actually an inverse mapping. That is, for each pixel in screen space, the corresponding texel position in texture space is calculated. The texture color at or around that point is sampled. The sampling process is called texture filtering. For more information, see Texture Filtering (Direct3D 9).

Each texel in a texture can be specified by its texel coordinate. However, in order to map texels onto primitives, Direct3D requires a uniform address range for all texels in all textures. Therefore, it uses a generic addressing scheme in which all texel addresses are in the range of 0.0 to 1.0 inclusive. Direct3D applications specify texture coordinates in terms of u,v values, much like 2D Cartesian coordinates are specified in terms of x,y coordinates. Technically, the system can actually process texture coordinates outside the range of 0.0 and 1.0, and does so by using the parameters you set for texture addressing. For more information, see Texture Addressing Modes (Direct3D 9).

A result of this is that identical texture addresses can map to different texel coordinates in different textures. In the following illustration, the texture address being used is (0.5,1.0). However, because the textures are different sizes, the texture address maps to different texels. Texture 1, on the left, is 5x5. The texture address (0.5,1.0) maps to texel (2,4). Texture 2, on the right, is 7x7. The texture address (0.5,1.0) maps to texel (3,6).

A simplified version of the texel mapping process is shown in the following diagram. Admittedly, this example is extremely simple. For more detailed information, see Directly Mapping Texels to Pixels (Direct3D 9).

Pixel idealized into a square of color

For this example, a pixel, shown at the left of the illustration, is idealized into a square of color. The addresses of the four corners of the pixel are mapped into the 3D primitive in object space. The shape of the pixel is often distorted because of the shape of the primitive in 3D space and because of the viewing angle. The corners of the surface area on the primitive that correspond the corners of the pixel are then mapped into texture space. The mapping process distorts the pixel's shape again, which is common. The final color value of the pixel is computed from the texels in the region to which the pixel maps. You determine the method that Direct3D uses to arrive at the pixel color when you set the texture filtering method. For more information, see Texture Filtering (Direct3D 9).

Your application can assign texture coordinates directly to vertices. This capability gives you control over which portion of a texture is mapped into a primitive. For instance, suppose you create a rectangular primitive that is exactly the same size as the texture in the following illustration. In this example, you want your application to map the whole texture onto the whole wall. The texture coordinates your application assigns to the vertices of the primitive are (0.0,0.0), (1.0,0.0), (1.0,1.0), and (0.0,1.0).

If you decide to decrease the height of the wall by one-half, you can distort the texture to fit onto the smaller wall, or you can assign texture coordinates that cause Direct3D to use the lower half of the texture.

If you decide to distort or scale the texture to fit the smaller wall, the texture filtering method that you use will influence the quality of the image. For more information, see Texture Filtering (Direct3D 9).

If, instead, you decide to assign texture coordinates to make Direct3D use the lower half of the texture for the smaller wall, the texture coordinates your application assigns to the vertices of the primitive in this example are (0.0,0.5), (1.0,0.5), (1.0,1.0), and (0.0,1.0). Direct3D applies the lower half of the texture to the wall.

It is possible for texture coordinates of a vertex to be greater than 1.0. When you assign texture coordinates to a vertex that are not in the range of 0.0 to 1.0 inclusive, you should also set the texture addressing mode. For more information, see Texture Addressing Modes (Direct3D 9).

Texture Coordinates and Texture Stages

Texture coordinates are associated with textures by way of texture stages. Textures get assigned to texture stages with SetTexture(stageIndex, pTexture). See IDirect3DDevice9::SetTexture.

A FVF code can define up to eight sets of texture coordinates. The texture coordinate data is furnished by the user in the vertex data. The data is referred to with a zero based index: 0 - 7. There are up to eight texture blending stages. A texture is associated with a particular stage using SetTexture( stageIndex, pTexture).

Once this is done, any set of texture coordinates can be used by any stage. Each set of coordinates is associated with a stage using SetTextureStageState( stageIndex, D3DTSS_TEXCOORDINDEX, textureCoordinateIndex ). See IDirect3DDevice9::SetTextureStageState. This way, the blending stages can be set up to use any texture and any texture coordinates. More than one stage can use the same textures, or texture coordinates.

Additional information is contained in the following topics.

  • Texture Coordinate Formats (Direct3D 9)
  • Texture Coordinate Processing (Direct3D 9)


Directly Mapping Texels to Pixels (Direct3D 9)

When rendering 2D output using pre-transformed vertices, care must be taken to ensure that each texel area correctly corresponds to a single pixel area, otherwise texture distortion can occur. By understanding the basics of the process that Direct3D follows when rasterizing and texturing triangles, you can ensure your Direct3D application correctly renders 2D output.

Figure 1: 6 x 6 resolution display

Figure 1 shows a diagram wherein pixels are modeled as squares. In reality, however, pixels are dots, not squares. Each square in Figure 1 indicates the area lit by the pixel, but a pixel is always just a dot at the center of a square. This distinction, though seemingly small, is important. A better illustration of the same display is shown in Figure 2:

Figure 2: Display is composed of pixels

This diagram correctly shows each physical pixel as a point in the center of each cell. The screen space coordinate (0, 0) is located directly at the top-left pixel, and therefore at the center of the top-left cell. The top-left corner of the display is therefore at (-0.5, -0.5) because it is 0.5 cells to the left and 0.5 cells up from the top-left pixel. Direct3D will render a quad with corners at (0, 0) and (4, 4) as illustrated in Figure 3.

Figure 3: Outline of an unrasterized quad between (0, 0) and (4, 4)

Figure 3 shows where the mathematical quad is in relation to the display, but does not show what the quad will look like once Direct3D rasterizes it and sends it to the display. In fact, it is impossible for a raster display to fill the quad exactly as shown because the edges of the quad do not coincide with the boundaries between pixel cells. In other words, because each pixel can only display a single color, each pixel cell is filled with only a single color; if the display were to render the quad exactly as shown, the pixel cells along the quad's edge would need to show two distinct colors: blue where covered by the quad and white where only the background is visible.

Instead, the graphics hardware is tasked with determining which pixels should be filled to approximate the quad. This process is called rasterization, and is detailed in Rasterization Rules (Direct3D 9). For this particular case, the rasterized quad is shown in Figure 4:

Figure 4: Untextured quad drawn from (0,0) to (4,4)

Note that the quad passed to Direct3D (Figure 3) has corners at (0, 0) and (4, 4), but the rasterized output (Figure 4) has corners at (-0.5,-0.5) and (3.5,3.5). Compare Figures 3 and 4 for rendering differences. You can see that what the display actually renders is the correct size, but has been shifted by -0.5 cells in the x and y directions. However, except for multi-sampling techniques, this is the best possible approximation to the quad. (See the Antialias Sample for thorough coverage of multi-sampling.) Be aware that if the rasterizer filled every cell the quad crossed, the resulting area would be of dimension 5 x 5 instead of the desired 4 x 4.

If you assume that screen coordinates originate at the top-left corner of the display grid instead of the top-left pixel, the quad appears exactly as expected. However, the difference becomes clear when the quad is given a texture. Figure 5 shows the 4 x 4 texture you'll map directly onto the quad.

Figure 5: 4 x 4 texture

Because the texture is 4 x 4 texels and the quad is 4 x 4 pixels, you might expect the textured quad to appear exactly like the texture regardless of the location on the screen where the quad is drawn. However, this is not the case; even slight changes in position influence how the texture is displayed. Figure 6 illustrates how a quad between (0, 0) and (4, 4) is displayed after being rasterized and textured.

Figure 6: Textured quad drawn from (0, 0) and (4, 4)

The quad drawn in Figure 6 shows the textured output (with a linear filtering mode and a clamp addressing mode) with the superimposed rasterized outline. The rest of this article explains exactly why the output looks the way it does instead of looking like the texture, but for those who want the solution, here it is: The edges of the input quad need to lie upon the boundary lines between pixel cells. By simply shifting the x and y quad coordinates by -0.5 units, texel cells will perfectly cover pixel cells and the quad can be perfectly recreated on the screen. (Figure 8 illustrates the quad at the corrected coordinates.)

The details of why the rasterized output only bears slight resemblance to the input texture are directly related to the way Direct3D addresses and samples textures. What follows assumes you have a good understanding of texture coordinate space And bilinear texture filtering.

Getting back to our investigation of the strange pixel output, it makes sense to trace the output color back to the pixel shader: The pixel shader is called for each pixel selected to be part of the rasterized shape. The solid blue quad depicted in Figure 3 could have a particularly simple shader:

float4 SolidBluePS() : COLOR
{
    return float4( 0, 0, 1, 1 );
}

For the textured quad, the pixel shader has to be changed slightly:

texture MyTexture;

sampler MySampler =
sampler_state
{
    Texture = <MyTexture>;
    MinFilter = Linear;
    MagFilter = Linear;
    AddressU = Clamp;
    AddressV = Clamp;
};

float4 TextureLookupPS( float2 vTexCoord : TEXCOORD0 ) : COLOR
{
    return tex2D( MySampler, vTexCoord );
}

That code assumes the 4 x 4 texture of Figure 5 is stored in MyTexture. As shown, the MySampler texture sampler is set to perform bilinear filtering on MyTexture. The pixel shader gets called once for each rasterized pixel, and each time the returned color is the sampled texture color at vTexCoord. Each time the pixel shader is called, the vTexCoord argument is set to the texture coordinates at that pixel. That means the shader is asking the texture sampler for the filtered texture color at the exact location of the pixel, as detailed in Figure 7:

Figure 7: Texture coordinate sampling locations

The texture (shown superimposed) is sampled directly at pixel locations (shown as black dots). Texture coordinates are not affected by rasterization (they remain in the projected screen-space of the original quad). The black dots show where the rasterization pixels are. The texture coordinates at each pixel are easily determined by interpolating the coordinates stored at each vertex: The pixel at (0,0) coincides with the vertex at (0, 0); therefore, the texture coordinates at that pixel are simply the texture coordinates stored at that vertex, UV (0.0, 0.0). For the pixel at (3, 1), the interpolated coordinates are UV (0.75, 0.25) because that pixel is located at three-fourths of the texture's width and one-fourth of its height. These interpolated coordinates are what get passed to the pixel shader.

The texels do not line up with the pixels in this example; each pixel (and therefore each sampling point) is positioned at the corner of four texels. Because the filtering mode is set to Linear, the sampler will average the colors of the four texels sharing that corner. This explains why the pixel expected to be red is actually three-fourths gray plus one-fourth red, the pixel expected to be green is one-half gray plus one-fourth red plus one-fourth green, and so on.

To fix this problem, all you need to do is correctly map the quad to the pixels to which it will be rasterized, and thereby correctly map the texels to pixels. Figure 8 shows the results of drawing the same quad between (-0.5, -0.5) and (3.5, 3.5), which is the quad intended from the outset.

Figure 8: Textured quad matches the rasterized quad

Figure 8 demonstrates that the quad (shown outlined from (-0.5, -0.5) to (3.5, 3.5)) exactly matches the rasterized area.

Summary

In summary, pixels and texels are actually points, not solid blocks. Screen space originates at the top-left pixel, but texture coordinates originate at the top-left corner of the texture's grid. Most importantly, remember to subtract 0.5 units from the x and y components of your vertex positions when working in transformed screen space in order to correctly align texels with pixels.


Texture Coordinate Formats (Direct3D 9)

Texture coordinates in Direct3D can include one, two, three, or four floating point elements to address textures with varying levels of dimension. A 1D texture - a texture surface with dimensions of 1-by-n texels - is addressed by one texture coordinate. The most common case, 2D textures, are addressed with two texture coordinates commonly called u and v. Direct3D supports two types of 3D textures, cubic-environment maps and volume textures. Cubic environment maps aren't truly 3D, but they are addressed with a 3-element vector. For details, see Cubic Environment Mapping (Direct3D 9).

As described in Fixed Function FVF Codes (Direct3D 9), applications encode texture coordinates in the vertex format. The vertex format can include multiple sets of texture coordinates. Use the D3DFVF_TEX0 through D3DFVF_TEX8 D3DFVF to describe a vertex format that includes no texture coordinates, or as many as eight sets.

Each texture coordinate set can have between one and four elements. The D3DFVF_TEXTUREFORMAT1 through D3DFVF_TEXTUREFORMAT4 flags describe the number of elements in a texture coordinate in a set, but these flags aren't used by themselves. Rather, the D3DFVF_TEXCOORDSIZEN set of macros use these flags to create bit patterns that describe the number of elements used by a particular set of texture coordinates in the vertex format. These macros accept a single parameter that identifies the index of the coordinate set whose number of elements is being defined. The following example illustrates how these macros are used.

// This vertex format contains two sets of texture coordinates.
// The first set (index 0) has 2 elements, and the second set
// has 1 element. The description for this vertex format would be:
//     dwFVF = D3DFVF_XYZ  | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX2 |
//             D3DFVF_TEXCOORDSIZE2(0) | D3DFVF_TEXCOORDSIZE1(1);
//
typedef struct CVF
{
    D3DVECTOR position;
    D3DVECTOR normal;
    D3DCOLOR  diffuse;
    float     u, v;   // 1st set, 2D
    float     t;      // 2nd set, 1D
} CustomVertexFormat;

Note With the exception of cubic-environment maps and volume textures, rasterizers cannot address textures by using any more than two elements. Applications can supply up to three elements for a texture coordinate, but only if the texture is a cube map, a volume texture, or the D3DTTFF_PROJECTED texture transform flag is used. The D3DTTFF_PROJECTED flag causes the rasterizer to divide the first two elements by the third (or n) element. For more information, see Texture Coordinate Transformations (Direct3D 9).


Texture Coordinate Processing (Direct3D 9)

The following figure shows the path taken by the texture coordinates from their source, through processing, and to the rasterizer.

Texture coordinate path

There are two sources from which the system can draw texture coordinates. For a given texture stage, you can use texture coordinates included in the vertex format (D3DFVF_TEX1 through D3DFVF_TEX8), or you can use texture coordinates automatically generated by Direct3D. For details about the latter case, see Automatically Generated Texture Coordinates (Direct3D 9). If the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state for the current texture stage is set to D3DTTFF_DISABLE (the default setting), input coordinates are not transformed. If D3DTSS_TEXTURETRANSFORMFLAGS> is set to any other value, the transformation matrix for that stage is applied to the input coordinates.

The D3DTEXTURETRANSFORMFLAGS enumerated type defines valid values for the D3DTSS_TEXTURETRANSFORMFLAGS texture-stage state. With the exception of the D3DTTFF_DISABLE flag, which bypasses texture coordinate transformation, the values defined in this enumeration configure the number of output coordinates that the system passes to the rasterizer. The D3DTTFF_COUNT1 through D3DTTFF_COUNT4 flags instruct the system to pass one, two, three, or four elements from the output coordinates to the rasterizer.

The D3DTTFF_PROJECTED flag is special: it tells the system that the texture coordinates are for a projected texture. Combine the D3DTTFF_PROJECTED flag with another member of D3DTEXTURETRANSFORMFLAGS to instruct the rasterizer to divide all the elements by the last element before rasterization takes place. For example, when explicitly using three-element texture coordinates, or when transformation results in a three-element texture coordinate, you can combine the D3DTTFF_COUNT3 and D3DTTFF_PROJECTED flags to cause the rasterizer to divide the first two elements by the last, producing 2D texture coordinates required to address a 2D texture.

Note With the exception of cubic-environment maps and volume textures, rasterizers cannot address textures by using texture coordinates with more than two elements. If you specify more elements than can be used to address the current texture for that stage, the extraneous elements are ignored. This also applies when using 2D texture coordinates for a 1D texture.

Additional information is contained in the following topics.

  • Automatically Generated Texture Coordinates (Direct3D 9)
  • Texture Coordinate Transformations (Direct3D 9)
  • Special Effects (Direct3D 9)


Automatically Generated Texture Coordinates (Direct3D 9)

The system can use the transformed camera-space position or the normal from a vertex as texture coordinates, or it can compute the three element vectors used to address a cubic environment map. Like texture coordinates that you explicitly specify in a vertex, you can use automatically generated texture coordinates as input for texture coordinate transformations.

Automatically generated texture coordinates can significantly reduce the bandwidth required for geometry data by eliminating the need for explicit texture coordinates in the vertex format. In many cases, the texture coordinates that the system generates can be used with transformations to produce special effects. Of course, this is a special-purpose feature, and you will use explicit texture coordinates for many occasions.

Configuring Automatically Generated Texture Coordinates

In C++, the D3DTSS_TEXCOORDINDEX texture-stage state (from the D3DTEXTURESTAGESTATETYPE enumerated type) controls how the system generates texture coordinates.

Normally, this state instructs the system to use a particular set of texture coordinates encoded in the vertex format. When you include the D3DTSS_TCI_CAMERASPACENORMAL, D3DTSS_TCI_CAMERASPACEPOSITION, or D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flags in the value that you assign to this state, the system behavior is quite different. If any of these flags are present, the texture stage ignores the texture coordinates within the vertex format in favor of coordinates that the system generates. The meanings for each flag are shown in the following list.

  • D3DTSS_TCI_CAMERASPACENORMAL

    Use the vertex normal, transformed to camera space, as input texture coordinates.

  • D3DTSS_TCI_CAMERASPACEPOSITION

    Use the vertex position, transformed to camera space, as input texture coordinates.

  • D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR

    Use the reflection vector, transformed to camera space, as input texture coordinates. The reflection vector is computed from the input vertex position and normal vector.

The texture coordinate index flags are mutually exclusive. This example uses:

  • The vertex position (in camera-space) as the input texture coordinates for this texture stage
  • The wrap mode set in the D3DRENDERSTATE_WRAP1 render state
// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface
d3dDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX,
                                   D3DTSS_TCI_CAMERASPACEPOSITION | 1);

Automatically generated texture coordinates are most useful as input values for a texture coordinate transformation, or to eliminate the need for your application to compute three-element vectors for cubic-environment maps.

Sphere-mapping uses a precomputed (at model time) texture map that contains the entire environment as reflected by a chrome sphere. Direct3D has a texture-coordinate generation feature using render state D3DTSS_TCI_CAMERASPACENORMAL, which takes the normal of the vertex in camera space and puts it through a texture transform to generate texture coordinates.

See Also

Texture Coordinate Transformations (Direct3D 9), Cubic Environment Mapping (Direct3D 9)


Texture Coordinate Transformations (Direct3D 9)

Direct3D devices can transform the texture coordinates for vertices by applying a 4x4 matrix. The system applies transformations to texture coordinates in the same manner as geometry. Any transformation (scale, rotation, translation, projection, shear, or any combination of these) can be done with a 4x4 matrix.

Note Direct3D does not modify transformed and lit vertices. As a result, an application using transformed and lit vertices cannot use Direct3D to transform the texture coordinates of the vertices.

Devices that support hardware-accelerated transformation and lighting operations (T&L HAL Device) also accelerate the transformation of texture coordinates. When hardware acceleration of transformations isn't available, platform-specific optimizations in the Direct3D geometry pipeline apply to texture coordinate transformations.

Texture coordinate transformations are useful for producing special effects while avoiding the need to directly modify the texture coordinates of your geometry. You could use simple translation or rotation matrices to animate textures on an object, or you can transform texture coordinates that are automatically generated by Direct3D to simplify and perhaps accelerate advanced effects such as projected textures and dynamic light-mapping. Additionally, you might use texture coordinate transforms to reuse a single set of texture coordinates for multiple purposes, in multiple texture stages.

Setting and Retrieving Texture Coordinate Transformations

Like the matrices that your application uses for geometry, you set and retrieve texture coordinate transformations by calling the IDirect3DDevice9::SetTransform and IDirect3DDevice9::GetTransform methods. These methods accept the D3DTS_TEXTURE0 through D3DTS_TEXTURE7 members of the D3DTRANSFORMSTATETYPE enumerated type to identify the transformation matrices for texture stages 0 through 7, respectively.

The following code sets a matrix to apply to the texture coordinates for texture stage 0.

// For this example, assume the d3dDevice variable contains a
//   valid pointer to an IDirect3DDevice9 interface.

D3DMATRIX matTrans = D3DXMatrixIdentity( NULL );

// Set up the matrix for the desired transformation.
d3dDevice->SetTransform( D3DTS_TEXTURE0, &matTrans );

Enabling Texture Coordinate Transformations

The D3DTSS_TEXTURETRANSFORMFLAGS texture stage state controls the application of texture coordinate transformations. Values for this texture stage state are defined by the D3DTEXTURETRANSFORMFLAGS enumerated type.

Texture coordinate transformations are disabled when D3DTSS_TEXTURETRANSFORMFLAGS is set to D3DTTFF_DISABLE (the default value). Assuming that texture coordinate transformations were enabled for stage 0, the following code disables them.

// For this example, assume the d3dDevice variable contains a
// valid pointer to an IDirect3DDevice9 interface.

d3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                 D3DTTFF_DISABLE );

The other values defined in D3DTEXTURETRANSFORMFLAGS are used to enable texture coordinate transformations, and to control how many resulting texture coordinate elements are passed to the rasterizer. For example, take the following code.

// For this example, assume the d3dDevice variable contains a
//   valid pointer to an IDirect3DDevice9 interface.

d3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                 D3DTTFF_COUNT2 );

The D3DTTFF_COUNT2 value instructs the system to apply the transformation matrix set for texture stage 0, and then pass the first two elements of the modified texture coordinates to the rasterizer.

The D3DTTFF_PROJECTED texture transformation flag indicates coordinates for a projected texture. When this flag is specified, the rasterizer divides the elements passed-in by the last element. Take the following code, for example.

// For this example, assume the d3dDevice variable contains a
//   valid pointer to an IDirect3DDevice9 interface.

d3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                 D3DTTFF_COUNT3 | D3DTTFF_PROJECTED );

This example informs the system to pass three texture coordinate elements to the rasterizer. The rasterizer divides the first two elements by the third, producing the 2D texture coordinates needed to address the texture.


Special Effects (Direct3D 9)

This topic contains examples of special effects accomplished with texture coordinate processing.

  • Animating textures (by translation or rotation) on a model
  • Creating texture coordinates as a linear function of a model's camera-space position
  • Performing environment mapping with a cubic environment map
  • Performing projective texturing

Animating textures (by translation or rotation) on a model

  • Define 2D texture coordinates in your vertex format.
    // Use a single texture, with 2D texture coordinates. This
// bit-pattern should be expanded to include position, normal,
// and color information as needed.
DWORD dwFVFTex = D3FVF_TEX1 | D3DFVF_TEXCOORDSIZE2(0);
  • Configure the rasterizer to use 2D texture coordinates.
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
  • Define and set an appropriate texture coordinate transformation matrix.
    // M is a D3DMATRIX being set to translate texture
// coordinates in the U and V directions.
//      1   0  0  0
//      0   1  0  0
//      du dv  1  0 (du and dv change each frame)
//      0   0  0  1

D3DMATRIX M = D3DXMatrixIdentity(); // declared in d3dutil.h
M._31 = du;
M._32 = dv;

Creating texture coordinates as a linear function of a model's camera-space position

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position, in camera space, as input to a texture transformation.
    // The input vertices have no texture coordinates, saving
// bandwidth. Three texture coordinates are generated by
// using vertex position in camera space (x, y, z).
SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
  • Instruct the rasterizer to expect 2D texture coordinates.
    // Two output coordinates are used.
SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
  • Define and set a matrix that applies a linear function.
    // Generate texture coordinates as linear functions
// so that:
//      u = Ux*x + Uy*y + Uz*z + Uw
//      v = Vx*x + Vy*y + Vz*z + Vw
// The matrix M for this case is:
//      Ux  Vx  0  0
//      Uy  Vy  0  0
//      Uz  Vz  0  0
//      Uw  Vw  0  0

SetTransform(D3DTS_TEXTURE0, &M);

Performing environment mapping with a cubic environment map

  • Use the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flag to instruct the system to automatically generate texture coordinates as reflection vectors for cubic mapping.
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR);
  • Instruct the rasterizer to expect texture coordinates with three elements.
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT3);

Performing projective texturing

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position as input to a texture transformation matrix.
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
  • Create and apply the texture projection matrix. This is beyond the scope of this documentation, and is the topic of several industry articles.
  • Instruct the rasterizer to expect three-element projected texture coordinates.
    // Two output coordinates are used.

SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTF_PROJECTED | D3DTTFF_COUNT3);


Texture Filtering (Direct3D 9)

When Direct3D renders a primitive, it maps the 3D primitive onto a 2D screen. If the primitive has a texture, Direct3D must use that texture to produce a color for each pixel in the primitive's 2D rendered image. For every pixel in the primitive's on-screen image, it must obtain a color value from the texture. This process is called texture filtering.

When a texture filter operation is performed, the texture being used is typically also being magnified or minified. In other words, it is being mapped into a primitive image that is larger or smaller than itself. Magnification of a texture can result in many pixels being mapped to one texel. The result can be a chunky appearance. Minification of a texture often means that a single pixel is mapped to many texels. The resulting image can be blurry or aliased. To resolve these problems, some blending of the texel colors must be performed to arrive at a color for the pixel.

Direct3D simplifies the complex process of texture filtering. It provides you with three types of texture filtering - linear filtering, anisotropic filtering, and mipmap filtering. If you select no texture filtering, Direct3D uses a technique called nearest-point sampling.

Each type of texture filtering has advantages and disadvantages. For instance, linear texture filtering can produce jagged edges or a chunky appearance in the final image. However, it is a computationally low-overhead method of texture filtering. Filtering with mipmaps usually produces the best results, especially when combined with anisotropic filtering. However, it requires the most memory of the techniques that Direct3D supports.

Applications that use texture interface pointers should set the current texture filtering method by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass a member of the D3DTEXTUREFILTERTYPE enumerated type as the value in the third parameter.

This section presents the texture filtering methods that Direct3D supports. It is organized into the following topics.

  • Nearest-Point Sampling (Direct3D 9)
  • Linear Texture Filtering (Direct3D 9)
  • Bilinear Texture Filtering (Direct3D 9)
  • Anisotropic Texture Filtering (Direct3D 9)
  • Texture Filtering with Mipmaps (Direct3D 9)

Note Although the texture-filtering render states present in the D3DRENDERSTATETYPE enumerated type are superseded by texture stage states, the IDirect3DDevice9::SetRenderState, as opposed to the IDirect3DDevice2 version, does not fail if you attempt to use them. Rather, the system maps the effects of these render states to the first stage in the multitexture cascade, stage 0. Applications should not mix the legacy render states with their corresponding texture stage states, as unpredictable results can occur.


Nearest-Point Sampling (Direct3D 9)

Applications are not required to use texture filtering. Direct3D can be set so that it computes the texel address, which often does not evaluate to integers, and copies the color of the texel with the closest integer address. This process is called nearest-point sampling. This can be a fast and efficient way to process textures if the size of the texture is similar to the size of the primitive's image on the screen. If not, the texture must be magnified or minified. The result can be a chunky, aliased, or blurred image.

Your C++ application can select nearest-point sampling by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass D3DTEXF_POINT in the third parameter.

You should use nearest-point sampling carefully, because it can sometimes cause graphic artifacts when the texture is sampled at the boundary between two texels. This boundary is the position along the texture (u or v) at which the sampled texel transitions from one texel to the next. When point sampling is used, the system chooses one sample texel or the other, and the result can change abruptly from one texel to the next texel as the boundary is crossed. This effect can appear as undesired graphic artifacts in the displayed texture. When linear filtering is used, the resulting texel is computed from both adjacent texels and smoothly blends between them as the texture index moves through the boundary.

This effect can be seen when mapping a very small texture onto a very large polygon: an operation often called magnification. For example, when using a texture that looks like a checkerboard, nearest-point sampling results in a larger checkerboard that shows distinct edges. By contrast, linear texture filtering results in an image where the checkerboard colors vary smoothly across the polygon.

In most cases, applications receive the best results by avoiding nearest-point sample wherever possible. The majority of hardware today is optimized for linear filtering, so your application should not suffer degraded performance. If the effect you desire absolutely requires the use of the nearest-point sampling - such as when using textures to display readable text characters - then your application should be extremely careful to avoid sampling at the texel boundaries, which might result in undesired effects. The following image shows what these artifacts can look like.

Six-sectioned box with noncontinuous red horizontal lines in the two upper-right squares

Notice that the two squares in the upper right of the group appear different than their neighbors, with diagonal offsets running through them. To avoid graphic artifacts like these, you must be familiar with Direct3D texture sampling rules for nearest-point filtering. Direct3D maps a floating-point texture coordinate ranging from [0.0, 1.0] (0.0 to 1.0, inclusive) to an integer texel space value ranging from [ - 0.5, n - 0.5], where n is the number of texels in a given dimension on the texture. The resulting texture index is rounded to the nearest integer. This mapping can introduce sampling inaccuracies at texel boundaries.

For a simple example, imagine an application that renders polygons with the D3DTADDRESS_WRAP texture addressing mode. Using the mapping employed by Direct3D, the u texture index maps as follows for a texture with a width of 4 texels.

Texture coordinates 0.0 and 1.0 at the boundary between texels

Notice that the texture coordinates, 0.0 and 1.0 for this illustration, are exactly at the boundary between texels. Using the method by which Direct3D maps values, the texture coordinates range from [ - 0.5, 4 - 0.5], where 4 is the width of the texture. For this case, the sampled texel is the 0 texel for a texture index of 1.0. However, if the texture coordinate was only slightly less than 1.0, the sampled texel would be the n texel instead of the 0 texel.

The implication of this is that magnifying a small texture using texture coordinates of exactly 0.0 and 1.0 with nearest-point filtering on a screen-space aligned triangle results in pixels for which the texture map is sampled at the boundary between texels. Any inaccuracies in the computation of texture coordinates, however small, results in artifacts along the areas in the rendered image which correspond to the texel edges of the texture map.

Performing this mapping of floating point texture coordinates to integer texels with perfect accuracy is difficult, computationally time-consuming, and generally not necessary. Most hardware implementations use an iterative approach for computing texture coordinates at each pixel location within a triangle. Iterative approaches tend to hide these inaccuracies because the errors are accumulated evenly during iteration.

The Direct3D reference rasterizer uses a direct-evaluation approach for computing texture indexes at each pixel location. Direct evaluation differs from the iterative approach in that any inaccuracy in the operation exhibits a more random error distribution. The result of this is that the sampling errors that occur at the boundaries can be more noticeable because the reference rasterizer does not perform this operation with perfect accuracy.

The best approach is to use nearest-point filtering only when necessary. When you must use it, it is recommended that you offset texture coordinates slightly from the boundary positions to avoid artifacts.


Linear Texture Filtering (Direct3D 9)

Direct3D uses a form of linear texture filtering called bilinear filtering. Like Nearest-Point Sampling (Direct3D 9), bilinear texture filtering first computes a texel address, which is usually not an integer address. Bilinear filtering then finds the texel whose integer address is closest to the computed address. In addition, the Direct3D rendering module computes a weighted average of the texels that are immediately above, below, to the left of, and to the right of the nearest sample point.

Select bilinear texture filtering by invoking the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass D3DTEXF_LINEAR in the third parameter.


Bilinear Texture Filtering (Direct3D 9)

Textures are always linearly addressed from (0.0, 0.0) at the top-left corner to (1.0, 1.0) at the bottom-right corner as shown in Figure 7a:

Textures are usually represented as if they were composed of solid blocks of color, but it's actually more correct to think of textures the same way you should think of the raster display: Each texel is defined at the exact center of a grid cell, as shown in Figure 7b:

If you ask the texture sampler for this texture's color at UV coordinates (0.375, 0.375) you'll get solid red (255, 0, 0). That makes perfect sense because the exact center of the red texel cell is at UV (0.375, 0.375). What if you ask the sampler for the texture's color at UV (0.25, 0.25)? That's not quite as easy, because the point at UV (0.25, 0.25) lies at the exact corner of 4 texels.

The simplest scheme is simply to have the sampler return the color of the closest texel; this is called Point filtering (see Nearest-Point Sampling (Direct3D 9)), and is usually undesirable due to grainy or blocky results. Point-sampling our texture at UV (0.25, 0.25) shows another subtle problem with nearest-point filtering: there are four texels equidistant from the sampling point, so there's no single nearest texel. One of those four texels will be chosen as the returned color, but the selection depends on how the coordinate is rounded, which may introduce tearing artifacts (see the Nearest-Point Sampling article in the SDK).

A slightly more accurate and more common filtering scheme is to calculate the weighted average of the 4 texels closest to the sampling point; this is called Bilinear filtering, and the extra computational cost is usually negligible because this routine is implemented in modern graphics hardware. Here are the colors we get at a few different sample points using bilinear filtering:

UV: (0.5, 0.5)

This point is at the exact border between red, green, blue, and white texels. The color the sampler returns is gray:

  0.25 * (255, 0, 0)
  0.25 * (0, 255, 0)
  0.25 * (0, 0, 255)
+ 0.25 * (255, 255, 255)
------------------------
= (128, 128, 128)

UV: (0.5, 0.375)

This point is at the midpoint of the border between red and green texels. The color the sampler returns is yellow-gray (note that the contributions of the blue and white texels are scaled to 0):

  0.5 * (255, 0, 0)
  0.5 * (0, 255, 0)
  0.0 * (0, 0, 255)
+ 0.0 * (255, 255, 255)
------------------------
= (128, 128, 0)

UV: (0.375, 0.375)

This is the address of the red texel, which is the returned color (all other texels in the filtering calculation are weighted to 0):

  1.0 * (255, 0, 0)
  0.0 * (0, 255, 0)
  0.0 * (0, 0, 255)
+ 0.0 * (255, 255, 255)
------------------------
= (255, 0, 0)

Compare these calculations against Figure 7c, which shows what we'll get if we perform the bilinear filtering calculation at every texture address across the 4x4 texture:


Anisotropic Texture Filtering (Direct3D 9)

The distortion visible in the texels of a 3D object whose surface is oriented at an angle with respect to the plane of the screen is called anisotropy. When a pixel from an anisotropic primitive is mapped to texels, its shape is distorted. Direct3D measures the anisotropy of a pixel as the elongation - that is, length divided by width - of a screen pixel that is inverse-mapped into texture space.

You can use anisotropic texture filtering in conjunction with linear texture filtering or mipmap texture filtering to improve rendering results. Your application enables anisotropic texture filtering by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Set the third parameter to D3DTEXF_ANISOTROPIC.

Your application must also set the degree of anisotropy to a value greater than one. Do this by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are setting the degree of isotropy. Pass D3DSAMP_MAXANISOTROPY as the value of the second parameter. The final parameter should be the degree of isotropy.

You can disable isotropic filtering by setting the degree of isotropy to one; any value larger than one enables it. Check the MaxAnisotropy flag in the D3DCAPS9 structure to determine the possible range of values for the degree of anisotropy.


Texture Filtering with Mipmaps (Direct3D 9)

A mipmap is a sequence of textures, each of which is a progressively lower resolution representation of the same image. The height and width of each image, or level, in the mipmap is a power of two smaller than the previous level. Mipmaps do not have to be square.

A high-resolution mipmap image is used for objects that are close to the user. Lower-resolution images are used as the object appears farther away. Mipmapping improves the quality of rendered textures at the expense of using more memory.

Direct3D represents mipmaps as a chain of attached surfaces. The highest resolution texture is at the head of the chain and has the next level of the mipmap as an attachment. In turn, that level has an attachment that is the next level in the mipmap, and so on, down to the lowest resolution level of the mipmap.

The following illustrations shows an example of these levels. The bitmap textures represent a sign on a container in a 3D first-person game. When created as a mipmap, the highest resolution texture is first in the set. Each succeeding texture in the mipmap set is smaller in height and width by a power of 2. In this case, the maximum-resolution mipmap is 256 pixels by 256 pixels. The next, texture is 128x128. The last texture in the chain is 64x64.

This sign has a maximum distance from which it is visible. If the user begins far away from the sign, the game displays the smallest texture in the mipmap chain, which in this case the 64x64 texture.

As the user moves the point of view closer to the sign, progressively higher-resolution textures in the mipmap chain are used. The resolution in the following illustration is 128x128.

The highest resolution texture is used when the user's point of view is at the minimum allowable distance from the sign.

This is a more efficient way of simulating perspective for textures. Rather than render a single texture at many resolutions, it is faster to use multiple textures at varying resolutions.

Direct3D can assess which texture in a mipmap set is the closest resolution to the desired output, and it can map pixels into its texel space. If the resolution of the final image is between the resolutions of the textures in the mipmap set, Direct3D can examine texels in both mipmaps and blend their color values together.

To use mipmaps, your application must build a set of mipmaps. Applications apply mipmaps by selecting the mipmap set as the first texture in the set of current textures. For more information, see Texture Blending (Direct3D 9).

Next, your application must set the filtering method that Direct3D uses to sample texels. The fastest method of mipmap filtering is to have Direct3D select the nearest texel. Use the D3DTEXF_POINT enumerated value to select this. Direct3D can produce better filtering results if your application uses the D3DTEXF_LINEAR enumerated value. This selects the nearest mipmap, and then computes a weighted average of the texels surrounding the location in the texture to which the current pixel maps.

Mipmap textures are used in 3D scenes to decrease the time required to render a scene. They also improve the scene's realism. However, they often require large amounts of memory.

Creating a Set of Mipmaps

The following example shows how your application can call the IDirect3DDevice9::CreateTexture method to build a chain of five mipmap levels: 256x256, 128x128, 64x64, 32x32, and 16x16.

// This code example assumes that m_d3dDevice is a
// valid pointer to a IDirect3DDevice9 interface

IDirect3DTexture9 * pMipMap;
m_pD3DDevice->CreateTexture(256, 256, 5, 0, D3DFMT_R8G8B8,
    D3DPOOL_MANAGED, &pMipMap);

The first two parameters that are accepted by IDirect3DDevice9::CreateTexture are the size and width of the top-level texture. The third parameter specifies the number of levels in the texture. If you set this to zero, Direct3D creates a chain of surfaces, each a power of two smaller than the previous one, down to the smallest possible size of 1x1. The fourth parameter specifies the usage for this resource; in this case, 0 is specified to indicate no specific usage for the resource. The fifth parameter specifies the surface format for the texture. Use a value from the D3DFORMAT enumerated type for this parameter. The sixth parameter specifies a member of the D3DPOOL enumerated type indicating the memory class into which to place the created resource. Unless you are using dynamic textures, D3DPOOL_MANAGED is recommended. The final parameter takes the address of a pointer to an IDirect3DTexture9 interface.

Note Each surface in a mipmap chain has dimensions that are one-half that of the previous surface in the chain. If the top-level mipmap has dimensions of 256x128, the dimensions of the second-level mipmap are 128x64, the third-level are 64x32, and so on, down to 1x1. You cannot request a number of mipmap levels in Levels that would cause either the width or height of any mipmap in the chain to be smaller than 1. In the simple case of a 4x2 top-level mipmap surface, the maximum value allowed for Levels is three. The top-level dimensions are 4x2, the second-level dimensions are 2x1, and the dimensions for the third level are 1x1. A value larger than 3 in Levels results in a fractional value in the height of the second-level mipmap, and is therefore disallowed.

Selecting and Displaying a Mipmap

Call the IDirect3DDevice9::SetTexture method to set the mipmap texture set as the first texture in the list of current textures. For more information, see Texture Blending (Direct3D 9).

After your application selects the mipmap texture set, it must assign values from the D3DTEXTUREFILTERTYPE enumerated type to the D3DSAMP_MIPFILTER sampler state. Direct3D then automatically performs mipmap texture filtering. Enabling mipmap texture filtering is demonstrated in the following code example.

m_pD3DDevice->SetTexture(0, pMipMap);
m_pD3DDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);

Your application can also manually traverse a chain of mipmap surfaces by using the IDirect3DTexture9::GetSurfaceLevel method and specifying the mipmap level to retrieve. The following example traverses a mipmap chain from highest to lowest resolutions.

IDirect3DSurface9 * pSurfaceLevel;
for (int iLevel = 0; iLevel < pMipMap->GetLevelCount(); iLevel++)
{
    pMipMap->GetSurfaceLevel(iLevel, &pSurfaceLevel);
    // Process this level
    pSurfaceLevel->Release();
}

Applications need to manually traverse a mipmap chain to load bitmap data into each surface in the chain. This is typically the only reason to traverse the chain. An application can retrieve the number of levels in a mipmap by calling IDirect3DBaseTexture9::GetLevelCount.


Texture Resources (Direct3D 9)

Texture resources are implemented in the IDirect3DTexture9 interface. To obtain a pointer to a texture interface, call the IDirect3DDevice9::CreateTexture method or any of the following D3DX functions.

  • D3DXCreateTexture
  • D3DXCreateTextureFromFile
  • D3DXCreateTextureFromFileEx
  • D3DXCreateTextureFromFileInMemory
  • D3DXCreateTextureFromFileInMemoryEx
  • D3DXCreateTextureFromResource
  • D3DXCreateTextureFromResourceEx

The following code example uses D3DXCreateTextureFromFile to load a texture from Tiger.bmp.

// The following code example assumes that D3dDevice
// is a valid pointer to an IDirect3DDevice9 interface.

LPDIRECT3DTEXTURE9 pTexture;

D3DXCreateTextureFromFile( d3dDevice, "tiger.bmp", &pTexture);

The first parameter that D3DXCreateTextureFromFile accepts is a pointer to an IDirect3DDevice9 interface. The second parameter tells Direct3D the name of the file from which to load the texture. The third parameter takes the address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Rendering with Texture Resources

Direct3D supports multiple texture blending through the concept of texture stages. Each texture stage contains a texture and operations that can be performed on the texture. The textures in the texture stages form the set of current textures. For more information, see Texture Blending (Direct3D 9). The state of each texture is encapsulated in its texture stage.

In a C++ application, the state of each texture must be set with the IDirect3DDevice9::SetTextureStageState method. Pass the stage number (0-7) as the value of the first parameter. Set the value of the second parameter to a member of the D3DTEXTURESTAGESTATETYPE enumerated type. The final parameter is the state value for the particular texture state.

Using texture interface pointers, your application can render a blend of up to eight textures. Set the current textures by invoking the IDirect3DDevice9::SetTexture method. Direct3D blends all current textures onto the primitives that it renders.

Note The IDirect3DDevice9::SetTexture method increments the reference count of the texture surface being assigned. When the texture is no longer needed, you should set the texture at the appropriate stage to NULL. If you fail to do this, the surface will not be released, resulting in a memory leak.

Your application can set the texture wrapping state for the current textures by calling the IDirect3DDevice9::SetRenderState method. Pass a value from D3DRS_WRAP0 through D3DRS_WRAP7 as the value of the first parameter, and use a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags to enable wrapping in the u, v, or w directions.

Your application can also set the texture perspective and texture filtering states. See Texture Filtering (Direct3D 9).


Texture Wrapping (Direct3D 9)

In short, texture wrapping changes the basic way that Direct3D rasterizes textured polygons using the texture coordinates specified for each vertex. While rasterizing a polygon, the system interpolates between the texture coordinates at each of the polygon's vertices to determine the texels that should be used for every pixel of the polygon. Normally, the system treats the texture as a 2D plane, interpolating new texels by taking the shortest route from point A within a texture to point B. If point A represents the u, v position (0.8, 0.1), and point B is at (0.1,0.1), the line of interpolation looks like the following illustration.

Line of interpolation

Note that the shortest distance between A and B in this illustration runs roughly through the middle of the texture. Enabling u-texture or v-texture coordinate wrapping changes how Direct3D perceives the shortest route between texture coordinates in the u-direction and v-direction. By definition, texture wrapping causes the rasterizer to take the shortest route between texture coordinate sets, assuming that 0.0 and 1.0 are coincident. The last bit is the tricky part: You can imagine that enabling texture wrapping in one direction causes the system to treat a texture as though it were wrapped around a cylinder. For example, consider the following illustration.

This diagram shows how wrapping in the u - direction affects how the system interpolates texture coordinates. Using the same points as in the example for normal, or nonwrapped, textures, you can see that the shortest route between points A and B is no longer across the middle of the texture; it's now across the border where 0.0 and 1.0 exist together. Wrapping in the v-direction is similar, except that it wraps the texture around a cylinder that is lying on its side. Wrapping in both the u-direction and v-direction is more complex. In this situation, you can envision the texture as a torus, or doughnut.

The most common practical application for texture wrapping is to perform environment mapping. Usually, an object textured with an environment map appears very reflective, showing a mirrored image of the object's surroundings in the scene. For the sake of this discussion, picture a room with four walls, each one painted with a letter R, G, B, Y and the corresponding colors: red, green, blue, and yellow. The environment map for such a simple room might look like the following illustration.

Vertical stripes of red, green, blue, and yellow

Imagine that the room's ceiling is held up by a perfectly reflective, four-sided, pillar. Mapping the environment map texture to the pillar is simple; making the pillar look as though it is reflecting the letters and colors is not as easy. The following diagram shows a wire frame of the pillar with the applicable texture coordinates listed near the top vertices. The seam where wrapping will cross the edges of the texture is shown with a dotted line.

Rectangle with bisecting dotted line

With wrapping enabled in the u-direction, the textured pillar shows the colors and symbols from the environment map appropriately and, at the seam in the front of the texture, the rasterizer properly chooses the shortest route between the texture coordinates, assuming that u-coordinates 0.0 and 1.0 share the same location. The textured pillar looks like the following illustration.

Rectangle made up of red, green, blue, and yellow quadrants

If texture wrapping isn't enabled, the rasterizer does not interpolate in the direction needed to generate a believable, reflected image. Rather, the area at the front of the pillar contains a horizontally compressed version of the texels between u-coordinates 0.175 and 0.875, as they pass through the center of the texture. The wrap effect is ruined.

Using Texture Wrapping

To enable texture wrapping, call the IDirect3DDevice9::SetRenderState method as shown in the code example below.

d3dDevice->SetRenderState(D3DRS_WRAP0, D3DWRAPCOORD_0);

The first parameter accepted by IDirect3DDevice9::SetRenderState is a render state to set. Specify one of the D3DRS_WRAP0 through D3DRS_WRAP7 enumerated values which specify which texture level to set the wrapping for. Specify the D3DWRAPCOORD_0 through D3DWRAPCOORD_3 flags in the second parameter to enable texture wrapping in the corresponding direction, or combine them to enable wrapping in multiple directions. If you omit a flag, texture wrapping in the corresponding direction is disabled. To disable texture wrapping for a set of texture coordinates, set the value for the corresponding render state to 0.

Do not confuse texture wrapping with the similarly named texture addressing modes. Texture wrapping is performed before texture addressing. Be sure the texture wrapping data does not contain any texture coordinates outside of the range of [0.0, 1.0] because this will produce undefined results. For more information about texture addressing, see Texture Addressing Modes (Direct3D 9).

Displacement Map Wrapping

Displacement maps are interpolated by the tesselation engine. Because the wrap mode cannot be specified for the tessellation engine, texture wrapping cannot be performed with displacement maps. An application is able to use a set of vertices that forces the interpolation to wrap in any direction. The application can also specify the interpolation to be done as a simple linear interpolation.


Texture Blending (Direct3D 9)

Direct3D can blend as many as eight textures onto primitives in a single pass. The use of multiple texture blending can profoundly increase the frame rate of a Direct3D application. An application employs multiple texture blending to apply textures, shadows, specular lighting, diffuse lighting, and other special effects in a single pass.

To use texture blending, your application should first check if the user's hardware supports it. This information is found in the TextureCaps member of the D3DCAPS9 structure. For details on how to query the user's hardware for texture blending capabilities, see IDirect3DDevice9::GetDeviceCaps.

Texture Stages and the Texture Blending Cascade

Direct3D supports single-pass multiple texture blending through the use of texture stages. A texture stage takes two arguments and performs a blending operation on them, passing on the result for further processing or for rasterization. You can visualize a texture stage as shown in the following illustration.

As the preceding illustration shows, texture stages blend two arguments by using a specified operator. Common operations include simple modulation or addition of the color or alpha components of the arguments, but more than two dozen operations are supported. The arguments for a stage can be an associated texture, the iterated color or alpha (iterated during Gouraud shading), arbitrary color and alpha, or the result from the previous texture stage. For more information, see Texture Blending Operations and Arguments (Direct3D 9).

Note Direct3D distinguishes color blending from alpha blending. Applications set blending operations and arguments for color and alpha individually, and the results of those settings are independent of one another.

The combination of arguments and operations used by multiple blending stages define a simple flow-based blending language. The results from one stage flow down to another stage, from that stage to the next, and so on. The concept of results flowing from stage to stage to eventually be rasterized on a polygon is often called the texture blending cascade. The following illustration shows how individual texture stages make up the texture blending cascade.

Texture blending cascade

Each stage in a device has a zero-based index. Direct3D allows up to eight blending stages, although you should always check device capabilities to determine how many stages the current hardware supports. The first blending stage is at index 0, the second is at 1, and so on, up to index 7. The system blends stages in increasing index order.

Use only the number of stages you need; the unused blending stages are disabled by default. So, if your application only uses the first two stages, it need only set operations and arguments for stage 0 and 1. The system blends the two stages, and ignores the disabled stages.

Note If your application varies the number of stages it uses for different situations - such as four stages for some objects, and only two for others - you don't need to explicitly disable all previously used stages. One option is to disable the color operation for the first unused stage, then all stages with a higher index will not be applied. Another option is to disable texture mapping altogether by setting the color operation for the first texture stage (stage 0). A third option is When a texture stage has D3DTSS_COLORARG1 equal to D3DTA_TEXTURE and the texture pointer for the stage is NULL, this stage and all stages after it are not processed.

Additional information is contained in the following topics.

  • Texture Blending Operations and Arguments (Direct3D 9)
  • Assigning the Current Textures (Direct3D 9)
  • Creating Blending Stages (Direct3D 9)
  • Alpha Texture Blending (Direct3D 9)
  • Multipass Texture Blending (Direct3D 9)
  • Light Mapping with Textures (Direct3D 9)


Texture Blending Operations and Arguments (Direct3D 9)

Applications associate a blending stage with each texture in the set of current textures. Direct3D evaluates each blending stage in order, beginning with the first texture in the set and ending with the eighth.

Direct3D applies the information from each texture in the set of current textures to the blending stage that is associated with it. Applications control what information from a texture stage is used by calling IDirect3DDevice9::SetTextureStageState. You can set separate operations for the color and alpha channels, and each operation uses two arguments. Specify color channel operations by using the D3DTSS_COLOROP stage state; specify alpha operations by using D3DTSS_ALPHAOP. Both stage states use values from the D3DTEXTUREOP enumerated type.

Texture blending arguments use the D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHARG1, and D3DTSS_ALPHARG2 members of the D3DTEXTURESTAGESTATETYPE enumerated type. The corresponding argument values are identified using D3DTA.

Note You can disable a texture stage - and any subsequent texture blending stages in the cascade - by setting the color operation for that stage to D3DTOP_DISABLE. Disabling the color operation effectively disables the alpha operation as well. Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.

To determine the supported texture blending operations of a device, query the TextureCaps member of the D3DCAPS9 structure.


Assigning the Current Textures (Direct3D 9)

Direct3D maintains a list of up to eight current textures. It blends these textures onto all the primitive it renders. Only textures created as texture interface pointers can be used in the set of current textures.

Applications call the IDirect3DDevice9::SetTexture method to assign textures into the set of current textures. The first parameter must be from the a number in the range of 0-7, inclusive. Pass the texture interface pointer as the second parameter.

The following C++ code example demonstrates how a texture can be assigned to the set of current textures.

// This code example assumes that the variable lpd3dDev is a
// valid pointer to an IDirect3DDevice9 interface and pTexture
// is a valid pointer to an IDirect3DBaseTexture9 interface.

// Set the third texture.
d3dDevice->SetTexture(2, pTexture);

Note Software devices do not support assigning a texture to more than one texture stage at a time.


Creating Blending Stages (Direct3D 9)

A blending stage is a set of texture operations and their arguments that define how textures are blended. When making a blending stage, C++ applications invoke the IDirect3DDevice9::SetTextureStageState method. The first call specifies the operation that is performed. Two additional invocations define the arguments to which the operation is applied. The following code example illustrates the creation of a blending stage.

// This example assumes that lpD3DDev is a valid pointer to an
// IDirect3DDevice9 interface.

// Set the operation for the first texture.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_ADD);

// Set argument 1 to the texture color.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);

// Set argument 2 to the iterated diffuse color.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);

Texel data in textures contain color and alpha values. Applications can define separate operations for both color and alpha values in a single blending stage. Each operation, color, and alpha, has its own arguments. For details, see D3DTEXTURESTAGESTATETYPE.

Although not part of the Direct3D API, you can insert the following macros into your application to abbreviate the code required for creating texture blending stages.

#define SetTextureColorStage( dev, i, arg1, op, arg2 )     \
    dev->SetTextureStageState( i, D3DTSS_COLOROP, op);      \
    dev->SetTextureStageState( i, D3DTSS_COLORARG1, arg1 ); \
    dev->SetTextureStageState( i, D3DTSS_COLORARG2, arg2 );

#define SetTextureAlphaStage( dev, i, arg1, op, arg2 )     \
    dev->SetTextureStageState( i, D3DTSS_ALPHAOP, op);      \
    dev->SetTextureStageState( i, D3DTSS_ALPHAARG1, arg1 );  \
    dev->SetTextureStageState( i  D3DTSS_ALPHAARG2, arg2 );


Alpha Texture Blending (Direct3D 9)

The lighting engine combines material color, vertex color, and lighting information to generate a per-vertex color. Once interpolated, this generates a per-pixel color that is written to the frame buffer. If an application enables texture blending, the pixel color will become a combination of the current pixel in the frame buffer and a texture color.

This formula determines the final blended pixel color:

Color = TexelColor x SourceBlend + CurrentPixelColor x DestBlend

Where:

  • Color is the output pixel color.
  • TexelColor is the input color after texture filtering.
  • SourceBlend is the percentage of the final pixel color that is made up of the source texel color.
  • CurrentPixelColor is the color of the current pixel.
  • DestBlend is the percentage of the final pixel color that is made up of the current pixel color.

The final blending equation is set by calling IDirect3DDevice9::SetRenderState and specifying the blend render state (D3DRS_BLENDXXX) with a corresponding blending factor (D3DBLEND). The values of SourceBlend and DestBlend range from 0.0 (transparent) to 1.0 (opaque) inclusive. In addition, an application can control the transparency of a pixel by setting the alpha value in a texture. In this case, use the following:

SourceBlend = D3DBLEND_ZERO
DestBlend = D3DBLEND_ONE

The blending equation will cause the rendered pixel to be transparent. The default values are:

SourceBlend = D3DBLEND_SRCALPHA
DestBlend = D3DBLEND_INVSRCALPHA

See Also

Texture Filtering (Direct3D 9), D3DRENDERSTATETYPE


Multipass Texture Blending (Direct3D 9)

Direct3D applications can achieve numerous special effects by applying various textures to a primitive over the course of multiple rendering passes. The common term for this is multipass texture blending. A typical use for multipass texture blending is to emulate the effects of complex lighting and shading models by applying multiple colors from several different textures. One such application is called light mapping. For more information, see Light Mapping with Textures (Direct3D 9).

Note Some devices are capable of applying multiple textures to primitives in a single pass. For details, see Texture Blending (Direct3D 9).

If the user's hardware does not support multiple texture blending, your application can use multipass texture blending to achieve the same visual effects. However, the application cannot sustain the frame rates that are possible when using multiple texture blending.

To perform multipass texture blending in a C/C++ application.

  1. Set a texture in texture stage 0 by calling the IDirect3DDevice9::SetTexture method.
  2. Select the desired color and alpha blending arguments and operations with the IDirect3DDevice9::SetTextureStageState method. The default settings are well-suited for multipass texture blending.
  3. Render the appropriate objects in the scene.
  4. Set the next texture in texture stage 0.
  5. Set the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states to adjust the source and destination blending factors as needed. The system blends the new textures with the existing pixels in the render-target surface according to these parameters.
  6. Repeat Steps 3, 4, and 5 with as many textures as needed.


Light Mapping with Textures (Direct3D 9)

For an application to realistically render a 3D scene, it must take into account the effect that light sources have on the appearance of the scene. Although techniques such as flat and Gouraud shading are valuable tools in this respect, they can be insufficient for your needs. Direct3D supports multipass and multiple texture blending. These capabilities enable your application to render scenes with a more realistic appearance than scenes rendered with shading techniques alone. By applying one or more light maps, your application can map areas of light and shadow onto its primitives.

A light map is a texture or group of textures that contains information about lighting in a 3D scene. You can store the lighting information in the alpha values of the light map, in the color values, or in both.

If you implement light mapping using multipass texture blending, your application should render the light map onto its primitives on the first pass. It should use a second pass to render the base texture. The exception to this is specular light mapping. In that case, render the base texture first; then add the light map.

Multiple texture blending enables your application to render the light map and the base texture in one pass. If the user's hardware provides for multiple texture blending, your application should take advantage of it when performing light mapping. This significantly improves your application's performance.

Using light maps, a Direct3D application can achieve a variety of lighting effects when it renders primitives. It can map not only monochrome and colored lights in a scene, but it can also add details such as specular highlights and diffuse lighting.

Information on using Direct3D texture blending to perform light mapping is presented in the following topics.

  • Monochrome Light Maps (Direct3D 9)
  • Color Light Maps (Direct3D 9)
  • Specular Light Maps (Direct3D 9)
  • Diffuse Light Maps (Direct3D 9)


Monochrome Light Maps (Direct3D 9)

Some older 3D accelerator boards do not support texture blending using the alpha value of the destination pixel. See Alpha Texture Blending (Direct3D 9) for more information. These adapters also generally do not support multiple texture blending. If your application is running on an adapter such as this, it can use multipass texture blending to perform monochrome light mapping.

To perform monochrome light mapping, an application stores the lighting information in the alpha data of its light map textures. The application uses the texture filtering capabilities of Direct3D to perform a mapping from each pixel in the primitive's image to a corresponding texel in the light map. It sets the source blending factor to the alpha value of the corresponding texel.

The following example illustrates how an application can use a texture as a monochrome light map:

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface and that lptexLightMap is a valid
// pointer to a texture that contains monochrome light map data.

// Set the light map texture as the current texture.
d3dDevice->SetTexture(0, lptexLightMap);

// Set the color operation.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);

// Set argument 1 to the color operation.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1,
                                D3DTA_TEXTURE | D3DTA_ALPHAREPLICATE);

Because display adapters that do not support destination alpha blending usually do not support multiple texture blending, this example sets the light map as the first texture, which is available on all 3D accelerator cards. The sample code sets the color operation for the texture's blending stage to blend the texture data with the primitive's existing color. It then selects the first texture and the primitive's existing color as the input data.


Color Light Maps (Direct3D 9)

Your application will usually render 3D scenes more realistically if it uses colored light maps. A colored light map uses the RGB data in the light map for its lighting information.

The following C++ code example demonstrates light mapping with RGB color data.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface and that lptexLightMap is a valid
// pointer to a texture that contains RGB light map data.

// Set the light map texture as the first texture.
d3dDevice->SetTexture(0, lptexLightMap);

d3dDevice->SetTextureStageState( 0,D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState( 0,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 0,D3DTSS_COLORARG2, D3DTA_DIFFUSE );

This example sets the light map as the first texture. It then sets the state of the first blending stage to modulate the incoming texture data. It uses the first texture and the current color of the primitive as the arguments to the modulate operation.


Specular Light Maps (Direct3D 9)

When illuminated by a light source, shiny objects - those that use highly reflective materials - receive specular highlights. In some cases, the specular highlights produced by the lighting module is not accurate. To produce a more appealing highlight, many Direct3D applications apply specular light maps to primitives.

To perform specular light mapping, add the specular light map to the primitive's texture, then modulate (multiply the result by) the RGB light map.

The following code example illustrates this process in C++.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface.
// lptexBaseTexture is a valid pointer to a texture.
// lptexSpecLightMap is a valid pointer to a texture that contains RGB
// specular light map data.
// lptexLightMap is a valid pointer to a texture that contains RGB
// light map data.

// Set the base texture.
d3dDevice->SetTexture(0, lptexBaseTexture );

// Set the base texture operation and arguments.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );

// Set the specular light map.
d3dDevice->SetTexture(1, lptexSpecLightMap);

// Set the specular light map operation and args.
d3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_ADD );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT );

// Set the RGB light map.
d3dDevice->SetTexture(2, lptexLightMap);

// Set the RGB light map operation and arguments.
d3dDevice->SetTextureStageState(2,D3DTSS_COLOROP, D3DTOP_MODULATE);
d3dDevice->SetTextureStageState(2,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(2,D3DTSS_COLORARG2, D3DTA_CURRENT );


Diffuse Light Maps (Direct3D 9)

When illuminated by a light source, matte surfaces display diffuse light reflection. The brightness of diffuse light depends on the distance from the light source and the angle between the surface normal and the light source direction vector. The diffuse lighting effects simulated by lighting calculations produce only general effects.

Your application can simulate more complex diffuse lighting with texture light maps. Do this by adding the diffuse light map to the base texture, as shown in the following C++ code example.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface.
// lptexBaseTexture is a valid pointer to a texture.
// lptexDiffuseLightMap is a valid pointer to a texture that contains
// RGB diffuse light map data.

// Set the base texture.
d3dDevice->SetTexture(0,lptexBaseTexture );

// Set the base texture operation and args.
d3dDevice->SetTextureStageState(0,D3DTSS_COLOROP,
                                D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(0,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(0,D3DTSS_COLORARG2, D3DTA_DIFFUSE );

// Set the diffuse light map.
d3dDevice->SetTexture(1,lptexDiffuseLightMap );

// Set the blend stage.
d3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT );


Automatic Generation of Mipmaps (Direct3D 9)

You can now automatically create a mipmap which is a series of textures, each filtered to a different resolution. Mipmaps are commonly used to provide different levels of detail when rendering. Automatically generating mipmaps at texture creation time takes advantage of hardware filtering because the mipmap resides in video memory.

To generate a mipmap automatically, set a new usage D3DUSAGE_AUTOGENMIPMAP before calling IDirect3DDevice9::CreateTexture. Sublevel generation from this point on is completely transparent to the application. Only the top texture level is accessible to the application; the texture sublevels are not accessible since they will be created only when needed by the driver. In cases where sublevel generation may take a lot of time, use IDirect3DBaseTexture9::GenerateMipSubLevels to hint to the driver that it should generate sublevels at a time appropriate for the application.

Mipmap Filtering

IDirect3DBaseTexture9::SetAutoGenFilterType controls the filtering quality during automatic generation. Changing the filter type dirties the mipmap sublevels and causes them to be regenerated. Use IDirect3DBaseTexture9::GetAutoGenFilterType to get the current filter type. The default filter type is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT.

These methods have no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP And no failure is returned. All filter types supported by the driver for regular texture filtering are supported for autogenerated except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, CubeTexture, and volumetexture filter caps.

To check which filter types are supported, check to see which caps are supported by the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9.

Mipmap Support

D3DUSAGE_AUTOGENMIPMAP is only a hint, and specifying this during texture creation or when calling IDirect3D9::CheckDeviceFormat would not cause an error on any of the device driver interface (DDI) types.

Calling IDirect3DDevice9::UpdateTexture is illegal when the source is an automatically generated mipmap, but the destination is not. The source can be a non-automatically generated mipmap and the destination can be an automatically generated mipmap. In this case, only the topmost matching level is updated. All other source sublevels are ignored. Similarly, when both the source and destination are automatically generated, only the topmost matching level is updated. The sublevels from the source are ignored and the destination sublevels are regenerated.

To check for support for automatic generation of mipmaps, check to see that D3DCAPS2_CANAUTOGENMIPMAP is set. If it is, call IDirect3D9::CheckDeviceFormat with D3DUSAGE_AUTOGENMIPMAP. If the return value is D3D_OK, the mipmaps are guaranteed to be autogenerated. If the return value is D3DOK_NOAUTOGEN, this means that the create call will succeed, but there won't be any mipmaps generated.


Automatic Texture Management (Direct3D 9)

Texture management is the process of determining which textures are needed for rendering at a given time and ensuring that those textures are loaded into video memory. As with any algorithm, texture management schemes vary in complexity, but any approach to texture management involves the following key tasks.

  • Tracking the amount of available texture memory.
  • Calculating which textures are needed for rendering, and which are not.
  • Determining which existing texture resources can be reloaded with another texture image, and which surfaces should be destroyed and replaced with new texture resources.

Direct3D implements system-supported texture management to ensure that textures are loaded for optimal performance. Texture resources that Direct3D manages are referred to as managed textures.

The texture manager tracks textures with a time-stamp that identifies when the texture was last used. It then uses a least-recently-used algorithm to determine which textures should be removed. Texture priorities are used as tie breakers when two textures are targeted for removal from memory. If two textures have the same priority value, the least-recently-used texture is removed. However, if two textures have the same time-stamp, the texture that has a lower priority is removed first.

You request automatic texture management for texture surfaces when you create them. To retrieve a managed texture in a C++ application, create a texture resource by calling IDirect3DDevice9::CreateTexture and specifying the D3DPOOL_MANAGED for the Pool parameter. You are not allowed to specify where you want the texture created. You cannot use the D3DPOOL_DEFAULT or D3DPOOL_SYSTEMMEM flags when creating a managed texture. After creating the managed texture, you can call the IDirect3DDevice9::SetTexture method to set it to a stage in the rendering device's texture cascade.

You can assign a priority to managed textures by calling the IDirect3DResource9::SetPriority method for the texture surface.

Direct3D automatically downloads textures into video memory as needed. The system might cache managed textures in local or nonlocal video memory, depending on the availability of nonlocal video memory or other factors. The cache location of your managed textures is not communicated to your application, nor is this information required to use automatic texture management. If your application uses more textures than can fit in video memory, Direct3D removes older textures from video memory to make room for the new textures. If you use a removed texture again, the system uses the original system-memory texture surface to reload the texture in the video-memory cache. Although reloading the texture is necessary, it also decreases the application's performance.

You can dynamically modify the original system-memory copy of the texture by updating or locking the texture resource. When the system detects a dirty surface - after an update is completed, or when the surface is unlocked - the texture manager automatically updates the video-memory copy of the texture. The performance hit incurred is similar to reloading a removed texture.

When entering a new level in a game, your application might need to flush all managed textures from video memory (by calling IDirect3DDevice9::EvictManagedResources).

For more information about resource management, see Managing Resources (Direct3D 9).


Compressed Texture Resources (Direct3D 9)

Texture maps are digitized images drawn on three-dimensional shapes to add visual detail. They are mapped into these shapes during rasterization, and the process can consume large amounts of both the system bus and memory. To reduce the amount of memory consumed by textures, Direct3D supports the compression of texture surfaces. Some Direct3D devices support compressed texture surfaces natively. On such devices, when you have created a compressed surface and loaded the data into it, the surface can be used in Direct3D like any other texture surface. Direct3D handles decompression when the texture is mapped to a 3D object.

Storage Efficiency and Texture Compression

All texture compression formats are powers of two. While this does not mean that a texture is necessarily square, it does mean that both x and y are powers of two. For example, if a texture is originally 512 by 128 bytes, the next mipmapping would be 256 by 64 and so on, with each level decreasing by a power of two. At lower levels, where the texture is filtered to 16 by 2 and 8 by 1, there will be wasted bits because the compression block is always a 4 by 4 block of texels. Unused portions of the block are padded. Although there are wasted bits at the lowest levels, the overall gain is still significant. The worst case is, in theory, a 2K by 1 texture (20 power). Here, only a single row of pixels is encoded per block, while the rest of the block is unused.

Mixing Formats Within a Single Texture

It is important to note that any single texture must specify that its data is stored as 64 or 128 bits per group of 16 texels. If 64-bit blocks - that is, format DXT1 - are used for the texture, it is possible to mix the opaque and 1-bit alpha formats on a per-block basis within the same texture. In other words, the comparison of the unsigned integer magnitude of color_0 and color_1 is performed uniquely for each block of 16 texels.

Once the 128-bit blocks are used, the alpha channel must be specified in either explicit (format DXT2 and DXT3) or interpolated mode (format DXT4 and DXT5) for the entire texture. As with color, when interpolated mode (format DXT4 and DXT5) is selected, then either eight interpolated alphas or six interpolated alphas mode can be used on a block-by-block basis. Again the magnitude comparison of alpha_0 and alpha_1 is done uniquely on a block-by-block basis.

Direct3D provides services to compress surfaces that are used for texturing 3D models. This section provides information about creating and manipulating the data in a compressed texture surface.

Information is contained in the following topics.

  • Opaque and 1-Bit Alpha Textures (Direct3D 9)
  • Textures with Alpha Channels (Direct3D 9)
  • Compressed Texture Formats (Direct3D 9)
  • Using Compressed Textures (Direct3D 9)


Opaque and 1-Bit Alpha Textures (Direct3D 9)

Texture format DXT1 is for textures that are opaque or have a single transparent color.

For each opaque or 1-bit alpha block, two 16-bit values (RGB 5:6:5 format) and a 4x4 bitmap with 2 bits per pixel are stored. This totals 64 bits for 16 texels, or four bits per texel. In the block bitmap, there are 2 bits per texel to select between the four colors, two of which are stored in the encoded data. The other two colors are derived from these stored colors by linear interpolation. This layout is shown in the following diagram:

The 1-bit alpha format is distinguished from the opaque format by comparing the two 16-bit color values stored in the block. They are treated as unsigned integers. If the first color is greater than the second, it implies that only opaque texels are defined. This means four colors are used to represent the texels. In four-color encoding, there are two derived colors and all four colors are equally distributed in RGB color space. This format is analogous to RGB 5:6:5 format. Otherwise, for 1-bit alpha transparency, three colors are used and the fourth is reserved to represent transparent texels.

In three-color encoding, there is one derived color and the fourth 2-bit code is reserved to indicate a transparent texel (alpha information). This format is analogous to RGBA 5:5:5:1, where the final bit is used for encoding the alpha mask.

The following code example illustrates the algorithm for deciding whether three- or four-color encoding is selected:

if (color_0 > color_1)
{
    // Four-color block: derive the other two colors.
    // 00 = color_0, 01 = color_1, 10 = color_2, 11 = color_3
    // These 2-bit codes correspond to the 2-bit fields
    // stored in the 64-bit block.
    color_2 = (2 * color_0 + color_1 + 1) / 3;
    color_3 = (color_0 + 2 * color_1 + 1) / 3;
}
else
{
    // Three-color block: derive the other color.
    // 00 = color_0,  01 = color_1,  10 = color_2,
    // 11 = transparent.
    // These 2-bit codes correspond to the 2-bit fields
    // stored in the 64-bit block.
    color_2 = (color_0 + color_1) / 2;
    color_3 = transparent;

}

It is recommended that you set the RGBA components of the transparency pixel to zero before blending.

The following tables show the memory layout for the 8-byte block. It is assumed that the first index corresponds to the y-coordinate and the second corresponds to the x-coordinate. For example, Texel[1][2] refers to the texture map pixel at (x,y) = (2,1).

This table contains the memory layout for the 8-byte (64-bit) block.

Word address | 16-bit word
0 | Color_0
1 | Color_1
2 | Bitmap Word_0
3 | Bitmap Word_1

Color_0 and Color_1, the colors at the two extremes, are laid out as follows:

Bits | Color
4:0 (LSB*) | Blue color component
10:5 | Green color component
15:11 | Red color component

*least-significant bit

Bitmap Word_0 is laid out as follows:

Bits | Texel
1:0 (LSB) | Texel[0][0]
3:2 | Texel[0][1]
5:4 | Texel[0][2]
7:6 | Texel[0][3]
9:8 | Texel[1][0]
11:10 | Texel[1][1]
13:12 | Texel[1][2]
15:14 (MSB*) | Texel[1][3]

*most significant bit (MSB)

Bitmap Word_1 is laid out as follows:

Bits | Texel
1:0 (LSB) | Texel[2][0]
3:2 | Texel[2][1]
5:4 | Texel[2][2]
7:6 | Texel[2][3]
9:8 | Texel[3][0]
11:10 | Texel[3][1]
13:12 | Texel[3][2]
15:14 (MSB) | Texel[3][3]

Example of Opaque Color Encoding

As an example of opaque encoding, assume that the colors red and black are at the extremes. Red is color_0, and black is color_1. There are four interpolated colors that form the uniformly distributed gradient between them. To determine the values for the 4x4 bitmap, the following calculations are used:

00 ? color_0
01 ? color_1
10 ? 2/3 color_0 + 1/3 color_1
11 ? 1/3 color_0 + 2/3 color_1

The bitmap then looks like this:

Expanded bitmap layout

This looks like the following series of colors.

Opaque encoded gradient

Example of 1-Bit Alpha Encoding

This format is selected when the unsigned 16-bit integer, color_0, is less than the unsigned 16-bit integer, color_1. An example of where this format can be used is leaves on a tree, shown against a blue sky. Some texels can be marked as transparent while three shades of green are still available for the leaves. Two colors fix the extremes, and the third is an interpolated color.

Here is an example of such a picture.

1-bit alpha example

Note that where the image is shown as white, the texel would be encoded as transparent. Also note that the RGBA components of the transparent texels should be set to zero before blending.

The bitmap encoding for the colors and the transparency is determined using the following calculations.

00 ? color_0
01 ? color_1
10 ? 1/2 color_0 + 1/2 color_1
11   ?   Transparent

The bitmap then looks like the following graphic.

Expanded bitmap layout


Textures with Alpha Channels (Direct3D 9)

There are two ways to encode texture maps that exhibit more complex transparency. In each case, a block that describes the transparency precedes the 64-bit block already described. The transparency is either represented as a 4x4 bitmap with 4 bits per pixel (explicit encoding), or with fewer bits and linear interpolation that is analogous to what is used for color encoding.

The transparency block and the color block are arranged as shown in the following table.

Word address | 64-bit block
3:0 | Transparency block
7:4 | Previously described 64-bit block

Explicit Texture Encoding

For explicit texture encoding (DXT2 and DXT3 formats), the alpha components of the texels that describe transparency are encoded in a 4x4 bitmap with 4 bits per texel. These four bits can be achieved through a variety of means such as dithering or by using the four most significant bits of the alpha data. However they are produced, they are used just as they are, without any form of interpolation.

The following diagram shows a 64-bit transparency block.

64-bit transparency block

Note The compression method of Direct3D uses the four most significant bits.

The following tables illustrate how the alpha information is laid out in memory, for each 16-bit word.

This table contains the layout for word 0.

Bits | Alpha
3:0 (LSB*) | [0][0]
7:4 | [0][1]
11:8 | [0][2]
15:12 (MSB*) | [0][3]

*least-significant bit, most significant bit (MSB)

This table contains the layout for word 1.

Bits | Alpha
3:0 (LSB) | [1][0]
7:4 | [1][1]
11:8 | [1][2]
15:12 (MSB) | [1][3]

This table contains the layout for word 2.

Bits | Alpha
3:0 (LSB) | [2][0]
7:4 | [2][1]
11:8 | [2][2]
15:12 (MSB) | [2][3]

This table contains the layout for word 3.

Bits | Alpha
3:0 (LSB) | [3][0]
7:4 | [3][1]
11:8 | [3][2]
15:12 (MSB) | [3][3]

The difference between DXT2 and DXT3 are that, in the DXT2 format, it is assumed that the color data has been premultiplied by alpha. In the DXT3 format, it is assumed that the color is not premultiplied by alpha. These two formats are needed because, in most cases, by the time a texture is used, just examining the data is not sufficient to determine if the color values have been multiplied by alpha. Because this information is needed at run time, the two FOURCC codes are used to differentiate these cases. However, the data and interpolation method used for these two formats is identical.

The color compare used in DXT1 to determine if the texel is transparent is not used in this format. It is assumed that without the color compare the color data is always treated as if in 4-color mode. In other words, the if statement at the top of the DXT1 code should be the following:

if ((color_0 > color_1) OR !DXT1) {

Three-Bit Linear Alpha Interpolation

The encoding of transparency for the DXT4 and DXT5 formats is based on a concept similar to the linear encoding used for color. Two 8-bit alpha values and a 4x4 bitmap with three bits per pixel are stored in the first eight bytes of the block. The representative alpha values are used to interpolate intermediate alpha values. Additional information is available in the way the two alpha values are stored. If alpha_0 is greater than alpha_1, then six intermediate alpha values are created by the interpolation. Otherwise, four intermediate alpha values are interpolated between the specified alpha extremes. The two additional implicit alpha values are 0 (fully transparent) and 255 (fully opaque).

The following code example illustrates this algorithm.

// 8-alpha or 6-alpha block?
if (alpha_0 > alpha_1) {
    // 8-alpha block:  derive the other six alphas.
    // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated.
    alpha_2 = (6 * alpha_0 + 1 * alpha_1 + 3) / 7;    // bit code 010
    alpha_3 = (5 * alpha_0 + 2 * alpha_1 + 3) / 7;    // bit code 011
    alpha_4 = (4 * alpha_0 + 3 * alpha_1 + 3) / 7;    // bit code 100
    alpha_5 = (3 * alpha_0 + 4 * alpha_1 + 3) / 7;    // bit code 101
    alpha_6 = (2 * alpha_0 + 5 * alpha_1 + 3) / 7;    // bit code 110
    alpha_7 = (1 * alpha_0 + 6 * alpha_1 + 3) / 7;    // bit code 111
}
else {
    // 6-alpha block.
    // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated.
    alpha_2 = (4 * alpha_0 + 1 * alpha_1 + 2) / 5;    // Bit code 010
    alpha_3 = (3 * alpha_0 + 2 * alpha_1 + 2) / 5;    // Bit code 011
    alpha_4 = (2 * alpha_0 + 3 * alpha_1 + 2) / 5;    // Bit code 100
    alpha_5 = (1 * alpha_0 + 4 * alpha_1 + 2) / 5;    // Bit code 101
    alpha_6 = 0;                                      // Bit code 110
    alpha_7 = 255;                                    // Bit code 111
}

The memory layout of the alpha block is as follows:

Byte | Alpha
0 | Alpha_0
1 | Alpha_1
2 | [0][2] (2 MSBs), [0][1], [0][0]
3 | [1][1] (1 MSB), [1][0], [0][3], [0][2] (1 LSB)
4 | [1][3], [1][2], [1][1] (2 LSBs)
5 | [2][2] (2 MSBs), [2][1], [2][0]
6 | [3][1] (1 MSB), [3][0], [2][3], [2][2] (1 LSB)
7 | [3][3], [3][2], [3][1] (2 LSBs)

The difference between DXT4 and DXT5 is that in the DXT4 format it is assumed that the color data has been premultiplied by alpha. In the DXT5 format, it is assumed the color is not premultiplied by alpha. These two formats are needed because, in most cases, by the time a texture is used, just examining the data is not sufficient to determine if the color values have been multiplied by alpha. Because this information is needed at run time, the two FOURCC codes are used to differentiate these cases. However, the data and interpolation method used for these two formats is identical.

The color compare used in DXT1 to determine if the texel is transparent is not used with these formats. It is assumed that without the color compare the color data is always treated as if in 4-color mode. In other words, the if statement at the top of the DXT1 code should be:

if ((color_0 > color_1) OR !DXT1) {


Compressed Texture Formats (Direct3D 9)

This section contains information about the internal organization of compressed texture formats. You do not need these details to use compressed textures, because you can use D3DX functions for conversion to and from compressed formats. However, this information is useful if you want to operate on compressed surface data directly.

Direct3D uses a compression format that divides texture maps into 4x4 texel blocks. If the texture contains no transparency - is opaque - or if the transparency is specified by a 1-bit alpha, an 8-byte block represents the texture map block. If the texture map does contain transparent texels, using an alpha channel, a 16-byte block represents it.

  • Opaque and 1-Bit Alpha Textures (Direct3D 9)
  • Textures with Alpha Channels (Direct3D 9)

Any single texture must specify that its data is stored as 64 or 128 bits per group of 16 texels. If 64-bit blocks - that is, format DXT1 - are used for the texture, it is possible to mix the opaque and 1-bit alpha formats on a per-block basis within the same texture. In other words, the comparison of the unsigned integer magnitude of color_0 and color_1 is performed uniquely for each block of 16 texels.

When 128-bit blocks are used, the alpha channel must be specified in either explicit (format DXT2 or DXT3) or interpolated mode (format DXT4 or DXT5) for the entire texture. As with color, when interpolated mode is selected, either eight interpolated alphas or six interpolated alphas mode can be used on a block-by-block basis. Again the magnitude comparison of alpha_0 and alpha_1 is done uniquely on a block-by-block basis.

The pitch for DXTn formats is different from what was returned in DirectX 7.0. Pitch is now measured in bytes (not blocks). For example, if you have a width of 16, then you will have a pitch of four blocks (4*8 for DXT1, 4*16 for DXT2-5).


Using Compressed Textures (Direct3D 9)

Determining Support for Compressed Textures

To test the adapter, specify any pixel format that uses the DXT1, DXT2, DXT3, DXT4, or DXT5. If IDirect3D9::CheckDeviceFormat returns D3D_OK, the device can create texture directly from a compressed texture surface that uses that format. If so, you can use compressed texture surfaces directly with Direct3D by calling the IDirect3DDevice9::SetTexture method. The following code example shows how to determine if the adapter supports a compressed texture format.

BOOL IsCompressedTextureFormatOk( D3DFORMAT TextureFormat,
                                  D3DFORMAT AdapterFormat )
{
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          0,
                                          D3DRTYPE_TEXTURE,
                                          TextureFormat);

    return SUCCEEDED( hr );
}

If the device does not support texturing from compressed texture surfaces, you can still store texture data in a compressed format surface, but you must convert any compressed textures to a supported format before they can be used for texturing.

Creating Compressed Textures

After creating a device that supports a compressed texture format on the adapter, you can create a compressed texture resource. Call IDirect3DDevice9::CreateTexture and specify a compressed texture format for the Format parameter.

Before loading an image into a texture object, retrieve a pointer to the texture surface by calling the IDirect3DTexture9::GetSurfaceLevel method.

Now you can use any D3DXLoadSurfacexxx function to load an image to the surface that was retrieved by using IDirect3DTexture9::GetSurfaceLevel. These functions handle conversion to and from compressed texture formats.

You can create and convert compressed texture (DDS) files using the DirectX Texture Editor (Dxtex.exe) supplied with the SDK.

The advantage of this behavior is that an application can copy the contents of a compressed surface to a file without calculating how much storage is required for a surface of a particular width and height in the specific format.

The following table shows the five types of compressed textures. For more information about how the data is stored, see Compressed Texture Formats (Direct3D 9). You only need this information if you are writing your own compression routines.

FOURCC | Description | Alpha premultiplied?
DXT1 | Opaque/1-bit alpha | N/A
DXT2 | Explicit alpha | Yes
DXT3 | Explicit alpha | No
DXT4 | Interpolated alpha | Yes
DXT5 | Interpolated alpha | No

When you transfer data from a nonpremultiplied format to a premultiplied format, Direct3D scales the colors based on the alpha values. Transferring data from a premultiplied format to a nonpremultiplied format is not supported. If you try to transfer data from a premultiplied alpha source to a nonpremultiplied alpha destination, the method returns D3DERR_INVALIDCALL. If you transfer data from a premultiplied alpha source to a destination that has no alpha, the source color components, which have been scaled by alpha, are copied as is.

Decompressing Compressed Texture Surfaces

As with compressing a texture surface, decompressing a compressed texture is performed through Direct3D copying services.

To copy a compressed texture surface to a uncompressed texture surface, use the function D3DXLoadSurfaceFromSurface. This functions handles compression to and from compressed and uncompressed surfaces.


Hardware Considerations for Texturing (Direct3D 9)

Current hardware does not necessarily implement all the functionality that the Direct3D interface enables. Your application must test user hardware and adjust its rendering strategies accordingly.

Many 3D accelerator cards do not support diffuse iterated values as arguments to blending units. However, your application can introduce iterated color data when it performs texture blending.

Some 3D hardware may not have a blending stage associated with the first texture. On these adapters, your application must perform blending in the second and third texture stages in the set of current textures.

Because of limitations in much of today's hardware, few display adapters can perform trilinear mipmap interpolation through the multiple texture blending interface offered by IDirect3DDevice9. Your application can use multipass texture blending to achieve the same effects, or degrade to the D3DTEXF_POINT mipmap filter mode, which is widely supported.


Volume Texture Resources (Direct3D 9)

Volume textures are three-dimensional collections of pixels (texels) that can be used to paint a two-dimensional primitive such as a triangle or a line. Three-element texture coordinates are required for each vertex of a primitive that is to be textured with a volume. As the primitive is drawn, each contained pixel is filled with the color value from some pixel within the volume, in accordance with rules analogous to the two-dimensional texture case. Volumes are not rendered directly because there are no three-dimensional primitives that can be painted with them.

You can use volume textures for special effects such as patchy fog, explosions, and so on.

Volumes are organized into slices and can be thought of as width x height 2D surfaces stacked to make a width x height x depth volume. Each slice is a single row. Volumes can have subsequent levels in which the dimensions of each level are truncated to half the dimensions of the previous level. The illustration below gives an idea of what a volume texture with multiple levels looks like.

Volume texture with 8x2x4, 4x1x2, and 2x1x1 cube representations

Creating a Volume Texture

The code examples below show the steps required to use a volume texture.

First, specify a custom vertex type that has three texture coordinates for each vertex, as shown in this code example.

struct VOLUMEVERTEX
{
    FLOAT x, y, z;
    DWORD color;
    FLOAT tu, tv, tw;
};

#define D3DFVF_VOLUMEVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|
                             D3DFVF_TEX1|D3DFVF_TEXCOORDSIZE3(0))

Next, fill the vertices with data.

VOLUMEVERTEX g_vVertices[4] =
{
    { 1.0f, 1.0f, 0.0f, 0xffffffff, 1.0f, 1.0f, 0.0f },
    {-1.0f, 1.0f, 0.0f, 0xffffffff, 0.0f, 1.0f, 0.0f },
    { 1.0f,-1.0f, 0.0f, 0xffffffff, 1.0f, 0.0f, 0.0f },
    {-1.0f,-1.0f, 0.0f, 0xffffffff, 0.0f, 0.0f, 0.0f }
};

Now, create a vertex buffer and fill it with data from the vertices.

The next step is to use the IDirect3DDevice9::CreateVolumeTexture method to create a volume texture, as shown in this code example.

LPDIRECT3DVOLUMETEXTURE9 pVolumeTexture;
d3dDevice->CreateVolumeTexture( 8, 4, 4, 1, 0, D3DFMT_R8G8B8,D3DPOOL_MANAGED,
                                &pVolumeTexture );

Before rendering the primitive, set the current texture to the volume texture created above. The code example below shows the entire rendering process for a strip of triangles.

if( SUCCEEDED( d3dDevice->BeginScene() ) )
{
    // Draw the quad, with the volume texture.
    d3dDevice->SetTexture( 0, pVolumeTexture );
    d3dDevice->SetFVF( D3DFVF_VOLUMEVERTEX );
    d3dDevice->SetStreamSource( 0, pVB, sizeof(VOLUMEVERTEX) );
    d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2);

   // End the scene.
   d3dDevice->EndScene();
}


D3DX (Direct3D 9)

D3DX is a library of tools designed to provide additional graphics functionality on top of Direct3D. D3DX is provided as a dynamic-link library (DLL).

Only one version of D3DX is provided in this release of the DirectX SDK. The retail D3DX DLL is included in the redistributable provided in the SDK, and is automatically installed as part of Installing DirectX with DirectSetup. The D3DX library included in this release is dependant on the Direct3D runtimes that shipped with this SDK. Applications linking against the version of D3DX in this release must also redistribute the runtime from this SDK.

Multiple releases of D3DX can reside independently on a single system simultaneously. By statically linking an application to D3dx9.lib, the application dynamically links to the corresponding retail D3DX DLL at run-time. This DLL corresponds to the D3DX headers the application is compiled against (named with the D3DX_SDK_VERSION constant in D3dx9core.h). As new versions of D3DX are shipped in future releases of the DirectX SDK, applications linking to earlier D3DX libraries will remain unaffected.

The D3DX library addresses these general areas of functionality:

  • Line Drawing Support in D3DX (Direct3D 9)
  • Mesh Support in D3DX (Direct3D 9)
  • Math Function Support in D3DX (Direct3D 9)
  • Texture Support in D3DX (Direct3D 9)


Line Drawing Support in D3DX (Direct3D 9)

D3DX is a utility library that provides helper services. It is a layer above the Direct3D component.

D3DX supports single-pixel-wide antialiased lines. Line patterns are no longer supported.

The line drawing library emulates lines using texture triangles and assumes the following:

  • Hardware is available through the Direct3D 9 interfaces.
  • At least one texture stage is available.
  • 64x64 textures are used.
  • The following modes are available:
    • Bilinear filtering
    • Clamp address mode
    • Wrap address mode
    • Alpha op modulate
    • Alpha blending (SRCBLEND = SRC_ALPHA, DESTBLEND = INV_SRC_ALPHA)
    • Alpha test if alpha blending is not available; lower quality result

For antialiased line rendering in multisample render targets, use ID3DXLine which generates textured polygons. The pixel coverage values, generated by antialiased line rasterization, modulate the pixel's alpha value computed by the pixel shader. To draw an antialiased line, an application must enable alpha blending and then it must set the D3DRS_ANTIALIASEDLINEENABLE render state to TRUE.

Functionality Description

The library supports drawing colored line strips with the following line features, each of which is independent of any other:

  • Line width
  • Line pattern with repetition (the line pattern counter resets with each ID3DXLine::Draw or ID3DXLine::DrawTransform call. It does not reset with each segment of the line strip.)
  • Antialiasing
  • OpenGL-style lines

Note No mitering is supported.

The library uses native hardware line drawing support (if available in the device) only if:

  • Line width is 1.
  • No line pattern is enabled.

Single-pixel-wide antialiased lines are supported by some hardware, so the library uses that, if available. The LineCaps member of the D3DCAPS9 structure enumerates hardware capabilities for line-drawing primitives.

When the software line drawing is used, each line is expanded into a rectangle and four vertices are sent down to the driver.

Each line segment is drawn with two triangles. The width of the primitive is the specified width plus 1.0, which may result in an extra row or column of pixels. As the line gets wider, the antialias gradient in the texture becomes more coarse, and more fully-opaque texels are replicated around the middle. The gradient is encoded in the v-direction of the texture, and typically replicated along the u-direction. The texture addressing mode for v is clamp.

Each line segment in the list can be considered to be a separate line that happens to start from the previous end point.

Antialiasing quality along the edges parallel to the length of the original line suffers as the line gets wider. It is expected that line widths greater than 32.0 will start to exhibit artifacts along these edges.


Math Function Support in D3DX (Direct3D 9)

D3DX is a utility library that provides helper services. It is a layer above the Direct3D component.

Math

Math support, contained in a set of functions, is provided for:

  • Color calculations
  • Planes
  • Matrix manipulation
  • Quaternions
  • 2D vectors
  • 3D vectors
  • 4D vectors

Please note that when coupled with the C++ overloads, the support for basic 3D math types is extensive.

For more information about these functions, see D3DX Functions. To help find the function you need, they are broken up in several folders.

FLOAT16

When using the FLOAT16 data type, be sure to limit values to a maximum of D3DX_16F_MAX. Any FLOAT16 value that exceeds this will result in undefined behavior in the pipeline. See Other D3DX Constants.


Mesh Support in D3DX (Direct3D 9)

D3DX is a utility library that provides helper services. It is a layer above the Direct3D component.

Meshes

D3DX implements the mesh construct to load, manipulate, and render .x file contents. A mesh is basically a collection of vertices defining some geometry, and a set of indices defining the faces. There are several mesh types.

ID3DXBaseMesh provides the fundamentals. ID3DXMesh and ID3DXPMesh inherit from ID3DXBaseMesh, and add, respectively, mesh optimization using per-chip vertex cache and progressive meshes modeled after Hugues Hoppe's progressive mesh work. ID3DXSPMesh provides simplification meshes and ID3DXSkinInfo provides skinned mesh support.

ID3DXBaseMesh provides methods to manipulate and query ID3DXMesh and ID3DXPMesh progressive-mesh objects, which inherit from the base mesh. This includes adjacency operations, geometry buffer retrieval, lock/unlock operations (vertex and index), and copying, rendering, face, and vertex information.

Mesh Architecture

A mesh contains the data for a complex model. It is an abstract data container that contains resources such as textures and materials, and attributes such as position data and adjacency data. There are several mesh operations that improve drawing performance and the appearance of a surface. In addition, there are a number of other mesh concepts that will effect the functionality of mesh operations. Understanding these mesh concepts so you can apply them will improve mesh performance.

Mesh Object Data

A mesh contains a vertex buffer, an index buffer, and an attribute buffer.

  • The vertex buffer contains the vertex data, which are the mesh vertices.
  • The index buffer contains vertex indices for accessing the vertex buffer. This can reduce the vertex buffer size by reducing duplicate vertices. Only an indexed mesh uses the index buffer. If a mesh is made up of a triangle list, for example, it does not use the index buffer.
  • The attribute buffer contains attribute data. Attributes are properties of the mesh vertices, in no particular order. A D3DX mesh stores attributes in a group of DWORDS, for each face.

Attribute Tables

An attribute table is a concise representation of the contents of an attribute buffer. Attribute tables can be created by calling one of the Optimize methods with D3DXMESHOPT_ATTRSORT, by locking the attribute buffer and filling it with data, or by calling SetAttributeTable. A mesh contains an attribute table when the mesh is reordered into groups. This happens when Optimize is called, assuming an attribute sorting option (D3DXMESHOPT_ATTRSORT or higher) is supplied. D3DX Meshes use indexed triangle lists, and are therefore drawn with IDirect3DDevice9::DrawIndexedPrimitive.

Attribute tables are created as a result of calling Optimize. The faces don't have to be adjacent, because Optimize will reorder them to be adjacent. For example, the hands of a human mesh could use the same attribute. The id helps sort the faces into groups. Meshes from .x files have automatically generated attributes for material and texture properties. You do need to call Optimize(ATTRSORT) or the more effective Optimize(VERTEXCACHE) to get good performance. The load functions try to present the data in the exact form it was saved out in. If you are using a vertex buffer/index buffer based mesh, the mesh API provides optimization functions and skinning transformations with little overhead.

The optimization types are cumulative, starting from the least optimal (D3DXMESHOPT_COMPACT) to the most optimal (D3DXMESHOPT_IGNOREVERTS). D3DXMESHOPT_STRIPREORDER does a compaction and attribute sort. D3DXMESHOPT_VERTEXCACHE is always recommended, even on devices without a true vertex cache.

Application Data

Application data is mesh data that is managed by an application. There is a tight coupling between the mesh vertex data and the data managed by these buffers.

The materials buffer contains n materials. The materials are returned by the Load function when the .x file is loaded. Each subset can have its own materials and textures. The materials buffer is static.

The adjacency buffer contains information about edges, faces, and adjacent faces. Some mesh operations depend on knowing which faces are adjacent to each other. This information, called adjacency data, is kept in an adjacency buffer. It is not part of the mesh but is maintained by the application and must be supplied to the mesh methods when necessary.

The effects instance buffer contains a list of effect instances. An effect instance stores state. This state information is used to initialize the pipeline. An effect instance contains name-value pairs in an effect.

Advanced Mesh Topics

Optimized meshes build on the base mesh functionality and add vertex-cache optimization capability with two methods: Optimize, which creates a new mesh, and OptimizeInPlace, which modifies the original mesh.

Progressive meshes are based on Hugues Hoppe's SIGGRAPH papers (from the Association for Computing Machinery's Special Interest Group, Graphics), with updated error metrics. The ID3DXPMesh adds methods for copying, face and vertex manipulation, and optimization.

D3DXGeneratePMesh uses the D3DX simplification algorithm to generate a progressive mesh from the input mesh. D3DXSimplifyMesh generates a standard mesh of the given level-of-detail from an input mesh using the same simplification algorithm. The user has control over the error metric used through the weights specified per-vertex component and weights specified per vertex. Per-component weights are multiplied against that components portion of error calculated per edge collapse. Per-vertex weights are multiplied against the error metric value determined for removal of that vertex. For example, if you never want a vertex to be removed, set that specific vertex's weight to a large value. Conversely, if you want it removed earlier, set it to a small value (less than 1).

ID3DXSkinInfo supports skinned characters. A skinned character is defined by a set of meshes and a set of bones that affect the vertices of the meshes. The bones are represented as a transform hierarchy. For each mesh, there is a matrix for every bone that affects it, which transforms the mesh into the local coordinate space of the bone. This matrix is the bone-space transform of the bone for the mesh. This is defined at the time the skeleton is associated with the mesh in the authoring process.

Skinning

Skinning is a technique for transforming mesh vertices using bones. Bones are typically arranged in a hierarchical skeleton, much like the bones in a human body. Object vertices are then associated with the bones, like attaching skin to the bones. When the bones get transformed, the skin is also transformed.

Skinned meshes use bones to influence a number of vertices. Bone transformation data is supplied by the user, to influence how to SRT the bones. The mesh uses the transformed bones to influence the vertices associated with the bones. Palettes are arrays of SRT transformations. Palettes are often implemented as matrices, but they can contain SRT values.

Progressive Mesh Trimming

Low detail areas can afford to lose vertices which don't change the rendered appearance of the surface. This is especially true of objects as they move farther from the camera. This is referred to as level-of-detail. Users have API-level render controls for setting the level-of-detail to maximize rendering efficiency.

Progressive mesh objects start with a high number of faces and use simplification to reduce the number of faces. A progressive mesh that is view independent is referred to as a view-independent progressive mesh (VIPM).

Another way to reduce the number of faces is by trimming. This actually removes vertices and faces from the mesh. Trimming can be done at the high end (to limit the max number of faces) or at the low end (to limit the minimum number of faces.) Trimming improves draw performance, however, care should be used to preserve the visual quality. Trimming is demonstrated in the Progressive Mesh SDK Sample.

For high visibility areas, the resolution can be increased using progressive level of detail (PLOD). This is a technique for breaking a single face into two faces.

Patch Meshes

Two specialized types of patch meshes are also supported: rectangle and triangle patches. The rectangle patch mesh is a patch mesh whose control points are laid out in a winding, rectangular sequence. Rectangle and triangle patches are used to create high-order surfaces. They are not as commonly used as triangle meshes.


Texture Support in D3DX (Direct3D 9)

D3DX is a utility library that provides helper services. It is a layer above the Direct3D component.

Textures

Many different textures are supported in the following topics.

  • Standard mipmapped texture support. See Automatic Generation of Mipmaps (Direct3D 9).
  • Cube map support. See Cubic Environment Mapping (Direct3D 9).
  • Volume texture support. See Volume Texture Resources (Direct3D 9).
  • Environment mapping support. See Environment Mapping (Direct3D 9).
  • Bump mapping support. See Bump Mapping (Direct3D 9).

Texture Color Conversion

When using any of the D3DXLoadSurfacexxx, D3DXLoadVolumexxx, D3DXCreateTexturexxx, D3DXCreateCubeTexturexxx, or D3DXCreateVolumeTexturexxx functions, color conversion might need to be performed. For example, one surface might be type RGBA and the other might be UVWQ. For cases of dissimilar formats, the conversion sequence is as follows:

Mapping RGBA to UVWQ

  • R <-> U, R channel is mapped to the U channel, or vice versa.
  • G <-> V, G channel is mapped to the V channel, or vice versa.
  • B <-> W, B channel is mapped to the W channel, or vice versa.
  • A <-> Q/L, A channel is mapped to either the Q or the L channel (depending on which one is available in the destination format), or vice versa.
R->U
G->V
B->W
A->Q or A->L

Mapping UV to RGBA

  • U <-> R, U channel is mapped to the R channel, or vice versa.
  • V <-> G, V channel is mapped to the G channel, or vice versa.
  • 1 <-> B, 1 is mapped to the B channel, or vice versa.
  • 1 <-> A, 1 is mapped to the A channel, or vice versa.

If a channel does not exist in the source, it is assumed to be 1 (with the exception of A8, where R,G,B are assumed to be 0). For example:

U -> R
V -> G
1 -> B
1 -> A


X Files (Legacy) (Direct3D 9)

The X file format refers to files with the .x file name extension. X files were introduced with DirectX 2.0. A binary version of this format was subsequently released with DirectX 3.0, which is also described in this documentation. DirectX 6.0 introduced interfaces and methods that enable reading from and writing to .x files.

X files provide a template-driven format that enables the storage of meshes, textures, animations, and user-definable objects. Support for animation sets enables you to store predefined paths for playback in real time. Instancing and hierarchies are also supported. Instancing enables multiple references to an object, such as a mesh, while storing its data only once per file. Hierarchies are used to express relationships between data records.

The .x file format provides low-level data primitives on which applications define higher-level primitives through templates.

Three-dimensional models created in Discreet's 3ds max or Alias|Wavefront's Maya applications can be converted to .x files with the DirectX Extensions for Alias Maya.

This section describes the structure of .x files and how to use them in your applications. Information is divided into the following topics.

  • Loading an X File (Legacy) (Direct3D 9)
  • Saving to an X File (Legacy) (Direct3D 9)
  • Defining a Simple Cube (Direct3D 9)
  • Adding Textures (Direct3D 9)
  • Adding Frames and Animations (Direct3D 9)

For more information about the .x file format, see X File Reference.

For more information about the .x file API, see X File Reference (Legacy).


Loading an X File (Legacy) (Direct3D 9)

Use the following procedure in legacy applications to load a .x file.

  1. Use the DirectXFileCreate function to create an IDirectXFile object.
  2. If templates are present in the DirectX file that you will load, use the IDirectXFile::RegisterTemplates method to register those templates.
  3. Use the IDirectXFile::CreateEnumObject method to create an IDirectXFileEnumObject enumerator object.
  4. Loop through the objects in the file. For each object, perform the following steps.
    1. Use the IDirectXFileEnumObject::GetNextDataObject method to retrieve each IDirectXFileData object.
    2. Use the IDirectXFileData::GetType method to retrieve the data's type.
    3. Load the data using the IDirectXFileData::GetData method.
    4. If the object has optional members, retrieve the optional members by calling the IDirectXFileData::GetNextObject method.
    5. Release the IDirectXFileData object.
  5. Release the IDirectXFileEnumObject object.
  6. Release the IDirectXFile object.


Saving to an X File (Legacy) (Direct3D 9)

Use the following procedure in legacy applications to save .x file templates and data to a .x file.

  1. Use the DirectXFileCreate function to create an IDirectXFile object.
  2. Use the IDirectXFile::RegisterTemplates method to inform the DirectX file system about any templates that you will use.
  3. Use the IDirectXFile::CreateSaveObject method to create an IDirectXFileSaveObject object.
  4. Use the IDirectXFileSaveObject::SaveTemplates method to save templates, if desired.
  5. Loop through the objects to save. For each top-level object, perform the following steps.
    • Use the IDirectXFileSaveObject::CreateDataObject method to create an IDirectXFileData object as a top-level object in the file. If the top-level data object has optional child objects, add them to the object by using the appropriate method from the next step.
    • Each IDirectXFileData object can have optional child objects if its template allows it. The child objects can be any of the three types of objects: IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary. Loop through the objects you need to save, adding each optional child member to the object list in the manner appropriate to its type, as illustrated in the following steps. Then, if the object type is Data, call the IDirectXFileSaveObject::CreateDataObject method to create an IDirectXFileData object, and then call the IDirectXFileData::AddDataObject method to add it as a child of the object. If the object type is Data Reference, call the IDirectXFileData::AddDataReference method to create and add the data reference object as a child of the object. Or, if the object type is Binary, call the IDirectXFileData::AddBinaryObject method to create and add the binary object as a child of the object.
    • Call the IDirectXFileSaveObject::SaveData method to save the data object and its children.
    • Release the IDirectXFileData object.
  6. Release the IDirectXFileSaveObject object.
  7. Release the IDirectXFile object.


Defining a Simple Cube (Direct3D 9)

The following file defines a simple cube that has four red sides and two green sides. In this file, optional information is used to add information to the data object defined by the Mesh template.

Material RedMaterial {
1.000000;0.000000;0.000000;1.000000;;    // R = 1.0, G = 0.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}

Material GreenMaterial {
0.000000;1.000000;0.000000;1.000000;;     // R = 0.0, G = 1.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}

// Define a mesh with 8 vertices and 12 faces (triangles). Use
// optional data objects in the mesh to specify materials, normals,
// and texture coordinates.
Mesh CubeMesh {
8;                                // 8 vertices.
1.000000;1.000000;-1.000000;,     // Vertex 0.
-1.000000;1.000000;-1.000000;,    // Vertex 1.
-1.000000;1.000000;1.000000;,     // And so on.
1.000000;1.000000;1.000000;,
1.000000;-1.000000;-1.000000;,
-1.000000;-1.000000;-1.000000;,
-1.000000;-1.000000;1.000000;,
1.000000;-1.000000;1.000000;;

12;                      // 12 faces.
3;0,1,2;,                // Face 0 has three vertices.
3;0,2,3;,                // And so on.
3;0,4,5;,
3;0,5,1;,
3;1,5,6;,
3;1,6,2;,
3;2,6,7;,
3;2,7,3;,
3;3,7,4;,
3;3,4,0;,
3;4,7,6;,
3;4,6,5;;

// All required data has been defined. Now define optional data
// using the hierarchical nature of the file format.
MeshMaterialList {
2;                    // Number of materials used.
12;                   // A material for each face.
0,                    // Face 0 uses the first material.
0,
0,
0,
0,
0,
0,
0,
1,                    // Face 8 uses the second material.
1,
1,
1;;
{RedMaterial}         // References to the definitions
{GreenMaterial}       // of material 0 and 1.
}
MeshNormals {
8;                    // Define 8 normals.
0.333333;0.666667;-0.666667;,
-0.816497;0.408248;-0.408248;,
-0.333333;0.666667;0.666667;,
0.816497;0.408248;0.408248;,
0.666667;-0.666667;-0.333333;,
-0.408248;-0.408248;-0.816497;,
-0.666667;-0.666667;0.333333;,
0.408248;-0.408248;0.816497;;
12;                   // For the 12 faces, define the normals.
3;0,1,2;,
3;0,2,3;,
3;0,4,5;,
3;0,5,1;,
3;1,5,6;,
3;1,6,2;,
3;2,6,7;,
3;2,7,3;,
3;3,7,4;,
3;3,4,0;,
3;4,7,6;,
3;4,6,5;;
}
MeshTextureCoords {
8;                        // Define texture coords for each vertex.
0.000000;1.000000;
1.000000;1.000000;
0.000000;1.000000;
1.000000;1.000000;
0.000000;0.000000;
1.000000;0.000000;
0.000000;0.000000;
1.000000;0.000000;;
}


Adding Textures (Direct3D 9)

To add textures, use the hierarchical nature of the file format and add an optional TextureFilename data object to the Material data objects. The Material objects now read as follows:

Material RedMaterial {
1.000000;0.000000;0.000000;1.000000;;    // R = 1.0, G = 0.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
TextureFilename { "tex1.ppm"; }
}

Material GreenMaterial {
0.000000;1.000000;0.000000;1.000000;;     // R = 0.0, G = 1.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
TextureFilename { "win95.ppm"; }
}


Adding Frames and Animations (Direct3D 9)

This section shows how to add frames and animations to a simple cube.

Working with Frames

A frame is expected to take the following structure.

Frame Aframe {        // The frame name is chosen for convenience.
FrameTransformMatrix {
...transform data...
}
[ Meshes ] and/or [ More frames]
}

Place the defined cube mesh inside a frame with an identity transform. Then apply an animation to this frame.

Frame CubeFrame {
FrameTransformMatrix {
1.000000, 0.000000, 0.000000, 0.000000,
0.000000, 1.000000, 0.000000, 0.000000,
0.000000, 0.000000, 1.000000, 0.000000,
0.000000, 0.000000, 0.000000, 1.000000;;
}
{CubeMesh}        // You could have the mesh inline, but this
                  // uses an object reference instead.
}

Working with Animations

An animation is defined by a set of keys. A key is a time value associated with a scaling operation, an orientation, or a position.

Animation Animation0 {        // The name is chosen for convenience.
{ Frame that it applies to - normally a reference }
AnimationKey {
...animation key data...
}
{ ...more animation keys... }
}

Animations are then grouped into AnimationSets:

AnimationSet AnimationSet0 { // The name is chosen for convenience.
{ an animation - could be inline or a reference }
{ ... more animations ... }
}

Now take the cube through an animation.

AnimationSet AnimationSet0 {
Animation Animation0 {
{CubeFrame}    // Use the frame containing the cube.
AnimationKey {
2;             // Position keys
9;             // 9 keys
10; 3; -100.000000, 0.000000, 0.000000;;,
20; 3; -75.000000, 0.000000, 0.000000;;,
30; 3; -50.000000, 0.000000, 0.000000;;,
40; 3; -25.500000, 0.000000, 0.000000;;,
50; 3; 0.000000, 0.000000, 0.000000;;,
60; 3; 25.500000, 0.000000, 0.000000;;,
70; 3; 50.000000, 0.000000, 0.000000;;,
80; 3; 75.500000, 0.000000, 0.000000;;,
90; 3; 100.000000, 0.000000, 0.000000;;;
}
}
}

For more information, see the Animation and AnimationSet templates.


HLSL Shaders (Direct3D 9)

At a very high level, data enters the graphics pipeline as per-vertex data, is processed by each of the three stages, and generates pixel colors. Briefly, each stage of the pipeline performs a series of steps:

  • Vertex processing. This includes vertex transforms, per-vertex fog, per-vertex material attributes, and per-vertex lighting.
  • Primitive processing. This is comprised of clipping, back-face culling, and per-primitive attribute evaluation in preparation for rasterizing.
  • Pixel processing. This is broken into two parts:

    Part 1 blends texture samples with per-pixel colors, completely replacing the fixed function multi-texture blender. This processing includes: iterating colors and texture coordinates, sampling textures, and blending texture samples with lighting and material colors.

    Part 2 includes all the operations that determine what is written out to the frame buffer. This includes: alpha testing, depth testing, stencil testing, calculating per-pixel fog, alpha blending, dithering, and making gamma adjustments.

By making vertex processing and the first part of pixel processing programmable, the user can now dramatically extend the functionality of the pipeline by implementing custom functionality in each of these stages.

  • Vertex Shader Basics
  • Pixel Shader Basics
  • Language Basics
  • Writing HLSL Shaders
  • Using HLSL Shaders
  • HLSL Tutorials
  • Getting Started Debugging Shaders
  • Shader Model 3

Programmable high-level shader language (HLSL) shaders use the HLSL compiler to generate asm shader code from HLSL source code.

A Simple HLSL Shader

To program this enormous variability, a shader language called HLSL was created to design these programmable shaders. Simply design and build shaders in HLSL and compile each shader into an Asm shader.

Here is an example of a vertex shader that implements the minimum vertex processing. This shader transforms vertex position from object space to projection space and assigns per-vertex color from the vertex input.

float4x4 mWorldViewProj;  // World * View * Projection transformation

struct VS_OUTPUT
{
    float4 Position   : POSITION;  // vertex position
    float4 Diffuse    : COLOR0;    // vertex diffuse color
};

VS_OUTPUT Vertex_Shader_Transform(
    in float4 vPosition : POSITION,
    in float4 vColor : COLOR0
 )
{
    VS_OUTPUT Output;

    // Transform the vertex into projection space.
    Output.Position = mul( vPosition, mWorldViewProj );

    // Output the diffuse color.
    Output.Diffuse = vColor;

    return Output;
}

Here is an example of a simple pixel shader. This shader simply copies the interpolated per-vertex color data, and outputs a pixel color.

float4 Pixel_Shader( VS_OUTPUT in ) : COLOR0
{
    float4 color = in.Color;

    return color;
}

These shaders looks very much like C code and contain one global variable, one data structure, and two functions. By browsing these shaders you can see that:

  • The shaders are readable.
  • The shaders use standard HLSL math functions like mul (Direct3D 9 HLSL), which does a matrix multiply.
  • In addition to standard C syntax, HLSL introduces a few new data types like float4 and float4x4 that make it easier to map the shader to hardware shaders.
  • HLSL defines semantics like POSITION And COLOR0 for inputs that are streamed into the shader from a vertex buffer.


Vertex Shader Basics (Direct3D 9)

When in operation, a programmable vertex shader replaces the vertex processing done by the Microsoft Direct3D graphics pipeline. While using a vertex shader, state information regarding transformation and lighting operations is ignored by the fixed function pipeline. When the vertex shader is disabled and fixed function processing is returned, all current state settings apply.

Tessellation of high-order primitives should be done before the vertex shader executes. Implementations that perform surface tessellation after the shader processing must do so in a way that is not apparent to the application and shader code.

As a minimum, a vertex shader must output vertex position in homogeneous clip space. Optionally, the vertex shader can output texture coordinates, vertex color, vertex lighting, fog factors, and so on.

See Also

HLSL Shaders (Direct3D 9)


Pixel Shader Basics (Direct3D 9)

Pixel processing is performed by pixel shaders on individual pixels. Pixel shaders work in concert with vertex shaders; the output of a vertex shader provides the inputs for a pixel shader. Other pixel operations (fog blending, stencil operations, and render-target blending) occur after execution of the shader.

Texture Stage and Sampler States

A pixel shader completely replaces the pixel-blending functionality specified by the multi-texture blender including operations previously defined by the texture stage states. Texture sampling and filtering operations which were controlled by the standard texture stage states for minification, magnification, mip filtering, and the wrap addressing modes, can be initialized in shaders. The application is free to change these states without requiring the regeneration of the currently bound shader. Setting state can be made even easier if your shaders are designed within an effect.

Pixel Shader Inputs

For pixel shader versions ps_1_1 - ps_2_0, diffuse and specular colors are saturated (clamped) to the range 0 through 1 before use by the shader because this is the range of valid inputs to the shader.

Color values input to the pixel shader are assumed to be perspective correct, but this is not guaranteed in all hardware. Colors generated from texture coordinates by the address shader are always iterated in a perspective correct manner. However, they are also clamped to the range 0 to 1 during iteration.

Pixel Shader Outputs

For pixel shader versions ps_1_1 - ps_1_4, the result emitted by the pixel shader is the contents of register r0. Whatever it contains when the shader completes processing is sent to the fog stage and render-target blender.

For pixel shader versions ps_2_0 and above, output color is emitter from oC0 - oC4.

See Also

HLSL Shaders (Direct3D 9)


HLSL Language Basics (Direct3D 9)

This page has been deprecated. See Data Types (DirectX HLSL).


Writing HLSL Shaders (Direct3D 9)

  • Declaring Shader Variables
  • Uniform Shader Inputs
  • Varying Shader Inputs and Semantics
  • Samplers and Texture Objects
  • Writing Functions
  • Flow Control
  • Procedural Shaders
  • Writing Shader Fragments

Declaring Shader Variables

The simplest variable declaration includes a type and a variable name, such as this floating-point declaration:

float fVar;

You can initialize a variable in the same statement.

float fVar = 3.1f;

An array of variables can be declared,

int iVar[3];

or declared and initialized in the same statement.

int iVar[3] = {1,2,3};

Here are a few declarations that demonstrate many of the characteristics of high-level shader language (HLSL) variables:

float4 color;
uniform float4 position : POSITION;
const float4 lightDirection = {0,0,1};

Data declarations can use any valid type including:

  • basic types
  • vector types
  • matrix types
  • shader types
  • sampler type
  • user-defined types.

A shader can have top-level variables, arguments, and functions.

// top-level variable
float globalShaderVariable;

// top-level function
void function(
in float4 position: POSITION0 // top-level argument
              )
{
  float localShaderVariable; // local variable
  function2(...)
}

void function2()
{
  ...
}

Top-level variables are declared outside of all functions. Top-level arguments are parameters to a top-level function. A top-level function is any function called by the application (as opposed to a function that is called by another function).

Uniform Shader Inputs

Vertex and pixel shaders accept two kinds of input data: varying and uniform. The varying input is the data that is unique to each execution of the shader. For a vertex shader, the varying data (for example: position, normal, etc.) comes from the vertex streams. The uniform data (for example: material color, world transform, etc.) is constant for multiple executions of a shader. For those familiar with the assembly shader models, uniform data is specified by constant registers and varying data by the v and t registers.

Uniform data can be specified by two methods. The most common method is to declare global variables and use them within a shader. Any use of global variables within a shader will result in adding that variable to the list of uniform variables required by that shader. The second method is to mark an input parameter of the top-level shader function as uniform. This marking specifies that the given variable should be added to the list of uniform variables.

Uniform variables used by a shader are communicated back to the application via the constant table. The constant table is the name for the symbol table that defines how the uniform variables used by a shader fit into the constant registers. The uniform function parameters appear in the constant table prepended with a dollar sign ($), unlike the global variables. The dollar sign is required to avoid name collisions between local uniform inputs and global variables of the same name.

The constant table contains the constant register locations of all uniform variables used by the shader. The table also includes the type information and the default value, if specified.

Varying Shader Inputs and Semantics

Varying input parameters (of a top-level shader function) must be marked either with a semantic or uniform keyword indicating the value is constant for the execution of the shader. If a top-level shader input is not marked with a semantic or uniform keyword, then the shader will fail to compile.

The input semantic is a name used to link the given input to an output of the previous part of the graphics pipeline. For example, the input semantic POSITION0 is used by the vertex shaders to specify where the position data from the vertex buffer should be linked.

Pixel and vertex shaders have different sets of input semantics due to the different parts of the graphics pipeline that feed into each shader unit. Vertex shader input semantics describe the per-vertex information (for example: position, normal, texture coordinates, color, tangent, binormal, etc.) to be loaded from a vertex buffer into a form that can be consumed by the vertex shader. The input semantics directly map to the vertex declaration usage and the usage index.

Pixel shader input semantics describe the information that is provided per pixel by the rasterization unit. The data is generated by interpolating between outputs of the vertex shader for each vertex of the current primitive. The basic pixel shader input semantics link the output color and texture coordinate information to input parameters.

Input semantics can be assigned to shader input by two methods:

  • Appending a colon and the semantic name to the parameter declaration.
  • Defining an input structure with input semantics assigned to each structure member.

Vertex and pixel shaders provide output data to the subsequent graphics pipeline stage. Output semantics are used to specify how data generated by the shader should be linked to the inputs of the next stage. For example, the output semantics for a vertex shader are used to link the outputs of the interpolators in the rasterizer to generate the input data for the pixel shader. The pixel shader outputs are the values provided to the alpha blending unit for each of the render targets or the depth value written to the depth buffer.

Vertex shader output semantics are used to link the shader both to the pixel shader and to the rasterizer stage. A vertex shader that is consumed by the rasterizer and not exposed to the pixel shader must generate position data as a minimum. Vertex shaders that generate texture coordinate and color data provide that data to a pixel shader after interpolation is done.

Pixel shader output semantics bind the output colors of a pixel shader with the correct render target. The pixel shader output color is linked to the alpha blend stage, which determines how the destination render targets are modified. The pixel shader depth output can be used to change the destination depth values at the current raster location. The depth output and multiple render targets are only supported with some shader models.

The syntax for output semantics is identical to the syntax for specifying input semantics. The semantics can be either specified directly on parameters declared as "out" parameters or assigned during the definition of a structure that either returned as an "out" parameter or the return value of a function.

Semantics identify where data comes from. Semantics are optional identifiers that identify shader inputs and outputs. Semantics appear in one of three places:

  • After a structure member.
  • After an argument in a function's input argument list.
  • After the function's input argument list.

This example uses a structure to provide one or more vertex shader inputs, and another structure to provide one or more vertex shader outputs. Each of the structure members uses a semantic.

vector vClr;

struct VS_INPUT
{
    float4 vPosition : POSITION;
    float3 vNormal : NORMAL;
    float4 vBlendWeights : BLENDWEIGHT;
};

struct VS_OUTPUT
{
    float4  vPosition : POSITION;
    float4  vDiffuse : COLOR;

};

float4x4 mWld1;
float4x4 mWld2;
float4x4 mWld3;
float4x4 mWld4;

float Len;
float4 vLight;

float4x4 mTot;

VS_OUTPUT VS_Skinning_Example(const VS_INPUT v, uniform float len=100)
{
    VS_OUTPUT out;

    // Skin position (to world space)
    float3 vPosition =
        mul(v.vPosition, (float4x3) mWld1) * v.vBlendWeights.x +
        mul(v.vPosition, (float4x3) mWld2) * v.vBlendWeights.y +
        mul(v.vPosition, (float4x3) mWld3) * v.vBlendWeights.z +
        mul(v.vPosition, (float4x3) mWld4) * v.vBlendWeights.w;
    // Skin normal (to world space)
    float3 vNormal =
        mul(v.vNormal, (float3x3) mWld1) * v.vBlendWeights.x +
        mul(v.vNormal, (float3x3) mWld2) * v.vBlendWeights.y +
        mul(v.vNormal, (float3x3) mWld3) * v.vBlendWeights.z +
        mul(v.vNormal, (float3x3) mWld4) * v.vBlendWeights.w;

    // Output stuff
    out.vPosition    = mul(float4(vPosition + vNormal * Len, 1), mTot);
    out.vDiffuse  = dot(vLight,vNormal);

    return out;
}

The input structure identifies the data from the vertex buffer that will provide the shader inputs. This shader maps the data from the position, normal, and blendweight elements of the vertex buffer into vertex shader registers. The input data type does not have to exactly match the vertex declaration data type. If it doesn't exactly match, the vertex data will automatically be converted into the HLSL's data type when it is written into the shader registers. For instance, if the normal data were defined to be of type UINT by the application, it would be converted into a float3 when read by the shader.

If the data in the vertex stream contains fewer components than the corresponding shader data type, the missing components will be initialized to 0 (except for w, which is initialized to 1).

Input semantics are similar to the values in the D3DDECLUSAGE.

The output structure identifies the vertex shader output parameters of position and color. These outputs will be used by the pipeline for triangle rasterization (in primitive processing). The output marked as position data denotes the position of a vertex in homogenous space. As a minimum, a vertex shader must generate position data. The screen space position is computed after the vertex shader completes by dividing the (x, y, z) coordinate by w. In screen space, -1 and 1 are the minimum and maximum x and y values of the boundaries of the viewport, while z is used for z-buffer testing.

Output semantics are also similar to the values in D3DDECLUSAGE. In general, an output structure for a vertex shader can also be used as the input structure for a pixel shader, provided the pixel shader does not read from any variable marked with the position, point size, or fog semantics. These semantics are associated with per-vertex scalar values that are not used by a pixel shader. If these values are needed for the pixel shader, they can be copied into another output variable that uses a pixel shader semantic.

Global variables are assigned to registers automatically by the compiler. Global variables are also called uniform parameters because the contents of the variable is the same for all pixels processed each time the shader is called. The registers are contained in the constant table, which can be read using the ID3DXConstantTable interface.

Input semantics for pixel shaders map values into specific hardware registers for transport between vertex shaders and pixel shaders. Each register type has specific properties. Because there are currently only two semantics for color and texture coordinates, it is common for most data to be marked as a texture coordinate even when it is not.

Notice that the vertex shader output structure used an input with position data, which is not used by the pixel shader. HLSL allows valid output data of a vertex shader that is not valid input data for a pixel shader, provided that it is not referenced in the pixel shader.

Input arguments can also be arrays. Semantics are automatically incremented by the compiler for each element of the array. For instance, consider the following explicit declaration:

struct VS_OUTPUT
{
    float4 Position   : POSITION;
    float3 Diffuse    : COLOR0;
    float3 Specular   : COLOR1;
    float3 HalfVector : TEXCOORD3;
    float3 Fresnel    : TEXCOORD2;
    float3 Reflection : TEXCOORD0;
    float3 NoiseCoord : TEXCOORD1;
};

float4 Sparkle(VS_OUTPUT In) : COLOR

The explicit declaration given above is equivalent to the following declaration that will have semantics automatically incremented by the compiler:

float4 Sparkle(float4 Position : POSITION,
                 float3 Col[2] : COLOR0,
                 float3 Tex[4] : TEXCOORD0) : COLOR0
{
   // shader statements
   ...

Just like input semantics, output semantics identify data usage for pixel shader output data. Many pixel shaders write to only one output color. Pixel shaders can also write out a depth value into one or more multiple render targets at the same time (up to four). Like vertex shaders, pixel shaders use a structure to return more than one output. This shader writes 0 to the color components, as well as to the depth component.

struct PS_OUTPUT
{
    float4 Color[4] : COLOR0;
    float  Depth  : DEPTH;
};

PS_OUTPUT main(void)
{
    PS_OUTPUT out;

   // Shader statements
   ...

  // Write up to four pixel shader output colors
  out.Color[0] =  ...
  out.Color[1] =  ...
  out.Color[2] =  ...
  out.Color[3] =  ...

  // Write pixel depth
  out.Depth =  ...

    return out;
}

Pixel shader output colors must be of type float4. When writing multiple colors, all output colors must be used contiguously. In other words, COLOR1 cannot be an output unless COLOR0 has already been written. Pixel shader depth output must be of type float1.

Samplers and Texture Objects

A sampler contains sampler state. Sampler state specifies the texture to be sampled, and controls the filtering that is done during sampling. Three things are required to sample a texture:

  • A texture
  • A sampler (with sampler state)
  • A sampling instruction

Samplers can be initialized with textures and sampler state as shown here:

sampler s = sampler_state
{
  texture = NULL;
  mipfilter = LINEAR;
};

Here's an example of the code to sample a 2D texture:

texture tex0;
sampler2D s_2D;

float2 sample_2D(float2 tex : TEXCOORD0) : COLOR
{
  return tex2D(s_2D, tex);
}

The texture is declared with a texture variable tex0.

In this example, a sampler variable named s_2D is declared. The sampler contains the sampler state inside of curly braces. This includes the texture that will be sampled and, optionally, the filter state (that is, wrap modes, filter modes, etc.). If the sampler state is omitted, a default sampler state is applied specifying linear filtering and a wrap mode for the texture coordinates. The sampler function takes a two-component floating-point texture coordinate, and returns a two-component color. This is represented with the float2 return type and represents data in the red and green components.

Four types of samplers are defined (see Keywords) and texture lookups are performed by the intrinsic functions: tex1D (Direct3D 9 HLSL), tex2D (Direct3D 9 HLSL), tex3D (Direct3D 9 HLSL), texCUBE (Direct3D 9 HLSL). Here is an example of 3D sampling:

texture tex0;
sampler3D s_3D;

float3 sample_3D(float3 tex : TEXCOORD0) : COLOR
{
  return tex3D(s_3D, tex);
}

This sampler declaration uses default sampler state for the filter settings and address mode.

Here is the corresponding cube sampling example:

texture tex0;
samplerCUBE s_CUBE;

float3 sample_CUBE(float3 tex : TEXCOORD0) : COLOR
{
  return texCUBE(s_CUBE, tex);
}

And finally, here is is the 1D sampling example:

texture tex0;
sampler1D s_1D;

float sample_1D(float tex : TEXCOORD0) : COLOR
{
  return tex1D(s_1D, tex);
}

Because the runtime does not support 1D textures, the compiler will use a 2D texture with the knowledge that the y-coordinate is unimportant. Since tex1D (Direct3D 9 HLSL) is implemented as a 2D texture lookup, the compiler is free to choose the y-component in an efficient manner. In some rare scenarios, the compiler cannot choose an efficient y-component, in which case it will issue a warning.

texture tex0;
sampler s_1D_float;

float4 main(float texCoords : TEXCOORD) : COLOR
{
    return tex1D(s_1D_float, texCoords);
}

This particular example is inefficient because the compiler must move the input coordinate into another register (because a 1D lookup is implemented as a 2D lookup and the texture coordinate is declared as a float1). If the code is rewritten using a float2 input instead of a float1, the compiler can use the input texture coordinate because it knows that y is initialized to something.

texture tex0;
sampler s_1D_float2;

float4 main(float2 texCoords : TEXCOORD) : COLOR
{
    return tex1D(s_1D_float2, texCoords);
}

All texture lookups can be appended with "bias" or "proj" (that is, tex2Dbias (Direct3D 9 HLSL), texCUBEproj (Direct3D 9 HLSL)). With the "proj" suffix, the texture coordinate is divided by the w-component. With "bias," the mip level is shifted by the w-component. Thus, all texture lookups with a suffix always take a float4 input. tex1D (Direct3D 9 HLSL) and tex2D (Direct3D 9 HLSL) ignore the yz- and z-components respectively.

Samplers may also be used in array, although no back end currently supports dynamic array access of samplers. Therefore, the following is valid because it can be resolved at compile time:

tex2D(s[0],tex)

However, this example is not valid.

tex2D(s[a],tex)

Dynamic access of samplers is primarily useful for writing programs with literal loops. The following code illustrates sampler array accessing:

sampler sm[4];

float4 main(float4 tex[4] : TEXCOORD) : COLOR
{
    float4 retColor = 1;

    for(int i = 0; i < 4;i++)
    {
        retColor *= tex2D(sm[i],tex[i]);
    }

    return retColor;
}

Note

Using the Microsoft Direct3D debug runtime can help you catch mismatches between the number of components in a texture and a sampler.

Writing Functions

Functions break large tasks into smaller ones. Small tasks are easier to debug and can be reused, once proven. Functions can be used to hide details of other functions, which makes a program composed of functions easier to follow.

HLSL functions are similar to C functions in several ways: They both contain a definition and a function body and they both declare return types and argument lists. Like C functions, HLSL validation does type checking on the arguments, argument types, and the return value during shader compilation.

Unlike C functions, HLSL entry point functions use semantics to bind function arguments to shader inputs and outputs (HLSL functions called internally ignore semantics). This makes it easier to bind buffer data to a shader, and bind shader outputs to shader inputs.

A function contains a declaration and a body, and the declaration must precede the body.

float4 VertexShader_Tutorial_1(float4 inPos : POSITION ) : POSITION
{
    return mul(inPos, WorldViewProj );
};

The function declaration includes everything in front of the curly braces:

float4 VertexShader_Tutorial_1(float4 inPos : POSITION ) : POSITION

A function declaration contains:

  • A return type
  • A function name
  • An argument list (optional)
  • An output semantic (optional)
  • An annotation (optional)

The return type can be any of the HLSL basic data types such as a float4:

float4 VertexShader_Tutorial_1(float4 inPos : POSITION ) : POSITION
{
   ...
}

The return type can be a structure that has already been defined:

struct VS_OUTPUT
{
    float4  vPosition        : POSITION;
    float4  vDiffuse         : COLOR;
};

VS_OUTPUT VertexShader_Tutorial_1(float4 inPos : POSITION )
{
   ...
}

If the function does not return a value, void can be used as the return type.

void VertexShader_Tutorial_1(float4 inPos : POSITION )
{
   ...
}

The return type always appears first in a function declaration.

float4 VertexShader_Tutorial_1(float4 inPos : POSITION ) : POSITION

An argument list declares the input arguments to a function. It may also declare values that will be returned. Some arguments are both input and output arguments. Here is an example of a shader that takes four input arguments.

float4 Light(float3 LightDir : TEXCOORD1,
             uniform float4 LightColor,
             float2 texcrd : TEXCOORD0,
             uniform sampler samp) : COLOR
{
    float3 Normal = tex2D(samp,texcrd);

    return dot((Normal*2 - 1), LightDir)*LightColor;
}

This function returns a final color, that is a blend of a texture sample and the light color. The function takes four inputs. Two inputs have semantics: LightDir has the TEXCOORD1 semantic, and texcrd has the TEXCOORD0 semantic. The semantics mean that the data for these variables will come from the vertex buffer. Even though the LightDir variable has a TEXCOORD1 semantic, the parameter is probably not a texture coordinate. The TEXCOORDn semantic type is often used to supply a semantic for a type that is not predefined (there is no vertex shader input semantic for a light direction).

The other two inputs LightColor and samp are labeled with the uniform keyword. These are uniform constants that will not change between draw calls. The values for these parameters come from shader global variables.

Arguments can be labeled as inputs with the in keyword, and output arguments with the out keyword. Arguments cannot be passed by reference; however, an argument can be both an input and an output if it is declared with the inout keyword. Arguments passed to a function that are marked with the inout keyword are considered copies of the original until the function returns, and they are copied back. Here's an example using inout:

void Increment_ByVal(inout float A, inout float B)
{
    A++; B++;
}

This function increments the values in A and B and returns them.

The function body is all of the code after the function declaration.

float4 VertexShader_Tutorial_1(float4 inPos : POSITION ) : POSITION
{
    return mul(inPos, WorldViewProj );
};

The body consists of statements which are surrounded by curly braces. The function body implements all of the functionality using variables, literals, expressions, and statements.

The shader body does two things: it performs a matrix multiply and returns a float4 result. The matrix multiply is accomplished with the mul (Direct3D 9 HLSL) function, which performs a 4x4 matrix multiply. mul (Direct3D 9 HLSL) is called an intrinsic function because it is already built into the HLSL library of functions. Intrinsic functions will be covered in more detail in the next section.

The matrix multiply combines an input vector Pos and a composite matrix WorldViewProj. The result is position data transformed into screen space. This is the minimum vertex shader processing we can do. If we were using the fixed function pipeline instead of a vertex shader, the vertex data could be drawn after doing this transform.

The last statement in a function body is a return statement. Just like C, this statement returns control from the function to the statement that called the function.

Function return types can be any of the simple data types defined in HLSL, including bool, int half, float, and double. Return types can be one of the complex data types such as vectors and matrices. HLSL types that refer to objects cannot be used as return types. This includes pixelshader, vertexshader, texture, and sampler.

Here is an example of a function that uses a structure for a return type.

float4x4 WorldViewProj : WORLDVIEWPROJ;

struct VS_OUTPUT
{
    float4 Pos  : POSITION;
};

VS_OUTPUT VS_HLL_Example(float4 inPos : POSITION )
{
    VS_OUTPUT Out;

    Out.Pos = mul(inPos,  WorldViewProj );

    return Out;
};

The float4 return type has been replaced with the structure VS_OUTPUT, which now contains a single float4 member.

A return statement signals the end of a function. This is the simplest return statement. It returns control from the function to the calling program. It returns no value.

void main()
{
    return ;
}

A return statement can return one or more values. This example returns a literal value:

float main( float input : COLOR0) : COLOR0
{
    return 0;
}

This example returns the scalar result of an expression:

return  light.enabled = true ;

This example returns a float4 constructed from a local variable and a literal:

return  float4(color.rgb, 1) ;

This example returns a float4 that is constructed from the result returned from an intrinsic function, and a few literal values:

float4 func(float2 a: POSITION): COLOR
{
    return float4(sin(length(a) * 100.0) * 0.5 + 0.5, sin(a.y * 50.0), 0, 1);
}

This example returns a structure that contains one or more members:

float4x4 WorldViewProj;

struct VS_OUTPUT
{
    float4 Pos  : POSITION;
};

VS_OUTPUT VertexShader_Tutorial_1(float4 inPos : POSITION )
{
    VS_OUTPUT out;
    out.Pos = mul(inPos, WorldViewProj );
    return out;
};

Flow Control

Most current vertex and pixel shader hardware is designed to run a shader line by line, executing each instruction once. HLSL supports flow control, which includes static branching, predicated instructions, static looping, dynamic branching, and dynamic looping.

Previously, using an if statement resulted in assembly-language shader code that implements both the if side and the else side of the code flow. Here is an example of the in HLSL code that was compiled for vs_1_1:

if (Value > 0)
    oPos = Value1;
else
    oPos = Value2;

And here is the resulting assembly code:

// Calculate linear interpolation value in r0.w
mov r1.w, c2.x
slt r0.w, c3.x, r1.w
// Linear interpolation between value1 and value2
mov r7, -c1
add r2, r7, c0
mad oPos, r0.w, r2, c1

Some hardware allows for either static or dynamic looping, but most require linear execution. On the models that do not support looping, all loops must be unrolled. An example is the DepthOfField Sample sample that uses unrolled loops even for ps_1_1 shaders.

HLSL now includes support for each of these types of flow control:

  • static branching
  • predicated instructions
  • static looping
  • dynamic branching
  • dynamic looping

The most common branching support in current hardware shading models is static branching. Static branching is a capability in a shader model that allows for blocks of code to be switched on or off based on a Boolean shader constant. This is a convenient method for enabling or disabling code paths based on the type of object currently being rendered. Between draw calls, you can decide which features you want to support with the current shader and then set the Boolean flags required to get that behavior. Now that HLSL supports branching, any statements that are disabled by a Boolean constant are skipped during execution.

The most familiar branching support is dynamic branching. With dynamic branching, the comparison condition resides in a variable, which means that the comparison is done for each vertex or each pixel at run time (as opposed to the comparison occuring at compile time, or between two draw calls). The performance hit is the cost of the branch plus the cost of the instructions on the side of the branch taken. Dynamic branching is currently available for vertex shaders. Optimizing shaders that work with these models is similar to optimizing code that runs on a CPU.

Procedural Shaders

What is it, how is it created, how is it compiled and rendered. D3DXFillVolumeTextureTX. HLSL workshop, Goal 4 uses a procedural texture.

Writing Shader Fragments

A fragment is a stand-alone shader function. A fragment can be compiled from a vertex shader or a pixel shader. By building encapsulated shader functions, they can be linked together to increase functionality.

You can share parameters from one fragment with another fragment using a semantic. Fragments can be compiled and linked at run time, or compiled offline and linked at run time. One way to use fragments is to generate overloaded shader functions so that each fragment can be compiled for a different compile target. This is a convenient way to use fragments to cover a range of shader models within an effect.

HLSL and assembly fragments can be linked with a fragment linker. The linker (ID3DXFragmentLinker) generates a symbol table that contains the constant table (ID3DXConstantTable). The linker can also optimize register use and remove dead code. Since the linker is part of D3DX, it can be updated independently of the runtime.

HLSL Fragment Syntax

You can turn any HLSL function into a shader fragment by adding a fragment declaration (see Fragment Declaration Syntax (Direct3D 9 HLSL)). Each parameter that is shared between fragments must be marked by adding an r_ prefix to its semantic. The semantic provides a data link between shared fragment parameters, and is used to build the vertex declaration. Each parameter that is not shared does not need the r_ prefix with its semantic.

Any HLSL function can be converted to a fragment. There are a few shader fragments in the FragmentLinker Sample. For example, here is a vertex shader fragment called AmbientDiffuse, that calculates ambient and diffuse scene lighting:

float3 g_vLightPosition = float3( 0.0f, 5.0f, -5.0f );
float4 g_vLightColor = float4( 1.0f, 1.0f, 1.0f, 1.0f );
float4 g_vMaterialAmbient = float4( 0.3f, 0.3f, 0.3f, 1.0f );
float4 g_vMaterialDiffuse = float4( 0.6f, 0.6f, 0.6f, 1.0f );

void AmbientDiffuse( float3 vPosWorld: r_PosWorld,
                     float3 vNormalWorld: r_NormalWorld,
                     out float4 vColor: COLOR0 )
{
    // Compute the light vector
    float3 vLight = normalize( g_vLightPosition - vPosWorld );

    // Compute the ambient and diffuse components of illumination
    vColor = g_vLightColor * g_vMaterialAmbient;
    vColor += g_vLightColor * g_vMaterialDiffuse * saturate( dot( vLight, vNormalWorld ) );
}
vertexfragment AmbientDiffuseFragment = compile_fragment vs_1_1 AmbientDiffuse();

The shader uses two shared parameters: vPosWorld and vNormalWorld. They are shared parameters because each of them has a custom semantic attached to it (r_PosWorld and r_NormalWorld). The last line of code is the fragment declaration.

Here is an example of a vertex shader fragment that does not have any shared parameters:

float4 g_vLightColor = float4( 1.0f, 1.0f, 1.0f, 1.0f );
float4 g_vMaterialAmbient = float4( 0.3f, 0.3f, 0.3f, 1.0f );

void Ambient( out float4 vColor: COLOR0 )
{
    // Compute the ambient component of illumination
    vColor = g_vLightColor * g_vMaterialAmbient;
}
vertexfragment AmbientFragment = compile_fragment vs_1_1 Ambient();

The fragment still requires the fragment declaration; but because there are no shared parameters, the color argument has a standard semantic with no r_ prefix.

Here's an example of a pixel shader fragment:

texture  g_MeshTexture;             // Color texture for mesh

sampler MeshTextureSampler =
sampler_state
{
    Texture = <g_MeshTexture>;
    MipFilter = LINEAR;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
};

void ModulateTexture( float4 vColorIn: COLOR0,
                      float2 vTexCoord: TEXCOORD0,
                      out float4 vColorOut: COLOR0 )
{
    // Sample and modulate the texture
    vColorOut = vColorIn * tex2D( MeshTextureSampler, vTexCoord );
}
pixelfragment PixelFragment = compile_fragment ps_2_0 ModulateTexture();

This pixel shader fragment is called ModulateTexture because it multiplies (or modulates) the input color by the sampled texture color. Just like an HLSL vertex shader fragment, an HLSL pixel shader fragment also requires a fragment declaration.

Each fragment declaration consists of the following:

  • a keyword that identifies the shader type VertexFragment or PixelFragment
  • the fragment name
  • the compile_fragment keyword
  • the shader compile target
  • the shader function name

Unlike a function prototype in C, a fragment declaration can occur before or after the shader fragment. For more about fragment declaration syntax, see Fragment Declaration Syntax (Direct3D 9 HLSL).

The shader compile target is included in the fragment declaration because each fragment is compiled (and validated) against this specific shader model (vs_1_1 in this case). When running an application, it is still the application's responsibility to check the hardware to make sure that it will support this shader model.

Assembly Fragment Syntax

Assembly fragment syntax is similar to the syntax of an assembly block in an effect file. The only difference is that the asm_fragment keyword is used instead of the asm keyword. Unlike HLSL, an assembly fragment does not require a fragment declaration. In assembly, the shared parameters require a custom semantic for each type of register:

  • Use c_ for constant registers.
  • Use r_ for temp registers.
  • Use v_ for input registers.

The semantic provides a data link between shared fragment parameters, and is used to build the vertex declaration. Each shared constant register must be defined at global scope.

Here is an example of a vertex shader fragment created from an assembly shader. The declaration contains the assembly block, with the c_, r_, and v_ prefix on the appropriate shared parameters:

vertexfragment ComputeGlowAsm =
asm_fragment
{
    vs_1_1

    dp3 r_Length.w, r_TransformedNormal.xyz, r_TransformedNormal.xyz
    rsq r_Length.w, r_Length.w
    mul r_TransformedNormal.xyz, r_TransformedNormal.xyz, r_Length.www
    mov r_Temp.x, c_One.x

    mad r_Power.z, r_TransformedNormal.z, -r_TransformedNormal.z, c_One.x
    mul r_Power.z, r_Power.z, r_Power.z
    mul oD0, c_vGlowColor, r_Power.z

    mad r_TransformedPosition.xyz, r_TransformedNormal.xyz,
                          c_vDisplace.xxx, r_TransformedPosition.xyz
    mov r_TransformedPosition.w, c_One.x
    m4x4 oPos, r_TransformedPosition, c_mProjection
};


Using HLSL Shaders in Direct3D 9 (Direct3D 9)

This page has been deprecated. See Shaders.


HLSL Tutorials (Direct3D 9)

The HLSL Workshop is a set of tutorials that make it easy to learn how to generate high-level shader language (HLSL) shaders. The tutorials offer a step-by-step approach to learning how to use vertex, pixel, and texture shaders in HLSL to create the following functionality:

  • Goal 1 - Hemispheric Lighting Tutorial
  • Goal 2: Vertex Animation Tutorial
  • Goal 3 - Environment Mapping
  • Goal 4 - Procedural Texture Tutorial

If you already have the right tools installed, you can also try the Goal 5 - Shader Debugging Tutorial. To see more about all the features of the debugger, see Shader Debugger.


Getting Started Debugging Shaders (Direct3D 9)

Do you want to debug your vertex and pixel shader code by stepping through the per-vertex code or the per-pixel code and watching instructions as they are executed, looking at the values in shader constants and variables, and setting breakpoints in trouble spots? The Microsoft DirectX extensions for Microsoft Visual Studio .NET, which we will refer to as the shader debugger, is fully integrated into the Visual Studio .NET Integrated Development Environment (IDE).

In order to prepare for shader debugging, you must install the right tools on your machine. These are listed below. If you already have the right tools installed, you can also try the Goal 5 - Shader Debugging Tutorial. To see more about all the features of the debugger, see Shader Debugger.

Using the Shader Debugger

Here is a list of some of the operations that you can perform within the IDE while a shader is running:

  • Debug vertex and pixel shaders.
  • Debug high-level shader language (HLSL) and assembly shaders.
  • Look at the contents of variables, registers, and device state.
  • Use the IDE to run the code, single step through code, or break where necessary.
  • Set breakpoints on lines or on a pixel area.
  • Perform expression evaluation in a watch window.
  • View the assembly code generated by the HLSL compiler.
  • View loaded texture(s) on the Direct3D device.
  • View render target(s) as pixel shaders write to them.
  • See syntax coloring for recognized file types, including: .fx (effects files), .vsh (assembly vertex shader files), and .psh (assembly pixel shader files).

Setting Up the Tools

To prepare for debugging, you must load the right tools on your machine, configure the runtime, and set up your application for debugging. This section will walk you through each of these preparation steps:

  • Install Visual Studio .NET
  • Install the DirectX SDK (install the software development kit (SDK) and the shader debugger from the SDK)
  • Enable Debug Mode from the Control Panel

Install Visual Studio .NET

Visual Studio .NET provides a compiler and debugging tools for several programming languages within an interactive development environment. The shader debugger is a Visual Studio .NET extension, meaning that it is designed and integrated into Visual Studio .NET. To perform shader debugging with this extension, you will need to have access to Visual Studio .NET. For information about getting Visual Studio .NET as well as the installation instructions, see 2002 or 2003.

Install the DirectX SDK

The shader debugger is installed as part of the DirectX SDK install. In fact, you must install the SDK for two reasons: you will need the proper debug or reference DLL's, and you will need the shader debugger. The DirectX debug DLL's or the reference DLL can be used to debug vertex shaders, but a reference DLL must be used to debug a pixel shader.

The SDK install wizard takes care of most of this for you, but here is a step-by-step description for installing the SDK and the shader debugger:

  1. Install the DirectX SDK.
  2. Click Next on the InstallShield Wizard.
  3. Select the Add radio button if you don't have the SDK on your machine. Or select Modify if you have the SDK installed, but you want to change something (such as adding the shader debugger).

  4. In the Custom Setup panel, you will see a listing of all the resources available on the CD. Anything marked with the red X will not be installed. Because we want to debug shaders, we need to make sure the shader debugger will be installed. This is in the DirectX Utilities folder, and is called DirectX extensions for Visual Studio .NET. If this does not have a red X on it, it will be installed. If it does have the red X, left click on the X and select "This feature will be installed on the local hard drive". It should look like this when you are done.

  5. Click Next one more time and wait for the install wizard to finish installing the SDK. This can take a few minutes, especially if you copy all the samples (C++, C#, and VB) to your hard drive. When the install finishes, you will get a message that it was successful. In addition you can now start Visual Studio .NET and check it to see the following on the splash screen when it starts up:

    The DirectX extensions for Visual Studio .NET logo in the bottom right corner means that Visual Studio .NET has the extensions loaded, and is now available for shader debugging.

Enable Debug Mode from the Control Panel

If you are are ready to enable the debug switches in the control panel, then you must already have done the following:

  • Install Visual Studio .NET
  • Install the DirectX SDK

With all the right tools installed, the next step is to enable the debugger settings. This is easily done by launching the DirectX dialog box from the control panel (Start/Control Panel/DirectX). This will open up a dialog box that looks like this:

There are a number of settings on this dialog box, but we are interested in two in particular to enable shader debugging. These are:

  • In the Debug/Retail D3D Runtime group of controls, select the Use Debug Version of Direct3D radio button. This tells DirectX to use the debug version of the dynamic-link libraries (DLLs) which allows you to debug any vertex shader that your graphics adapter supports. If you set this to retail, Direct3D will run the release DLLs which do not support any type of shader debugging.
  • In the Debugging group of controls, set the Enable Shader Debugging check box. This enables Visual Studio .NET to debug shader code.

The debug mode can also be enabled from within Visual Studio .NET by clicking on Tools | Options | Debugger | DirectX.

This concludes preparing the tools for shader debugging. In summary, you need to rememember to:

  • Install Visual Studio .NET.
  • Install the DirectX SDK with debug or reference DLLs and the shader debugger.
  • Enable the DirectX debug flags.

Choosing the Device Type

To debug a shader, the shader must be running on the right type of Direct3D device since vertex and pixel shaders can only be debugged on certain devices. Once you determine whether you want to debug a vertex shader, a pixel shader, or both, you can use the following table to choose a device type that supports debug.

 | HAL Device | HAL Device | REF Device | REF Device
Shader | SWVP | HWVP or pure HWVP | SWVP | HWVP or pure HWVP
Vertex Shader | Yes, with the debug runtime | No | Yes, with the debug runtime | No
Pixel Shader | No | No | Yes | Yes

Choose the device type(s) that support the type of shader you want to debug. Then when your application runs create that device type with IDirect3D9::CreateDevice. The SDK samples also use F2 to switch the device type once the sample is running. Any entry in the table that says "No" means that it is not possible to debug that type of shader on that type of device.

Setting the Shader Flags

With the device type chosen, you can now make the appropriate choice for the shader compile flags. These flags are one or more #defines that are enumerated in D3DXSHADER Flags. These flags are specified at shader creation time when calling functions like D3DXCompileShaderXXX, ID3DXEffectCompiler::CompileShader or ID3DXEffectCompiler::CompileEffect.

Since we want to debug the shader, we need to use these two flags:

  • D3DXSHADER_DEBUG tells the compiler to build a shader with source debugging information.
  • D3DXSHADER_SKIPOPTIMIZATION tells the compiler to skip optimization. Optimization may reorder instructions; this is good for making shaders fast, but also makes debugging more difficult. On the other hand, unoptimized shaders might exceed the maximum instruction limits if they are close to the limits without optimization.

If you run into the problem of exceeding instruction slot limits when running unoptimized, there is an additional flag that you can choose. D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT (or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT) force the compiler to compile against the next higher available software target. Because software shader models do not have instruction slot limits, this flag ensures that unoptimized shaders do not have this problem. This flag still does the other things that the skip optimization flag does, such as preventing instruction reordering and dead code elimination. The shaders will run in software which will reduce their performance.

Troubleshooting

If you have read this shader debugging tutorial and followed the steps, you are probably debugging a vertex shader already. If you skipped through the tutorial and are still having problems, the table below offers a summary of the problems you may encounter, and what you need to do to solve them. The solutions listed in the table are the same ones covered in the tutorial.

If you cannot: You may need to:
Launch VS .NET. | Install VS .NET. See Install Visual Studio .NET.
See the "DX extensions for VS.NET" icon on the start up screen when you launch Visual Studio .NET or cannot find the debugger menu option Debug, Direct3D, Start With Direct3D Debugging. | Need to install the shader debugger from the SDK. See Install DirectX9 (installing the SDK and the shader debugger from the SDK).
Put a breakpoint in your shader code

The shader debugger will give you the following message: "The breakpoint will not currently be hit. No executable code is currently loaded at this location."

 You need to do one or more of the following:
  • Enable Direct3D shader debugging from the control panel. See Enable Debug Mode from the Control Panel. The shader will warn you with a message box if this is not enabled.
  • Build a Visual Studio .NET debug project.
  • Install the DirectX SDK to get the debug or reference Dlls and the shader debugger.

    The shader debugger warns you with a message box if the debug or reference Dlls are not installed.

  • Launch the debugger from Debug, Direct3D, Start With Direct3D Debugging.
  • Use a shader/effect compile flag compatible with debugging.

    If you don't compile the with D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION, the debugger will warn you with a message box.

  • Use a device compatible with debugging.

    The debugger warns you if you try to use a HWVP device with a vertex shader, or a hardware abstraction layer (HAL) device with a pixel shader.


Shader Model 3 (Direct3D 9)

Vertex shaders and pixel shaders are simplified considerably from earlier shader versions. If you are implementing shaders in hardware, you may not use vs_3_0 or ps_3_0 with any other shader versions, and you may not use either shader type with the fixed function pipeline. These changes make it possible to simplify drivers and the runtime. The only exception is that software-only vs_3_0 shaders may be used with any pixel shader version. In addition, if you are using a software-only vs_3_0 shader with a previous pixel shader version, the vertex shader can only use output semantics that are compatible with flexible vertex format (FVF) codes.

The semantics used on vertex shader outputs must be used on pixel shader inputs. The semantics are used to map the vertex shader outputs to the pixel shader inputs, similar to the way the vertex declaration is mapped to the vertex shader input registers and previous shader models. See Match Semantics on vs 3.0 and ps 3.0 Shaders.

Additional wrap mode render states have been added to cover the possibility of additional texture coordinates in this new scheme. Attributes with D3DDECLUSAGE_TEXCOORD and usage index from 0 to 15 are interpolated in wrap mode when the corresponding D3DRS_WRAP* is set.

  • Vertex Shader Model 3 Features
  • Pixel Shader Model 3 Features
  • Match Semantics on vs_3_0 and ps_3_0 Shaders
  • Fog, Depth, and Shading Mode Changes
  • Floating Point and Integer Conversions
  • Specifying Full or Partial Precision
  • Software Vertex and Pixel Shaders

Vertex Shader Model 3 Features

The vertex shader output register types have been collapsed into twelve registers (see Output Registers). Each register that is used needs to be declared using the dcl instruction and a semantic (for example, dcl_color0 o0.xyzw).

The 3_0 vertex shader model (vs_3_0) expands on the features of vs_2_0 with more powerful register indexing, a set of simplified output registers, the ability to sample a texture in a vertex shader, and the ability to control the rate at which shader inputs are initialized.

Index Any Register

All registers( Input Register and Output Registers) can be indexed using Loop Counter Register (only constant registers could be indexed in earlier versions.)

You must declare input and output registers before indexing them. However, you may not index any output register that has been declared with a position or point size semantic. In fact, if indexing is used the position and psize semantics have to be declared in the o0 and o1 registers respectively.

You are only allowed to index a continuous range of registers; that is, you cannot index across registers that have not been declared. While this restriction may be inconvenient, it permits hardware optimization to take place. Attempting to index across non-contiguous registers will produce undefined results. Shader validation does not enforce this restriction.

Simplify Output Registers

All the various types of output registers have been collapsed into twelve output registers: 1 for position, 2 for color, 8 for texture, and 1 for fog or point size. These registers will interpolate any data they contain for the pixel shader. Output register declarations are required and semantics are assigned to each register.

The registers can be broken down as follows:

  • At least one register must be declared as a four-component position register. This is the only vertex shader register that is required.
  • The first ten registers consumed by a shader may use up to four components (xyzw) maximum.
  • The last (or twelfth) register may only contain a scalar (such as point size).

For a listing of the registers, see Registers - vs_3_0.

Texture Sample in a Vertex Shader

Vertex shader 3_0 supports texture lookup in the vertex shader using texldl - vs. See Vertex Textures in vs_3_0 (Direct3D 9).

Pixel Shader Model 3 Features

The pixel shader color and texture registers have been collapsed into ten input registers (see Input Register Types). The Face Register is a floating point scalar register. Only the sign of this register is valid. If the sign is negative the primitive is a back face. This can be used inside a pixel shader to achieve two-sided lighting, for instance. The Position Register references the current (x,y) pixels.

The shader constant registers can be set using:

  • IDirect3DDevice9::SetPixelShaderConstantB
  • IDirect3DDevice9::SetPixelShaderConstantI
  • IDirect3DDevice9::SetPixelShaderConstantF

Match Semantics on vs_3_0 and ps_3_0 Shaders

There are some restrictions on semantic usage with vs_3_0 and ps_3_0. In general, you need to be careful when using a semantic for a shader input that matches a semantic used on a shader output.

For instance, this pixel shader packs multiple names into one register:

ps_3_0
dcl_texcoord0 v0.x
dcl_texcoord1 v0.yz // Valid to pack multiple names into one register
dcl_texcoord2_centroid v1.w
...

Each register has a different semantic. Notice that you can also name v0.x and v0.yz with different (multiple) semantics because of the use of the write mask.

Given the pixel shader, the following vs_3_0 shader cannot be paired with it:

vs_3_0
...
dcl_texcoord0 o5.x
dcl_texcoord1 o6.yzw
...

These two shaders conflict with their use of the D3DDECLUSAGE_TEXCOORD0 And D3DDECLUSAGE_TEXCOORD1 semantics.

Rewrite the vertex shader like this to avoid the semantic collision:

vs_3_0
...
dcl_texcoord2 o3
dcl_texcoord3 o9
...

Similarly, a semantic name declared on different input registers in the pixel shader (v0 and v1 in the pixel shader) cannot be used in a single output register in this vertex shader. For instance, this vertex shader cannot be paired with the pixel shader because D3DDECLUSAGE_TEXCOORD1 is used for both pixel shader input registers (v0, v1) and the vertex shader output register o3.

vs_3_0
...
dcl_texcoord0 o3.x
dcl_texcoord1 o3.yz

dcl_texcoord2 o3.w // BAD! Would be valid if this were not o3
dcl_texcoord3 o9 ...

On the other hand, this vertex shader cannot be paired with the pixel shader because the output mask for a parameter with a given semantic does not provide the data that is requested by the pixel shader:

vs_3_0
...
dcl_texcoord0 o5.x
dcl_texcoord1 o5.yzw
dcl_texcoord2 o7.yz // BAD! Would be valid if w were included
dcl_texcoord3 o9
...

This vertex shader does not provide an output with one of the semantic names requested by the pixel shader, so the shader pairing is invalid:

vs_3_0
...
dcl_texcoord0 o5.x
dcl_texcoord1 o5.yzw
dcl_texcoord3 o9
// The pixel shader wants texcoord2, with a w component,
// but it isn't output by this vertex shader at all!
...

Fog, Depth, and Shading Mode Changes

When D3DRS_SHADEMODE is set for flat shading during clipping and triangle rasterization, attributes with D3DDECLUSAGE_COLOR are interpolated as flat shaded. If any components of a register are declared with a color semantic but other components of the same register are given different semantics, flat shading interpolation (linear vs. flat) will be undefined on the components in that register without a color semantic.

If fog rendering is desired, vs_3_0 and ps_3_0 shaders must implement fog. No fog calculations are done outside of the shaders. There is no fog register in vs_3_0 and additional semantics D3DDECLUSAGE_FOG (for fog blend factor computed per vertex) and D3DDECLUSAGE_DEPTH"/> (for passing in a depth value to the pixel shader to compute the fog blend factor) have been added.

Texture stage state D3DTSS_TEXCOORDINDEX is ignored when using pixel shader 3.0.

The following values have been added to accommodate these changes:

// Fog and Depth usages
D3DDECLUSAGE_FOG
D3DDECLUSAGE_DEPTH

// Additional wrap states for vs_3_0 attributes with D3DDECLUSAGE_TEXCOORD
D3DRS_WRAP8
D3DRS_WRAP9
D3DRS_WRAP10
D3DRS_WRAP11
D3DRS_WRAP12
D3DRS_WRAP13
D3DRS_WRAP14
D3DRS_WRAP15

Floating Point and Integer Conversions

Floating point math happens at different precision and ranges (16-bit, 24-bit, and 32-bit) in different parts of the pipeline. A value greater than the dynamic range of the pipeline that enters that pipeline (for example, a 32-bit float texture map is sampled into a 24-bit float pipeline in ps_2_0) creates an undefined result. For predictable behavior, you should clamp such a value to the dynamic range maximum.

Conversion from a floating point value to an integer happens in several places such as:

  • When encountering a mova - vs instruction.
  • During texture addressing.
  • When writing out to a non-floating point render target.

Specifying Full or Partial Precision

Both ps_3_0 and ps_2_x provide support for two levels of precision:

ps_3_0 | ps_2_0 | Precision | Value
x |  | Full | fp32 or higher
x |  | Partial precision | fp16=s10e5
x | x | Full | fp24=s16e7 or higher
x | x | Partial precision | fp16=s10e5

ps_3_0 supports more precision than ps_2_0 does. By default, all operations occur at the full precision level.

Partial precision (see Pixel Shader Register Modifiers) is requested by adding the _pp modifier to shader code (provided that the underlying implementation supports it). Implementations are always free to ignore the modifier and perform the affected operations in full precision.

The _pp modifier can occur in two contexts:

  • On a texture coordinate declaration to pass partial-precision texture coordinates to the pixel shader. This could be used when texture coordinates relay color data to the pixel shader, which may be faster with partial precision than with full precision in some implementations.
  • On any instruction to request the use of partial precision, including texture load instructions. This indicates that the implementation is allowed to execute the instruction with partial precision and store a partial-precision result. In the absence of an explicit modifier, the instruction must be performed at full precision (regardless of the precision of the input operands).

An application might deliberately choose to trade off precision for performance. There are several kinds of shader input data which are natural candidates for partial precision processing:

  • Color iterators are well represented by partial-precision values.
  • Texture values from most formats can be accurately represented by partial-precision values (values sampled from 32-bit, floating-point format textures are an obvious exception).
  • Constants may be represented by partial-precision representation as appropriate to the shader.

In all these cases the developer may choose to specify partial precision to process the data, knowing that no input data precision is lost. In some cases, a shader may require that the internal steps of a calculation be performed at full precision even when input and final output values do not have more than partial precision.

Software Vertex and Pixel Shaders

Software implementations (run-time and reference for vertex shaders and reference for pixel shaders) of version 2_0 shaders and above have some validation relaxed. This is useful for debugging and prototyping purposes. The application indicates to the runtime/assembler that it needs some of the validation relaxed using the _sw flag in the assembler (for example, vs_2_sw). A software shader will not work with hardware.

vs_2_sw is a relaxation to the maximum caps of vs_2_x; similarly, ps_2_sw is a relaxation to the maximum caps of ps_2_x. Specifically, the following validations are relaxed:

Shader Model | Resource | Limit
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Instruction Counts | Unlimited
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Float Constant Registers | 8192
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Integer Constant Registers | 2048
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Boolean Constant Registers | 2048
ps_2_sw | Dependent-read depth | Unlimited
vs_2_sw | flow control instructions and labels | Unlimited
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Loop start/step/counts | Iteration start and iteration step size for rep and loop instructions are 32-bit signed integers. Count can be up to MAX_INT/64.
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Port limits | Port limits for all register files are relaxed.
vs_3_sw | Number of interpolators | 16 output registers in vs_3_sw.
ps_3_sw | Number of interpolators | 14(16-2) input registers for ps_3_sw.


Vertex Textures in vs_3_0 (Direct3D 9)

The vertex shader 3.0 model supports texture lookup in the vertex shader using the texldl - vs texture load statement. The vertex engine contains four texture sampler stages, named D3DVERTEXTEXTURESAMPLER0, D3DVERTEXTEXTURESAMPLER1, D3DVERTEXTEXTURESAMPLER2, and D3DVERTEXTEXTURESAMPLER3. These are distinct from the displacement map sampler and texture samplers in the pixel engine.

To sample textures set at those four stages, you can use the vertex engine and program the stages with the IDirect3D9::CheckDeviceFormat method. Set textures at those stages using IDirect3DDevice9::SetTexture, with the stage index D3DVERTEXTEXTURESAMPLER0 through D3DVERTEXTEXTURESAMPLER3. A new register has been introduced in the vertex shader, the sampler register (like in ps_2_0), which represents the vertex texture sampler. This register needs to be defined in the shader before using it.

An application can query if a format is supported as a vertex texture by calling IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_VERTEXTEXTURE.

Note This is a query flag so it is not accepted in any Createxxx function. A vertex texture created in the default pool can be set as a pixel texture and vice versa. However, to use the software vertex processing, the vertex texture must be created in the scratch pool (no matter if it is a mixed-mode device or a software vertex processing device).

The functionality is identical to the pixel textures, except for the following:

  • Anisotropic texture filtering is not supported, hence D3DSAMP_MAXANISOTROPY is ignored and D3DTEXF_ANISOTROPIC cannot be set for magnify, or minify for these stages.
  • Rate of change information is not available, hence the application has to compute the level of detail and provide that information as a parameter to texldl - vs.

Restrictions include:

  • As in pixel shaders, if multielement textures are supported, D3DSAMP_ELEMENTINDEX is used to figure out which element to sample from.
  • The state D3DSAMP_DMAPOFFSET is ignored for these stages.
  • Use IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_VERTEXTEXTURE" to query a texture to see if it can be used as a vertex texture.
  • VertexTextureFilterCaps indicates what kind of filters are allowed at the vertex texture samplers. D3DPTFILTERCAPS_MINFANISOTROPIC and D3DPTFILTERCAPS_MAGFANISOTROPIC are disallowed.

Sampling Stage Registers

A sampling stage register identifies a sampling unit that can be used in texture load statements. A sampling unit corresponds to the texture sampling stage, encapsulating the sampling-specific state provided in IDirect3DDevice9::SetSamplerState.

Each sampler uniquely identifies a single texture surface that is set to the corresponding sampler using IDirect3DDevice9::SetTexture. However, the same texture surface can be set at multiple samplers.

At draw time, a texture cannot be simultaneously set as a render target and a texture at a stage.

Because vs_3_0 supports four samplers, up to four texture surfaces can be read from in a single shader pass. A sampler register might appear only as an argument in the texture load statement: texldl - vs.

In vs_3_0, if you use a sampler, it must be declared at the beginning of the shader program, using the dcl_samplerType - vs (as in ps_2_0).

Software Processing

This feature will be supported in software vertex processing. The specific filter types supported can be checked by calling IDirect3DDevice9::GetDeviceCaps and checking VertexTextureFilterCaps. All published texture formats will be supported as vertex textures in software vertex processing.

Applications can check if a particular texture format is supported in the software vertex processing mode by calling IDirect3D9::CheckDeviceFormat and providing (D3DVERTEXTEXTURESAMPLER | D3DUSAGE_SOFTWAREPROCESSING) as usage. All formats are supported for software vertex processing. The scratch pool is required for software vertex processing.

API Changes

// New define
#define D3DVERTEXTEXTURESAMPLER0 (D3DDMAPSAMPLER+1)
#define D3DVERTEXTEXTURESAMPLER1 (D3DDMAPSAMPLER+2)
#define D3DVERTEXTEXTURESAMPLER2 (D3DDMAPSAMPLER+3)
#define D3DVERTEXTEXTURESAMPLER3 (D3DDMAPSAMPLER+4)

#define D3DVERTEXTEXTURESAMPLER  (0x00100000L)

// New caps field in D3DCAPS9
DWORD VertexTextureFilterCaps;


Effects (Direct3D 9)

A Microsoft DirectX effect enables the integration of vertex and pixel shaders with pipeline state to render objects. Effects are the next logical step in combining shaders to produce unique render conditions.

Effects also provide a convenient way to write shaders for different hardware versions. Because different video cards support different functionalities, an application can write several techniques that will run on a variety of devices. This way, if the application is running on the latest and greatest hardware, the application can run the most sophisticated effect technique. On the other hand, less sophisticated effect techniques can automatically be chosen to run on less-expensive or less-capable hardware.

An effect can replace the vertex processing and part of the pixel processing performed by the graphics pipeline. An example of an effect that uses a vertex shader and a pixel shader is in the BasicHLSL Sample.

For more information about effects, see these topics:

  • Writing an Effect
  • Using an Effect

Effects and the 3D Pipeline

A block diagram of the pipeline looks like this:

The pipeline transforms input data into output pixels that fill the frame buffer. The input data comes from objects that are made up of vertices in object space, or higher-order surfaces created from N-patches, rectangle patches, and triangle patches. Once the input data has been tessellated, the pipeline performs vertex processing, primitive processing, and pixel processing before generating the final pixel colors.

Vertex and pixel processing can be performed by the fixed function pipeline, or can be implemented with programmable shaders. The input data tessellation, primitive processing, and data outputs are controlled by pipeline state. All this can be integrated into an effect. An effect sets the state that controls how the pipeline functions. Effects manage programmable shaders as well as fixed function state.

Effects can save and restore state, leaving the device in the same state as before the effect was run. The types of state that an effect can manage include:

  • Shader state. This includes creating and deleting shaders, setting shader constants, setting shader state, and rendering with shaders.
  • Texture and sampler state. This includes specifying texture files, initializing texture stages, creating sampler objects, and setting sampler state.
  • Other pipeline state. This includes states for setting transformations, lighting, materials, and rendering options. These can be global or local variables. The variables can be set by either the effect itself or by the application.

Effects contain multiple rendering options called techniques. Each technique encapsulates global variables, pipeline state, texture and sampler state, and shader state. A single style is implemented in a rendering pass. One or more passes can be encapsulated in a technique. All of the passes and techniques can be validated to see if the effect code will run on the hardware device.

Effects Save and Restore State

Effects manage state. The word state is used very broadly here as it includes all kinds of information that the pipeline needs to specify the render conditions. This includes nearly all the functional areas of the pipeline.

Rendering options are controlled by techniques and passes. An application renders an effect by setting one active technique, and rendering one or more passes. All rendering in an effect is done within a matching pair of ID3DXEffect::Begin and ID3DXEffect::End calls. When ID3DXEffect::Begin is called, a stateblock is created and device state is saved (unless you specify otherwise). After a technique renders the passes that the application specifies to render, ID3DXEffect::End is called to end the active technique. The effect system responds by automatically restoring the pipeline state that was captured in the state block (unless you choose to disable this save and restore functionality).

When programming multiple-pass rendering sequences, each of which requires its own state setup, effects can reduce the housekeeping required for tracking state changes. To see more information about the states that can be saved and restored by effects, see Effect States.

Effects Can Share Parameters

Effect parameters are all the non-static variables declared in an effect. This can include global variables and annotations. Effect parameters can be shared between different effects by declaring parameters with the shared keyword and then creating the effect with an effect pool.

Cloned effects use the same effect pool as the effect from which they are cloned. Cloning an effect makes an exact copy of an effect, including global variables, techniques, passes, and annotations.


Writing an Effect (Direct3D 9)

Writing an effect requires that you understand effect syntax, and generate the required state information. You can add shader state, texture and sampler state, and all of the pipeline state that your application requires in an effect.

The effect syntax is detailed in the Effect Format. An effect is typically encapsulated into an effect file (.fx) but could also be written as a text string in an application.

Effect Example

Effects contain three types of state: shader state, texture and sampler state, and pipeline state. Here is an example of an effect from the BasicHLSL Sample:

// Global variables
float4 g_MaterialAmbientColor;      // Material's ambient color
float4 g_MaterialDiffuseColor;      // Material's diffuse color
int g_nNumLights;

float3 g_LightDir[3];               // Light's direction in world space
float4 g_LightDiffuse[3];           // Light's diffuse color
float4 g_LightAmbient;              // Light's ambient color

texture g_MeshTexture;              // Color texture for mesh

float    g_fTime;                   // App's time in seconds
float4x4 g_mWorld;                  // World matrix for object
float4x4 g_mWorldViewProjection;    // World * View * Projection matrix
// Texture samplers
sampler MeshTextureSampler =
sampler_state
{
    Texture = <g_MeshTexture>;
    MipFilter = LINEAR;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
};
struct VS_OUTPUT
{
    float4 Position   : POSITION;   // vertex position
    float2 TextureUV  : TEXCOORD0;  // vertex texture coords
    float4 Diffuse    : COLOR0;     // vertex diffuse color
};
VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
                         float3 vNormal : NORMAL,
                         float2 vTexCoord0 : TEXCOORD0,
                         uniform int nNumLights,
                         uniform bool bTexture,
                         uniform bool bAnimate )
{
    VS_OUTPUT Output;
    float3 vNormalWorldSpace;

    float4 vAnimatedPos = vPos;

    // Animation the vertex based on time and the vertex's object space position
    if( bAnimate )
        vAnimatedPos += float4(vNormal, 0) * (sin(g_fTime+5.5)+0.5)*5;

    // Transform the position from object space to homogeneous projection space
    Output.Position = mul(vAnimatedPos, g_mWorldViewProjection);

    // Transform the normal from object space to world space
    vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld));

    // Compute simple directional lighting equation
    float3 vTotalLightDiffuse = float3(0,0,0);
    for(int i=0; i < nNumLights; i++ )
        vTotalLightDiffuse += g_LightDiffuse[i] * max(0,dot(vNormalWorldSpace, g_LightDir[i]));

    Output.Diffuse.rgb = g_MaterialDiffuseColor * vTotalLightDiffuse +
                         g_MaterialAmbientColor * g_LightAmbient;
    Output.Diffuse.a = 1.0f;

    // Just copy the texture coordinate through
    if( bTexture )
        Output.TextureUV = vTexCoord0;
    else
        Output.TextureUV = 0;

    return Output;
}
struct PS_OUTPUT
{
    float4 RGBColor : COLOR0;  // Pixel color
};
PS_OUTPUT RenderScenePS( VS_OUTPUT In,
                         uniform bool bTexture )
{
    PS_OUTPUT Output;

    // Lookup mesh texture and modulate it with diffuse
    if( bTexture )
        Output.RGBColor = tex2D(MeshTextureSampler, In.TextureUV) * In.Diffuse;
    else
        Output.RGBColor = In.Diffuse;

    return Output;
}
technique RenderSceneWithTexture1Light
{
    pass P0
    {
        VertexShader = compile vs_1_1 RenderSceneVS( 1, true, true );
        PixelShader  = compile ps_1_1 RenderScenePS( true );
    }
}

This effect contains:

  • The shader state, which is all of the state associated with the vertex shader and pixel shader. This is defined by the vertex and pixel shader functions, any global variables they require, and their input and output data structures, all of which are listed here:

    struct VS_OUTPUT
{  ...  };
VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
                         ...
{  ...  }

struct PS_OUTPUT
{  ...  };
PS_OUTPUT RenderScenePS( VS_OUTPUT In,
                         uniform bool bTexture )
{  ...  }

  • Texture and sampler state, which are the the global variables for the texture object and the sampler object:

    texture g_MeshTexture;              // Color texture for mesh

sampler MeshTextureSampler =
sampler_state
{
   ...
};

  • The other effect state. There is no other effect state explicitly used in this example. If there were, it would be the technique inside of the pass to which it applied:

    technique RenderSceneWithTexture1Light
{
    pass P0
    {
        // Any other effect state can be set here.

        VertexShader = compile vs_1_1 RenderSceneVS( 1, true, true );
        PixelShader  = compile ps_1_1 RenderScenePS( true );
    }
}

Effects Contain One or More Techniques and Passes

Effect rendering options are controlled by adding techniques and passes.

Effects can be created with additional passes to facilitate more complex rendering effects. A technique supports an arbitrary number of passes:

technique T0
{
    pass P0
    { ... }

    pass P1
    { ... }

    ...

    pass Pn
    { ... }
}

Effects can also be created with an arbitrary number of techniques.

technique T0
{
    pass P0
    { ... }
}

technique T1
{
    pass P0
    { ... }

    pass P1
    { ... }
}

...

technique Tn
{
    pass P0
    { ... }
}

technique TVertexShaderOnly
{
    pass P0
    {
        VertexShader =
        asm
        {
         // assembly-language shader code goes here
         ...
        };
    }
}

The techniques and passes can be given arbitrary names.


Using an Effect (Direct3D 9)

This page will show you how to generate and use an effect. The topics covered include how to:

  • Create an Effect
  • Render an Effect
  • Use Semantics to Find Effect Parameters
  • Use Handles to Get and Set Parameters Efficiently
  • Add Parameter Information with Annotations
  • Share Effect Parameters
  • Compile an Effect Offline
  • Improve Performance with Preshaders
  • Use Parameter Blocks to Manage Effect Parameters

Create an Effect

Here is an example of creating an effect taken from the BasicHLSL Sample. The effect creation code for creating a debug shader is from OnCreateDevice:

ID3DXEffect* g_pEffect = NULL;
DWORD dwShaderFlags = 0;

    dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
    dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
    dwShaderFlags |= D3DXSHADER_NO_PRESHADER;

    // Read the D3DX effect file
    WCHAR str[MAX_PATH];
    DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL.fx" );

    D3DXCreateEffectFromFile(
        pd3dDevice,
        str,
        NULL, // CONST D3DXMACRO* pDefines,
        NULL, // LPD3DXINCLUDE pInclude,
        dwShaderFlags,
        NULL, // LPD3DXEFFECTPOOL pPool,
        &g_pEffect,
        NULL );

This function takes these arguments:

  • The device.
  • The file name of the effect file.
  • A pointer to a NULL-terminated list of #defines, to be used while parsing the shader.
  • An optional pointer to a user-written include handler. The handler is called by the processor whenever it needs to resolve a #include.
  • A shader compile flag that gives the compiler hints about how the shader will be used. The options include:
    • Skipping validation, if known good shaders are being compiled.
    • Skipping optimization (sometimes used when optimizations make debugging harder).
    • Requesting debug information to be included in the shader so it can be debugged.
  • The effect pool. If more than one effect uses the same memory pool pointer, the global variables in the effects are shared with each other. If there is no need to share effect variables, the memory pool can be set to NULL.
  • A pointer to the new effect.
  • A pointer to a buffer to which validation errors can be sent. In this example, the parameter was set to NULL and not used.

Note:Beginning with the December 2006 SDK, the DirectX 10 HLSL compiler is now the default compiler in both DirectX 9 and DirectX 10. See DirectX 10 HLSL Compiler (Direct3D 10) for details.

Render an Effect

The sequence of calls for applying effect state to a device is:

  • ID3DXEffect::Begin sets the active technique.
  • ID3DXEffect::BeginPass sets the active pass.
  • ID3DXEffect::CommitChanges updates changes to any set calls in the pass. This should be called before any draw call.
  • ID3DXEffect::EndPass ends a pass.
  • ID3DXEffect::End ends the active technique.

Effect render code is also simpler than the corresponding render code without an effect. Here's the render code with an effect:

// Apply the technique contained in the effect
g_pEffect->Begin(&cPasses, 0);

for (iPass = 0; iPass < cPasses; iPass++)
{
    g_pEffect->BeginPass(iPass);

    // Only call CommitChanges if any state changes have happened
    // after BeginPass is called
    g_pEffect->CommitChanges();

    // Render the mesh with the applied technique
    g_pMesh->DrawSubset(0);

    g_pEffect->EndPass();
}
g_pEffect->End();

The render loop consists of querying the effect to see how many passes it contains, and then calling all the passes for a technique. The render loop could be expanded to call multiple techniques, each with multiple passes.

Use Semantics to Find Effect Parameters

A semantic is an identifier that is attached to an effect parameter to allow an application to search for the parameter. A parameter can have at most one semantic. The semantic is located following a colon (:) after the parameter name. For instance:

float4x4 matWorldViewProj : WORLDVIEWPROJ;

If you declared the effect global variable without using a semantic, it would look like this instead:

float4x4 matWorldViewProj;

The effect interface can use a semantic to get a handle to a particular effect parameter. For instance, the following returns the handle of the matrix:

D3DHANDLE handle =
    m_pEffect->GetParameterBySemantic(NULL, "WORLDVIEWPROJ");

In addition to searching by semantic name, the effect interface has many other methods to search for parameters.

Use Handles to Get and Set Parameters Efficiently

Handles provide an efficient means for referencing effect parameters, techniques, passes, and annotations with an effect. Handles (which are of type D3DXHANDLE) are string pointers. The handles that are passed into functions such as GetParameterxxx or GetAnnotationxxx can be in one of three forms:

  • A handle returned by a function such as GetParameterxxx.
  • A string containing the name of the parameter, technique, pass, or annotation.
  • A handle set to NULL.

This example returns a handle to the parameter that has the WORLDVIEWPROJ semantic attached to it:

D3DHANDLE handle =
    m_pEffect->GetParameterBySemantic(NULL, "WORLDVIEWPROJ");

Add Parameter Information with Annotations

Annotations are user-specific data that can be attached to any technique, pass, or parameter. An annotation is a flexible way to add information to individual parameters. The information can be read back and used any way the application chooses. An annotation can be of any data type and can be added dynamically. Annotation declarations are delimited by angle brackets. An annotation contains:

  • A data type.
  • A variable name.
  • An equals sign (=).
  • The data value.
  • A ending semicolon (;).

For instance, both of the previous examples in this paper contain this annotation:

texture Tex0 < string name = "tiger.bmp"; >;

The annotation is attached to the texture object and specifies the texture file that should be used to initialize the texture object. The annotation does not initialize the texture object, it is simply a piece of user information that is attached to the variable. An application can read the annotation with either ID3DXBaseEffect::GetAnnotation or ID3DXBaseEffect::GetAnnotationByName to return the string. Annotations can also be added by the application.

Each annotation:

  • Must be either numeric or strings.
  • Must always be initialized with a default value.
  • Can be associated with Techniques and Passes and top-level Effect Parameters.
  • Can be written to and read from with either ID3DXEffect or ID3DXEffectCompiler.
  • Can be added with ID3DXEffect.
  • Cannot be referenced inside the effect.
  • Cannot have sub-semantics or sub-annotations.

Share Effect Parameters

Effect parameters are all the non-static variables declared in an effect. This can include global variables and annotations. Effect parameters can be shared between different effects by declaring parameters with the "shared" keyword and then creating the effect with an effect pool.

An effect pool contains shared effect parameters. The pool is created by calling D3DXCreateEffectPool, which returns an ID3DXEffectPool interface. The interface can be supplied as an input to any of the D3DXCreateEffectxxx functions when an effect is created. For a parameter to be shared across multiple effects, the parameter must have the same name, type, and semantic in each of the shared effects.

ID3DXEffectPool* g_pEffectPool = NULL;   // Effect pool for sharing parameters

    D3DXCreateEffectPool( &g_pEffectPool );

Effects that share parameters must use the same device. This is enforced to prevent the sharing of device-dependent parameters (such as shaders or textures) across different devices. Parameters are deleted from the pool whenever the effects that contain the shared parameters are released. If sharing parameters is not necessary, supply NULL for the effect pool when an effect is created.

Cloned effects use the same effect pool as the effect from which they are cloned. Cloning an effect makes an exact copy of an effect, including global variables, techniques, passes, and annotations.

Compile an Effect Offline

You can compile an effect at run time with D3DXCreateEffect, or you can compile an effect offline using the command-line compiler tool fxc.exe. The effect in the CompiledEffect Sample contains a vertex shader, a pixel shader, and one technique:

// File: CompiledEffect.fx

// Global variables
float4 g_MaterialAmbientColor;    // Material's ambient color
...

// Texture samplers
sampler RenderTargetSampler =
   ...

// Type: Vertex shader
VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
                         float3 vNormal : NORMAL,
                         float2 vTexCoord0 : TEXCOORD0 )
{
   ...
};
// Type: Pixel shader
PS_OUTPUT RenderScenePS( VS_OUTPUT In )
{
   ...
}

// Type: Technique
technique RenderScene
{
    pass P0
    {
        ZENABLE = true;
        VertexShader = compile vs_1_1 RenderSceneVS();
        PixelShader  = compile ps_1_1 RenderScenePS();
    }
}

Using fxc to compile the shader for vs_1_1 generated the following assembly shader instructions:

//
// Generated by Microsoft (R) D3DX9 Shader Compiler 4.09.02.1188
//
//   fxc /T vs_1_1 /E RenderSceneVS /Fc CompiledEffect.txt CompiledEffect.fx
//
//
// Parameters:
//
//   float4 g_LightAmbient;
//   float4 g_LightDiffuse;
//   float3 g_LightDir;
//   float4 g_MaterialAmbientColor;
//   float4 g_MaterialDiffuseColor;
//   float g_fTime;
//   float4x4 g_mWorld;
//   float4x4 g_mWorldViewProjection;
//
//
// Registers:
//
//   Name                   Reg   Size
//   ---------------------- ----- ----
//   g_mWorldViewProjection c0       4
//   g_mWorld               c4       3
//   g_MaterialAmbientColor c7       1
//   g_MaterialDiffuseColor c8       1
//   g_LightDir             c9       1
//   g_LightAmbient         c10      1
//   g_LightDiffuse         c11      1
//   g_fTime                c12      1
//
//
// Default values:
//
//   g_LightDir
//     c9   = { 0.57735, 0.57735, 0.57735, 0 };
//
//   g_LightAmbient
//     c10  = { 1, 1, 1, 1 };
//
//   g_LightDiffuse
//     c11  = { 1, 1, 1, 1 };
//

    vs_1_1
    def c13, 0.159154937, 0.25, 6.28318548, -3.14159274
    def c14, -2.52398507e-007, 2.47609005e-005, -0.00138883968, 0.0416666418
    def c15, -0.5, 1, 0.5, 0
    dcl_position v0
    dcl_normal v1
    dcl_texcoord v2
    mov r0.w, c12.x
    mad r0.w, r0.w, c13.x, c13.y
    expp r3.y, r0.w
    mov r0.w, r3.y
    mad r0.w, r0.w, c13.z, c13.w
    mul r0.w, r0.w, r0.w
    mad r1.w, r0.w, c14.x, c14.y
    mad r1.w, r0.w, r1.w, c14.z
    mad r1.w, r0.w, r1.w, c14.w
    mad r1.w, r0.w, r1.w, c15.x
    mad r0.w, r0.w, r1.w, c15.y
    mul r0.w, r0.w, v0.x
    mul r0.x, r0.w, c15.z
    dp3 r1.x, v1, c4
    dp3 r1.y, v1, c5
    dp3 r1.z, v1, c6
    mov r0.yzw, c15.w
    dp3 r2.x, r1, r1
    add r0, r0, v0
    rsq r1.w, r2.x
    dp4 oPos.x, r0, c0
    mul r1.xyz, r1, r1.w
    dp4 oPos.y, r0, c1
    dp3 r1.x, r1, c9
    dp4 oPos.z, r0, c2
    max r1.w, r1.x, c15.w
    mov r1.xyz, c8
    mul r1.xyz, r1, c11
    mov r2.xyz, c7
    mul r2.xyz, r2, c10
    dp4 oPos.w, r0, c3
    mad oD0.xyz, r1, r1.w, r2
    mov oD0.w, c15.y
    mov oT0.xy, v2

// approximately 34 instruction slots used

Improve Performance with Preshaders

A preshader is a technique for increasing shader efficiency by pre-calculating constant shader expressions. The effect compiler automatically pulls out shader computations from the body of a shader and executes them on the CPU prior to the shader running. Consequently, preshaders only work with effects. For instance, these two expressions can be evaluated outside of the shader before it runs.

mul(World,mul(View, Projection));
sin(time)

Shader computations that can be moved are those associated with uniform parameters; that is, the computations do not change for each vertex or pixel. If you are using effects, the effect compiler automatically generates and runs a preshader for you; there are no flags to enable. Preshaders can reduce the number of instructions per shader and can also reduce the number of constant registers a shader consumes.

Think of the effect compiler as a sort of multi-processor compiler because it compiles shader code for two types of processors: a CPU and a GPU. In addition, the effect compiler is designed to move code from the GPU to the CPU and therefore improve shader performance. This is very similar to pulling a static expression out of a loop. A shader that transforms position from world space to projection space, and copies texture coordinates would look like this in HLSL:

float4x4 g_mWorldViewProjection;    // World * View * Projection matrix
float4x4 g_mWorldInverse;           // Inverse World matrix
float3 g_LightDir;                  // Light direction in world space
float4 g_LightDiffuse;              // Diffuse color of the light

struct VS_OUTPUT
{
    float4 Position   : POSITION;   // vertex position
    float2 TextureUV  : TEXCOORD0;  // vertex texture coords
    float4 Diffuse    : COLOR0;     // vertex diffuse color
};

VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
                         float3 vNormal : NORMAL,
                         float2 vTexCoord0 : TEXCOORD0)
{
    VS_OUTPUT Output;

    // Transform the position from object space to projection space
    Output.Position = mul(vPos, g_mWorldViewProjection);

    // Transform the light from world space to object space
    float3 vLightObjectSpace = normalize(mul(g_LightDir, (float3x3)g_mWorldInverse));

    // N dot L lighting
    Output.Diffuse = max(0,dot(vNormal, vLightObjectSpace));

    // Copy the texture coordinate
    Output.TextureUV = vTexCoord0;

    return Output;
}
technique RenderVS
{
    pass P0
    {
        VertexShader = compile vs_1_1 RenderSceneVS();
    }
}

Using fxc to compile the shader for vs_1_1 generates the following assembly instructions:

technique RenderVS
{
    pass P0
    {
        vertexshader =
            asm {
            //
            // Generated by Microsoft (R) D3DX9 Shader Compiler 9.15.779.0000
            //
            // Parameters:
            //
            //   float3 g_LightDir;
            //   float4x4 g_mWorldInverse;
            //   float4x4 g_mWorldViewProjection;
            //
            //
            // Registers:
            //
            //   Name                   Reg   Size
            //   ---------------------- ----- ----
            //   g_mWorldViewProjection c0       4
            //   g_mWorldInverse        c4       3
            //   g_LightDir             c7       1
            //

                vs_1_1
                def c8, 0, 0, 0, 0
                dcl_position v0
                dcl_normal v1
                dcl_texcoord v2
                mov r1.xyz, c7
                dp3 r0.x, r1, c4
                dp3 r0.y, r1, c5
                dp3 r0.z, r1, c6
                dp4 oPos.x, v0, c0
                dp3 r1.x, r0, r0
                dp4 oPos.y, v0, c1
                rsq r0.w, r1.x
                dp4 oPos.z, v0, c2
                mul r0.xyz, r0, r0.w
                dp4 oPos.w, v0, c3
                dp3 r0.x, v1, r0
                max oD0, r0.x, c8.x
                mov oT0.xy, v2

            // approximately 14 instruction slots used
            };

        //No embedded pixel shader
    }
}

This uses up approximately 14 slots and consumes 9 constant registers. With a preshader, the compiler moves the static expressions out of the shader and into the preshader. The same shader would look like this with a preshader:

technique RenderVS
{
    pass P0
    {
        vertexshader =
            asm {
            //
            // Generated by Microsoft (R) D3DX9 Shader Compiler 9.15.779.0000
            //
            // Parameters:
            //
            //   float3 g_LightDir;
            //   float4x4 g_mWorldInverse;
            //
            //
            // Registers:
            //
            //   Name            Reg   Size
            //   --------------- ----- ----
            //   g_mWorldInverse c0       3
            //   g_LightDir      c3       1
            //

                preshader
                dot r0.x, c3.xyz, c0.xyz
                dot r0.y, c3.xyz, c1.xyz
                dot r0.z, c3.xyz, c2.xyz
                dot r1.w, r0.xyz, r0.xyz
                rsq r0.w, r1.w
                mul c4.xyz, r0.w, r0.xyz

            // approximately 6 instructions used
            //
            // Generated by Microsoft (R) D3DX9 Shader Compiler 9.15.779.0000
            //
            // Parameters:
            //
            //   float4x4 g_mWorldViewProjection;
            //
            //
            // Registers:
            //
            //   Name                   Reg   Size
            //   ---------------------- ----- ----
            //   g_mWorldViewProjection c0       4
            //

                vs_1_1
                def c5, 0, 0, 0, 0
                dcl_position v0
                dcl_normal v1
                dcl_texcoord v2
                dp4 oPos.x, v0, c0
                dp4 oPos.y, v0, c1
                dp4 oPos.z, v0, c2
                dp4 oPos.w, v0, c3
                dp3 r0.x, v1, c4
                max oD0, r0.x, c5.x
                mov oT0.xy, v2

            // approximately 7 instruction slots used
            };

        //No embedded pixel shader
    }
}

An effect executes a preshader just before executing a shader. The result is the same functionality with increased shader performance because the number of instructions that need to be executed (for each vertex or pixel depending on the type of shader) has been reduced. In addition, fewer constant registers are consumed by the shader as a result of the static expressions being moved to the preshader. This means that shaders previously limited by the number of constant registers they required may now compile because they require fewer constant registers. It is reasonable to expect a 5 percent and a 20 percent performance improvement from preshaders.

Keep in mind that the input constants are different from the output constants in a preshader. The output c1 is not the same as the input c1 register. Writing to a constant register in a preshader actually writes into the corresponding shader's input (constant) slot.

// BaseDelta c0 1
// Refinements c1 1
preshader
mul c1.x, c0.x, (-2)
add c0.x, c0.x, c0.x
cmp c5.x, c1.x, (1), (0)

The cmp instruction above will read the preshader c1 value, while the mul instruction will write to the hardware shader registers to be used by the vertex shader.

Use Parameter Blocks to Manage Effect Parameters

Parameter blocks are blocks of effect state changes. A parameter block can record state changes, so that they can be applied later on with a single call. Create a parameter block by calling ID3DXEffect::BeginParameterBlock:

    m_pEffect->SetTechnique( "RenderScene" );

    m_pEffect->BeginParameterBlock();
    D3DXVECTOR4 v4( Diffuse.r, Diffuse.g, Diffuse.b, Diffuse.a );
    m_pEffect->SetVector( "g_vDiffuse", &v4 );
    m_pEffect->SetFloat( "g_fReflectivity", fReflectivity );
    m_pEffect->SetFloat( "g_fAnimSpeed", fAnimSpeed );
    m_pEffect->SetFloat( "g_fSizeMul", fSize );
    m_hParameters = m_pEffect->EndParameterBlock();

The parameter block saves four changes applied by the API calls. Calling ID3DXEffect::BeginParameterBlock starts recording the state changes. ID3DXEffect::EndParameterBlock stops adding the changes to the parameter block and returns a handle. The handle will be used when calling ID3DXEffect::ApplyParameterBlock.

In the EffectParam Sample, the parameter block is applied in the render sequence:

CObj g_aObj[NUM_OBJS];       // Object instances

    if( SUCCEEDED( pd3dDevice->BeginScene() ) )
    {
        // Set the shared parameters using the first mesh's effect.

        // Render the mesh objects
        for( int i = 0; i < NUM_OBJS; ++i )
        {
            ID3DXEffect *pEffect = g_aObj[i].m_pEffect;

            // Apply the parameters
            pEffect->ApplyParameterBlock( g_aObj[i].m_hParameters );

            ...

            pEffect->Begin( &cPasses, 0 );
            for( iPass = 0; iPass < cPasses; iPass++ )
            {
              ...
            }
            pEffect->End();
        }

        ...
        pd3dDevice->EndScene();
    }

The parameter block sets the value of all four of the state changes just before ID3DXEffect::Begin is called. Parameter blocks are a handy way to set multiple state changes with a single API call.


Advanced Topics (Direct3D 9)

Microsoft Direct3D provides a powerful set of tools that you can use to increase the realistic appearance of a 3D scene. Once you have mastered the topics in Getting Started (Direct3D 9), you can move on to advanced topics like antialiasing, working with the frame buffer, querying for resource status, and profiling your application.

The following topics contain more information:

  • Vertex Pipeline
  • Pixel Pipeline
  • Frame Buffer
  • Precomputed Radiance Transfer
  • HDR Lighting
  • Accurately Profiling Direct3D API Calls
  • Queries
  • Efficiently Drawing Multiple Instances of Geometry
  • Using UVAtlas


Vertex Pipeline (Direct3D 9)

This is a list of advanced topics that are implemented by vertex processing.

  • Tessellation (Direct3D 9)
  • Displacement Mapping (Direct3D 9)
  • Geometry Blending (Direct3D 9)
  • Higher-Order Primitives (Direct3D 9)
  • Point Sprites (Direct3D 9)
  • Matrix Stacks (Direct3D 9)


Tessellation (Direct3D 9)

Tessellator Unit

The tessellator unit has been enhanced. You can now use it to:

  • Perform adaptive tessellation of all higher-order primitives.
  • Look up per-vertex displacement values from a displacement map and pass them on to a vertex shader.
  • Support rectangle-patch tessellation. This is specified through a vertex declaration using D3DDECLMETHOD_PARTIALU or D3DDECLMETHOD_PARTIALV. If a vertex declaration containing these methods is used to draw a triangle patch, IDirect3DDevice9::DrawTriPatch will fail. For more information about vertex declarations, see D3DVERTEXELEMENT9.

In DirectX 8.x, what was called ORDER was really the degree. In Direct3D 9, the degree is now specified by D3DDEGREETYPE.

 // This used to be D3DORDERTYPE and D3DORDER*
 typedef enum _D3DDEGREETYPE
 {
 D3DDEGREE_LINEAR = 1,
 D3DDEGREE_QUADRATIC = 2,
 D3DDEGREE_CUBIC = 3,
 D3DDEGREE_QUINTIC = 5,
 D3DDEGREE_FORCE_DWORD = 0x7fffffff,
 } D3DDEGREETYPE;

The change in degree type affected two other structures.

typedef struct _D3DRECTPATCH_INFO
 {
 UINT StartVertexOffsetWidth;
 UINT StartVertexOffsetHeight;
 UINT Width;
 UINT Height;
 UINT Stride;
 D3DBASISTYPE Basis;
 D3DDEGREETYPE Degree;
 } D3DRECTPATCH_INFO;

 typedef struct _D3DTRIPATCH_INFO
 {
 UINT StartVertexOffset;
 UINT NumVertices;
 D3DBASISTYPE Basis;
 D3DDEGREETYPE Degree;
 } D3DTRIPATCH_INFO;

Drivers need to fix compilation errors that will result from this change when they compile with the new headers. No functionality has to be changed.

Adaptive Tessellation

Adaptive tessellation can be applied to high-order primitives including N-patches, rectangle patches, and triangle patches. This feature is enabled by the D3DRS_ENABLEADAPTIVETESSELLATION and adaptively tessellates a patch, based on the depth value of the control vertex in eye space.

The z-coordinates (Zi) of control vertices (Vi), which are transformed into eye space (Zieye) by performing a dot product with a 4-vector, are used as the depth values. The 4D vector (Mdm) is specified by the application using four render states (D3DRS_ADAPTIVETESS_X, D3DRS_ADAPTIVETESS_Y, D3DRS_ADAPTIVETESS_Z, and D3DRS_ADAPTIVETESS_W). This 4-vector could be the third column of the concatenated world and view matrices. It also could be used to apply a scale to Zieye.

The function to compute a tessellation level Ti from Zieye is assumed to be (MaxTessellationLevel/Zieye), which means that the MaxTessellationLevel is the tessellation level at Z = 1 in eye space. The MaxTessellationLevel is equal to a value set by IDirect3DDevice9::SetNPatchMode for N-patches and, for RT-patches, it is equal to pNumSegs. The tessellation level is then clamped to values, defined by the two additional render states D3DRS_MINTESSELLATIONLEVEL and D3DRS_MAXTESSELLATIONLEVEL, which define the minimum and maximum tessellation levels to be clamped to. The Ti's for each vertex along an edge of a patch are averaged to obtain a tessellation level for that edge. The algorithm for computing Ti for rectangle patches, triangle patches, and N-patches differs in what control vertices are used to compute the tessellation level.

For the rectangle patches with a B-spline basis, the four outermost control vertices are used. For example, with D3DORDER_CUBIC order: vertices (1,1) and (1,width-2) are used with pNumSegs[0], vertices (1,width-2) and (height-2,height-2) are used with pNumSegs[1], vertices (height-2,width-2) and (1,width-2) are used with pNumSegs[2], and vertices (2,1) and (1,1) are used with pNumSegs[3].

For the triangle patches, the corner patch vertices are used. With D3DORDER_CUBIC order: vertices (0) and (9) are used with pNumSegs[0], vertices (9) and (6) are used with pNumSegs[1] and vertices (6) and (0) are used with pNumSegs[3].

For N-patches the triangle vertices are used.

For the rectangle and triangle patches with a Bezier basis, the corner-control vertices are used.

Per-vertex tessellation rate control. An application can optionally supply a single positive floating-point value per vertex, which can be used to control the rate of tessellation. This is supplied using the D3DDECLUSAGE_TESSFACTOR, for which usage index must be 0 and input type must be D3DDECLTYPE_FLOAT1. This is multiplied to the per-vertex tessellation level.

Math

The tessellation level (Te) for an edge e, represented by two control vertices (Ve1, Ve2), is computed as shown below :

Vertex Vi: (Xi, Yi, Zi, TFactori (optional)).
Ze1eye = Ve1 . Mdm
Ze2eye = Ve2 . Mdm
Te1 = MaxTessellationLevel * TFactore1 / Ze1eye
Te2 = MaxTessellationLevel * TFactore2 / Ze2eye
Te = ( Te1 + Te2 ) / 2;
if Te > D3DRS_MAXTESSELLATIONLEVEL || Te < 0, then Te = D3DRS_MAXTESSELLATIONLEVEL
if Te < D3DRS_MINTESSELLATIONLEVEL, then Te = D3DRS_MINTESSELLATIONLEVEL

When D3DRS_ENABLEADAPTIVETESSELLATION is TRUE, triangle primitives (triangle lists, fans, strips) are drawn as N-patches, IDirect3DDevice9::SetNPatchMode has set value less than 1.0.

API Changes

New render states:

 D3DRS_ENABLEADAPTIVETESSELLATION // BOOL
 D3DRS_MAXTESSELLATIONLEVEL       // Float
 D3DRS_MINTESSELLATIONLEVEL       // Float
 D3DRS_ADAPTIVETESS_X             // Float
 D3DRS_ADAPTIVETESS_Y             // Float
 D3DRS_ADAPTIVETESS_Z             // Float
 D3DRS_ADAPTIVETESS_W             // Float

 // D3DRS_MINTESSELLATIONLEVEL and D3DRS_MAXTESSELLATIONLEVEL
 // cannot be less than 1

And their default values:

D3DRS_MAXTESSELLATIONLEVEL = 1.0f
D3DRS_MINTESSELLATIONLEVEL = 1.0f
D3DRS_ADAPTIVETESS_X = 0.0f
D3DRS_ADAPTIVETESS_Y = 0.0f
D3DRS_ADAPTIVETESS_Z = 1.0f
D3DRS_ADAPTIVETESS_W = 0.0f
D3DRS_ENABLEADAPTIVETESSELLATION = FALSE

New hardware caps:

D3DDEVCAPS2_ADAPTIVETESSRTPATCH // Can adaptively tessellate RT-patches
D3DDEVCAPS2_ADAPTIVETESSNPATCH  // Can adaptively tessellate N-patches


Displacement Mapping (Direct3D 9)

Displacement maps are similar to texture maps but are accessed by the vertex engine.

Block Diagram

An additional sampler stage is present in the early part of the vertex pipe, which can sample a displacement map to provide vertex displacement data.

Tessellator block diagram

The displacement map sampler state can be set by the IDirect3DDevice9::SetSamplerState using stage number 256, which is a new stage number. The displacement map texture is set by IDirect3DDevice9::SetTexture.

The map can be presampled or not, which means that it can be ordered in a way that enables the lookup of the displacement values without filtering.

  • Displacement maps are analogous to texture maps but are accessed by the vertex engine.
  • An additional sampler stage is present in the early part of the vertex pipe that can sample a displacement map. This stage is accessed by the usual SetSamplerState API but the stage number is D3DDMAPSAMPLER = 256.
  • The displacement map sampler state can be set by the SetSamplerState(D3DDMAPSAMPLER, ...) API.
  • The displacement map texture is set by the SetTexture(D3DDMAPSAMPLER, texture) API.
  • The map can be pre-sampled or not. This means that it can be ordered in a particular way that enables the lookup of the displacement values without filtering.
  • The changes in the declaration structure allow the specification of the texture coordinate used to look up the texture map. For example, Stream0, Offset, FLOAT2, LOOKUP, Displacement_value. This tells the tessellator to use the 2D float vector in stream0 at a certain offset as a texture coordinate to look up the displacement map and associate the Displacement_value usage semantic to it. The vertex shader declaration would contain a line similar to {dcl_texture0, v0} indicating that the texture0 semantic is to be associated with the v0 input register. The displacement value looked up is copied into input register v0.
  • There is a special type of displacement mapping, when the texture map is pre-sampled. Sequential index of generated vertices is used as a texture coordinate to a texture map. For example, 0,0,(D3DDECLTYPE)0,D3DDECLMETHOD_LOOKUPPRESAMPLED, Usage, UsageIndex.
  • The output of the lookup is 4 floats.
  • Displacement mapping is supported only with N-patches.
  • Drivers need to ignore D3DDMAPSAMPLER in SetTextureStageState if they do not handle displacement maps.
  • D3DTEXF_ANISOTROPIC filter mode is not supported.
  • When D3DSAMP_MIPFILTER in the displacement map sampler is not D3DTEXF_NONE, the level of detail is computed as follows (Note that the adaptive tessellation state is used even if the D3DRS_ENABLEADAPTIVETESSELLATION is FALSE): Tmax = render state D3DRS_MAXTESSELLATIONLEVEL
  • Compute tessellation level Te for a vertex Vi: (Xi, Yi, Zi) the same way as described in the "Adaptive tessellation" section. Level of detail L = log2(Tmax) - log2 (Te).
  • Texture filtering and sampling operations follow the same rules as the pixel pipeline (level of detail (LOD) bias is applied, etc.).
  • Not all formats can be used as displacement maps but only those that support the D3DUSAGE_DMAP. The application can query that with the CheckDeviceFormat IDirect3D9::CheckDeviceFormat.
  • D3DUSAGE_DMAP must be specified in IDirect3DDevice9::CreateTexture to notify the driver that this texture is to be used as a displacement map.
  • D3DUSAGE_DMAP can only be used with textures. It cannot be used with cube maps or volumes.
  • Textures and render targets created with D3DUSAGE_DMAP can be set at regular sampler stages and as render targets.
  • The render states to set the wrap mode for the texture coordinates are ignored in displacement mapping. In general, there are no wrap modes for the tessellator engine.
  • A displacement map sampler has behavior identical to that of the pixel texture samplers. If a texture with less than four channels (like R32f) is looked up, the looked-up values go to the appropriate channels of the destination register (the vertex shader input register tagged with the _sample semantic), while the other channels default to (1, 1, 1). When looked up, D3DFMT_L8 gets broadcast into the R, G, B channels and A defaults to 1. The reference rasterizer has the full implementation details.

Pre-Sampled Displacement Mapping

  • New sampler state is introduced: D3DSAMP_DMAPOFFSET (DWORD) - offset (in vertices) in a pre-sampled displacement map.
  • New declaration method is introduced: D3DDECLMETHOD_LOOKUPPRESAMPLED.
  • Adaptive tessellation should be disabled.
  • Texture filter settings are ignored. Point sampling is done. The mip texture filter is assumed to be D3DTEXF_NONE. All other texture filter modes are assumed to be D3DTEXF_POINT.
  • Texture coordinates are computed as: U = (Index % TextureWidthInPixeles) / (float)(TextureWidthInPixeles) V = (Index / TextureWidthInPixeles) / (float)(TextureHeightInPixeles) where Index is a sequential index of generated vertices plus TSS[D3DSAMP_DMAPOFFSET]. The sequential index is set to zero at the start of each primitive and is increased after a vertex is generated.

These are the API changes that support displacement mapping.

  • A single channel format added, D3DFMT_L16.
  • A new usage flag, D3DUSAGE_DMAP.
  • A special texture stage, used to set a displacement map texture, D3DDMAPSAMPLER.
  • New hardware caps have been added, D3DDEVCAPS2_DMAPNPATCH and D3DDEVCAPS2_PRESAMPLEDDMAPNPATCH. See D3DDEVCAPS2.


Geometry Blending (Direct3D 9)

Direct3D enables an application to increase the realism of its scenes by rendering segmented polygonal objects - especially characters - that have smoothly blended joints. These effects are often referred to as skinning. The system achieves this effect by applying additional world transformation matrices to a single set of vertices to create multiple results, and then performing a linear blend between the resultant vertices to create a single set of geometry for rendering. The following image of a banana illustrates this.

Blended composite of two objects with banana texture

This image shows how you might imagine the geometry-blending process. In a single rendering call, the system takes the vertices for the banana, transforms them twice - once without modification, and once with a simple rotation - and blends the results to create a bent banana. The system blends the vertex position, as well as the vertex normal when lighting is enabled. Applications are not limited to two blending paths; Direct3D can blend geometry between as many as four world matrices, including the standard world matrix, D3DTS_WORLD.

Note

When lighting is enabled, vertex normals are transformed by a corresponding inverse world-view matrix, weighted in the same way as the vertex position computations. The system normalizes the resulting normal vector if the D3DRS_NORMALIZENORMALS render state is set to TRUE.

Without geometry blending, dynamic articulated models are often rendered in segments. For instance, consider a 3D model of the human arm. In the simplest view, an arm has two parts: the upper arm which connects to the body, and the lower arm, which connects to the hand. The two are connected at the elbow, and the lower arm rotates at that point. An application that renders an arm might retain vertex data for the upper and lower arm, each with a separate world transformation matrix. The following code example illustrates this.

typedef struct _Arm
{
    VERTEX upper_arm_verts[200];
    D3DMATRIX matWorld_Upper;

    VERTEX lower_arm_verts[200];
    D3DMATRIX matWorld_Lower;
} ARM, *LPARM;

ARM MyArm; // This needs to be initialized.

To render the arm, two rendering calls are made, as shown in the following code.

// Render the upper arm.
d3dDevice->SetTransform( D3DTS_WORLD, &MyArm.matWorld_Upper );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, numFaces );

// Render the lower arm, updating its world matrix to articulate
// the arm by pi/4 radians (45 degrees) at the elbow.
MyArm.matWorld_Lower = RotateMyArm(MyArm.matWorld, pi/4);
d3dDevice->SetTransform( D3DTS_WORLD, &MyArm.matWorld_Lower );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, numFaces );

The following image is a banana, modified to use this technique.

Blended banana image

The differences between the blended geometry and the nonblended geometry are obvious. This example is somewhat extreme. In a real-world application, the joints of segmented models are designed so that seams are not as obvious. However, seams are visible at times, which presents constant challenges for model designers.

Geometry blending in Direct3D presents an alternative to the classic segmented-modeling scenario. However, the improved visual quality of segmented objects comes at the cost of the blending computations during rendering. To minimize the impact of these additional operations, the Direct3D geometry pipeline is optimized to blend geometry with the least possible overhead. Applications that intelligently use the geometry blending services offered by Direct3D can improve the realism of their characters while avoiding serious performance repercussions.

Blending Transform and Render States

The IDirect3DDevice9::SetTransform method recognizes the D3DTS_WORLD and D3DTS_WORLDn macros, which correspond to values that can be defined by the D3DTS_WORLDMATRIX macro. These macros are used to identify the matrices between which geometry will be blended.

The D3DRENDERSTATETYPE enumerated type includes the D3DRS_VERTEXBLEND render state to enable and control geometry blending. Valid values for this render state are defined by the D3DVERTEXBLENDFLAGS enumerated type. If geometry blending is enabled, the vertex format must include the appropriate number of blending weights.

Blending Weights

A blending weight, sometimes called a beta weight, controls the extent to which a given world matrix affects a vertex. Blending weights are floating-point values that range from 0.0 to 1.0, encoded in the vertex format, where a value of 0.0 means the vertex is not blended with that matrix, and 1.0 means that the vertex is affected in full by the matrix.

Geometry blending weights are encoded in the vertex format, appearing immediately after the position for each vertex, as described in Fixed Function FVF Codes (Direct3D 9). You communicate the number of blending weights in the vertex format by including one of the FVF constants in the vertex description that you provide to the rendering methods.

The system performs a linear blend between the weighted results of the blend matrices. The following is the complete blending formula.

Formula for linear blending, using world transformation matrices

In the preceding formula, vBlend is the output vertex, the v-elements are the vertices produced by the applied world matrix (D3DTS_WORLDn). The W elements are the corresponding weight values within the vertex format. A vertex blended between n matrices can have - 1 blending weight values, one for each blending matrix, except the last. The system automatically generates the weight for the last world matrix so that the sum of all weights is 1.0, expressed in sigma notation here. This formula can be simplified for each of the cases supported by Direct3D.

Formulas for linear blending for three blending cases

These are the simplified forms of the complete blending formula for the two, three, and four blend matrix cases.

Note Although Direct3D includes FVF descriptors to define vertices that contain up to five blending weights, only three can be used in this release of DirectX.

Additional information is contained in the following topics.

  • Using Geometry Blending (Direct3D 9)
  • Indexed Vertex Blending (Direct3D 9)
  • Vertex Tweening (Direct3D 9)


Using Geometry Blending (Direct3D 9)

The following user-defined structure can be used for vertices that will be blended between two matrices.

// The flexible vertex format (FVF) descriptor for this vertex would be:
//   FVF = D3DFVF_XYZB1 | D3DFVF_NORMAL | D3DFVF_TEX1;

struct D3DBLENDVERTEX {
    D3DVECTOR v;
    FLOAT     blend;
    D3DVECTOR n;
    FLOAT     tu, tv;
};

The blend weight must appear after the position and RHW data in the FVF, and before the vertex normal.

Notice that the preceding vertex format contains only one blending weight value. This is because there will be two world matrices, defined in the D3DTS_WORLDMATRIX(0) and D3DTS_WORLDMATRIX(1) transform states. The system blends each vertex between these two matrices using the single weight value. For three matrices, only two weights are required, and so on.

Note

Defining skin weights is easy. Using a linear function of the distance between joints is good start, but a smoother sigmoid function looks better. Choosing a skin-weight distribution function can result in sharp creases at joints, if desired, by using a large variation in skin weight over a short distance.

Setting Blending Matrices

You set the transformation matrices between which the system blends by calling the IDirect3DDevice9::SetTransform method. Set the first parameter to a value defined by the D3DTS_WORLDMATRIX macro, and set the second parameter to the address of the matrix to be set.

The following C++ code example sets two world matrices, between which geometry is blended to create the illusion of a jointed arm.

// For this example, the d3dDevice variable is assumed to be a valid pointer
//   to an IDirect3DDevice9 interface for an initialized 3D scene.

float     BendAngle = 3.1415926f / 4.0f; // 45 degrees
D3DMATRIX matUpperArm, matLowerArm;

// The upper arm is immobile. Use the identity matrix.
D3DXMatrixIdentity( matUpperArm );
d3dDevice->SetTransform( D3DTS_WORLDMATRIX(0), &matUpperArm );

// The lower arm rotates about the x-axis, attached to the upper arm.
D3DXMatrixRotationX( matLowerArm, -BendAngle );
d3dDevice->SetTransform( D3DTS_WORLDMATRIX(1), &matLowerArm );

Setting a blending matrix merely causes the system to cache the matrix for later use; it doesn't instruct the system to begin blending vertices.

Enabling Geometry Blending

Geometry blending is disabled by default. To enable geometry blending, call the IDirect3DDevice9::SetRenderState method to set the D3DRS_VERTEXBLEND render state to a value from the D3DVERTEXBLENDFLAGS enumerated type. The following code example shows what this call might look like when setting the render state for a blend between two world matrices.

d3dDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_1WEIGHTS );

When D3DRS_VERTEXBLEND is set to any value other than D3DVBF_DISABLE, the system assumes that the appropriate number of blending weights will be included in the vertex format. It is your responsibility to provide a compliant vertex format, and to provide a proper description of that format to the Direct3D rendering methods.

When enabled, the system performs geometry blending for all objects rendered by the DrawPrimitive rendering methods.

See Also

Fixed Function FVF Codes (Direct3D 9)


Indexed Vertex Blending (Direct3D 9)

Indexed vertex blending extends the vertex blending support in Direct3D to allow matrices to be used for blending. These matrices are referred to by using a matrix index. These indices are supplied on a per-vertex basis and refer to a palette of up to 256 matrices. Each index is 8 bits and each vertex can have up to four indices, which allows four matrices to be blended per vertex. The indices are packed into a DWORD. Because indices are specified on a per-vertex basis, up to 12 matrices can affect a single triangle, and any matrix in the palette can affect the vertices of one draw call. This approach has the following advantages.

  • It enables more matrices to affect a single triangle.
  • It enables more blended triangles to be passed in the same draw call.
  • It makes vertex blending independent of triangle indices. This enables progressive meshes to work in conjunction with vertex blending.

One disadvantage of this approach is that it does not work with curved-surface primitives when tessellation occurs before vertex processing.

The following illustration demonstrates how four matrices can affect a vertex. Each vertex has up to four indices, so four matrices can be blended per vertex. The illustration below uses the matrices indexed at 0, 2, 5, and 6.

Indexed vertex blending using 4 of 256 available matrices

The illustration below demonstrates how up to 12 matrices can affect a triangle. Using indices specified on a per-vertex basis, up to 12 matrices can affect the triangle.

Indexed vertex blending for a triangle, using 12 of 256 available matrices

The following formula determines the general case for how matrices effect a vertex.

Formula for the general case of indexed vertex blending

Vmodel is the input model space vertex position. Index0..Index3 are the per-vertex matrix indices packed into a DWORD. M[] is the array of world matrices that get indexed into. b0..b2 are the blend weights. Vworld is the output world space vertex position.

For more information about indexed vertex blending, see Using Indexed Vertex Blending (Direct3D 9).


Using Indexed Vertex Blending (Direct3D 9)

Transform states 256-511 are reserved to store up to 256 matrices that can be indexed using 8-bit indices. Use the macro D3DTS_WORLDMATRIX to map indices 0-255 to the corresponding transform states. The following code example shows how to use the IDirect3DDevice9::SetTransform method to set the matrix at transform state number 256 to an identity matrix.

D3DMATRIX matBlend1;
D3DXMatrixIdentity( &matBlend1 );
m_pD3DDevice->SetTransform( D3DTS_WORLDMATRIX(0), &matBlend );

To enable or disable indexed vertex blending, set the D3DRS_INDEXEDVERTEXBLENDENABLE render state to TRUE. When the render state is enabled ,you must pass matrix indices as packed DWORDs with every vertex. When this render state is disabled and vertex blending is enabled, it is equivalent to having the matrix indices 0, 1, 2, and 3 in every vertex. The code example below uses the IDirect3DDevice9::SetRenderState method to enable indexed vertex blending.

m_pD3DDevice->SetRenderState( D3DRS_INDEXEDVERTEXBLENDENABLE, TRUE );

To enable or disable vertex blending, set the IDirect3DDevice9::SetRenderState render state to a value other than D3DRS_DISABLE from the D3DVERTEXBLENDFLAGS enumerated type. If this render state is not set to D3DRS_DISABLE, then you must pass the required number of weights for each vertex. The following code example uses IDirect3DDevice9::SetRenderState to enable vertex blending with three weights for each vertex.

m_pD3DDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_3WEIGHTS );

Determining Indexed Vertex Blending Support

To determine the maximum size for the indexed vertex blending matrix, check the D3DCAPS9 structure's MaxVertexBlendMatrixIndex member. The code example below uses the IDirect3DDevice9::GetDeviceCaps method to retrieve this size.

D3DCAPS9 d3dCaps;

m_pD3DDevice->GetDeviceCaps( &d3dCaps );
IndexedMatrixMaxSize = d3dCaps.MaxVertexBlendMatrixIndex;

If the value set in MaxVertexBlendMatrixIndex is 0, the device does not support indexed matrices.

Note When software vertex processing is used, 256 matrices can be used for indexed vertex blending, with or without normal blending.

Passing Matrix Indices to Direct3D

World matrix indices can be passed to Direct3D by using legacy vertex shaders - FVF - or declarations.

The code example below shows how to use legacy vertex shaders.

struct VERTEX
{
    float x,y,z;
    float weight;
    DWORD matrixIndices;
    float normal[3];
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZB2 | D3DFVF_LASTBETA_UBYTE4 |
                             D3DFVF_NORMAL);

When a legacy vertex shader is used, matrix indices are passed together with vertex positions using D3DFVF_XYZBn flags. Matrix indices are passed as bytes inside a DWORD and must be present immediately after the last vertex weight. Vertex weights are also passed using D3DFVF_XYZBn. A packed DWORD contains index3, index2, index1, and index0, where index0 is located in the lowest byte of the DWORD. The number of used world-matrix indices is equal to the number passed to the number of matrices used for blending as defined by D3DRS_VERTEXBLEND.

When a declaration is used, D3DVSDE_BLENDINDICES defines the input vertex register to get matrix indices from. Matrix indices must be passed as D3DVSDT_UBYTE4.

The code example below shows how to use declarations. Note that the order of the components is no longer important unless using a fixed-function vertex shader.

Here is the vertex declaration.

struct VERTEX
{
    float x,y,z;
    float weight;
    DWORD matrixIndices;
    float normal[3];
}

Here is the corresponding register declaration.

// Create the shader declaration.
D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_FLOAT1, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 },
    { 0, 16, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 },
    { 0, 20, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
    D3DDECL_END()
};


Vertex Tweening (Direct3D 9)

Vertex tweening blends two user-provided positions (or normals). Tweening is mutually exclusive from vertex blending with weights. Tweening is performed before lighting and clipping, and is enabled by setting D3DRS_VERTEXBLEND to D3DVBF_TWEENING. The resulting vertex position is computed by:

POSITION = POSITION1 * (1.0 - TWEENFACTOR) + POSITION2 * TWEENFACTOR

The same approach is used for calculating normals. For more information, see Using Vertex Tweening (Direct3D 9).


Using Vertex Tweening (Direct3D 9)

To determine if Direct3D supports vertex tweening, check for the D3DVTXPCAPS_TWEENING flag in the VertexProcessingCaps member of the D3DCAPS9 structure. The following code example uses the IDirect3DDevice9::GetDeviceCaps method to determine if tweening is supported.

// This example assumes that m_pD3DDevice is
// a valid pointer to a IDirect3DDevice9 interface.
//
D3DCAPS9 d3dCaps;

m_pD3DDevice->GetDeviceCaps( &d3dCaps );
if( 0 != (d3dCaps.VertexProcessingCaps & D3DVTXPCAPS_TWEENING) )
    // Vertex tweening is supported.

To use vector tweening, you must first set up a custom vertex type that uses a second normal or a second position. The following code example shows a sample declaration that includes both a second point and a second position.

struct TEX_VERTEX
{
    D3DVECTOR position;
    D3DVECTOR normal;
    D3DVECTOR position2;
    D3DVECTOR normal2;
};

//Create a vertex buffer with the type TEX_VERTEX.

The next step is to set the current declaration. The code example below shows how to do this.

// Create the shader declaration.
D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
    { 0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 1 },
    { 0, 36, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 1 },
    D3DDECL_END()
};

For more information about creating a custom vertex type and a vertex buffer, see Creating a Vertex Buffer (Direct3D 9).

Note When vertex tweening is enabled, a second position or a second normal must be present in the current declaration.


Higher-Order Primitives (Direct3D 9)

Direct3D 9 supports points, lines, triangles, and grid primitives. These have been extended to support higher-order interpolation beyond linear. While triangles and lines have spatial extent, until now they were both rendered using linear interpolation. In Direct3D 9, Direct3D supports rendering of these primitive types using higher order, up to quintic, interpolation. Furthermore, a new quad primitive type is now supported. This new type can also be rendered with higher-order interpolation. This feature is primarily driven by requirements for animation and rendering of characters. It can also be used for other surfaces such as terrain or water.

Higher-order primitives support higher-order interpolation when transmitted to the API as lists, strips, fans, or indexed meshes. This is achieved by using additional information encoded in the vertices themselves. For example, normal vectors can be used to define tangent planes at the vertices to enable cubic interpolation. Most implementations support higher-order interpolation by tessellation into planar triangles. The tessellation step is applied logically before the vertex shader stage. Because the vertex shader API does not impose semantics on its input data, a special mechanism is provided to identify the vertex stream component that represents the position, and optionally the normal vector. All other components are interpolated accordingly.

This section introduces higher-order primitives and discusses how they can be used in your applications. Information is divided into the following topics.

  • Improved Quality through Resolution Enhancement
  • Direct Mapping from Spline-Based Tools

Improved Quality through Resolution Enhancement

Current primitives are not ideal for representing smooth surfaces. Higher-order interpolation methods, such as cubic polynomials, allow more accurate calculations in rendering curved shapes. This provides increased realism by reducing or eliminating faceting artifacts visible on silhouette edges or on specular surface lighting. Furthermore, when tessellation occurs on the chip, the tessellated triangles do not impact the bus bandwidth. In many cases, a small amount of tessellation can provide improvements in image quality with minimal performance impact.

Direct3D 9 provides a simple way to apply resolution enhancement to content created by existing polygon-oriented tools and art pipelines. The application need only provide a desired level of tessellation, and transmit the data using standard triangle syntax that includes normal vectors.

Direct Mapping from Spline-Based Tools

Many current authoring tools support higher-order primitives to enable more powerful modeling operations than are commonly provided for with planar triangle meshes. When used efficiently, so that the number of patches generated is reasonable, such tools can produce content that can be rendered directly by the API. To meet this requirement, a new entry point has been added that interprets the incoming vertex data stream as a 2D array of control points and tessellates it to the desired resolution.

  • Using Higher-Order Primitives (Direct3D 9)


Using Higher-Order Primitives (Direct3D 9)

This section shows you how to use higher-order primitives in your application.

  • Determining Higher-Order Primitive Support
  • Drawing Patches
  • Generating Normals and Texture Coordinates

Determining Higher-Order Primitive Support

The D3DCAPS9 structure's DevCaps member can be queried to determine the level of support for operations involving higher-order primitives. The following table lists the device capabilities related to higher-order primitives in Direct3D 9.

Device capability | Description
D3DDEVCAPS_NPATCHES | Device supports N-patches.
D3DDEVCAPS_QUINTICRTPATCHES | Device supports quintic Bezier curves and B-splines.
D3DDEVCAPS_RTPATCHES | Device supports rectangular and triangular patches (RT-patches).
D3DDEVCAPS_RTPATCHHANDLEZERO | RT-patches might be drawn efficiently using handle zero.

Note that D3DDEVCAPS_RTPATCHHANDLEZERO does not mean that a patch with handle zero can be drawn. A handle zero patch can always be drawn, whether this device capability is set or not. When this capability is set, the hardware architecture does not require caching of any information and that uncached patches (handle zero) be drawn as efficiently as cached ones.

Drawing Patches

Direct3D 9 supports two types of higher-order primitives, or patches. These are referred to as N-Patches and Rect/Tri patches. N-patches can be rendered using any triangle rendering call by enabling N-patches through the call to IDirect3DDevice9::SetNPatchMode( nSegments ) with nSegments value greater than 1.0. Rect/Tri patches must be rendered using the following explicit entry points.

You can use the following methods to draw patches.

  • IDirect3DDevice9::DrawRectPatch. To better understand how the patch data is referenced in the vertex buffer, see D3DRECTPATCH_INFO.
  • IDirect3DDevice9::DrawTriPatch. To better understand how the patch data is referenced in the vertex buffer, see D3DTRIPATCH_INFO.

IDirect3DDevice9::DrawRectPatch draws a rectangular high-order patch specified by the pRectPatchInfo parameter using the currently set streams. The Handle parameter is used to associate the patch with a handle, so that the next time the patch is drawn, there is no need to respecify pRectPatchInfo. This makes it possible to precompute and cache forward difference coefficients or other information, which in turn enables subsequent calls to IDirect3DDevice9::DrawRectPatch using the same handle to run efficiently.

It is intended that for static patches, an application would set the vertex shader and appropriate streams, supply patch information in the pRectPatchInfo parameter, and specify a handle so that Direct3D can capture and cache information. The application can then call IDirect3DDevice9::DrawRectPatch subsequently with pRectPatchInfo set to NULL to efficiently draw the patch. When drawing a cached patch, the currently set streams are ignored. However, it is possible to override the cached pNumSegs by specifying new values for pNumSegs. Also, it is required to set the same vertex shader when rendering a cached patch as was set when it was captured.

For dynamic patches, the patch data changes for every rendering of the patch, so it is not efficient to cache information. The application can convey this to Direct3D by setting Handle to 0. In this case, Direct3D draws the patch using the currently set streams and the pNumSegs values and does not cache any information. It is not valid to simultaneously set Handle to 0 and pPatch to NULL.

By respecifying pRectPatchInfo for the same handle, the application can overwrite the previously cached information.

IDirect3DDevice9::DrawTriPatch is similar to IDirect3DDevice9::DrawRectPatch except that it draws a triangular high-order patch.

Generating Normals and Texture Coordinates

If you are using a flexible vertex format (FVF) shader, automatic generation of normals and texture coordinates is not possible.

For normals, you can either directly supply them or have Direct3D calculate them for you.

The coordinates generated for rectangular patches are spline-based coordinates, as illustrated by the following images.

The coordinates generated for triangular patches are barycentric spline-based coordinates, as illustrated by the images below.

Barycentric spline-based coordinates

If an application must change the range of the generated texture coordinates, this can be done using texture transforms.


Point Sprites (Direct3D 9)

Support for point sprites in Direct3D 9 enables the high-performance rendering of points (particle systems). Point sprites are generalizations of generic points that enable arbitrary shapes to be rendered as defined by textures.

  • Point Primitive Rendering Controls
  • Point Size Computations
  • Point Rendering

Point Primitive Rendering Controls

Direct3D 9 supports additional parameters to control the rendering of point sprites (point primitives). These parameters enable points to be of variable size and have a full texture map applied. The size of each point is determined by an application-specified size combined with a distance-based function computed by Direct3D. The application can specify point size either as per-vertex or by setting D3DRS_POINTSIZE, which applies to points without a per-vertex size. The point size is expressed in camera space units, with the exception of when the application is passing post-transformed flexible vertex format (FVF) vertices. In this case, the distance-based function is not applied and the point size is expressed in units of pixels on the render target.

The texture coordinates computed and used when rendering points depends on the setting of D3DRS_POINTSPRITEENABLE. When this value is set to TRUE, the texture coordinates are set so that each point displays the full texture. In general, this is only useful when points are significantly larger than one pixel. When D3DRS_POINTSPRITEENABLE is set to FALSE, each point's vertex texture coordinate is used for the entire point.

Point Size Computations

Point size is determined by D3DRS_POINTSCALEENABLE. If this value is set to FALSE, the application-specified point size is used as the screen-space (post-transformed) size. Vertices that are passed to Direct3D in screen space do not have point sizes computed; the specified point size is interpreted as screen-space size.

If D3DRS_POINTSCALEENABLE is TRUE, Direct3D computes the screen-space point size according to the following formula. The application-specified point size is expressed in camera space units.

S s = Vh * S i * sqrt(1/(A + B * D e + C *( D e2 )))

In this formula, the input point size, S i, is either per-vertex or the value of the D3DRS_POINTSIZE render state. The point scale factors, D3DRS_POINTSCALE_A, D3DRS_POINTSCALE_B, and D3DRS_POINTSCALE_C, are represented by the points A, B, and C. The height of the viewport, V h, is the D3DVIEWPORT9 structure's Height member representing the viewport. D e, the distance from the eye to the position (the eye at the origin), is computed by taking the eye space position of the point (Xe, Ye, Ze) and performing the following operation.

D e = sqrt (Xe2 + Y e2 + Z e2)

The maximum point size, Pmax, is determined by taking the smaller of either the D3DCAPS9 structure's MaxPointSize member or the D3DRS_POINTSIZE_MAX render state. The minimum point size, Pmin, is determined by querying the value of D3DRS_POINTSIZE_MIN. Thus the final screen-space point size, S, is determined in the following manner.

  • If Ss > Pmax, then S = P max
  • if S < Pmin, then S = P min
  • Otherwise, S = S s

Point Rendering

A screen-space point, P = ( X, Y, Z, W), of screen-space size S is rasterized as a quadrilateral of the following four vertices.

(( X + S/2, Y + S/2, Z, W), ( X + S/2, Y - S/2, Z, W), ( X - S/2, Y- S/2, Z, W), ( X - S/2, Y + S/2, Z, W))

The vertex color attributes are duplicated at each vertex; thus each point is always rendered with constant colors.

The assignment of texture indices is controlled by the D3DRS_POINTSPRITEENABLE render state setting. If D3DRS_POINTSPRITEENABLE is set to FALSE, then the vertex texture coordinates are duplicated at each vertex. If D3DRS_POINTSPRITEENABLE is set to TRUE, then the texture coordinates at the four vertices are set to the following values.

(0.F, 0.F), (0.F, 1.F), (1.F, 0.F), (1.F, 1.F)

This is shown in the following diagram.

Square with vertices labeled with (u,v) and (x,y) coordinate values

When clipping is enabled, points are clipped in the following manner. If the vertex exceeds the range of depth values - MinZ and MaxZ of the D3DVIEWPORT9 structure - into which a scene is to be rendered, the point exists outside of the view frustum and is not rendered. If the point, taking into account the point size, is completely outside the viewport in X and Y, then the point is not rendered; the remaining points are rendered. It is possible for the point position to be outside the viewport in X or Y and still be partially visible.

Points may or may not be correctly clipped to user-defined clip planes. If D3DPMISCCAPS_CLIPPLANESCALEDPOINTS is not set in the D3DCAPS9 structure's PrimitiveMiscCaps member, points are clipped to user-defined clip planes based only on the vertex position, ignoring the point size. In this case, scaled points are fully rendered when the vertex position is inside the clip planes, and discarded when the vertex position is outside a clip plane. Applications can prevent potential artifacts by adding a border geometry to clip planes that is as large as the maximum point size.

If the D3DPMISCCAPS_CLIPPLANESCALEDPOINTS bit is set, then the scaled points are correctly clipped to user-defined clip planes.

Hardware vertex processing may or may not support point size. For example, if a device is created with D3DCREATE_HARDWARE_VERTEXPROCESSING on a hardware abstraction layer (HAL) device (D3DDEVTYPE_HAL) that has the D3DCAPS9 structure's MaxPointSize member set to 1.0 or 0.0, then all points are a single pixel. To render pixel point sprites less than 1.0, you must use either FVF TL (transformed and lit) vertices or software vertex processing (D3DCREATE_SOFTWARE_VERTEXPROCESSING), in which case the Direct3D run time emulates the point sprite rendering.

A hardware device that does vertex processing and supports point sprites - MaxPointSize set to greater than 1.0f - is required to perform the size computation for nontransformed sprites and is required to properly set the per-vertex or D3DRS_POINTSIZED3DRS_POINTSIZE for TL vertices.

For information about rendering rules for points, lines, and triangles, see Rasterization Rules (Direct3D 9).


Matrix Stacks (Direct3D 9)

The D3DX utility library provides the ID3DXMATRIXStack interface. It supplies a mechanism to enable matrices to be pushed onto and popped off of a matrix stack. Implementing a matrix stack is an efficient way to track matrices while traversing a transform hierarchy.

The D3DX utility library uses a matrix stack to store transformations as matrices. The various methods of the ID3DXMATRIXStack interface deal with the current matrix, or the matrix located on top of the stack. You can clear the current matrix with the ID3DXMATRIXStack::LoadIdentity method. To explicitly specify a certain matrix to load as the current transformation matrix, use the ID3DXMATRIXStack::LoadMatrix method. Then you can call either the ID3DXMATRIXStack::MultMatrix method or the ID3DXMATRIXStack::MultMatrixLocal method to multiply the current matrix by the specified matrix.

The ID3DXMATRIXStack::Pop method enables you to return to the previous transformation matrix and the ID3DXMATRIXStack::Push method adds a transformation matrix to the stack.

The individual matrices on the matrix stack are represented as 4x4 homogeneous matrices, defined by the D3DX utility library D3DXMATRIX structure.

The D3DX utility library provides a matrix stack through a component object model (COM) object.

Implementing a Scene Hierarchy

A matrix stack simplifies the construction of hierarchical models, in which complicated objects are constructed from a series of simpler objects.

A scene, or transform, hierarchy is usually represented by a tree data structure. Each node in the tree data structure contains a matrix. A particular matrix represents the change in coordinate systems from the node's parent to the node. For example, if you are modeling a human arm, you might implement the following hierarchy.

Hierarchy of modeling of a human arm

In this hierarchy, the Body matrix places the body in the world. The UpperArm matrix contains the rotation of the shoulder, the LowerArm matrix contains the rotation of the elbow, and the Hand matrix contains the rotation of the wrist. To determine where the hand is relative to the world, you multiply all the matrices from Body down through Hand together.

The previous hierarchy is overly simplistic, because each node has only one child. If you begin to model the hand in more detail, you will probably add fingers and a thumb. Each digit can be added to the hierarchy as children of Hand.

Hierarchy of modeling of a human hand

If you traverse the complete graph of the arm in depth-first order - traversing as far down one path as possible before moving on to the next path - to draw the scene, you perform a sequence of segmented rendering. For example, to render the hand and fingers, you implement the following pattern.

  1. Push the Hand matrix onto the matrix stack.
  2. Draw the hand.
  3. Push the Thumb matrix onto the matrix stack.
  4. Draw the thumb.
  5. Pop the Thumb matrix off the stack.
  6. Push the Finger 1 matrix onto the matrix stack.
  7. Draw the first finger.
  8. Pop the Finger 1 matrix off the stack.
  9. Push the Finger 2 matrix onto the matrix stack. You continue in this manner until all the fingers and thumb are rendered.

After you have completed rendering the fingers, you would pop the Hand matrix off the stack.

You can follow this basic process in code with the following examples. When you encounter a node during the depth-first search of the tree data structure, push the matrix onto the top of the matrix stack.

MatrixStack->Push();

MatrixStack->MultMatrix(pNode->matrix);

When you are finished with a node, pop the matrix off the top of the matrix stack.

MatrixStack->Pop();

In this way, the matrix on the top of the stack always represents the world-transform of the current node. Therefore, before drawing each node, you should set the Direct3D matrix.

pD3DDevice->SetTransform(D3DTS_WORLDMATRIX(0), *MatrixStack->GetTop());

For more information about the specific methods that you can perform on a D3DX matrix stack, see the ID3DXMATRIXStack reference topic.


Pixel Pipeline (Direct3D 9)

This is a list of advanced topics that are implemented by pixel processing.

  • Scissor Test
  • Depth Bias
  • Stencil Buffer Techniques
  • Shadowing
  • Bump Mapping
  • Environment Mapping
  • Antialiasing
  • Multiple Render Targets
  • Multiple-element Textures


Scissor Test (Direct3D 9)

The scissor test culls pixels that are outside of the scissor rectangle, a user-defined rectangular sub-section of the render target.

The scissor rectangle could be used to indicate the area of the render target where the game world is drawn. The area outside the rectangle is culled and could be devoted to a game's GUI. The scissor test can not cull non-rectangular areas.

Scissor rectangles can not be set larger than the render target, but they can be set larger than the viewport.

The scissor rectangle is managed by a device render state. A scissor test is enabled or disabled by setting the renderstate to TRUE or FALSE. This test is performed after the fragment color is computed but before alpha testing. IDirect3DDevice9::SetRenderTarget resets the scissor rectangle to the full render target, analogous to the viewport reset. IDirect3DDevice9::SetScissorRect is recorded by stateblocks, and IDirect3DDevice9::CreateStateBlock with the all state setting (D3DSBT_ALL value in D3DSTATEBLOCKTYPE). The scissor test also affects the device IDirect3DDevice9::Clear operation.

// Methods
HRESULT IDirect3DDevice9::SetScissorRect(CONST RECT* pRect);
HRESULT IDirect3DDevice9::GetScissorRect(RECT* pRect);

// New RenderState, values are TRUE or FALSE
D3DRS_SCISSORTESTENABLE

// New hardware cap
D3D9CAPS.RasterCaps -> D3DPRASTERCAPS_SCISSORTEST;

The default scissor rectangle is the full viewport.

Scissor testing is done just after pixel processing is completed by a pixel shader or the fixed function pipeline, as shown below.

Figure 1. Scissor test flowchart


Depth Bias (Direct3D 9)

Polygons that are coplanar in your 3D space can be made to appear as if they are not coplanar by adding a z-bias to each one. This is a technique commonly used to ensure that shadows in a scene are displayed properly. For instance, a shadow on a wall will likely have the same depth value as the wall does. If you render the wall first and then the shadow, the shadow might not be visible, or depth artifacts might be visible. You can reverse the order in which you render the coplanar objects in hopes of reversing the effect, but depth artifacts are still likely.

An application can help ensure that coplanar polygons are rendered properly by adding a bias to the z-values that the system uses when rendering the sets of coplanar polygons. To add a z-bias to a set of polygons, call the IDirect3DDevice9::SetRenderState method just before rendering them, setting the State parameter to D3DRS_DEPTHBIAS, and the Value parameter to a value between 0-16 inclusive. A higher z-bias value increases the likelihood that the polygons you render will be visible when displayed with other coplanar polygons.

Offset = m * D3DRS_SLOPESCALEDEPTHBIAS + D3DRS_DEPTHBIAS

where m is the maximum depth slope of the triangle being rendered.

m = max(abs(delta z / delta x), abs(delta z / delta y))

The units for the D3DRS_DEPTHBIAS and D3DRS_SLOPESCALEDEPTHBIAS render states depend on whether z-buffering or w-buffering is enabled. The application must provide suitable values.

The bias is not applied to any line and point primitive. However, this bias needs to be applied to triangles drawn in wireframe mode.

// RenderStates
D3DRS_SLOPESCALEDEPTHBIAS, // Defaults to zero
D3DRS_DEPTHBIAS,           // Defaults to zero

// Caps
D3DPRASTERCAPS_DEPTHBIAS
D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS


Stencil Buffer Techniques (Direct3D 9)

Applications use the stencil buffer to mask pixels in an image. The mask controls whether the pixel is drawn or not. Some of the more common effects are shown below.

  • Compositing
  • Decaling
  • Dissolves, Fades, and Swipes
  • Outlines and Silhouettes
  • Two-Sided Stencil

The stencil buffer enables or disables drawing to the rendering target surface on a pixel-by-pixel basis. At its most fundamental level, it enables applications to mask sections of the rendered image so that they are not displayed. Applications often use stencil buffers for special effects such as dissolves, decaling, and outlining.

Stencil buffer information is embedded in the z-buffer data. Your application can use the IDirect3D9::CheckDeviceFormat method to check for hardware stencil support, as shown in the following code example.

// Reject devices that cannot perform 8-bit stencil buffering.
// The following example assumes that pCaps is a valid pointer
// to an initialized D3DCAPS9 structure.

if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal,
                                       pCaps->DeviceType,
                                       Format,
                                       D3DUSAGE_DEPTHSTENCIL,
                                       D3DRTYPE_SURFACE,
                                       D3DFMT_D24S8 ) ) )
return E_FAIL;

IDirect3D9::CheckDeviceFormat allows you to choose a device to create based on the capabilities of that device. In this case, devices that do not support 8-bit stencil buffers are rejected. Note that this is only one possible use for IDirect3D9::CheckDeviceFormat; for details see Determining Hardware Support (Direct3D 9).

How the Stencil Buffer Works

Direct3D performs a test on the contents of the stencil buffer on a pixel-by-pixel basis. For each pixel in the target surface, it performs a test using the corresponding value in the stencil buffer, a stencil reference value, and a stencil mask value. If the test passes, Direct3D performs an action. The test is performed using the following steps.

  1. Perform a bitwise AND operation of the stencil reference value with the stencil mask.
  2. Perform a bitwise AND operation of the stencil buffer value for the current pixel with the stencil mask.
  3. Compare the result of step 1 to the result of step 2, using the comparison function.

These steps are shown in the following code example.

(StencilRef & StencilMask) CompFunc (StencilBufferValue & StencilMask)

StencilBufferValue is the contents of the stencil buffer for the current pixel. This code example uses the ampersand (&) symbol to represent the bitwise AND operation. StencilMask represents the value of the stencil mask, and StencilRef represents the stencil reference value. CompFunc is the comparison function.

The current pixel is written to the target surface if the stencil test passes, and is ignored otherwise. The default comparison behavior is to write the pixel, no matter how each bitwise operation turns out (D3DCMP_ALWAYS). You can change this behavior by changing the value of the D3DRS_STENCILFUNC render state, passing a member of the D3DCMPFUNC enumerated type to identify the desired comparison function.

Your application can customize the operation of the stencil buffer. It can set the comparison function, the stencil mask, and the stencil reference value. It can also control the action that Direct3D takes when the stencil test passes or fails. For more information, see Stencil Buffer State (Direct3D 9).

Examples

The following code examples demonstrate setting up the stencil buffer.

// Enable stencil testing
pDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);

// Specify the stencil comparison function
pDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_EQUAL);

// Set the comparison reference value
pDevice->SetRenderState(D3DRS_STENCILREF, 0);

//  Specify a stencil mask
pDevice->SetRenderState(D3DRS_STENCILMASK, 0);

By default, the stencil reference value is zero. Any integer value is valid. Direct3D performs a bitwise AND of the stencil reference value and a stencil mask value before the stencil test.

You can control what pixel information is written out depending on the stencil comparison.

// A write mask controls what is written
pDevice->SetRenderState(D3DRS_STENCILWRITEMASK, D3DSTENCILOP_KEEP);
// Specify when to write stencil data
pDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP);

You can write your own formula for the value you want written into the stencil buffer as shown in the following example.

NewStencilBufferValue = (StencilBufferValue & ~StencilWriteMask) |
                        (StencilWriteMask & StencilOp(StencilBufferValue))


Compositing (Direct3D 9)

Your application can use the stencil buffer to composite 2D or 3D images onto a 3D scene. A mask in the stencil buffer is used to occlude an area of the rendering target surface. Stored 2D information, such as text or bitmaps, can then be written to the occluded area. Alternately, your application can render additional 3D primitives to the stencil-masked region of the rendering target surface. It can even render an entire scene.

Games often composite multiple 3D scenes together. For instance, driving games typically display a rear-view mirror. The mirror contains the view of the 3D scene behind the driver. It is essentially a second 3D scene composited with the driver's forward view.


Decaling (Direct3D 9)

Direct3D applications use decaling to control which pixels from a particular primitive image are drawn to the rendering target surface. Applications apply decals to the images of primitives to enable coplanar polygons to render correctly.

For instance, when applying tire marks and yellow lines to a roadway, the markings should appear directly on top of the road. However, the z values of the markings and the road are the same. Therefore, the depth buffer might not produce a clean separation between the two. Some pixels in the back primitive may be rendered on top of the front primitive and vice versa. The resulting image appears to shimmer from frame to frame. This effect is called z-fighting or flimmering.

To solve this problem, use a stencil to mask the section of the back primitive where the decal will appear. Turn off z-buffering and render the image of the front primitive into the masked-off area of the render-target surface.

Although multiple texture blending can be used to solve this problem, doing so limits the number of other special effects that your application can produce. Using the stencil buffer to apply decals frees up texture blending stages for other effects.


Dissolves, Fades, and Swipes (Direct3D 9)

Increasingly, applications employ special effects that are commonly used in movies and video, such as dissolves, swipes, and fades.

In a dissolve, one image is gradually replaced by another in a smooth sequence of frames. Although Direct3D provides methods of using multiple texture blending to achieve the same effect, applications that use the stencil buffer for dissolves can use texture-blending capabilities for other effects while they do a dissolve.

When your application performs a dissolve, it must render two different images. It uses the stencil buffer to control which pixels from each image are drawn to the rendering target surface. You can define a series of stencil masks and copy them into the stencil buffer on successive frames. Alternately, you can define a base stencil mask for the first frame and alter it incrementally.

At the beginning of the dissolve, your application sets the stencil function and stencil mask so that most of the pixels from the starting image pass the stencil test. Most of the pixels from the ending image should fail the stencil test. On successive frames, the stencil mask is updated so that fewer and fewer of the pixels in the starting image pass the test. As the frames progress, fewer and fewer of the pixels in the ending image fail the test. In this manner, your application can perform a dissolve using any arbitrary dissolve pattern.

Fading in or fading out is a special case of dissolving. When fading in, the stencil buffer is used to dissolve from a black or white image to a rendering of a 3D scene. Fading out is the opposite, your application starts with a rendering of a 3D scene and dissolves to black or white. The fade can be done using any arbitrary pattern you want to employ.

Direct3D applications use a similar technique for swipes. For example, when an application performs a left-to-right swipe, the ending image appears to slide gradually on top of the starting image from left to right. As in a dissolve, you must define a series of stencil masks that are loaded into the stencil buffer on successive frames, or successively modify the starting stencil mask. The stencil masks are used to disable the writing of pixels from the starting image and to enable the writing of pixels from the ending image.

A swipe is somewhat more complex than a dissolve in that your application must read pixels from the ending image in the reverse order of the swipe. That is, if the swipe is moving from left to right, your application must read pixels from the ending image from right to left.


Outlines and Silhouettes (Direct3D 9)

You can use the stencil buffer for more abstract effects, such as outlining and silhouetting.

If your application applies a stencil mask to the image of a primitive that is the same shape but slightly smaller, the resulting image contains only the primitive's outline. The application can then fill the stencil-masked area of the image with a solid color, giving the primitive an embossed look.

If the stencil mask is the same size and shape as the primitive you are rendering, the resulting image contains a hole where the primitive should be. Your application can then fill the hole with black to produce a silhouette of the primitive.


Two-Sided Stencil (Direct3D 9)

Shadow Volumes are used for drawing shadows with the stencil buffer. The application computes the shadow volumes cast by occluding geometry, by computing the silhouette edges and extruding them away from the light into a set of 3D volumes. These volumes are then rendered twice into the stencil buffer.

The first render draws forward-facing polygons, and increments the stencil-buffer values. The second render draws the back-facing polygons of the shadow volume, and decrements the stencil buffer values. Normally, all incremented and decremented values cancel each other out. However, the scene was already rendered with normal geometry causing some pixels to fail the z-buffer test as the shadow volume is rendered. Values left in the stencil buffer correspond to pixels that are in the shadow. These remaining stencil-buffer contents are used as a mask, to alpha-blend a large, all-encompassing black quad into the scene. With the stencil buffer acting as a mask, the result is to darken pixels that are in the shadows.

This means that the shadow geometry is drawn twice per light source, hence putting pressure on the vertex throughput of the GPU. The two-sided stencil feature has been designed to mitigate this situation. In this approach, there are two sets of stencil state (named below), one set each for the front-facing triangles and the other for the back-facing triangles. This way, only a single pass is drawn per shadow volume, per light.

The API changes are restricted to a new set of render states. The new render state D3DRS_Two_Sided_StencilMODE can be set to TRUE or FALSE. It is false by default, meaning current (DirectX 8) behavior. When this is set to TRUE (it will work only if D3DSTENCILCAPS_TWOSIDED is set), the following render states will apply only to the front-facing (clockwise) triangles.

Render state | Description
D3DRS_STENCILFAIL | D3DSTENCILOP to do if stencil test fails.
D3DRS_STENCILZFAIL | D3DSTENCILOP to do if stencil test passes and z-test fails.
D3DRS_STENCILPASS | D3DSTENCILOP to do if both stencil and z-tests pass.
D3DRS_STENCILFUNC | D3DCMPFUNC fn. Stencil Test passes if ((ref & mask) stencilfn (stencil & mask)) is true.

A new set of render states apply to the back-facing (counterclockwise) triangles.

Render state | Description
D3DRS_CCW_STENCILFAIL | D3DSTENCILOP to do if stencil test fails.
D3DRS_CCW_STENCILZFAIL | D3DSTENCILOP to do if stencil test passes and z-test fails.
D3DRS_CCW_STENCILPASS | D3DSTENCILOP to do if both stencil and z-tests pass.
D3DRS_CCW_STENCILFUNC | D3DCMPFUNC function. Stencil test passes if ((ref & mask) stencilfn (stencil & mask)) is true.

The remaining stencil render states always apply to both clockwise and counterclockwise triangles.

D3DRS_Two_Sided_StencilMODE is ignored for lines and point sprites, which means that the behavior is unchanged from DirectX 8. The D3DRS_CCW_STENCIL* render states are ignored.

A new cap bit indicates if the device supports this feature. Drivers that do not support this feature are expected to ignore these new render states. All other stencil cap bits apply to both modes of stencil buffering. Because Two_Sided_Stencil implies the ability to draw with D3DCULLMODE_NONE set, the corresponding cap must be set by the driver if it supports this new stencil mode. Microsoft Windows Hardware Quality Labs (WHQL) should enforce this.

New render states:

D3DRS_Two_Sided_StencilMODE // BOOL (default is FALSE)
D3DRS_CCW_STENCILFAIL     // Same default as D3DRS_STENCILFAIL
D3DRS_CCW_STENCILZFAIL    // Same default as D3DRS_STENCILZFAIL
D3DRS_CCW_STENCILPASS     // Same default as D3DRS_STENCILPASS
D3DRS_CCW_STENCILFUNC     // Same default as D3DRS_STENCILFUNC

New cap:

D3DSTENCILCAPS_TWOSIDED // a flag on D3DCAPS9.StencilCaps

See Also

D3DRENDERSTATETYPE


Shadowing (Direct3D 9)

Stencil buffers are a depth-buffer technique that can be updated as geometry is rendered, and used again as a mask for drawing more geometry. Common effects include mirrors, shadows (an advanced technique), dissolves, and so on. The ShadowVolume Sample uses stencil buffers to implement real-time shadows. Additional information is contained in Two-Sided Stencil (Direct3D 9).


Bump Mapping (Direct3D 9)

Bump mapping is a special form of specular or diffuse environment mapping that simulates the reflections of finely tessellated objects without requiring extremely high polygon counts. Bump mapping implemented by Direct3D can be accurately described as per-pixel texture coordinate perturbation of specular or diffuse environment maps, because you provide information about the contour of the bump map in terms of delta values, which the system applies to the u and v texture coordinates of an environment map in the next texture stage. The delta values are encoded in the pixel format of the bump map surface (see Bump Map Pixel Formats).

Bump mapping relies on blending multiple textures. This means the device must support at least two blending stages; one for the bump map and another for an environment map. A minimum of three texture blending stages are required to apply an additional base texture map, which is the most common case. This figure shows the relationships between the base texture, the bump map, and the environment map in the texture blending cascade:

Texture blending cascade used to generate polygon texture

You must prepare the texture stages appropriately to enable bump mapping. The following topics introduce bump mapping, and provide details about how you can use it in your applications:

  • Bump Map Pixel Formats
  • Bump Mapping Formulas
  • Using Bump Mapping

Direct3D does not natively support height maps; they are merely a convenient format in which to store and visualize contour data. Your application can store contour information in any format, or even generate a procedural bump map.


Bump Map Pixel Formats (Direct3D 9)

A bump map is an IDirect3DTexture9 object that uses a specialized pixel format. Rather than storing red, green, and blue color components, each pixel in a bump map stores the delta values for u and v (DU and DV) and sometimes a luminance component, L. These values are applied by the system as described in the Bump Mapping Formulas (Direct3D 9) topic.

You can specify a bump map pixel format by setting the format to one of the following: D3DFMT_CxV8U8, D3DFMT_V8U8, D3DFMT_L6V5U5, D3DFMT_X8L8V8U8, D3DFMT_Q8W8V8U8, or D3DFMT_V16U16. For descriptions, see D3DFORMAT.

The DU and DV components of a pixel are signed values that range from - 1.0 to +1.0. The luminance component, when used, is an unsigned integer value that ranges from 0 to 255.

Note Before picking a bump map pixel format, check if the particular format is supported. For more information, see Using Bump Mapping (Direct3D 9).


Bump Mapping Formulas (Direct3D 9)

Direct3D applies the following formulas to the DU and DV components in each bump map pixel.

Formula for bump mapping matrix transformation

In these formulas, the DU and DV variables are taken directly from a bump map pixel and transformed by a 2x2 matrix to produce the output delta values DU' and DU'. The system uses the output values to modify the texture coordinates that address the environment map in the next texture stage. The coefficients of the transformation matrix are set though the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT10, D3DTSS_BUMPENVMAT01, and D3DTSS_BUMPENVMAT11 texture stage states.

In addition to the u and v delta values, the system can compute a luminance value that it uses to modulate the color of the environment map in the next blending stage.

Formula for output luminance, computed from scale factor and offset

In this formula, L' is the output luminance being computed. The L variable is the luminance value taken from a bump map pixel, which is multiplied by the scaling factor, S, and offset by the value in the variable O. The D3DTSS_BUMPENVLSCALE and D3DTSS_BUMPENVLOFFSET texture stage states control the values for the S and O variables in the formula. This formula is only applied when the texture blending operation for the stage that contains the bump map is set to D3DTOP_BUMPENVMAPLUMINANCE. When using D3DTOP_BUMPENVMAP, the system uses a value of 1.0 for L'.

After computing the output delta values DU' and DV', the system adds them to the texture coordinates in the next texture stage, and modulates the chosen color by the luminance to produce the color applied to the polygon.


Using Bump Mapping (Direct3D 9)

Detecting Support for Bump Mapping

A device can perform bump mapping if it supports either the D3DTOP_BUMPENVMAP or D3DTOP_BUMPENVMAPLUMINANCE texture blending operation. Use IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_LEGACYBUMPMAP to see if a format is supported for bump mapping.

Additionally, applications should check the device capabilities to make sure the device supports an appropriate number of blending stages, usually at least three, and exposes at least one bump-mapping pixel format.

The following code example checks device capabilities to detect support for bump mapping in the current device, using the given criteria.

BOOL SupportsBumpMapping()
{
    D3DCAPS9 d3dCaps;

    d3dDevice->GetDeviceCaps( &d3dCaps );

    // Does this device support the two bump mapping blend operations?
    if ( 0 == d3dCaps.TextureOpCaps & ( D3DTEXOPCAPS_BUMPENVMAP |
                                            D3DTEXOPCAPS_BUMPENVMAPLUMINANCE ))
        return FALSE;

    // Does this device support up to three blending stages?
    if( d3dCaps.MaxTextureBlendStages < 3 )
        return FALSE;

    return TRUE;
}

Creating a Bump Map Texture

You create a bump map texture like any other texture. Your application verifies support for bump mapping and retrieves a valid pixel format, as discussed in Detecting Support for Bump Mapping.

After the surface is created, you can load each pixel with the appropriate delta values, and luminance, if the surface format includes luminance. The values for each pixel component are described in Bump Map Pixel Formats (Direct3D 9).

Configuring Bump Mapping Parameters

When your application has created a bump map and set the contents of each pixel, you can prepare for rendering by configuring bump mapping parameters. Bump mapping parameters include setting the required textures and their blending operations, as well as the transformation and luminance controls for the bump map itself.

  1. Set the base texture map if used, bump map, and environment map textures into texture blending stages.
  2. Set the color and alpha blending operations for each texture stage.
  3. Set the bump map transformation matrix.
  4. Set the luminance scale and offset values as needed.

The following code example sets three textures (the base texture map, the bump map, and a specular environment map) to the appropriate texture blending stages.

// Set the three textures.
d3dDevice->SetTexture( 0, d3dBaseTexture );
d3dDevice->SetTexture( 1, d3dBumpMap );
d3dDevice->SetTexture( 2, d3dEnvMap );

After setting the textures to their blending stages, the following code example prepares the blending operations and arguments for each stage.

// Set the color operations and arguments to prepare for
//   bump mapping.

// Stage 0: The base texture
d3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
d3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
d3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 1 );

// Stage 1: The bump map - Use luminance for this example.
d3dDevice->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, 1 );
d3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_BUMPENVMAPLUMINANCE);
d3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG2, D3DTA_CURRENT );

// Stage 2: A specular environment map
d3dDevice->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX, 0 );
d3dDevice->SetTextureStageState( 2, D3DTSS_COLOROP, D3DTOP_ADD );
d3dDevice->SetTextureStageState( 2, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 2, D3DTSS_COLORARG2, D3DTA_CURRENT );

When the blending operations and arguments are set, the following code example sets the 2x2 bump mapping matrix to the identity matrix by setting the D3DTSS_BUMPENVMAPMAT00 and the D3DTSS_BUMPENVMAPMAT11 members of D3DTEXTURESTAGESTATETYPE to 1.0. Setting the matrix to the identity causes the system to use the delta values in the bump map unmodified, but this is not a requirement.

// Set the bump mapping matrix.
//
// Note  These calls rely on the following inline shortcut function:
//   inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT00, F2DW(1.0f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT01, F2DW(0.0f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT10, F2DW(0.0f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT11, F2DW(1.0f) );

If you set the bump mapping operation to include luminance (D3DTOP_BUMPENVMAPLUMINANCE), you must set the luminance controls. The luminance controls configure how the system computes luminance before modulating the color from the texture in the next stage. For details, see Bump Mapping Formulas (Direct3D 9).

// Set luminance controls. This is only needed when using
// a bump map that contains luminance, and when the
// D3DTOP_BUMPENVMAPLUMINANCE texture blending operation is
// being used.
//
// Note  These calls rely on the following inline shortcut function:
//   inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVLSCALE, F2DW(0.5f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVLOFFSET, F2DW(0.0f) );

After your application configures bump mapping parameters, it can render as normal, and the rendered polygons receive bump mapping effects.

Note that the preceding example shows parameters set for specular environment mapping. When performing diffuse light mapping, applications set the texture blending operation for the last stage to D3DTOP_MODULATE. For more information, see Diffuse Light Maps (Direct3D 9).


Environment Mapping (Direct3D 9)

Environment mapping is a technique that simulates highly reflective surfaces without using ray tracing. In practice, environment mapping applies a special texture map that contains an image of the scene surrounding an object to the object itself. The result approximates the appearance of a reflective surface, close enough to fool the eye, without incurring any of the complex computations involved in ray tracing.

The following image demonstrates a type of environment mapping called spherical environment mapping. For details, see Spherical Environment Mapping.

Teapot image with applied texture that simulates reflection of the surroundings

The teapot in this image appears to reflect its surroundings; this is actually a texture being applied to the object. Because environment mapping uses a texture, combined with specially computed texture coordinates, it can be performed in real-time.

This section provides information about performing two common types of environment mapping with Direct3D. There are many types of environment mapping in use throughout the graphics industry, but the following topics target the two most common forms: cubic environment mapping and spherical environment mapping.

  • Cubic Environment Mapping
  • Spherical Environment Mapping


Cubic Environment Mapping (Direct3D 9)

Cubic environment maps - sometimes referred to as cube maps - are textures that contain image data representing the scene surrounding an object, as if the object were in the center of a cube. Each face of the cubic environment map covers a 90-degree field of view in the horizontal and vertical, and there are six faces per cube map. The orientation of the faces is given in the following illustration.

Cube with central coordinate axes perpendicular to cube faces

Each face of the cube is oriented perpendicular to the x/y, y/z, or x/z plane, in world space. The following figure shows how each plane corresponds to a face.

Faces of cube with coordinate projections on each face

Cubic environment maps are implemented as a series of texture objects. Applications can use static images for cubic environment mapping, or they can render into the faces of the cube map to perform dynamic environment mapping. This technique requires that the cube-map surfaces be valid render-target surfaces, created with the D3DUSAGE_RENDERTARGET flag set.

The faces of a cube map don't need to contain extremely detailed renderings of the surrounding scene. In most cases, environment maps are applied to curved surfaces. Given the amount of curvature used by most applications, the resulting reflective distortion makes extreme detail in the environment map wasteful in terms of memory and rendering overhead.

Mipmapped Cubic Environment Maps

Cube maps can be mipmapped. To create a mipmapped cube map, set the Levels parameter of the IDirect3DDevice9::CreateCubeTexture method to the number of levels that you want. You can envision the topography of these surfaces as shown in the following graphic.

Mipmapped cube map with n mip levels

Applications that create mipmapped cubic environment maps can access each face by calling the IDirect3DCubeTexture9::GetCubeMapSurface method. Start by setting the appropriate value from the D3DCUBEMAP_FACES enumerated type, as discussed in Creating Cubic Environment Map Surfaces (Direct3D 9). Next, select the level to retrieve by setting the IDirect3DCubeTexture9::GetCubeMapSurface level parameter to the mipmap level that you want. Remember that 0 corresponds with the top-level image.

Texture Coordinates for Cubic Environment Maps

Texture coordinates that index a cubic environment map aren't simple u, v style coordinates, as used when standard textures are applied. In fact, cubic environment maps don't use texture coordinates at all. In place of a set of texture coordinates, cubic environment maps require a 3D vector. You must take care to specify a proper vertex format. In addition to telling the system how many sets of texture coordinates your application uses, you must provide information about how many elements are in each set. Direct3D offers the D3DFVF_TEXCOORDSIZEN set of macros for this purpose. These macros accept a single parameter, identifying the index of the texture coordinate set for which the size is being described. In the case of a 3D vector, you include the bit pattern created by the D3DFVF_TEXCOORDSIZE3 macro. The following code example shows how this macro is used.

// Create a flexible vertex format descriptor for a vertex that contains
//   a position, normal, and one set of 3D texture coordinates.

DWORD dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE3(0);

In some cases, such as diffuse light mapping, you use the camera-space vertex normal for the vector. In other cases, like specular environment mapping, you use a reflection vector. Because transformed vertex normals are widely understood, the information here concentrates on computing a reflection vector.

Computing a reflection vector on your own requires understanding of the position of each vertex, and of a vector from the viewpoint to that vertex. Direct3D can automatically compute the reflection vectors for your geometry. Using this feature saves memory because you don't need to include texture coordinates for the environment map. It also reduces bandwidth and, in the case of a T&L HAL Device, it can be significantly faster than the computations that your application can make on its own. To use this feature, in the texture stage that contains the cubic environment map, set the D3DTSS_TEXCOORDINDEX texture stage state to a combination of the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR member of D3DTEXTURESTAGESTATETYPE and the index of a texture coordinate set. In some situations, like diffuse light mapping, you might use the D3DTSS_TCI_CAMERASPACENORMAL member of D3DTEXTURESTAGESTATETYPE, which causes the system to use the transformed, camera-space, vertex normal as the addressing vector for the texture. The index is only used by the system to determine the wrapping mode for the texture.

The following code example shows how this value is used.

// The m_d3dDevice variable is a valid pointer
// to an IDirect3DDevice9 interface.

// Automatically generate texture coordinates for stage 2.
// This assumes that stage 2 is assigned a cube map.
// Use the wrap mode from the texture coordinate set at index 1.

m_d3dDevice->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX,
                                   D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR | 1);

When you enable automatic texture coordinate generation, the system uses one of two formulas to compute the reflection vector for each vertex. When the D3DRS_LOCALVIEWER render state is set to TRUE, the formula used is the following:

R = 2(ExN)N-E

In the preceding formula, R is the reflection vector being computed, E is the normalized position-to-eye vector, and N is the camera-space vertex normal.

When the D3DRS_LOCALVIEWER render state is set to FALSE, the system uses the following formula.

R = 2NzN-I

The R and N elements in this formula are identical to the previous formula. The NZ element is the world-space z of the vertex normal, and I is the vector (0,0,1) of an infinitely distant viewpoint. The system uses the reflection vector from either formula to select and address the appropriate face of the cube map.

Note In most cases, applications should enable automatic normalization of vertex normals. To do this, set D3DRS_NORMALIZENORMALS to TRUE. If you do not enable this render state, the appearance of the environment map will be drastically different than you might expect.

Additional information is contained in the following topic.

  • Creating Cubic Environment Map Surfaces (Direct3D 9)


Creating Cubic Environment Map Surfaces (Direct3D 9)

You create a cubic environment map texture by calling the IDirect3DDevice9::CreateCubeTexture method. Cubic environment map textures must be square, with dimensions that are a power of two.

The following code example shows how your C++ application might create a simple cubic environment map.

// Init m_d3dDevice to point to an IDirect3DDevice9 interface

LPDIRECT3DCUBETEXTURE9 m_pCubeMap;

m_d3dDevice->CreateCubeTexture(256, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R8G8B8,
                                D3DPOOL_DEFAULT, &m_pCubeMap);

Accessing Cubic Environment Map Faces

You can navigate between faces of a cubic environment map by using the IDirect3DCubeTexture9::GetCubeMapSurface method.

The following code example uses IDirect3DCubeTexture9::GetCubeMapSurface to retrieve the cube-map surface used for the positive y-face (face 2).

// Init m_pCubeMap to point to an IDirect3DCubeTexture9 interface

LPDIRECT3DSURFACE9 pFace2;
m_pCubeMap->GetCubeMapSurface(D3DCUBEMAP_FACE_POSITIVE_Y, 0, &pFace2);

The first parameter that IDirect3DCubeTexture9::GetCubeMapSurface accepts is a D3DCUBEMAP_FACES enumerated value that describes the attached surface that the method should retrieve. The second parameter tells Direct3D which level of a mipmapped cube texture to retrieve. The third parameter accepted is the address of the IDirect3DSurface9 interface, representing the returned cube texture surface. Because this cube-map is not mipmapped, 0 is used here.

Note

After calling this method, the internal reference count on the IDirect3DSurface9 interface is increased. When you are done using this surface, be sure to call the IUnknown method on this IDirect3DSurface9 interface or you will have a memory leak.

Rendering to Cubic Environment Maps

You can copy images to the individual faces of the cube map just like you would any other texture or surface object. The most important thing to do before rendering to a face is set the transformation matrices so that the camera is positioned properly and points in the proper direction for that face: forward (+z), backward (-z), left (-x), right (+x), up (+y), or down (-y).

The following C++ code example prepares and sets a view matrix according to the face being rendered.

// Init pCubeMap to point to an IDirect3DCubeTexture9 interface
// Init d3dDevice to point to an IDirect3DDevice9 interface

void RenderFaces()
{
    // Save transformation matrices of the device
    D3DXMATRIX matProjSave, matViewSave;
    d3dDevice->GetTransform(D3DTS_VIEW,       &matViewSave ;
    d3dDevice->GetTransform(D3DTS_PROJECTION, &matProjSave);

    // Store the current back buffer and z-buffer
    LPDIRECT3DSURFACE9 pBackBuffer, pZBuffer;
    d3dDevice->GetRenderTarget(&pBackBuffer);
    d3dDevice->GetDepthStencilSurface(&pZBuffer);

Remember, each face of a cubic environment map represents a 90-degree field of view. Unless your application requires a different field of view angle - for special effects, for example - take care to set the projection matrix accordingly.

This code example creates and sets a projection matrix for the most common case.

    // Use 90-degree field of view in the projection
    D3DMATRIX matProj;
    D3DXMatrixPerspectiveFovLH(matProj, D3DX_PI/2, 1.0f, 0.5f, 1000.0f);
    d3dDevice->SetTransform(D3DTS_PROJECTION, &matProj);

    // Loop through the six faces of the cube map
    for(DWORD i=0; i<6; i++)
    {
        // Standard view that will be overridden below
        D3DVECTOR vEnvEyePt = D3DVECTOR(0.0f, 0.0f, 0.0f);
        D3DVECTOR vLookatPt, vUpVec;

        switch(i)
        {
            case D3DCUBEMAP_FACE_POSITIVE_X:
                vLookatPt = D3DVECTOR(1.0f, 0.0f, 0.0f);
                vUpVec    = D3DVECTOR(0.0f, 1.0f, 0.0f);
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_X:
                vLookatPt = D3DVECTOR(-1.0f, 0.0f, 0.0f);
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f);
                break;
            case D3DCUBEMAP_FACE_POSITIVE_Y:
                vLookatPt = D3DVECTOR(0.0f, 1.0f, 0.0f);
                vUpVec    = D3DVECTOR(0.0f, 0.0f,-1.0f);
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_Y:
                vLookatPt = D3DVECTOR(0.0f,-1.0f, 0.0f);
                vUpVec    = D3DVECTOR(0.0f, 0.0f, 1.0f);
                break;
            case D3DCUBEMAP_FACE_POSITIVE_Z:
                vLookatPt = D3DVECTOR( 0.0f, 0.0f, 1.0f);
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f);
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_Z:
                vLookatPt = D3DVECTOR(0.0f, 0.0f,-1.0f);
                vUpVec    = D3DVECTOR(0.0f, 1.0f, 0.0f);
                break;
        }

         D3DMATRIX matView;
         D3DXMatrixLookAtLH(matView, vEnvEyePt, vLookatPt, vUpVec);
         d3dDevice->SetTransform(D3DTS_VIEW, &matView);

When the camera is in position and the projection matrix set, you can render the scene. Each object in the scene should be positioned as you would normally position them. The following code example, provided for completeness, outlines this task.

        // Get pointer to surface in order to render to it
        LPDIRECT3DSURFACE9 pFace;
        pCubeMap->GetCubeMapSurface((D3DCUBEMAP_FACES)i, 0, &pFace);
        d3dDevice->SetRenderTarget (pFace , pZBuffer);
        SAFE_RELEASE(pFace);

        d3dDevice->BeginScene();
        // Render scene here
        ...
        d3dDevice->EndScene();
    }

    // Change the render target back to the main back buffer.
    d3dDevice->SetRenderTarget(pBackBuffer, pZBuffer);
    SAFE_RELEASE(pBackBuffer);
    SAFE_RELEASE(pZBuffer);

    // Restore the original transformation matrices
    d3dDevice->SetTransform(D3DTS_VIEW,       &matViewSave);
    d3dDevice->SetTransform(D3DTS_PROJECTION, &matProjSave);
}

Note the call to the IDirect3DDevice9::SetRenderTarget method. When rendering to the cube map faces, you must assign the face as the current render-target surface. Applications that use depth buffers can explicitly create a depth-buffer for the render-target, or reassign an existing depth-buffer to the render-target surface. The code sample above uses the latter approach.


Spherical Environment Mapping (Direct3D 9)

Spherical environment maps, or sphere maps, are special textures that contain an image of the scene surrounding an object, or the lighting effects around the object. Unlike cubic environment maps, sphere maps don't directly represent an object's surroundings. The teapot image in Environment Mapping (Direct3D 9) topic shows the reflection effects you can achieve with sphere mapping. A sphere map is a 2D representation of the full 360-degree view of the scene surrounding of an object, as if taken through a fish-eye lens.

Sphere map of the inside of a building

Texture Coordinates for Spherical Environment Maps

The texture coordinates that you specify for each vertex receiving an environment mapping should address the texture as a function of the reflective distortion created by the curvature of the surface. Applications must compute these texture coordinates for each vertex to achieve the desired effect. One simple and effective way to generate texture coordinates uses the vertex normal as input. Although several methods exist, the following formula is common among applications that perform environment mapping with sphere maps.

Formula for computing texture coordinates for a sphere map

In these formulas, u and v are the texture coordinates being computed, and NX and NY are the x and y components of the camera-space vertex normal. The formula is simple but effective. If the normal has a positive x component, the normal points to the right, and the u coordinate is adjusted to address the texture appropriately. Likewise for the v coordinate: positive y indicates that the normal points up. The opposite is true for negative values in each component.

If the normal points directly at the camera, the resulting coordinates should receive no distortion. The +0.5 bias to both coordinates places the point of zero-distortion at the center of the sphere map, and a vertex normal of (0, 0, z) addresses this point. This formula doesn't account for the z component of the normal, but applications that use the formula can optimize computations by skipping vertices with a normal that has a positive z element. This works for flat-shaded objects because, in camera space, if the normal points away from the camera (positive z), the vertex is culled when the object is rendered. For Gouraud-shaded objects, a normal can point away from the camera (positive x), and the triangle containing the vertex can still be visible. If you don't compute u and v for this vertex, the face might still be used, resulting in unexpected behavior.

Applying Spherical Environment Maps

You apply an environment map to objects in the same manner as for any other texture, by setting the texture to the appropriate texture stage with the IDirect3DDevice9::SetTexture method. Set the first parameter to the index for the desired texture stage, and set the second parameter to the address of the IDirect3DDevice9 interface returned when you created the texture for the environment map. You can set the color and alpha blending operations and arguments as needed to achieve the desired texture blending effects.


Antialiasing (Direct3D 9)

Antialiasing is a technique you can use to reduce the appearance of stair-step pixels when drawing any line that is not exactly horizontal or vertical. In three-dimensional scenes, this artifact is most noticeable on the boundaries between polygons of different colors. Antialiasing effectively blends the pixels at these boundaries to produce a more natural look to the scene.

  • Full-Scene Antialiasing
  • Motion Blur


Full-Scene Antialiasing (Direct3D 9)

Full-scene antialiasing refers to blurring the edges of each polygon in the scene as it is rasterized in a single pass; no second pass is required. Full-scene antialiasing, when supported, affects only triangles and groups of triangles. Lines cannot be antialiased by using Direct3D services. Full-scene antialiasing is done in Direct3D by using multisampling on each pixel. When multisampling is enabled, all subsamples of a pixel are updated in one pass but when used for other effects that involve multiple rendering passes, the application can specify that only some subsamples are to be affected by a given rendering pass. This latter approach enables simulation of motion blur, depth-of-field focus effects, reflection blur, and so on.

In both cases, the various samples recorded for each pixel are blended together and output to the screen. This enables the improved image quality of antialiasing or other effects.

Before creating a device with the IDirect3D9::CreateDevice method, you need to determine if full-scene antialiasing is supported. Do this by calling the IDirect3D9::CheckDeviceMultiSampleType method as shown in the code example below.

/*
* The code below assumes that pD3D is a valid pointer
*   to a IDirect3D9 interface.
*/

if( SUCCEEDED(pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT,
                    D3DDEVTYPE_HAL , D3DFMT_R8G8B8, FALSE,
                    D3DMULTISAMPLE_2_SAMPLES, NULL ) ) )
// Full-scene antialiasing is supported. Enable it here.

The first parameter that IDirect3D9::CheckDeviceMultiSampleType accepts is an ordinal number that denotes the display adapter to query. This sample uses D3DADAPTER_DEFAULT to specify the primary display adapter. The second parameter is a value from the D3DDEVTYPE enumerated type, specifying the device type. The third parameter specifies the format of the surface. The fourth parameter tells Direct3D whether to inquire about full-windowed multisampling (TRUE) or full-scene antialiasing (FALSE). This sample uses FALSE to tell Direct3D that it is inquiring about full-scene antialiasing. The last parameter specifies the multisampling technique that you want to test. Use a value from the D3DMULTISAMPLE_TYPE enumerated type. This sample tests to see if two levels of multisampling are supported.

If the device supports the level of multisampling that you want to use, the next step is to set the presentation parameters by filling in the appropriate members of the D3DPRESENT_PARAMETERS structure to create a multisample rendering surface. After that, you can create the device. The sample code below shows how to set up a device with a multisampling render surface.

/*
* The example below assumes that pD3D is a valid pointer
* to a IDirect3D9 interface, d3dDevice is a pointer to a
* IDirect3DDevice9 interface, and hWnd is a valid handle
* to a window.
*/

D3DPRESENT_PARAMETER d3dPP
ZeroMemory( &d3dPP, sizeof( d3dPP ) );
d3dPP.Windowed        = FALSE
d3dPP.SwapEffect      = D3DSWAPEFFECT_DISCARD;
d3dPP.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES;
pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                    D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                    &d3dpp, &d3dDevice)

To use multisampling, the SwapEffect member of D3DPRESENT_PARAMETER must be set to D3DSWAPEFFECT_DISCARD.

The last step is to enable multisampling antialiasing by calling the IDirect3DDevice9::SetRenderState method and setting the D3DRS_MULTISAMPLEANTIALIAS to TRUE. After setting this value to TRUE, any rendering that you do will have multisampling applied to it. You might want to enable and disable multisampling, depending on what you are rendering.


Motion Blur (Direct3D 9)

You can enhance the perceived speed of an object in a 3D scene by blurring the object and leaving a blurred trail of object images behind the object. Direct3D applications accomplish this by rendering the object multiple times per frame.

Recall that Direct3D applications typically render scenes into an off-screen buffer. The contents of the buffer are displayed on the screen when the application calls the IDirect3DDevice9::Present method. Your Direct3D application can render the object multiple times into a scene before it displays the frame on the screen.

Programmatically, your application makes multiple calls to a DrawPrimitive method, repeatedly passing the same 3D object. Before each call, the position of the object is updated slightly, producing a series of blurred object images on the target rendering surface. If the object has one or more textures, your application can enhance the motion blur effect by rendering the first image of the object with all its textures nearly transparent. Each time the object renders, the transparency of the object's texture decreases. When your application renders the object in its final position, it should render the object's textures without transparency. The exception is if you're adding motion blur to another effect that requires texture transparency. In any case, the initial image of the object in the frame should be the most transparent. The final image should be the least transparent.

After your application renders the series of object images onto the target rendering surface and renders the rest of the scene, it should call the IDirect3DDevice9::Present method to display the frame on the screen.

If your application is simulating the effect of the user moving through a scene at high speed, it can add motion blur to the entire scene. In this case, your application renders the entire scene multiple times per frame. Each time the scene renders, your application must move the viewpoint slightly. If the scene is highly complex, the user may see a visible performance degradation as acceleration is increased because of the increasing number of scene renderings per frame.


Multiple Render Targets (Direct3D 9)

Multiple Render Targets (MRT) refers to the ability to render to multiple surfaces (see IDirect3D9Surface) with a single draw call. These surfaces can be created independently of each other. Render targets can be set using IDirect3DDevice9::SetRenderTarget.

Multiple render targets have the following restrictions:

  • All render target surfaces used together must have the same bit depth but can be of different formats, unless the D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS cap is set.
  • All surfaces of a multiple render target should have the same width and height.
  • Some implementations cannot perform post-pixel shader operations on multiple render targets, including: no dithering, alpha test, no fogging, no blending or masking, except the z-test and stencil test. Devices that can support post-pixel shader operations set the cap bit to D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING.

    When the D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING cap is set, you must first consult the IDirect3D9::CheckDeviceFormat with the USAGE_QUERY_POSTPIXELSHADER_BLENDING result for the specific surface format. If false, no post-pixel shader blending operations will be available for that specific surface format. If true, the device is expected to apply the same state to all simultaneous render targets as follows:

    • Alpha blend: The color value in oCi is blended with the ith render target.
    • Alpha test: Comparison will happen with oC0. If the comparison fails, the pixel test is terminated for all render targets.
    • Fog: Render target 0 will get fogged. Other render targets are undefined. Implementations can choose to fog them all using the same state.
    • Dithering: Undefined.
  • No antialiasing is supported.
  • Some of the implementations do not apply the output write mask (D3DRS_COLORWRITEENABLE). Those that can, have independent color write masks. This is expressed using a new capability bit. The number of independent color write masks available will be equal to the maximum number of elements the device is capable of.

New hardware caps:

D3DCAPS9.NumSimultaneousRTs
// The value is 1 for all hardware except those that
//   can support this feature. It is never 0.
D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS - True if the hardware can support it
D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING - True if the hardware can support it


Multiple-element Textures (Direct3D 9)

Traditional textures are considered to be single-element textures. Multiple-element textures enable applications to write simultaneously to multiple elements of a texture from the pixel shader. The result in the next rendering pass is that an application can use one or more of the elements as a single-element texture - that is, as inputs to the pixel shader. These additional elements can be thought of as a temporary store for intermediate results that will be used in a later pass by the application.

The first generation of hardware that exposes this feature has the following restrictions:

  • All multiple-element texture surfaces will be allocated automatically. This limitation is addressed by treating this as a new type of surface format with multiple RGBA channels interleaved.
  • All elements of the multiple element texture can have the same bit depth. This limitation is expressed by the name of the new surface formats.
  • A multiple-element texture cannot be the primary/displayable. In other words, it must be off-screen only. This limitation is expressed by the surface-format enumeration.
  • No dithering, alpha test, fogging, blending, raster-op, or masking is allowed. No post-pixel shader processing is done, except the z-test and stencil test.
  • The texture cannot be a mipmap. Creation of the mip chain will fail.
  • The same element cannot be set as a texture at the same time it is a render target. However, different elements of the same multiple-element texture surface can simultaneously be textures and render targets.
  • No antialiasing is supported.
  • Multiple-element texture surfaces, when used as a texture, cannot be filtered. This limitation can be verified using IDirect3D9::CheckDeviceFormat.
  • Multiple-element texture surfaces cannot be locked.
  • More than one multiple-element texture surface can be used simultaneously by assigning each to various stages, just as with normal textures.
  • Multiple-element texture surfaces support conversion of gamma from 2.2 to 1.0 conversion on a read operation, just as with other texture formats.
  • Some of the implementations do not apply the output write mask (D3DRS_COLORWRITEENABLE). Those that can have independent color write masks. This is expressed using a new capability bit. The number of independent color write masks available will be equal to the maximum number of elements of which the device is capable.
  • IDirect3DDevice9::Clear clears all elements of the multiple-element texture which is set as the render target.

The usage of multiple-element textures follows these steps:

  1. Applications discover support for this feature by checking for the availability of multiple-element texture formats.
  2. The application creates these surfaces by calling IDirect3DDevice9::CreateTexture.
  3. The application sets the surface as a render target using the IDirect3DDevice9::SetRenderTarget call. The pixel shader provides output to the surfaces using the mov - ps instruction.
  4. IDirect3DDevice9::SetTexture is called to set a multiple-element texture surface to a particular stage. As with other textures, the same surface is allowed to be set to multiple stages at once.
  5. IDirect3DDevice9::SetSamplerState is called to set D3DSAMP_ELEMENTINDEX to the appropriate element number in the multiple-element texture from which the sampler samples. Default value for this state is 0, which means non-multiple-element textures will work. Setting this state to an inappropriate number results in an undefined behavior - if the multiple-element texture is only two elements wide but the sampler is asked to sample from the fourth element, for example.

API Support

The following is a summary of the API elements that support multiple-element textures:

  • The D3DFMT_MULTI2_ARGB8 surface format expresses the interleaved nature of the format.
  • The D3DSAMP_ELEMENTINDEX sampler state indicates which element index to use.
  • The following render states support multiple-element textures:
    • D3DRS_COLORWRITEENABLE1
    • D3DRS_COLORWRITEENABLE2
    • D3DRS_COLORWRITEENABLE3

    D3DRS_COLORWRITEENABLE applies to render target (or element) zero.

  • The D3DPMISCCAPS_INDEPENDENTWRITEMASKS flag indicates that the device supports independent write masks for multiple element textures or multiple render targets.


Frame Buffer (Direct3D 9)

  • Fog Types
  • Alpha Examples
  • Gamma


Fog Types (Direct3D 9)

There are two ways to add fog to a scene: with pixel fog and/or vertex fog. The following topics illustrate the formulas used in fog equations, as well as implementing vertex and pixel fog. An application can implement fog with a vertex shader, and pixel fog simultaneously if desired.

  • Fog Formulas
  • Fog Parameters
  • Fog Blending
  • Fog Color
  • Vertex Fog
  • Pixel Fog

Fog blending is controlled by render states; it is not part of the programmable pixel pipeline.


Fog Formulas (Direct3D 9)

C++ applications can control how fog affects the color of objects in a scene by changing how Microsoft Direct3D computes fog effects over distance. The D3DFOGMODE enumerated type contains members that identify the three fog formulas. All formulas calculate a fog factor as a function of distance, given parameters that your application sets.

Linear Fog

This is set with D3DFOG_LINEAR.

Direct3D linear fog equation

where

  • start is the distance at which fog effects begin.
  • end is the distance at which fog effects no longer increase.
  • d represents depth, or the distance from the viewpoint. For range based fog, the value for d is the distance between the camera position and a vertex. For non-range based fog, the value for d is the absolute value of the Z-coordinate in camera space.

Exponential Fog

Linear and exponential formulas are supported for both pixel fog and vertex fog.

This is set with D3DFOG_EXP.

Direct3D exponential fog equation

where

  • e is the base of natural logarithms (approximately 2.71828).
  • density is an arbitrary fog density that can range from 0.0 to 1.0.
  • d represents depth, or the distance from the viewpoint, as stated earlier.

This is set with D3DFOG_EXP2.

Direct3D exponential fog equation

where

  • e is the base of natural logarithms as stated above.
  • density is an arbitrary fog density that can range from 0.0 to 1.0 as stated above.
  • d represents depth, or the distance from the viewpoint, as stated above.

Note The system stores the fog factor in the alpha component of the specular color for a vertex. If your application performs its own transformation and lighting, you can insert fog factor values manually, to be applied by the system during rendering.

The following illustration graphs these formulas, using common values as in the formula parameters.

D3DFOG_LINEAR is 1.0 at start and 0.0 at end. It is not measured relative to the near or far planes.

When Direct3D calculates fog effects, it uses the fog factor from one of the preceding equations in a blending formula, shown here.

This formula effectively scales the color of the current polygon C by the fog factor f, and adds the product to the fog color C, scaled by the bitwise inverse of the fog factor. The resulting color value is a blend of the fog color and the original color, as a factor of distance. The formula applies to all devices supported in Microsoft DirectX 7.0 and later. For the legacy ramp device, the fog factor scales the diffuse and specular color components, clamped to the range of 0.0 and 1.0, inclusive. The fog factor typically starts at 1.0 for the near plane and decreases to 0.0 at the far plane.


Fog Parameters (Direct3D 9)

Fog parameters are controlled through device render states. Both pixel and vertex fog types support all the fog formulas introduced in Fog Formulas (Direct3D 9). The D3DFOGMODE enumerated type defines constants that you can use to identify the fog formula you want Microsoft Direct3D to use. The D3DRS_FOGTABLEMODE render state controls the fog mode that Direct3D uses for pixel fog, and the D3DRS_FOGVERTEXMODE render state controls the mode for vertex fog.

When using the linear fog formula, you set the starting and ending distances through the D3DRS_FOGSTART and D3DRS_FOGEND render states. How the system interprets these values depends on the type of fog your application uses - pixel or vertex fog - and, when using pixel fog, if z-based or w-based depth is being used. The following table summarizes fog types and their start and end units.

Fog type | Fog start/end units
Pixel (Z) | Device space [0.0,1.0]
Pixel (W) | Camera space
Vertex | Camera space

The D3DRS_FOGDENSITY render state controls the fog density applied when an exponential fog formula is enabled. Fog density is essentially a weighting factor, ranging from 0.0 to 1.0 (inclusive), that scales the distance value in the exponent.

The color that the system uses for fog blending is controlled through the D3DRS_FOGCOLOR device render state. For more information, see Fog Color (Direct3D 9) and Fog Blending (Direct3D 9).


Fog Blending (Direct3D 9)

Fog blending refers to the application of the fog factor to the fog and object colors to produce the final color that appears in a scene, as discussed in Fog Formulas (Direct3D 9). The D3DRS_FOGENABLE render state controls fog blending. Set this render state to TRUE to enable fog blending as shown in the following example code. The default is FALSE.

// For this example, g_pDevice is a valid pointer
// to an IDirect3DDevice9 interface.
HRESULT hr;
hr = g_pDevice->SetRenderState(
                    D3DRS_FOGENABLE,
                    TRUE);
if FAILED(hr)
    return hr;

You must enable fog blending for both pixel fog and vertex fog. For information about using these types of fog, see Pixel Fog (Direct3D 9) and Vertex Fog (Direct3D 9).


Fog Color (Direct3D 9)

Fog color for both pixel and vertex fog is set through the D3DRS_FOGCOLOR render state. The render state values can be any RGB color, specified as an RGBA color. The alpha component is ignored.

The following C++ example sets the fog color to white.

/* For this example, the d3dDevice variable is
* a valid pointer to an IDirect3DDevice9 interface.
*/
HRESULT hr;
hr = d3dDevice->SetRenderState(
                    D3DRS_FOGCOLOR,
                    0x00FFFFFF); // Highest 8 bits are not used.
if(FAILED(hr))
    return hr;

Fog is applied differently by the fixed function pipeline and the programmable pipeline.

  1. If the driver supports D3DPMISCCAPS_FOGANDSPECULARALPHA:
    • If the fixed function pipeline is used and D3DRS_FOGCOLOR is set, v1.w (in the pixel shader) equals the value set in fog renderstate.
    • If the programmable pipeline is used, then v1.w (in the pixel shader) equals 0, even if oD1.w is explicitly written in a vertex shader.
  2. If the driver does NOT support D3DPMISCCAPS_FOGANDSPECULARALPHA:
    • If the fixed function pipeline is used and D3DRS_FOGCOLOR is set, then v1.w (in the pixel shader) equals value set in fog renderstate.
    • If oFog is explicitly written in a vertex shader, v1.w (in the pixel shader) equals oFog, clamped between 0 and 1.
    • If neither of the above two cases applies, v1.w (in the pixel shader) equals 0, even if oD1.w is explicitly written in a vertex shader.

For more information, see D3DPMISCCAPS.


Vertex Fog (Direct3D 9)

When the system performs vertex fogging, it applies fog calculations at each vertex in a polygon, and then interpolates the results across the face of the polygon during rasterization. Vertex fog effects are computed by the Direct3D lighting and transformation engine. For more information, see Fog Parameters (Direct3D 9).

If your application does not use Direct3D for transformation and lighting, the application must perform fog calculations. In this case, place the fog factor that is computed in the alpha component of the specular color for each vertex. You are free to use whatever formulas you want - range-based, volumetric, or otherwise. Direct3D uses the supplied fog factor to interpolate across the face of each polygon. Applications that perform their own transformation and lighting must also perform their own vertex fog calculations. As a result, such an application need only enable fog blending and set the fog color through the associated render states, as described in Fog Blending (Direct3D 9) and Fog Color (Direct3D 9).

Note When using a vertex shader, you must use vertex fog. This is accomplished by using the vertex shader to write the per-vertex fog intensity to the oFog register. After the pixel shader completes, the oFog data is used to linearly interpolate with the fog color. This intensity is not available in a pixel shader.

Range-Based Fog

Note Direct3D uses range-based fog calculations only when using vertex fog with the Direct3D transformation and lighting engine. This is because pixel fog is implemented in the device driver, and no hardware currently exists to support per-pixel range-based fog. If your application performs its own transformation and lighting, it must perform its own fog calculations, range-based or otherwise.

Sometimes, using fog can introduce graphic artifacts that cause objects to be blended with the fog color in nonintuitive ways. For example, imagine a scene in which there are two visible objects: one distant enough to be affected by fog, and the other near enough to be unaffected. If the viewing area rotates in place, the apparent fog effects can change, even if the objects are stationary. The following illustration shows a top-down view of such a situation.

Effects on fog of changing the viewpoint

Range-based fog is another, more accurate, way to determine the fog effects. In range-based fog, Direct3D uses the actual distance from the viewpoint to a vertex for its fog calculations. Direct3D increases the effect of fog as the distance between the two points increases, rather than the depth of the vertex within in the scene, thereby avoiding rotational artifacts.

If the current device supports range-based fog, it will set the D3DPRASTERCAPS_FOGRANGE value in the RasterCaps member of D3DCAPS9 when you call the IDirect3DDevice9::GetDeviceCaps method. To enable range-based fog, set the D3DRS_RANGEFOGENABLE render state to TRUE.

Range-based fog is computed by Direct3D during transformation and lighting. Applications that don't use the Direct3D transformation and lighting engine must also perform their own vertex fog calculations. In this case, provide the range-based fog factor in the alpha component of the specular component for each vertex.

Using Vertex Fog

Use the following steps to enable vertex fog in your application.

  1. Enable fog blending by setting D3DRS_FOGENABLE to TRUE.
  2. Set the fog color in the D3DRS_FOGCOLOR render state.
  3. Choose the desired fog formula by setting the D3DRS_FOGVERTEXMODE render state to a member of the D3DFOGMODE enumerated type.
  4. Set the fog parameters as desired for the selected fog formula in the render states.

The following example, written in C++, shows what these steps might look like in code.

// For brevity, error values in this example are not checked
//   after each call. A real-world application should check
//   these values appropriately.
//
// For the purposes of this example, g_pDevice is a valid
//   pointer to an IDirect3DDevice9 interface.
void SetupVertexFog(DWORD Color, DWORD Mode, BOOL UseRange, FLOAT Density)
{
    float Start = 0.5f,    // Linear fog distances
          End   = 0.8f;

    // Enable fog blending.
    g_pDevice->SetRenderState(D3DRS_FOGENABLE, TRUE);

    // Set the fog color.
    g_pDevice->SetRenderState(D3DRS_FOGCOLOR, Color);

    // Set fog parameters.
    if(D3DFOG_LINEAR == Mode)
    {
        g_pDevice->SetRenderState(D3DRS_FOGVERTEXMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGSTART, *(DWORD *)(&Start));
        g_pDevice->SetRenderState(D3DRS_FOGEND,   *(DWORD *)(&End));
    }
    else
    {
        g_pDevice->SetRenderState(D3DRS_FOGVERTEXMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)(&Density));
    }

    // Enable range-based fog if desired (only supported for
    //   vertex fog). For this example, it is assumed that UseRange
    //   is set to a nonzero value only if the driver exposes the
    //   D3DPRASTERCAPS_FOGRANGE capability.
    // Note: This is slightly more performance intensive
    //   than non-range-based fog.
    if(UseRange)
        g_pDevice->SetRenderState(D3DRS_RANGEFOGENABLE, TRUE);
}

Some fog parameters are required as floating-point values, even though the IDirect3DDevice9::SetRenderState method only accepts DWORD values in the second parameter. This example successfully provides the floating-point values to these methods without data translation by casting the addresses of the floating-point variables as DWORD pointers, and then dereferencing them.


Pixel Fog (Direct3D 9)

Pixel fog gets its name from the fact that it is calculated on a per-pixel basis in the device driver. This is different from vertex fog, which is computed by the pipeline during transformation and lighting calculations. Pixel fog is sometimes called table fog because some drivers use a precalculated lookup table to determine the fog factor, using the depth of each pixel to apply in blending computations. It can be applied using any fog formula identified by members of the D3DFOGMODE enumerated type. The implementations of these formulas are driver-specific. If a driver doesn't support a complex fog formula, it should degrade to a less complex formula.

Eye-Relative vs. Z-Based Depth

To alleviate fog-related graphic artifacts caused by uneven distribution of z-values in a depth buffer, most hardware devices use eye-relative depth instead of z-based depth values for pixel fog. Eye-relative depth is essentially the w element from a homogeneous coordinate set. Microsoft Direct3D takes the reciprocal of the RHW element from a device space coordinate set to reproduce true w. If a device supports eye-relative fog, it sets the D3DPRASTERCAPS_WFOG flag in the RasterCaps member of the D3DCAPS9 structure when you call the IDirect3DDevice9::GetDeviceCaps method. With the exception of the reference rasterizer, software devices always use z to calculate pixel fog effects.

When eye-relative fog is supported, the system automatically uses eye-relative depth rather than z-based depth if the provided projection matrix produces z-values in world space that are equivalent to w-values in device space. You set the projection matrix by calling the IDirect3DDevice9::SetTransform method, using the D3DTS_PROJECTION value and passing a D3DMATRIX structure that represents the desired matrix. If the projection matrix isn't compliant with this requirement, fog effects are not applied properly. For details about producing a compliant matrix, see Projection Transform (Direct3D 9).

Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, an application must set a compliant projection matrix to receive the desired w-based features, even if it does not use the Direct3D transformation pipeline.

Direct3D checks the fourth column of the projection matrix. If the coefficients are [0,0,0,1] (for an affine projection) the system will use z-based depth values for fog. In this case, you must also specify the start and end distances for linear fog effects in device space, which ranges from 0.0 at the nearest point to the user, and 1.0 at the farthest point.

Using Pixel Fog

Use the following steps to enable pixel fog in your application.

  1. Enable fog blending by setting the D3DRS_FOGENABLE render state to TRUE.
  2. Set the desired fog color in the D3DRS_FOGCOLOR render state.
  3. Choose the fog formula to use by setting the D3DRS_FOGTABLEMODE render state to the corresponding member of the D3DFOGMODE enumerated type.
  4. Set the fog parameters as desired for the selected fog mode in the associated render states. This includes the start and end distances for linear fog, and fog density for exponential fog mode.

The following example shows what these steps might look like in code.

// For brevity, error values in this example are not checked
//   after each call. A real-world application should check
//   these values appropriately.
//
// For the purposes of this example, g_pDevice is a valid
//   pointer to an IDirect3DDevice9 interface.
void SetupPixelFog(DWORD Color, DWORD Mode)
{
    float Start   = 0.5f;    // For linear mode
    float End     = 0.8f;
    float Density = 0.66f;   // For exponential modes

    // Enable fog blending.
    g_pDevice->SetRenderState(D3DRS_FOGENABLE, TRUE);

    // Set the fog color.
    g_pDevice->SetRenderState(D3DRS_FOGCOLOR, Color);

    // Set fog parameters.
    if( Mode == D3DFOG_LINEAR )
    {
        g_pDevice->SetRenderState(D3DRS_FOGTABLEMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGSTART, *(DWORD *)(&Start));
        g_pDevice->SetRenderState(D3DRS_FOGEND,   *(DWORD *)(&End));
    }
    else
    {
        g_pDevice->SetRenderState(D3DRS_FOGTABLEMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)(&Density));
    }

Some fog parameters are required as floating-point values, even though the IDirect3DDevice9::SetRenderState method accepts only DWORD values in the second parameter. The preceding example provides the floating-point values to IDirect3DDevice9::SetRenderState without data translation by casting the addresses of the floating-point variables as DWORD pointers, and then dereferencing them.


Alpha Examples (Direct3D 9)

Alpha blending is used to display an image that has transparent or semi-transparent pixels. In addition to a red, green, and blue color channel, each pixel in an alpha bitmap has a transparency component known as its alpha channel. The alpha channel typically contains as many bits as a color channel. For example, an 8-bit alpha channel can represent 256 levels of transparency, from 0 (the entire pixel is transparent) to 255 (the entire pixel is opaque). The list below shows some special effects you can create using alpha blending.

  • Billboarding
  • Clouds, Smoke, and Vapor Trails
  • Fire, Flares, and Explosions


Billboarding (Direct3D 9)

When creating 3D scenes, an application can sometimes gain performance advantages by rendering 2D objects in a way that makes them appear to be 3D objects. This is the basic idea behind the technique of billboarding.

A billboard in the normal sense of the word is a sign along a roadway. Microsoft Direct3D applications can create and render this type of billboard by defining a rectangular solid and applying a texture to it. Billboarding in the more specialized sense of 3D graphics is an extension of this. The goal is to make 2D objects appear to be 3D. The technique is to apply a texture that contains the object's image to a rectangular primitive. The primitive is rotated so that it always faces the user. It doesn't matter if the object's image is not rectangular. Portions of the billboard can be made transparent, so the parts of the billboard image that you don't want seen are not visible.

Many games employ billboarding for animated sprites. For instance, when the user is moving through a 3D maze, he or she may see weapons or rewards that can be picked up. These are typically 2D images textured on a rectangular primitive. Billboarding is often used in games to render images of trees, bushes, and clouds.

When an image is applied to a billboard, the rectangular primitive must first be rotated so that the resulting image faces the user. Your application must then translate it into position. The application can then apply a texture to the primitive.

Billboarding works best for symmetrical objects, especially objects that are symmetrical along the vertical axis. It also requires that the altitude of the viewpoint doesn't increase too much. If the user is allowed to view the billboarded from above, it becomes readily apparent that the object is 2D rather than 3D.


Clouds, Smoke, and Vapor Trails (Direct3D 9)

Clouds, smoke, and vapor trails can all be created by an extension of the billboarding technique. See Billboarding (Direct3D 9). By rotating the billboard on two axes instead of one, your application can enable the user to view a billboard from any angle. Typically, an application rotates the billboard on the horizontal and vertical axes.

To make a simple cloud, your application can rotate a rectangular primitive on one or two axes so that the primitive faces the user. A cloud-like texture can then be applied to the primitive with transparency. For details on applying transparent textures to primitives, see Texture Blending (Direct3D 9). You can animate the cloud by applying a series of textures over time.

An application can create more complex clouds by forming them from a group of primitives. Each part of the cloud is a rectangular primitive. The primitives can be moved independently over time to give the appearance of a dynamic mist. This concept is illustrated in the following figure.

Formation from a group of primitives

The appearance of smoke is displayed in a manner similar to clouds. It typically requires multiple billboards, like complex clouds. Smoke usually billows and rises over time, so the billboards that make up the smoke plume need to move accordingly. You may need to add more billboards as the plume rises and disperses.

A vapor trail is a smoke plume that doesn't rise. However, like a smoke plume, it disperses over time. The following figure illustrates the technique of using billboards to simulate a vapor trail.


Fire, Flares, and Explosions (Direct3D 9)

You can use Microsoft Direct3D to simulate natural phenomena involving energy releases. For instance, an application can generate the appearance of fire by applying flame-like textures to a set of billboards. This is especially effective if the application uses a sequence of fire textures to animate the flames on each billboard in the fire. Varying the speed of the animation playback from billboard to billboard increases the appearance of real flames. The semblance of intermingled 3D flames can be achieved by layering the billboards and the textures on the billboards.

You can simulate flares and flashes by applying successively brighter light maps to all primitives in a scene. Although this is a computationally high-overhead technique, it allows your application to simulate a localized flare or flash. That is, the portion of the scene where the flare or flash originates can brighten first.

Another technique is to position a billboard in front of the scene so that the entire render-target area is covered. The application applies successively whiter textures to the billboard and decreases the transparency over time. The entire scene fades to white as time passes. This is a low overhead method of creating a flare. However, using this technique, it can be difficult to generate the appearance of a bright flash from a single point light source.

Explosions can be displayed in a 3D scene procedure similar to those used for fire, flashes, and flares. For instance, your application might use a billboard to display a shock wave and rising plume of smoke when the explosion occurs. At the same time, your application can use a set of billboards to simulate flames. In addition, it can position a single billboard in front of the scene to add a flare of light to the entire scene.

Energy beams can be simulated using billboards. Your application can also display them using primitives that are defined as line lists or line strips. For details, see Line Lists (Direct3D 9) and Line Strips (Direct3D 9).

Your application can create force fields using billboards or primitives defined as triangle lists. To create a force field from triangle lists, define a set of disjoint triangles in a triangle list equally spaced over the region covered by the force field. The gaps between the triangles allow the user to see the scene behind the triangles, as you might expect when looking at a force field. Apply a texture to the triangle list that gives the triangles the appearance of glowing with energy. For further information, see Triangle Lists (Direct3D 9).


Gamma (Direct3D 9)

Texture content is often stored in sRGB format. Traditionally, pixel pipelines assumed the colors to be linear so blending operations were performed in linear space. However, since sRGB content is gamma corrected, blending operations in linear space will produce incorrect results. Video cards can now fix this problem by undoing the gamma correction when they read any sRGB content, and convert pixel data back to the sRGB format when writing out pixels. In this case, all operations inside the pixel pipeline are performed in the linear space.

Gamma Correction

Direct3D 9 can:

  • Indicate whether a texture is gamma 2.2 corrected or not (sRGB or not). The driver will either convert to a linear gamma for blending operations at SetTexture time, or the sampler will convert it to linear data at lookup time.
  • Indicate whether the pixel pipeline should gamma correct back to sRGB space when writing out to the render target.

All other colors (clear color, material color, vertex color, etc.) are assumed to be in linear space. Applications can gamma-correct the colors written into the frame buffer using pixel shader instructions. The linearization should be applied only to the RGB channels and not to the alpha channel.

Not all surface formats can be linearized. Only the formats that pass IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_SRGBREAD can be linearized. The sampler state D3DSAMP_SRGBTEXTURE is ignored for the rest. Only unsigned texture formats are expected to support this conversion. Unsigned texture formats include only R, G, B, and L components. If the alpha channel is present, it is ignored. If mixed formats support sRGB linearization, only the unsigned channels are affected. Ideally, hardware should perform the linearization before filtering but in Direct3D 9, hardware is allowed to perform the linearization after filtering.

Not all surface formats can be written in sRGB space. Only the formats that pass the IDirect3D9::CheckDeviceFormat with the usage flag D3DUSAGE_QUERY_SRGBWRITE can be linearized. The render state D3DRS_SRGBWRITEENABLE is ignored for the rest. Eight bits per channel RGB unsigned formats are expected to expose this ability.

Ideally, hardware should perform the frame buffer blending operations in the linear space, but hardware is allowed to perform it after the pixel shader but before the frame buffer blender. This means that the frame buffer blending operations that take place in sRGB space will produce incorrect results. D3DRS_SRGBWRITEENABLE is honored while performing a clear of the render target. For hardware that supports Multiple Render Targets (Direct3D 9) or Multiple-element Textures (Direct3D 9), only the first render target or element is written.

API Changes

// New sampler state (DWORD)
// If this is nonzero, the texture is linearized on lookup.
D3DSAMP_SRGBTEXTURE       // Default FALSE

// New render state (DWORD)
D3DRS_SRGBWRITEENABLE     // Default FALSE

// New usage flags
D3DUSAGE_QUERY_SRGBWRITE
D3DUSAGE_QUERY_SRGBREAD

Windowed Swap Chains

It is valuable for applications to keep the back buffers of their swap chains in linear space in order to enable correct blending operations. Since the desktop is typically not in linear space, a gamma correction is required before the contents of the back buffer can be presented. The application can effect this correction itself by allocating an additional buffer and performing its own correcting copy from the linear buffer to the back buffer. This necessitates an extra copy which can be avoided if the driver performs gamma correction as part of the presentation blit.

In Direct3D 9 a new flag, D3DPRESENT_LINEAR_CONTENT, is available for IDirect3DSwapChain9::Present that allows the presentation to implicitly convert from linear space to sRGB/gamma 2.2.


Precomputed Radiance Transfer (Direct3D 9)

Using Precomputed Radiance Transfer

There are several forms of complexity present in interesting scenes, including how the lighting environment is modeled (that is, area lighting models versus point/directional ones) and what kind of global effects are modeled (for example, shadows, interreflections, subsurface scattering.) Traditional interactive rendering techniques model a limited amount of this complexity. PRT enables these effects with some significant restrictions:

  • Objects are assumed to be rigid (that is, no deformations).
  • It is an object-centric approach (unless objects are moved together, these global effects are not maintained between them).
  • Only low-frequency lighting is modeled (resulting in soft shadows.) For high-frequency lights (sharp shadows), traditional techniques would have to be employed.

PRT requires either of the following, but not both:

  • highly-tessellated models and vs_1_1
  • ps_2_0

Standard Diffuse Lighting versus PRT

The following picture is rendered using the traditional (n • l) lighting model. Sharp shadows could be enabled using another pass and some form of shadowing technique (shadow depth maps or shadow volumes). Adding multiple lights would require either multiple passes (if shadows are to be used) or more complex shaders with traditional techniques.

The next picture is rendered with PRT using the best approximation of a single directional light that it can resolve. This results in soft shadows that would be difficult to produce with traditional techniques. Because PRT always models complete lighting environments adding multiple lights or using an environment map, you would only change the values (but not the number) of constants used by the shader.

PRT with Interreflections

Direct lighting reaches the surface directly from the light. Interreflections are light reaching the surface after bouncing off some other surface some number of times. PRT can model this behavior without changing the performance at run time by simply running the simulator with different parameters.

The following image is created using direct PRT only (0 bounces with no interreflections).

This image is created using PRT with interreflections (2 bounces with interreflections).

PRT with Subsurface Scattering

Subsurface scattering is a technique that models how light passes through certain materials. As an example, press a lit flashlight against the palm of your hand. The light from the flashlight passes through your hand, bounces around (changing color in the process), and exits from the other side of your hand. This can also be modeled with simple changes to the simulator and no changes to the runtime.

The following image demonstrates PRT with subsurface scattering.

How PRT Works

The following terms are useful for understanding how PRT works, as illustrated in Figure 1 below.

Source Radiance: The source radiance represents the lighting environment as a whole. In PRT an arbitrary environment is approximated using the spherical harmonic basis - this lighting is assumed to be distant relative to the object (the same assumption that is made with environment maps.)

Exit Radiance: Exit radiance is the light leaving from a point on the surface from any possible source (reflected radiance, subsurface scattering, emission).

Transfer Vectors: Transfer vectors map Source Radiance into exit radiance and are precomputed offline using a complex light transport simulation.

Figure 1: PRT Conceptual Diagram

PRT factors the rendering process into two stages:

  1. An expensive light transport simulation precomputes transfer coefficients that can be used at run time.
  2. A relatively lightweight run-time stage first approximates the lighting environment using the spherical harmonic basis, then uses these lighting coefficients and the precomputed transfer coefficients (from stage 1) with a simple shader, resulting in exit radiance (the light leaving the object).

Figure 2: Simplified PRT Data Flow

How to Use the PRT API

  1. Compute the transfer vectors with one of the Compute... methods of ID3DXPRTEngine.

    Directly dealing with these transfer vectors requires a significant amount of memory and shader computation. Compression significantly reduces the amount of memory and shader computation required.

    The final lighting values are calculated in a vertex shader that implements the following compressed rendering equation:

    PRT rendering equation

    Where:

    Parameter | Description
    Rp | A single channel of exit radiance at vertex p and is evaluated at every vertex on the mesh.
    Mk | The mean for cluster k. This is an Order2 vector of coefficients.
    k | The cluster ID for vertex p.
    L' | The approximation of the source radiance into the SH basis functions. This is an Order2 vector of coefficients.
    j | An integer that sums over the number of PCA vectors.
    wpj | The jth PCA weight for point p. This is a single coefficient.
    Bkj | The jth PCA basis vector for cluster k. This is an Order2 vector of coefficients.

    The Extract... methods of ID3DXPRTCompBuffer provide access to compressed data from the simulation.

  2. Compute the source radiance.

    There are several helper functions in the API to handle a variety of common lighting scenarios.

    Function | Purpose
    D3DXSHEvalDirectionalLight | Approximates a conventional directional light.
    D3DXSHEvalSphericalLight | Approximates local spherical light sources. (Note that PRT only works with distance lighting environments.)
    D3DXSHEvalConeLight | Approximates a distant area light source. An example would be the sun (very small cone angle).
    D3DXSHEvalHemisphereLight | Evaluates a light that is a linear interpolation between two colors (one on each pole of a sphere).

  3. Compute the exit radiance.

    Equation 1 now has to be evaluated at every point using either a vertex or pixel shader. Before the shader can be evaluated, constants have to be precomputed and loaded into the constant table (see the PRT Demo Sample for details). The shader itself is a straightforward implementation of this equation.

    struct VS_OUTPUT
{
    float4 Position   : POSITION;   // vertex position
    float2 TextureUV  : TEXCOORD0;  // vertex texture coordinates
    float4 Diffuse    : COLOR0;     // vertex diffuse color
};

VS_OUTPUT Output;
Output.Position = mul(vPos, mWorldViewProjection);

float4 vExitR = float4(0,0,0,0);
float4 vExitG = float4(0,0,0,0);
float4 vExitB = float4(0,0,0,0);

for (int i=0; i < (NUM_PCA_VECTORS/4); i++)
{
   vExitR += vPCAWeights[i] *
       vClusteredPCA[iClusterOffset+i+1+(NUM_PCA_VECTORS/4)*0];
   vExitG += vPCAWeights[i] *
       vClusteredPCA[iClusterOffset+i+1+(NUM_PCA_VECTORS/4)*1];
   vExitB += vPCAWeights[i] *
       vClusteredPCA[iClusterOffset+i+1+(NUM_PCA_VECTORS/4)*2];
}

float4 vExitRadiance = vClusteredPCA[iClusterOffset];
vExitRadiance.r += dot(vExitR,1);
vExitRadiance.g += dot(vExitG,1);
vExitRadiance.b += dot(vExitB,1);

Output.Diffuse = vExitRadiance;

References

For more information about PRT and spherical harmonics, see the following papers:

Precomputed Radiance Transfer for Real-Time Rendering in Dynamic,
Low-Frequency Lighting Environments
P.-P. Sloan, J. Kautz, J. Snyder
SIGGRAPH 2002

Clustered Principal Components for Precomputed Radiance Transfer
P.-P. Sloan, J. Hall, J. Hart, J. Snyder
SIGGRAPH 2003

Efficient Evaluation of Irradiance Environment Maps
P.-P. Sloan
ShaderX 2,  W. Engel

Spherical Harmonic Lighting: The Gritty Details
R. Green
GDC 2003

An Efficient Representation for Irradiance Environment Maps
R. Ramamoorthi, P. Hanrahan

A Practical Model for Subsurface Light Transport
H. W. Jensen, S. R. Marschner, M. Levoy, and P. Hanrahan
SIGGRAPH 2001

Bi-Scale Radiance Transfer
P.-P. Sloan, X. Liu, H.-Y. Shum, J. Snyder
SIGGRAPH 2003

Fast, Arbitrary BRDF Shading for Low-Frequency Lighting Using Spherical
Harmonics
J. Kautz, P.-P. Sloan, J. Snyder
12th Eurographics Workshop on Rendering

Precomputing Interactive Dynamic Deformable Scenes
D. James, K. Fatahalian
SIGGRAPH 2003

All-Frequency Shadows Using Non-linear Wavelet Lighting Approximation
R. Ng, R. Ramamoorth, P. Hanrahan
SIGGRAPH 2003

Matrix Radiance Transfer
J. Lehtinen, J. Kautz
SIGGRAPH 2003

Math World
E. W. Weisstein, Wolfram Research, Inc.

Quantum Theory of Angular Momentum
D. A. Varshalovich, A.N. Moskalev, V.K. Khersonskii

See Also

PRT Equations (Direct3D 9), Representing PRT With Textures (Direct3D 9), ID3DXPRTBuffer, ID3DXPRTCompBuffer, ID3DXPRTEngine, ID3DXTextureGutterHelper, Precomputed Radiance Transfer Functions, Math Functions


PRT Equations (Direct3D 9)

To fully understand a shader that implements PRT, it is useful to derive the formula the shader uses to calculate exit radiance.

To start off, the general equation to calculate exit radiance resulting from direct lighting on a diffuse object with arbitrary distant lighting is:

where:

Parameter | Description
Rp | The exit radiance at vertex p. Evaluated at every vertex on the mesh.
pd | The albedo of the surface.
pi | A constant, used as an energy conservation normalization factor.
L(s) | The lighting environment (source radiance).
Vp(s) | A binary visibility function for point p. It is 1 if the point can see the light, 0 if not.
Hnp(s) | The cosine term from Lambert's law. Equal to max((Np • s), 0) where Np is the surface normal at point p.
s | The variable that integrates over the sphere.

Using spherical basis functions, such as spherical harmonics, the formula to approximate the lighting environment is:

where:

Parameter | Description
L(s) | The lighting environment (source radiance).
i | An integer that sums over the number of basis functions.
O | The order of spherical harmonics.
li | A coefficient.
Yi(s) | Some basis function over the sphere.

The collection of these coefficients, L', provides the optimal approximation for function L(s) with the basis functions Y(s). Substituting and distributing yields:

The integral of Yi(s)Vp(s)Hnp(s) is a transfer coefficient tpi that the simulator precomputes for every vertex on the mesh. Substituting this yields:

Changing this to vector notation yields the uncompressed formula to calculate exit radiance for each channel:

where:

Parameter | Description
Rp | The exit radiance at vertex p.
pd | The albedo of the surface.
L' | The vector of li, and is the projection of the source radiance into the spherical harmonic basis functions. This is an order2 vector of spherical harmonic coefficients.
Tp | An order2 transfer vector for vertex p. The simulator divides the transfer coefficients by p.

Both of these vectors are an order2 vector of spherical harmonic coefficients, so notice that this is simply a dot product. Depending on the order, the dot can be expensive so compression can be used. An algorithm called Clustered Principal Component Analysis (CPCA) efficiently compresses the data. This enables the use of a higher-order spherical harmonic approximation which results in sharper shadows.

CPCA provides this approximation for the transfer vector:

where:

Parameter | Description
Tp | The transfer vector for vertex p.
Mk | The mean for cluster k.
j | An integer that sums over the number of PCA vectors.
N | The number of PCA vectors.
wpj | The jth PCA weight for point p.
Bkj | The jth PCA basis vector for cluster k.

A cluster is simply some number of vertices that share the same mean vector. How to get the cluster mean, the PCA weights, the PCA basis vectors, and the cluster ids for the vertices is discussed below.

Substituting these two equations yields:

Then distributing the dot product yields:

Because both (Mk • L') and (Bkj • L') are constant per vertex, the sample calculates these values with the CPU and passes them as constants into the vertex shader; because wpj changes for each vertex, the sample stores this per-vertex data in the vertex buffer.


Representing PRT With Textures (Direct3D 9)

The PRTDemo sample and PRTCmdLine simulator included in the DirectX SDK represent transfer vectors at the vertices of a mesh. In order to represent the PRT signal accurately, this can require tessellations that may be impractical for current games. Representing transfer vectors in texture maps is an alternative approach that has the same data cost independent of mesh complexity. There are several ways to generate transfer vector texture maps using the D3DX PRT Library.

Precomputing Transfer Vectors

One approach would be to modify the PRTDemo and PRTCmdLine samples to compute a transfer vector at every texel in a parameterization of a surface. To do this:

  1. Modify the call to D3DXCreatePRTEngine to extract texture coordinates from the mesh (ExtractUVs must be TRUE)
  2. Replace D3DXCreatePRTBuffer calls with D3DXCreatePRTBufferTex using the same texture size.

All ID3DXPRTEngine methods work with per-texel simulations except for: ComputeBounceAdaptive, ComputeSSAdaptive, ComputeSS, and ComputeDirectLightingSHAdaptive. While texture-space simulation will generate the correct result, it can often be fairly slow since it will most likely be computing transfer vectors at a high density.

Another approach is to compute an adaptive per-vertex PRT simulation (with texture coordinates that will be used for the per-texel data) and then call ID3DXPRTEngine::ResampleBuffer (using an output buffer created using D3DXCreatePRTBufferTex at the appropriate resolution). This works with all D3DX PRT functionality in the SDK and can often be much more efficient than directly computing a per-texel transfer buffer.

Runtime Calculations

If a single cluster is used the results can be filtered and mip-mapped like any other texture and the pixel shader is identical to the vertex shader code that ships with PRTDemo.

If compression generates multiple clusters, you cannot filter or mipmap the data because clustering indexes are not continuous. Here are some alternatives for handling multi-clustered data:

  • Do all of the filtering yourself in the pixel shader. Unfortunately, this is generally impractical for performance reasons.
  • If the textures are low resolution non mip-mapped textures (ie: light maps), it is most likely more efficient to just compute the lighting directly in texture space - where no filtering will occur, and render the object with a shaded texture. This is essentially a dynamic light map that is created entirely on the GPU.
  • If a texture atlas is used (see Using UVAtlas (Direct3D 9)), you could manually cluster the scene by having all transfer vectors in a connected component in texture space be in the same cluster. This way you can filter the texture because all texels accessed would be in the same cluster by construction. The cluster ID for a given face could be propagated from the vertex shader.

Pixel shaders have much fewer constant registers that cannot be indexed, so the pixel shader is somewhat different than the vertex shader. Storing the per-cluster work in a low resolution dynamic texture and using texture loads would be the most efficient way to render when using multiple clusters.

See Also

PRT Demo Sample, PRT Simulator (prtcmdline.exe)


HDR Lighting (Direct3D 9)

Lighting in the real world contains a very high dynamic range (HDR) of luminance values. The real world has about 10 orders of dynamic range (DR) for luminance values spread across the spectrum of darkness to brightness. On the other hand, a computer screen has a very limited display gamut (or range of luminance values): approximately two orders of dynamic range. The challenge to producing HDR rendered images is to map the real world HDR values into the limited gamut of a computer screen.

Tone mapping is the technique used by DirectX for mapping HDR information into a more limited range. Tone mapping applied to CGI rendering can dramatically improve the amount of lighting detail rendered, allowing details in the darkest areas to be seen, and providing contrast in areas that are so bright, they appear burned. The resulting scenes render with far more visible lighting detail.

HDRLighting Sample is a SDK sample that demonstrates HDR lighting.

Tone Mapping

Tone mapping generally simulates optical phenomena that can not be caused by the DR of the monitor. Examples of this are flares or blooming (which are mostly properties of lenses), the blue shift that happens in the human eye in low light conditions, and other adaptations that are a result of the biochemistry of the eye. If the DR of the display were large enough, tone mapping would not be as neccessary, except for providing artistic effects or some of the properties of a camera lens or a charge coupled device (CCD).

Tone mapping divides the range of luminance values in a scene into a set of zones. Each zone encompasses a range of luminance values.

HDR uses the following terms:

  • Zone - range of luminance values
  • Middle gray - middle brightness region of the scene
  • Dynamic range - ratio of the highest scene luminance to the lowest scene luminance
  • Key - subjective measurement of scene lighting: this varies from light to moderate to dark

To calculate luminance from RGB values, use this:

L = 0.27R + 0.67G + 0.06B;

The log-average luminance is a useful approximation for the key of a scene. A general equation looks like this:

Lw = exp[ 1 / N( sum[ log( delta + Lw( x, y ) ) ] ) ]

Where:

  • Lw - log-average luminance
  • N - number of pixels in the image
  • delta - a small factor to avoid problems with black pixels
  • Lw( x, y ) - the world space luminance for pixel ( x, y )

To map this to a middle-gray value, here is a luminance scaling operator:

L( x, y ) = a * Lw( x, y ) / Lw

Where:

  • L( x, y ) - scaled luminance for pixel ( x, y )
  • a - image key value after applying the scaling

And finally, here is a simple tone mapping operator for compressing the high luminances:

Ld( x, y ) = L( x, y ) / ( 1 + L( x, y ) )

Where:

  • Ld( x, y ) - compressed and scaled luminance for pixel ( x, y )
  • a - image key value after applying the scaling

This operator scales high luminances by 1/L and low luminances by 1. For more details, see the following paper.

Reinhard, Erik, Mike Stark, Peter Shirley, and James Ferwerda. "Photographic Tone Reproduction for Digital Images". ACM Transactions on Graphics (TOG), Proceedings of the 29th Annual Conference on Computer Graphics and Interactive Techniques (SIGGRAPH), pp. 267-276. New York, NY: ACM Press, 2002.


Accurately Profiling Direct3D API Calls (Direct3D 9)

  • Accurately Profiling Direct3D Is Difficult
  • How to Accurately Profile a Direct3D Render Sequence
  • Profiling Direct3D State Changes
  • Summary
  • Appendix

Once you have a functional Microsoft Direct3D application and you want to improve its performance, you generally use an off-the-shelf profiling tool or some custom measurement technique to measure the time it takes to execute one or more application programming interface (API) calls. If you have done this but are getting timing results that vary from one render sequence to the next, or you are making hypotheses that do not hold up to actual experiment results, the following information may help you to understand why.

The information provided here is based upon the assumption that you have knowledge of and experience with the following:

  • C/C++ programming
  • Direct3D API programming
  • Measuring API timing
  • The video card and its software driver
  • Possible unexplainable results from previous profiling experience

Accurately Profiling Direct3D Is Difficult

A profiler reports on the amount of time spent in each API call. This is done to improve performance by finding and tuning away hot spots. There are different kinds of profilers and profiling techniques.

  • A sampling profiler sits idle much of the time, awakening at specific intervals to sample (or to record) the functions being executed. It returns the percentage of time spent in each call. Generally, a sampling profiler is not very invasive to the application and has minimal impact on the overhead for the application.
  • An instrumenting profiler measures the actual time it takes for a call to return. It requires compiling start and stop delimiters into an application. An instrumenting profiler is comparatively more invasive to an application than a sampling profiler.
  • It is also possible to use a custom profiling technique with a high-performance timer. This produces results very much like an instrumenting profiler.

The type of profiler or profiling technique used is only part of the challenge of generating accurate measurements.

Profiling gives you answers that help you budget performance. For instance, suppose you know that an API call averages one thousand clock cycles to execute. You can assert some conclusions about performance such as the following:

  • A 2 GHz CPU (which spends 50 percent of its time rendering) is limited to calling this API 1 million times a second.
  • To achieve 30 frames per second, you cannot call this API more than 33,000 times per frame.
  • You can only render 3.3K objects per frame (assuming 10 of these API calls for each object's render sequence).

In other words, if you had sufficient time per API call, you could answer a budgeting question such as the number of primitives that can be rendered interactively. But the raw numbers returned by an instrumenting profiler will not accurately answer the budgeting questions. This is because the graphics pipeline has complex design issues such as the number of components that need to do work, the number of processors that control how the work flows between components, and optimization strategies implemented in the runtime and in a driver that are designed to make the pipeline more efficient.

Each API Call Goes through Several Components

Each call is processed by several components on its way from the application to the video card. For instance, consider the following render sequence containing two calls for drawing a single triangle:

SetTexture(...);
DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

The following conceptual diagram shows the different components through which the calls must pass:

The application invokes Direct3D which controls the scene, handles user interactions, and determines how rendering is done. All of this work is specified in the render sequence, which is sent to the runtime using Direct3D API calls. The render sequence is virtually hardware independent (that is, the API calls are hardware independent but an application has knowledge of what features a video card supports).

The runtime converts these calls into a device-independent format. The runtime handles all the communication between the application and the driver, so that an application will run on more than one compatible piece of hardware (depending on the features required). When measuring a function call, an instrumenting profiler measures the time it spent in a function as well as the time for the function to return. One limitation of an instrumenting profiler is that it may not include the time it takes a driver to send the resulting work to the video card nor the time for the video card to process the work. In other words, an off-the-shelf instrumenting profiler fails to attribute all of the work associated with each function call.

The software driver uses hardware specific knowledge about the video card to convert the device-independent commands into a sequence of video card commands. Drivers may also optimize the sequence of commands that are sent to the video card, so that rendering on the video card is done efficiently. These optimizations can cause profiling problems because the amount of work done is not what it appears to be (you may need to understand the optimizations to account for them). The driver typically returns control to the runtime before the video card has finished processing all the commands.

The video card performs the majority of the rendering by combining data from the vertex and index buffers, textures, render state information, and the graphics commands. When the video card finishes rendering, the work created from the render sequence is complete.

Each Direct3D API call must be processed by each component (the runtime, the driver, and the video card) to render anything.

There Is More than One Processor Controlling the Components

The relationship between these components is even more complex, as the application, runtime, and the driver are controlled by one processor and the video card is controlled by a separate processor. This figure shows two kinds of processors: a central processing unit (CPU) and a central processing unit (CPU).

PC systems have at least one CPU and one GPU, but can have more than one of either or both. The CPUs are located on the motherboard, and the GPUs are located either on the motherboard or on the video card. The speed of the CPU is determined by a clock chip on the motherboard, and the speed of the GPU is determined by a separate clock chip. The CPU clock controls the speed of the work done by the application, the runtime, and the driver. The application sends work to the GPU via the runtime and the driver.

The CPU and the GPU generally run at different speeds, independent of one another. The GPU may respond to the work as soon as the work is available (assuming the GPU has finished processing previous work). The GPU work is done in parallel with the CPU work as highlighted by the curved line in the figure above. A profiler generally measures the performance of the CPU, not the GPU. This makes profiling challenging, because the measurements made by an instrumenting profiler include the CPU time but may not include the GPU time.

The purpose of the GPU is to off-load processing from the CPU to a processor specifically designed for graphics work. On modern video cards, the GPU replaces much of the transform and lighting work in the pipeline from the CPU to the GPU. This greatly reduces the CPU workload, leaving more CPU cycles available for other processing. To tune a graphical application for peak performance, you need to measure the performance of both the CPU and the GPU, and balance the work between the two types of processors.

This document does not cover topics related to measuring the performance of the GPU or balancing the work between the CPU and the GPU. If you want to better understand the performance of a GPU (or a particular video card), visit the vendor's web site to look for more information about GPU performance. Instead, this document focuses on the work done by the runtime and the driver by reducing the GPU work to a negligible amount. This is, in part, based on experience that applications experiencing performance problems are generally CPU-limited.

Runtime and Driver Optimizations Can Mask API Measurements

The runtime has a performance optimization built into it that can overwhelm the measurement of an individual call. Here's an example scenario that demonstrates this problem. Consider the following render sequence:

  BeginScene();
    ...
    SetTexture(...);
    DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
    ...
  EndScene();
  Present();

Example 1: Simple Render Sequence

Looking at the results for the two calls in the render sequence, an instrumenting profiler could return results similar to these:

Number of cycles for SetTexture       : 100
Number of cycles for DrawPrimitive    : 950,500

The profiler returns the number of CPU cycles required to process the work associated with each call (remember that the GPU isn't included in these numbers because the GPU hasn't started working on these commands yet). Because IDirect3DDevice9::DrawPrimitive required almost a million cycles to process, you could conclude that it is not very efficient. However, you'll soon see why this conclusion is incorrect and how you can generate results that can be used for budgeting.

Measuring State Changes Requires Careful Render Sequences

All calls other than IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawIndexedPrimitive, or IDirect3DDevice9::Clear (such as IDirect3DDevice9::SetTexture, IDirect3DDevice9::SetVertexDeclaration, and IDirect3DDevice9::SetRenderState) produce a state change. Each state change sets pipeline state that controls how rendering will be done.

Optimizations in the runtime and/or the driver are designed to speed up rendering by reducing the amount of work required. The following are a couple of state change optimizations that may pollute profile averages:

  • A driver (or the runtime) could save a state change as a local state. Because the driver could operate in a "lazy" algorithm (postponing work until it is absolutely necessary), work associated with some state changes could get delayed.
  • The runtime (or a driver) may remove state changes by optimizing. An example of this might be to remove a redundant state change that disables lighting because lighting has previously been disabled.

There is no foolproof way to look at a render sequence and conclude which state changes will set a dirty bit and defer work, or will simply be removed by optimization. Even if you could identify optimized state changes in today's runtime or driver, tomorrow's runtime or driver is likely to be updated. You also don't readily know what the previous state was so it is difficult to identify redundant state changes. The only way to verify the cost of a state change is to measure the render sequence that includes the state changes.

As you can see, the complications caused by having multiple processors, commands being processed by more than one component, and optimizations built into the components make profiling difficult to predict. In the next section, each of these profiling challenges will be addressed. Sample Direct3D render sequences will be shown, with the accompanying measurement techniques. With this knowledge, you will be able to generate accurate, repeatable measurements on individual calls.

How to Accurately Profile a Direct3D Render Sequence

Now that some of the profiling challenges have been highlighted, this section will show you techniques that will help you generate profile measurements that can be used for budgeting. Accurate, repeatable profiling measurements are possible if you understand the relationship between the components controlled by the CPU, and how to avoid performance optimizations implemented by the runtime and the driver.

To begin, you need to be able to accurately measure the execution time of a single API call.

Pick an Accurate Measurement Tool Like QueryPerformanceCounter

The Microsoft Windows operating system includes a high-resolution timer that can be used to measure high-resolution elapsed times. The current value of one such timer can be returned using QueryPerformanceCounter. By invoking QueryPerformanceCounter before and after a render sequence to return start and stop values, the difference between the two values can be converted to the actual elapsed time in seconds using .

The advantages of using QueryPerformanceCounter are that it is available in Windows and it is easy to use. Simply surround the calls with a QueryPerformanceCounter call and save the start and stop values. Therefore, this paper will demonstrate how to use QueryPerformanceCounter to profile execution times, similar to the way an instrumenting profiler would measure it. Here's an example that shows how to embed QueryPerformanceCounter in your source code:

  BeginScene();
    ...
    // Start profiling
    LARGE_INTEGER start, stop, freq;
    QueryPerformanceCounter(&start);

    SetTexture(...);
    DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

    QueryPerformanceCounter(&stop);
    stop.QuadPart -= start.QuadPart;
    QueryPerformanceFrequency(&freq);
    // Stop profiling
    ...
  EndScene();
  Present();

Example 2: Custom Profiling Implementation with QPC

start and stop are two large integers that will hold the start and stop values returned by the high-performance timer. Notice that QueryPerformanceCounter(&start) is called just before IDirect3DDevice9::SetTexture and QueryPerformanceCounter(&stop) is called just after IDirect3DDevice9::DrawPrimitive. After getting the stop value, QueryPerformanceFrequency is called to return freq, which is the frequency of the high-resolution timer. In this hypothetical example, suppose you get the following results for start, stop, and freq:

Local Variable | Number of Ticks
start | 1792998845094
stop | 1792998845102
freq | 3579545

You could convert these values to the number of cycles it takes to execute the API calls like this:

# ticks = (stop - start) = 1792998845102 - 1792998845094 = 8 ticks

# cycles = CPU speed * number of ticks / QPF
# 4568   = 2 GHz      * 8              / 3,579,545

In other words, it takes about 4568 clock cycles to process IDirect3DDevice9::SetTexture and IDirect3DDevice9::DrawPrimitive on this 2 GHz machine. You could convert these values to the actual time it took to execute all the calls like this:

(stop - start)/ freq = elapsed time
8 ticks / 3,579,545 = 2.2E-6 seconds or between 2 and 3 microseconds.

Using QueryPerformanceCounter requires that you add start and stop measurements to your render sequence and use QueryPerformanceFrequency to convert the difference (number of ticks) to the number of CPU cycles or to actual time. Identifying the measurement technique is a good start for developing a custom profiling implementation. But before you jump in and start making measurements, you need to know how to deal with the video card.

Focus on CPU Measurements

As stated earlier, the CPU and the GPU work in parallel to process the work generated by the API calls. A real world application requires profiling both types of processors to find out if your application is CPU-limited or GPU-limited. Since GPU performance is vendor specific, it would be very challenging to produce results in this paper that cover the variety of video cards available.

Instead, this paper will focus only on profiling the work performed by the CPU by using a custom technique for measuring the runtime and driver work. The GPU work will be reduced to an insignificant amount, so that CPU results are more visible. One benefit of this approach is that this technique yields results in the Appendix that you should be able to correlate with your measurements. To reduce the work required by the video card to an insignificant level, simply reduce the rendering work to the least amount possible. This can be accomplished by limiting draw calls to render a single triangle, and can be further constrained so that each triangle only contains one pixel.

The unit of measure used in this paper for measuring CPU work will be the number of CPU clock cycles rather than actual time. CPU clock cycles has the advantage that it is more portable (for CPU-limited applications) than actual elapsed time across machines with different CPU speeds. This can easily be converted to actual time if desired.

This document does not cover topics related to balancing the work load between the CPU and the GPU. Remember, the goal of this paper is not to measure the overall performance of an application, but to show you how to accurately measure the time it takes the runtime and the driver to process API calls. With these accurate measurements, you can take on the task of budgeting the CPU to understand certain performance scenarios.

Controlling Runtime and Driver Optimizations

With a measurement technique identified, and a strategy for reducing GPU work, the next step is to understand the runtime and driver optimizations that get in the way when you are profiling.

The CPU work can be divided into three buckets: the application work, the runtime work, and the driver work. Ignore the application work since this is under programmer control. From the application's standpoint, the runtime and the driver are like black boxes, as the application has no control over what is implemented in them. The key is to understand the optimization techniques that may be implemented in the runtime and the driver. If you don't understand these optimizations, it is very easy to jump to the wrong conclusion about the amount of work the CPU is doing based on the profile measurements. In particular, there are two topics related to something called the command buffer and what it can do to obfuscate profiling. These topics are:

  • Runtime optimization with the Command Buffer. The command buffer is a runtime optimization that reduces the impact of a mode transition. To control the timing of the mode transition, see Controlling the Command Buffer.
  • Negating the timing effects of the Command Buffer. The elapsed time of a mode transition can have a big impact on profiling measurements. The strategy for this is to Make the Render Sequence Large Compared to the Mode Transition.

Controlling the Command Buffer

When an application makes an API call, the runtime converts the API call to a device-independent format (which we will call a command), and stores it in the command buffer. The command buffer is shown added to the block diagram:

Each time the application makes another API call, the runtime repeats this sequence and adds another command to the command buffer. At some point, the runtime empties the buffer (sending the commands to the driver). In Windows XP, emptying the command buffer causes a mode transition as the operating system switches from the runtime (running in user mode) to the driver (running in kernel mode).

  • user mode - The non-privileged processor mode that executes application code. User-mode applications cannot gain access to system data except through system services.
  • kernel mode - The privileged processor mode in which Windows-based executive code runs. A driver or thread running in kernel mode has access to all system memory, direct access to hardware, and the CPU instructions to perform I/O with the hardware.

The transition happens each time the CPU switches from user to kernel mode (and vice versa) and the number of cycles it requires is large compared to an individual API call. If the runtime sent each API call to the driver when it was invoked, every API call would incur the cost of a mode transition.

Instead, the command buffer is a runtime optimization designed to reduce the effective cost of the mode transition. The command buffer queues many driver commands in preparation for a single mode transition. When the runtime adds a command to the command buffer, control is returned to the application. A profiler has no way of knowing that the driver commands have probably not even been sent to the driver yet. As a result, the numbers returned by an off-the-shelf instrumenting profiler are misleading since it measures the runtime work but not the associated driver work.

Profile Results without a Mode Transition

Using the render sequence from example 2, here are some typical timing measurements that illustrate the magnitude of a mode transition. Assuming that IDirect3DDevice9::SetTexture and IDirect3DDevice9::DrawPrimitive calls do not cause a mode transition, an off-the-shelf instrumenting profiler could return results similar to these:

Number of cycles for SetTexture           : 100
Number of cycles for DrawPrimitive        : 900

Each of these numbers are the amount of time it takes for the runtime to add these calls to the command buffer. Since there is no mode transition, the driver has not done any work yet. The profiler results are accurate, but they do not measure all of the work that the render sequence will eventually cause the CPU to perform.

Profile Results with a Mode Transition

Now, look at what happens for the same example when a mode transition occurs. This time, assume IDirect3DDevice9::SetTexture and IDirect3DDevice9::DrawPrimitive cause a mode transition. Once again, an off-the-shelf instrumenting profiler could return results similar to these:

Number of cycles for SetTexture           : 98
Number of cycles for DrawPrimitive        : 946,900

The time measured for IDirect3DDevice9::SetTexture is about the same, however, the dramatic increase in the amount of time spent in IDirect3DDevice9::DrawPrimitive is due to the mode transition. Here's what is happening:

  1. Assume the command buffer has room for one command before our render sequence starts.
  2. IDirect3DDevice9::SetTexture is converted to a device-independent format and added to the command buffer. In this scenario, this call fills the command buffer.
  3. The runtime tries to add IDirect3DDevice9::DrawPrimitive to the command buffer but cannot, because it is full. Instead, the runtime empties the command buffer. This causes the kernel-mode transition. Assume the transition takes about 5000 cycles. This time contributes to time spent in IDirect3DDevice9::DrawPrimitive.
  4. The driver then processes the work associated with all the commands that were emptied from the command buffer. Assume that the driver time to process the commands that nearly filled the command buffer is about 935,000 cycles. Assume that the driver work associated with IDirect3DDevice9::SetTexture is about 2750 cycles. This time contributes to time spent in IDirect3DDevice9::DrawPrimitive.
  5. When the driver finishes its work, the user-mode transition returns control to the runtime. The command buffer is now empty. Assume the transition takes about 5000 cycles.
  6. The render sequence finishes by converting IDirect3DDevice9::DrawPrimitive and adding it to the command buffer. Assume this takes about 900 cycles. This time contributes to time spent in IDirect3DDevice9::DrawPrimitive.

Summarizing the results, you see:

DrawPrimitive = kernel-transition + driver work    + user-transition + runtime work
DrawPrimitive = 5000              + 935,000 + 2750 + 5000            + 900
DrawPrimitive = 947,950

Just like the measurement for IDirect3DDevice9::DrawPrimitive without the mode transition (900 cycles), the measurement for IDirect3DDevice9::DrawPrimitive with the mode transition (947,950 cycles) is accurate but useless in terms of budgeting CPU work. The result contains the correct runtime work, the driver work for IDirect3DDevice9::SetTexture, the driver work for any commands that preceded IDirect3DDevice9::SetTexture, and two mode transitions. However, the measurement is missing the IDirect3DDevice9::DrawPrimitive driver work.

A mode transition could happen in response to any call. It depends on what was previously in the command buffer. You need to control the mode transition to understand how much CPU work (runtime and driver) is associated with each call. To do that, you need a mechanism for controlling the command buffer and the timing of the mode transition.

The Query Mechanism

The query mechanism in Microsoft Direct3D 9 was designed to allow the runtime to query the GPU for progress and return certain data from the GPU. While profiling, if the GPU work is minimized so that it has a negligible impact on performance, you can return status from the GPU to help measure the driver work. After all, the driver work is complete when the GPU has seen the driver commands. Additionally, the query mechanism can be coaxed into controlling two command buffer characteristics that are important to profiling: when the command buffer empties and how much work is in the buffer.

Here's the same render sequence using the query mechanism:

// 1. Create an event query from the current device
IDirect3DQuery9* pQuery;
m_pD3DDevice->CreateQuery(D3DQUERYTYPE_EVENT, &pQuery);

// 2. Add an end marker to the command buffer queue.
pEvent->Issue(D3DISSUE_END);

// 3. Empty the command buffer and wait until the GPU is idle.
while(S_FALSE == pEvent->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;

// 4. Start profiling
LARGE_INTEGER start, stop;
QueryPerformanceCounter(&start);

// 5. Invoke the API calls to be profiled.
SetTexture(...);
DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

// 6. Add an end marker to the command buffer queue.
pEvent->Issue(D3DISSUE_END);

// 7. Force the driver to execute the commands from the command buffer.
// Empty the command buffer and wait until the GPU is idle.
while(S_FALSE == pEvent->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;

// 8. End profiling
QueryPerformanceCounter(&stop);

Example 3: Using a Query to Control the Command Buffer

Here is a more detailed explanation of each of these lines of code:

  1. Create an event query by creating a query object with D3DQUERYTYPE_EVENT.
  2. Add a query event marker to the command buffer by calling IDirect3DQuery9::Issue(D3DISSUE_END). This marker tells the driver to track when the GPU finishes executing whatever commands preceded the marker.
  3. The first call empties the command buffer because calling IDirect3DQuery9::GetData with D3DGETDATA_FLUSH forces the command buffer to be emptied. Each subsequent call is checking the GPU to see when it finishes processing all the command-buffer work. This loop does not return S_OK until the GPU is idle.
  4. Sample the start time.
  5. Invoke the API calls being profiled.
  6. Add a second query event marker to the command buffer. This marker will be used to track the completion of the calls.
  7. The first call empties the command buffer because calling IDirect3DQuery9::GetData with D3DGETDATA_FLUSH forces the command buffer to be emptied. When the GPU finishes processing all the command-buffer work, IDirect3DQuery9::GetData returns S_OK, and the loop is exited because the GPU is idle.
  8. Sample the stop time.

Here are the results measured with QueryPerformanceCounter and QueryPerformanceFrequency:

Local Variable | Number of Ticks
start | 1792998845060
stop | 1792998845090
freq | 3579545

Converting ticks to cycles once again (on a 2 GHz machine):

# ticks  = (stop - start) = 1792998845090 - 1792998845060 = 30 ticks
# cycles = CPU speed * number of ticks / QPF
# 16,450 = 2 GHz      * 30             / 3,579,545

Here is the breakdown of the number of cycles per call:

Number of cycles for SetTexture           : 100
Number of cycles for DrawPrimitive        : 900
Number of cycles for Issue                : 200
Number of cycles for GetData              : 16,450

The query mechanism has allowed us to control the runtime and the driver work that is being measured. To understand each of these numbers, here's what is happening in response to each of the API calls, along with the estimated timings:

  1. The first call empties the command buffer by calling IDirect3DQuery9::GetData with D3DGETDATA_FLUSH. When the GPU finishes processing all the command-buffer work, IDirect3DQuery9::GetData returns S_OK, and the loop is exited because the GPU is idle.
  2. The render sequence starts by converting IDirect3DDevice9::SetTexture to a device-independent format and adding it to the command buffer. Assume this takes about 100 cycles.
  3. IDirect3DDevice9::DrawPrimitive is converted and added to the command buffer. Assume this takes about 900 cycles.
  4. IDirect3DQuery9::Issue adds a query marker to the command buffer. Assume this takes about 200 cycles.
  5. IDirect3DQuery9::GetData causes the command buffer to be emptied which forces the kernel-mode transition. Assume this takes about 5000 cycles.
  6. The driver then processes the work associated with all four calls. Assume that the driver time to process IDirect3DDevice9::SetTexture is about 2964 cycles, IDirect3DDevice9::DrawPrimitive is about 3600 cycles, IDirect3DQuery9::Issue is about 200 cycles. So the total driver time for all four commands is about 6450 cycles.

    Note The driver also takes a little time to see what the status of the GPU is. Because the GPU work is trivial, the GPU should be done already. IDirect3DQuery9::GetData will return S_OK based on the likelihood that the GPU is finished.

  7. When the driver finishes its work, the user-mode transition returns control to the runtime. The command buffer is now empty. Assume this takes about 5000 cycles.

The numbers for IDirect3DQuery9::GetData include:

GetData = kernel-transition + driver work + user-transition
GetData = 5000              + 6450        + 5000
GetData = 16,450

driver work = SetTexture + DrawPrimitive + Issue =
driver work = 2964       + 3600          + 200   = 6450 cycles

The query mechanism used in combination with QueryPerformanceCounter measures all of the CPU work. This is done with a combination of query markers, and query status comparisons. Start and stop query markers added to the command buffer are used to control how much work is in the buffer. By waiting until the right return code is returned, the start measurement is made just before a clean render sequence starts, and the stop measurement is made just after the driver has finished the work associated with the command buffer contents. This effectively captures the CPU work done by the runtime as well as the driver.

Now that you know about the command buffer and the effect it can have on profiling, you should know that there are a few other conditions that can cause the runtime to empty the command buffer. You need to watch out for these in your render sequences. Some of these conditions are in response to API calls, others are in response to resource changes in the runtime. Any of the following conditions will cause a mode transition:

  • When one of the lock methods (IDirect3DVertexBuffer9::Lock) is called on a vertex buffer, index buffer, or texture (under certain conditions with certain flags).
  • When a device or vertex buffer, index buffer, or texture is created.
  • When a device or vertex buffer, index buffer, or texture is destroyed by the last release.
  • When IDirect3DDevice9::ValidateDevice is called.
  • When IDirect3DDevice9::Present is called.
  • When the command buffer fills up.
  • When IDirect3DQuery9::GetData is called with D3DGETDATA_FLUSH.

Be careful to watch for these conditions in your render sequences. Every time a mode transition is added, 10,000 cycles of driver work will be added to your profiling measurements. In addition, the command buffer is not statically sized. The runtime may change the buffer's size in response to the amount of work that is being generated by the application. This is yet another optimization that is dependent on a render sequence.

So be careful to control mode transitions during profiling. The query mechanism offers a robust method for emptying the command buffer so that you can control the timing of the mode transition as well as the amount of work the buffer contains. However, even this technique can be improved by reducing the mode transition time to make it insignificant with respect to the measured result.

Make the Render Sequence Large Compared to the Mode Transition

In the previous example, the the kernel-mode switch and the user-mode switch consume about 10,000 cycles that have nothing to do with runtime and driver work. Since the mode transition is built into the operating system, it cannot be reduced to zero. To make the mode transition insignificant, the render sequence needs to adjusted so that the driver and runtime work are an order of magnitude larger than the mode switches. You could try to do a subtraction to remove the transitions, but amortizing the cost over a much larger render sequence cost is more reliable.

The strategy for reducing the mode transition until it becomes insignificant is to add a loop to the render sequence. For example, let look at the profiling results if a loop is added that will repeat the render sequence 1500 times:

// Initialize the array with two textures, same size, same format
IDirect3DTexture* texArray[2];

CreateQuery(D3DQUERYTYPE_EVENT, pEvent);
pEvent->Issue(D3DISSUE_END);
while(S_FALSE == pEvent->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;

LARGE_INTEGER start, stop;
// Now start counting because the video card is ready
QueryPerformanceCounter(&start);

// Add a loop to the render sequence
for(int i = 0; i < 1500; i++)
{
  SetTexture(taxArray[i%2]);
  DrawPrimitive(D3DPT_TRIANGLELIST, i*3, 1);
}

pEvent->Issue(D3DISSUE_END);

while(S_FALSE == pEvent->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;
QueryPerformanceCounter(&stop);

Example 4: Add a Loop to the Render Sequence

Here are the results measured with QueryPerformanceCounter and QueryPerformanceFrequency:

Local Variable | Number of Tics
start | 1792998845000
stop | 1792998847084
freq | 3579545

Using QueryPerformanceCounter measures 2,840 ticks now. Converting ticks to cycles is the same as we have already shown:

# ticks  = (stop - start) = 1792998847084 - 1792998845000 = 2840 ticks
# cycles    = machine speed * number of ticks / QPF
# 6,900,000 = 2 GHz          * 2840           / 3,579,545

In other words, it takes about 6.9 million cycles on this 2 GHz machine to process the 1500 calls in the render loop. Of the 6.9 million cycles, the amount of time in the mode transitions is approximately 10k, so now the profile results are almost entirely measuring work associated with IDirect3DDevice9::SetTexture and IDirect3DDevice9::DrawPrimitive.

Notice that the code sample requires an array of two textures. To avoid a runtime optimization that would remove IDirect3DDevice9::SetTexture if it sets the same texture pointer every time it is called, simply use an array of two textures. That way, each time through the loop, the texture pointer changes, and the full work associated with IDirect3DDevice9::SetTexture is performed. Be sure that both textures are the same size and format, so that no other state will change when the texture does.

And now you have a technique for profiling Direct3D. It relies on the high performance counter (QueryPerformanceCounter) to record the number of ticks it takes the CPU to process work. The work is carefully controlled to be the runtime and driver work associated with API calls using the query mechanism. A query provides two means of control: first to empty the command buffer before the render sequence starts, and secondly to return when the GPU work is finished.

So far, this paper has shown how to profile a render sequence. Each render sequence has been fairly simple, containing a single IDirect3DDevice9::DrawPrimitive call and a IDirect3DDevice9::SetTexture call. This was done to focus on the command buffer and the use of the query mechanism to control it. Here is a brief summary of how to profile an arbitrary render sequence:

  • Use a high performance counter like QueryPerformanceCounter to measure the time it takes to process each API call. Use QueryPerformanceFrequency and the CPU clock rate to convert this to the number of CPU cycles per API call.
  • Minimize the amount of GPU work by rendering triangle lists, where each triangle contains one pixel.
  • Use the query mechanism to empty the command buffer before the render sequence. This guarantees that profiling will capturing the correct amount of runtime and driver work associated with the render sequence.
  • Control the amount of work added to the command buffer with query event markers. This same query detects when the GPU finishes its work. Since the GPU work is trivial, this is virtually equivalent to measuring when the driver work is completed.

All of these techniques are used to profile state changes. Assuming that you have read and understood how to control the command buffer, and have successfully completed baseline measurements on IDirect3DDevice9::DrawPrimitive (watch out for this optimization problem - ), you are ready to add state changes to your render sequences. There are a few additional profiling challenges when adding state changes to a render sequence. If you intend to add state changes to your render sequences, be sure to continue into the next section.

Profiling Direct3D State Changes

Direct3D uses many render states to control almost every aspect of the pipeline. The APIs that cause state changes include any function or method other than the Draw*Primitive calls.

State changes are tricky because you may not be able to see the cost of a state change without rendering. This is a result of the lazy algorithm that the driver and the GPU use to defer work until it absolutely has to be done. In general, you should follow these steps to measure a single state change:

  1. Profile IDirect3DDevice9::DrawPrimitive first.
  2. Add one state change to the render sequence and profile the new sequence.
  3. Subtract the difference between the two sequences to get the cost of the state change.

Naturally, everything you have learned about using the query mechanism and putting the render sequence in a loop to negate the cost of the mode transition still applies.

Profiling a Simple State Change

Starting with a render sequence that contains IDirect3DDevice9::DrawPrimitive, here is the code sequence for measuring the cost of adding IDirect3DDevice9::SetTexture:

// Get the start counter value as shown in Example 4

// Initialize a texture array as shown in Example 4
IDirect3DTexture* texArray[2];

// Render sequence loop
for(int i = 0; i < 1500; i++)
{
  SetTexture(0, texArray[i%2];

  // Force the state change to propogate to the GPU
  DrawPrimitive(D3DPT_TRIANGLELIST, i*3, 1);
}

// Get the stop counter value as shown in Example 4

Example 5: Measuring One State Change API Call

Notice that the loop contains two calls, IDirect3DDevice9::SetTexture and IDirect3DDevice9::DrawPrimitive. The render sequence loops 1500 times and generates results similar to these:

Local Variable | Number of Tics
start | 1792998860000
stop | 1792998870260
freq | 3579545

Converting ticks to cycles once again yields:

# ticks  = (stop - start) = 1792998870260 - 1792998860000 = 10,260 ticks
# cycles    = machine speed * number of ticks / QPF
5,775,000   = 2 GHz          * 10,260         / 3,579,545

Dividing by the number of iterations in the loop yields:

5,775,000 cycles / 1500 iterations = 3850 cycles for one iteration

Each iteration of the loop contains a state change and a draw call. Subtracting out the result of the IDirect3DDevice9::DrawPrimitive render sequence leaves:

3850 - 1100 = 2750 cycles for SetTexture

This is the average number of cycles to add IDirect3DDevice9::SetTexture to this render sequence. This same technique can be applied to other state changes.

Why is IDirect3DDevice9::SetTexture called a simple state change? Because the state that is being set is constrained so that the pipeline does the same amount of work each time the state is changed. Constraining both textures to the same size and format assures the same amount of work for each IDirect3DDevice9::SetTexture call.

Profiling a State Change that Needs to Be Toggled

There are other state changes that cause the amount of work performed by the graphics pipeline to change for every iteration of the render loop. For example, if z-testing is enabled, each pixel color updates a render target only after the new pixel's z value is tested against the z-value for the existing pixel. If z-testing is disabled, this per-pixel test is not done and the output is written much faster. Enabling or disabling the z-test state dramatically changes the amount of work done (by the CPU as well as the GPU) during rendering.

IDirect3DDevice9::SetRenderState requires a particular render state and a state value to enable or disable z-testing. The particular state value is evaluated at runtime to determine how much work is necessary. It is difficult to measure this state change in a render loop and still precondition the pipeline state so that it switches. The only solution is to toggle the state change during the render sequence.

For example, the profiling technique needs to be repeated twice as follows:

  1. Start by profiling the IDirect3DDevice9::DrawPrimitive render sequence. Call this the baseline.
  2. Profile a second render sequence that toggles the state change. The render sequence loop contains:
    • A state change to set the state into a "false" condition.
    • IDirect3DDevice9::DrawPrimitive just like the original sequence.
    • A state change to set the state into a "true" condition.
    • A second IDirect3DDevice9::DrawPrimitive to force the second state change to be realized.
  3. Find the difference between the two render sequences. This is done by:
    • Multiply the baseline IDirect3DDevice9::DrawPrimitive sequence by 2 because there are two IDirect3DDevice9::DrawPrimitive calls in the new sequence.
    • Subtract the result of the new sequence from the original sequence.
    • Divide the result by 2 to get the average cost of both the "false" and the "true" state change.

With the looping technique used in the render sequence, the cost of changing pipeline state needs to be measured by toggling the state from a "true" to a "false" condition and vice versa, for each iteration in the render sequence. The meaning of "true" and "false" here are not literal, this simply means that the state needs to be set into opposing conditions. This causes both state changes to be measured during profiling. Of course everything you have learned about using the query mechanism and putting the render sequence in a loop to negate the cost of the mode transition still applies.

For example, here is the code sequence for measuring the cost of toggling z-testing on or off:

// Get the start counter value as shown in Example 4

// Add a loop to the render sequence
for(int i = 0; i < 1500; i++)
{
  // Precondition the pipeline state to the "false" condition
  SetRenderState(D3DRS_ZENABLE, FALSE);

  // Force the state change to propogate to the GPU
  DrawPrimitive(D3DPT_TRIANGLELIST, (2*i + 0)*3, 1);

  // Set the pipeline state to the "true" condition
  SetRenderState(D3DRS_ZENABLE, TRUE);

  // Force the state change to propogate to the GPU
  DrawPrimitive(D3DPT_TRIANGLELIST, (2*i + 1)*3, 1);
}

// Get the stop counter value as shown in Example 4

Example 5: Measuring a Toggling State Change

The loop toggles the state by executing two IDirect3DDevice9::SetRenderState calls. The first IDirect3DDevice9::SetRenderState call disables z-testing and the second IDirect3DDevice9::SetRenderState enables z-testing. Each IDirect3DDevice9::SetRenderState is followed by IDirect3DDevice9::DrawPrimitive so that the work associated with the state change is processed by the driver instead of only setting a dirty bit in the driver.

These numbers are reasonable for this render sequence:

Local Variable | Number of Ticks
start | 1792998845000
stop | 1792998861740
freq | 3579545

Converting ticks to cycles once again yields:

# ticks  = (stop - start) = 1792998861740 - 1792998845000 = 15,120 ticks
# cycles    = machine speed * number of ticks / QPF
 9,300,000  = 2 GHz          * 16,740         / 3,579,545

Dividing by the number of iterations in the loop yields:

9,300,000 cycles / 1500 iterations = 6200 cycles for one iteration

Each iteration of the loop contains two state changes and two draw calls. Subtracting out the draw calls (assuming 1100 cycles) leaves:

6200 - 1100 - 1100 = 4000 cycles for both state changes

This is the average number of cycles for both state changes so the average time for each state change is:

4000 / 2  = 2000 cycles for each state change

Therefore, the average number of cycles to enable or disable z-testing is 2000 cycles. It is worth noting that QueryPerformanceCounter is measuring z-enable half the time and z-disable half of the time. This technique actually measures the average of both state changes. In other words, you are measuring the time to toggle a state. Using this technique, you have no way of knowing if the enable and disable times are equivalent since you have measured the average of both of them. Nevertheless, this is a reasonable number to use when budgeting a toggling state as an application that causes this state change can only do so by toggling this state.

So now you can apply these techniques and profile all the state changes you want, right? Not quite. You still need to be careful about optimizations that are designed to reduce the amount of work that needs to be done. There are two types of optimizations that you should be aware of when designing your render sequences.

Watch Out for State Change Optimizations

The previous section show how to profile both kinds of state changes: a simple state change that is constrained to generate the same amount of work for each iteration, and a toggling state change that dramatically changes the amount of work done. What happens if you take the previous render sequence and add another state change to it? For instance, this example takes the z>-enable render sequence and adds a z-func comparison to it:

// Add a loop to the render sequence
for(int i = 0; i < 1500; i++)
{
  // Precondition the pipeline state to the opposite condition
  SetRenderState(D3DRS_ZFUNC, D3DCMP_NEVER);

  // Precondition the pipeline state to the opposite condition
  SetRenderState(D3DRS_ZENABLE, FALSE);

  // Force the state change to propogate to the GPU
  DrawPrimitive(D3DPT_TRIANGLELIST, (2*i + 0)*3, 1);

  // Now set the state change you want to measure
  SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);

  // Now set the state change you want to measure
  SetRenderState(D3DRS_ZENABLE, TRUE);

  // Force the state change to propogate to the GPU
  DrawPrimitive(D3DPT_TRIANGLELIST, (2*i + 1)*3, 1);
}

The z-func state sets the comparison level when writing to the z-buffer (between the z-value of a current pixel with the z-value of a pixel in the depth buffer). D3DCMP_NEVER turns off the z-testing comparison while D3DCMP_ALWAYS sets the comparison to happen every time z-testing is done.

Profiling either one of these state changes in a render sequence with IDirect3DDevice9::DrawPrimitive generates results similar to these:

Single State Change | Average Number of Cycles
D3DRS_ZENABLE only | 2000

or

Single State Change | Average Number of Cycles
D3DRS_ZFUNC only | 600

But, if you profile both D3DRS_ZENABLE and D3DRS_ZFUNC in the same render sequence you could see results like these:

Both State Changes | Average Number of Cycles
D3DRS_ZENABLE + D3DRS_ZFUNC | 2000

You could expect the result to be to be the sum of 2000 and 600 (or 2600) cycles because the driver is doing all the work associated with setting both render states. Instead, the average is 2000 cycles.

This result reflects a state change optimization implemented in the runtime, the driver, or the GPU. In this case, the driver could see the first IDirect3DDevice9::SetRenderState and set a dirty state which would postpone the work until later. When the driver sees the second IDirect3DDevice9::SetRenderState, the same dirty state could be redundantly set and the same work would be postponed once again. When IDirect3DDevice9::DrawPrimitive is called, the work associated with the dirty state is finally processed. The driver executes the work one time, which means that the first two state changes are effectively consolidated by the driver. Similarly, the third and fourth state changes are effectively consolidated by the driver into a single state change when the second IDirect3DDevice9::DrawPrimitive is called. The net result is that the driver and the GPU process a single state change for each draw call.

This is a good example of a sequence-dependent driver optimization. The driver postponed work twice by setting a dirty state, and then performed the work once to clear the dirty state. This is a good example of the kind of efficiency improvement that can take place when work is deferred until absolutely necessary.

How do you know which state changes set a dirty state internally and therefore postpone work until later? Only by testing render sequences (or talking to driver writers). Drivers are updated and improved periodically so the list of optimizations is not static. There is only one way to absolutely know what a state change costs in a given render sequence, on a particular set of hardware; and that is to measure it.

Watch Out for DrawPrimitive Optimizations

In addition to state change optimizations, the runtime will attempt to optimize the number of draw calls that the driver has to process. For example, consider these back to back draw calls:

DrawPrimitive(D3DPT_TRIANGLELIST, 0, 3); // Draw 3 primitives, vertices 0 - 8
DrawPrimitive(D3DPT_TRIANGLELIST, 9, 4); // Draw 4 primitives, vertices 9 - 20

Example 5a: Two Draw Calls

This sequence contains two draw calls, which the runtime will consolidate into a single call equivalent to:

DrawPrimitive(D3DPT_TRIANGLELIST, 0, 7); // Draw 7 primitives, vertices 0 - 20

Example 5b: A Single Concatenated Draw Call

The runtime will concatenate both of these particular draw calls into a single call, which reduces the driver work by 50 percent because the driver will now only need to process one draw call.

In general, the runtime will concatenate two or more back-to-back IDirect3DDevice9::DrawPrimitive calls when:

  1. The primitive type is a triangle list (D3DPT_TRIANGLELIST).
  2. Each successive IDirect3DDevice9::DrawPrimitive call must reference consecutive vertices within the vertex buffer.

Similarly, the right conditions for concatenating two or more back-to-back IDirect3DDevice9::DrawIndexedPrimitive calls are:

  1. The primitive type is a triangle list (D3DPT_TRIANGLELIST).
  2. Each successive IDirect3DDevice9::DrawIndexedPrimitive call must sequential reference consecutive indices within the index buffer.
  3. Each successive IDirect3DDevice9::DrawIndexedPrimitive call must use the same value for BaseVertexIndex.

To prevent concatenation during profiling, modify the render sequence so that the primitive type is not a triangle list, or modify the render sequence so that there are no back-to-back draw calls that use consecutive vertices (or indices). More specifically, the runtime will also concatenate draw calls that meet both of the following conditions:

  • When the previous call is IDirect3DDevice9::DrawPrimitive, if the next draw call:
    • uses a triangle list, AND
    • specifies the StartVertex = previous StartVertex + previous PrimitiveCount * 3
  • When using IDirect3DDevice9::DrawIndexedPrimitive, if the next draw call:
    • uses a triangle list, AND
    • specifies the StartIndex = previous StartIndex + previous PrimitiveCount * 3, AND
    • specifies the BaseVertexIndex = previous BaseVertexIndex

Here is a more subtle example of draw call concatenation that is easy to overlook when you are profiling. Assume the render sequence looks like this:

  for(int i = 0; i < 1500; i++)
  {
    SetTexture(...);
    DrawPrimitive(D3DPT_TRIANGLELIST, i*3, 1);
  }

Example 5c: One State Change and One Draw Call

The loop iterates through 1500 triangles, setting a texture and drawing each triangle. This render loop takes approximately 2750 cycles for IDirect3DDevice9::SetTexture and 1100 cycles for IDirect3DDevice9::DrawPrimitive as shown in previous sections. You might intuitively expect that moving IDirect3DDevice9::SetTexture outside the render loop should reduce the amount of work done by the driver by 1500 * 2750 cycles, which is the amount of work associated with calling IDirect3DDevice9::SetTexture 1500 times. The code snippet would look like this:

  SetTexture(...); // Set the state outside the loop
  for(int i = 0; i < 1500; i++)
  {
//    SetTexture(...);
    DrawPrimitive(D3DPT_TRIANGLELIST, i*3, 1);
  }

Example 5d: Example 5c with the State Change Outside the Loop

Moving IDirect3DDevice9::SetTexture outside the render loop does reduce the amount of work associated with IDirect3DDevice9::SetTexture since it is called once instead of 1500 times. A less obvious secondary effect is that the work for IDirect3DDevice9::DrawPrimitive is also reduced from 1500 calls to 1 call because all of the conditions for concatenating draw calls are satisfied. When the render sequence is processed, the runtime will process 1500 calls into a single driver call. By moving this one line of code, the amount of driver work has been reduced dramatically:

total work done = runtime + driver work

Example 5c: with SetTexture in the loop:
runtime work = 1500 SetTextures + 1500 DrawPrimitives
driver  work = 1500 SetTextures + 1500 DrawPrimitives

Example 5d: with SetTexture outside of the loop:
runtime work = 1 SetTexture + 1 DrawPrimitive + 1499 Concatenated DrawPrimitives
driver  work = 1 SetTexture + 1 DrawPrimitive

These results are entirely correct, but are very misleading in the context of the original question. The draw call optimization has caused the amount of driver work to be dramatically reduced. This is a common problem when doing custom profiling. When eliminating calls from a render sequence, be careful to avoid draw call concatenation. In fact, this scenario is a powerful example of the amount of improvement in driver performance possible by this runtime optimization.

So now you know how to measure state changes. Start by profiling IDirect3DDevice9::DrawPrimitive. Then add each additional state change to the sequence (in some cases adding one call and in other cases adding two calls) and measure the difference between the two sequences. You can convert the results to ticks or cycles or time. Just like measuring render sequences with QueryPerformanceCounter, measuring individual state changes relies on the query mechanism to control the command buffer, and putting the state changes in a loop to minimize the impact of the mode transitions. This technique measures the cost of toggling a state, since the profiler returns the average of enabling and disabling the state.

With this capability, you can start generating arbitrary rendering sequences and accurately measuring the associated runtime and driver work. The numbers can then be used to answer budgeting questions like "how many more of these calls" can be made in the render sequence while still maintaining a reasonable frame rate, assuming CPU-limited scenarios.

Summary

This paper demonstrates how to control the command buffer so that individual calls can be accurately profiled. The profiling numbers can be generated in ticks, cycles, or absolute time. They represent the amount of runtime and driver work associated with each API call.

Start by profiling a Draw*Primitive call in a render sequence. Remember to:

  1. Use QueryPerformanceCounter to measure the number of ticks per API call. Use QueryPerformanceFrequency to convert the results to cycles or time if you like.
  2. Use the query mechanism to empty the command buffer before starting.
  3. Include the render sequence in a loop to minimize the impact of the mode transition.
  4. Use the query mechanism to measure when the GPU has completed its work.
  5. Watch out for runtime concatenation that will have a major impact on the amount of work done.

This gives you a baseline performance for IDirect3DDevice9::DrawPrimitive that can be used to build from. To profile one state change, follow these additional tips:

  1. Add the state change to a known render sequence profile the new sequence. Since the testing is done in a loop, this requires setting the state twice into opposite values (like enable and disable for instance).
  2. Compare the difference in cycle times between the two sequences.
  3. For state changes that significantly change the pipeline (like IDirect3DDevice9::SetTexture), subtract the difference between the two sequences to get the time for state change.
  4. For state changes that significantly change the pipeline (and therefore require toggling states like IDirect3DDevice9::SetRenderState), subtract the difference between the render sequences and divide by 2. This will generate the average number of cycles for each state change.

But be careful of optimizations that cause unexpected results when profiling. State change optimizations may set dirty states which causes work to be deferred. This can cause profile results which are not as intuitive as expected. Draw calls that are concatenated will dramatically reduce driver work which can lead to misleading conclusions. Carefully planned render sequences are used to prevent state change and draw call concatenations from occuring. The trick is to prevent the optimizations from happening during profiling so that the numbers you generate are reasonable budgeting numbers.

Note Duplicating this profiling strategy in an application without the query mechanism is more difficult. Prior to Direct3D 9 the only predictable way to empty the command buffer is to lock an active surface (such as a render target) to wait until the GPU is idle. This is because locking a surface forces the runtime to empty the command buffer in case there are any rendering commands in the buffer that should update the surface before it gets locked, in addition to waiting for the GPU to finish. This technique is functional, although it is more obtrusive that using the query mechanism introduced in Direct3D 9.

Appendix

The numbers in this table are a range of approximations for the amount of runtime and driver work associated with each of these state changes. The approximations are based on actual measurements made on drivers using the techniques shown in the paper. These numbers were generated using the Direct3D 9 runtime and are driver-dependent.

The techniques in this paper are designed to measure runtime and driver work. In general, it is impractical to provide results that match the performance of the CPU and the GPU in every application as this would require an exhaustive array of render sequences. In addition, it is particularly difficult to benchmark performance of the GPU because it is highly dependent on the state setup in the pipeline before the render sequence. For instance, enabling alpha blending does little to affect the amount of CPU work necessary, but can have a big impact on the amount of work done by the GPU. Therefore, the techniques in this paper constrain the GPU work to the minimum amount possible by limiting the amount of data that needs to be rendered. This means that the numbers in the table will most closely match the results attained from applications that are CPU limited (as opposed to an application that is limited by the GPU).

You are encouraged to use the techniques presented to cover the scenarios and configurations most important to you. The values in the table can be used to compare with the numbers you generate. Since each driver varies, the only way to generate the actual numbers you will see is to generate profiling results using your scenarios.

API Call | Average number of Cycles
SetVertexDeclaration | 6500 - 11250
SetFVF | 6400 - 11200
SetVertexShader | 3000 - 12100
SetPixelShader | 6300 - 7000
SPECULARENABLE | 1900 - 11200
SetRenderTarget | 6000 - 6250
SetPixelShaderConstant (1 Constant) | 1500 - 9000
NORMALIZENORMALS | 2200 - 8100
LightEnable | 1300 - 9000
SetStreamSource | 3700 - 5800
LIGHTING | 1700 - 7500
DIFFUSEMATERIALSOURCE | 900 - 8300
AMBIENTMATERIALSOURCE | 900 - 8200
COLORVERTEX | 800 - 7800
SetLight | 2200 - 5100
SetTransform | 3200 - 3750
SetIndices | 900 - 5600
AMBIENT | 1150 - 4800
SetTexture | 2500 - 3100
SPECULARMATERIALSOURCE | 900 - 4600
EMISSIVEMATERIALSOURCE | 900 - 4500
SetMaterial | 1000 - 3700
ZENABLE | 700 - 3900
WRAP0 | 1600 - 2700
MINFILTER | 1700 - 2500
MAGFILTER | 1700 - 2400
SetVertexShaderConstant (1 Constant) | 1000 - 2700
COLOROP | 1500 - 2100
COLORARG2 | 1300 - 2000
COLORARG1 | 1300 - 1980
CULLMODE | 500 - 2570
CLIPPING | 500 - 2550
DrawIndexedPrimitive | 1200 - 1400
ADDRESSV | 1090 - 1500
ADDRESSU | 1070 - 1500
DrawPrimitive | 1050 - 1150
SRGBTEXTURE | 150 - 1500
STENCILMASK | 570 - 700
STENCILZFAIL | 500 - 800
STENCILREF | 550 - 700
ALPHABLENDENABLE | 550 - 700
STENCILFUNC | 560 - 680
STENCILWRITEMASK | 520 - 700
STENCILFAIL | 500 - 750
ZFUNC | 510 - 700
ZWRITEENABLE | 520 - 680
STENCILENABLE | 540 - 650
STENCILPASS | 560 - 630
SRCBLEND | 500 - 685
Two_Sided_StencilMODE | 450 - 590
ALPHATESTENABLE | 470 - 525
ALPHAREF | 460 - 530
ALPHAFUNC | 450 - 540
DESTBLEND | 475 - 510
COLORWRITEENABLE | 465 - 515
CCW_STENCILFAIL | 340 - 560
CCW_STENCILPASS | 340 - 545
CCW_STENCILZFAIL | 330 - 495
SCISSORTESTENABLE | 375 - 440
CCW_STENCILFUNC | 250 - 480
SetScissorRect | 150 - 340


Queries (Direct3D 9)

There are several types of queries which are designed to query the status of resources. The status of a given resource includes graphics processing unit (GPU) status, driver status, or runtime status. To understand the difference between the different query types, you need to understand the query states. Here's a state transition diagram that explains each of the query states:

The diagram shows three states, each defined by circles. Each of the solid lines are application-driven events that cause a state transition. The dashed line is a resource-driven event that switches a query from the issued state to the signaled state. Each of these states has a different purpose:

  • The signaled state is like an idle state. The query object has been generated and is waiting for the application to issue the query. Once a query has completed and transitioned back to the signaled state, the answer to the query can be retrieved.
  • The building state is like a staging area for a query. From the building state, a query has been issued (by calling D3DISSUE_BEGIN) but has not yet transitioned to the issued state. When an application issues a query end (by calling D3DISSUE_END), the query transitions to the issued state.
  • The issued state means that the resource being queried has control of the query. Once the resource finishes its work, the resource transitions the state machine to the signaled state. During the issued state, the application must poll to detect the transition to the signaled state. Once the transition to the signaled state occurs, IDirect3DQuery9::GetData returns the query result (through an argument) to the application.

The following table lists the available query types.

Query Type | Issue Event | GetData buffer | Runtime | Implicit beginning of query
BANDWIDTHTIMINGS | D3DISSUE_BEGIN, D3DISSUE_END | D3DDEVINFO_D3D9BANDWIDTHTIMINGS | Retail/Debug | N/A
CACHEUTILIZATION | D3DISSUE_BEGIN, D3DISSUE_END | D3DDEVINFO_D3D9CACHEUTILIZATION | Retail/Debug | N/A
EVENT | D3DISSUE_END | BOOL | Retail/Debug | IDirect3D9::CreateDevice
INTERFACETIMINGS | D3DISSUE_BEGIN, D3DISSUE_END | D3DDEVINFO_D3D9INTERFACETIMINGS | Retail/Debug | N/A
OCCLUSION | D3DISSUE_BEGIN, D3DISSUE_END | DWORD | Retail/Debug | N/A
PIPELINETIMINGS | D3DISSUE_BEGIN, D3DISSUE_END | D3DDEVINFO_D3D9PIPELINETIMINGS | Retail/Debug | N/A
RESOURCEMANAGER | D3DISSUE_END | D3DDEVINFO_ResourceManager | Debug only | IDirect3DDevice9::Present
TIMESTAMP | D3DISSUE_END | UINT64 | Retail/Debug | N/A
TIMESTAMPDISJOINT | D3DISSUE_BEGIN, D3DISSUE_END | BOOL | Retail/Debug | N/A
TIMESTAMPFREQ | D3DISSUE_END | UINT64 | Retail/Debug | N/A
VCACHE | D3DISSUE_END | D3DDEVINFO_VCACHE | Retail/Debug | IDirect3D9::CreateDevice
VERTEXSTATS | D3DISSUE_END | D3DDEVINFO_D3DVERTEXSTATS | Debug only | IDirect3DDevice9::Present
VERTEXTIMINGS | D3DISSUE_BEGIN, D3DISSUE_END | D3DDEVINFO_D3D9STAGETIMINGS | Retail/Debug | N/A

Some of the queries require a begin and end event, while others only require an end event. The queries that only require an end event begin when another implicit event occurs (which is listed in the table). All queries return an answer, except the event query whose answer is always TRUE. An application uses either the state of the query or the return code of IDirect3DQuery9::GetData.

Create a Query

Before you create a query, you can check to see if the runtime supports queries by calling IDirect3DDevice9::CreateQuery with a NULL pointer like this:

IDirect3DQuery9* pEventQuery;

// Create a device pointer m_pd3dDevice

// Create a query object
HRESULT hr = m_pd3dDevice->CreateQuery(D3DQUERYTYPE_EVENT, NULL);

This method returns a success code if a query can be created; otherwise it returns an error code. Once IDirect3DDevice9::CreateQuery succeeds, you can create a query object like this:

IDirect3DQuery9* pEventQuery;
m_pd3dDevice->CreateQuery(D3DQUERYTYPE_EVENT, &pEventQuery);

If this call succeeds, a query object is created. The query is essentially idle in the signaled state (with an uninitialized answer) waiting to be issued. When you are finished with the query, release it like any other interface.

Issue a Query

An application changes a query state by issuing a query. Here is an example of issuing a query:

IDirect3DQuery9* pEventQuery;
m_pD3DDevice->CreateQuery(D3DQUERYTYPE_EVENT, &pEventQuery);

// Issue a Begin event
pEventQuery->Issue(D3DISSUE_BEGIN);

or

// Issue an End event
pEventQuery->Issue(D3DISSUE_END);

A query in the signaled state will transition like this when issued:

Issue Type | Query Transitions to the . . .
D3DISSUE_BEGIN | Building state.
D3DISSUE_END | Issued state.

A query in the building state will transition like this when issued:

Issue Type | Query Transitions to the . . .
D3DISSUE_BEGIN | (No transition, stays in the building state. Restarts the query bracket.)
D3DISSUE_END | Issued state.

An query in the issued state will transition like this when issued:

Issue Type | Query Transitions to the . . .
D3DISSUE_BEGIN | Building state and restarts the query bracket.
D3DISSUE_END | Issued state after abandoning the existing query.

Check the Query State and Get the Answer to the Query

IDirect3DQuery9::GetData does two things:

  1. Returns the query state in the return code.
  2. Returns the answer to the query in pData.

From each of the three query states, here are the IDirect3DQuery9::GetData return codes:

Query State | GetData return code
Signaled | S_OK
Building | Error code
Issued | S_FALSE

For example, when a query is in the issued state and the answer to the query is not available, IDirect3DQuery9::GetData returns S_FALSE. When the resource finishes its work and the application has issued a query end, the resource transitions the query to the signaled state. From the signaled state, IDirect3DQuery9::GetData returns S_OK which means that the answer to the query is also returned in pData. For instance, here is the sequence of events to return the number of pixels drawn in a render sequence:

  • Create the query.
  • Issue a begin event.
  • Draw something.
  • Issue an end event.

The following is the corresponding sequence of code:

IDirect3DQuery9* pOcclusionQuery;
DWORD numberOfPixelsDrawn;

m_pD3DDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &pOcclusionQuery);

// Add an end marker to the command buffer queue.
pOcclusionQuery->Issue(D3DISSUE_BEGIN);

// API render loop
...
Draw(...)
...

// Add an end marker to the command buffer queue.
pOcclusionQuery->Issue(D3DISSUE_END);

// Force the driver to execute the commands from the command buffer.
// Empty the command buffer and wait until the GPU is idle.
while(S_FALSE == pOcclusionQuery->GetData( &numberOfPixelsDrawn,
                                  sizeof(DWORD), D3DGETDATA_FLUSH ))
    ;

These lines of code do several things:

  • Call IDirect3DQuery9::GetData to return the number of pixels drawn.
  • Specify D3DGETDATA_FLUSH to enable the resource to transition the query to the signaled state.
  • Poll the query resource by calling IDirect3DQuery9::GetData from a loop. As long as IDirect3DQuery9::GetData returns S_FALSE, this means the resource has not returned the answer yet.

The return value of IDirect3DQuery9::GetData essentially tells you in what state the query is. Possible values are S_OK, S_FALSE, and an error. Do not call IDirect3DQuery9::GetData on a query that is in the building state.

  • S_OK means the resource (GPU or driver, or runtime) is finished. The query is returning to the signaled state. The answer (if any) is being returned by IDirect3DQuery9::GetData.
  • S_FALSE means the resource (GPU or driver, or runtime) cannot return an answer yet. This could be because the GPU is not finished or has not seen the work yet.
  • An error means that the query has generated an error from which it cannot recover. This could be the case if the device is lost during a query. Once a query has generated an error (other than S_FALSE), the query must be recreated which will restart the query sequence from the signaled state.

Instead of specifying D3DGETDATA_FLUSH, which provides more up-to-date information, you could supply zero which is a more light-weight check if the query is in the issued state. Supplying zero will cause IDirect3DQuery9::GetData to not flush the command buffer. For this reason, care must be taken to avoid infinate loops (see IDirect3DQuery9::GetData for details). Since the runtime queues up work in the command buffer, D3DGETDATA_FLUSH is a mechanism for flushing the command buffer to the driver (and hence the GPU; see Accurately Profiling Direct3D API Calls (Direct3D 9)). During the command buffer flush, a query may transition to the signaled state.

Example: An Event Query

An event query does not support a begin event.

  • Create the query.
  • Issue an end event.
  • Poll until the GPU is idle.
  • Issue an end event.
IDirect3DQuery9* pEventQuery = NULL;
m_pD3DDevice->CreateQuery(D3DQUERYTYPE_EVENT, &pEventQuery);

// Add an end marker to the command buffer queue.
pEventQuery->Issue(D3DISSUE_END);

// Empty the command buffer and wait until the GPU is idle.
while(S_FALSE == pEventQuery->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;

... // API calls

// Add an end marker to the command buffer queue.
pEventQuery->Issue(D3DISSUE_END);

// Force the driver to execute the commands from the command buffer.
// Empty the command buffer and wait until the GPU is idle.
while(S_FALSE == pEventQuery->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;

This is the sequence of commands an event query uses to profile application programming interface (API) calls (see Accurately Profiling Direct3D API Calls (Direct3D 9)). This sequence uses markers to help control the amount of work in the command buffer.

Note that applications should pay special attention to the large cost associated with flushing the command buffer because this causes the operating system to switch into kernel mode, thus incurring a sizeable performance penalty. Applications should also be aware of wasting CPU cycles by waiting for queries to complete.

Queries are an optimization to be used during rendering to increase performance. Therefore, it is not beneficial to spend time waiting for a query to finish. If a query is issued and if the results are not yet ready by the time the application checks for them, the attempt at optimizing did not succeed and rendering should continue as normal.

The classic example of this is during Occlusion Culling. Instead of the while loop above, an application using queries can implement occlusion culling to check to see if a query had finished by the time it needs the result. If the query has not finished, continue (as a worst-case scenario) as if the object being tested against is not occluded (i.e. it is visible) and render it. The code would look similar to the following.

IDirect3DQuery9* pOcclusionQuery = NULL;
m_pD3DDevice->CreateQuery( D3DQUERYTYPE_OCCLUSION, &pOcclusionQuery );

// Add a begin marker to the command buffer queue.
pOcclusionQuery->Issue( D3DISSUE_BEGIN );

... // API calls

// Add an end marker to the command buffer queue.
pOcclusionQuery->Issue( D3DISSUE_END );

// Avoid flushing and letting the CPU go idle by not using a while loop.
// Check if queries are finished:
DWORD dwOccluded = 0;
if( S_FALSE == pOcclusionQuery->GetData( &dwOccluded, sizeof(DWORD), 0 ) )
{
    // Query is not done yet or object not occluded; avoid flushing/wait by continuing with worst-case scenario
    pSomeComplexMesh->Render();
}
else if( dwOccluded != 0 )
{
    // Query is done and object is not occluded.
    pSomeComplexMesh->Render();
}


Efficiently Drawing Multiple Instances of Geometry (Direct3D 9)

Given a scene that contains many objects that use the same geometry, you can draw many instances of that geometry at different orientations, sizes, colors, and so on with dramatically better performance by reducing the amount of data you need to supply to the renderer.

This can be accomplished through the use of two techniques: the first for drawing indexed geometry and the second for non-indexed geometry. Both techniques use two vertex buffers: one to supply geometry data and one to supply per-object instance data. The instance data can be a wide variety of information such as a transform, color data, or lighting data - basically anything that you can describe in a vertex declaration. Drawing many instances of geometry with these techniques can dramatically reduce the amount of data sent to the renderer.

  • Drawing Indexed Geometry
  • Drawing Non-Indexed Geometry
  • See Also

Drawing Indexed Geometry

The vertex buffer contains per-vertex data that is defined by a vertex declaration. Suppose that part of each vertex contains geometry data, and part of each vertex contains per-object instance data. This would look like this:

Figure 1: Indexed Geometry Vertex Buffer Layout

This technique requires a device that supports the 3_0 vertex shader model. This technique works with any programmable shader but not with the fixed function pipeline.

For the vertex buffers shown above, here are the corresponding vertex buffer declarations:

const D3DVERTEXELEMENT9 g_VBDecl_Geometry[] =
{
{0,  0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
{0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL,   0},
{0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT,  0},
{0, 36, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0},
{0, 48, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
D3DDECL_END()
};

const D3DVERTEXELEMENT9 g_VBDecl_InstanceData[] =
{
{1, 0,  D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1},
{1, 16, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2},
{1, 32, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3},
{1, 48, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4},
{1, 64, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,    0},
D3DDECL_END()
};

These declarations define two vertex buffers. The first declaration (for stream 0, indicated by the zeros in column 1) defines the geometry data which consists of: position, normal, tangent, binormal, and texture coordinate data.

The second declaration (for stream 1, indicated by the ones in column 1) defines the per-object instance data. Each instance is defined by four four-component floating point numbers, and a four-component color. The first four values could be used to initialize a 4x4 matrix, which means that this data will uniquely size, position, and rotate each instance of the geometry. The first four components use a texture coordinate semantic which, in this case, means "this is a general four-component number." When you use arbitrary data in a vertex declaration, use a texture coordinate semantic to mark it. The last element in the stream is used for color data. This could be applied in the vertex shader to give each instance a unique color.

Before rendering, you need to call IDirect3DDevice9::SetStreamSourceFreq to bind the vertex buffer streams to the device. Here is an example that binds both vertex buffers:

// Set up the geometry data stream
pd3dDevice->SetStreamSourceFreq(0,
    (D3DSTREAMSOURCE_INDEXEDDATA | g_numInstancesToDraw));
pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
    D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

// Set up the instance data stream
pd3dDevice->SetStreamSourceFreq(1,
    (D3DSTREAMSOURCE_INSTANCEDATA | 1));
pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
    D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

IDirect3DDevice9::SetStreamSourceFreq uses D3DSTREAMSOURCE_INDEXEDDATA to identify the the indexed geometry data. In this case, stream 0 contains the indexed data that describes the object geometry. This value is logically combined with the number of instances of the geometry to draw.

In the second call, IDirect3DDevice9::SetStreamSourceFreq uses D3DSTREAMSOURCE_INSTANCEDATA to identify the stream containing the instance data. This value is logically combined with 1 since each vertex contains one set of instance data.

The last two calls to IDirect3DDevice9::SetStreamSource bind the vertex buffer pointers to the device.

When you are finished rendering the instance data, be sure to reset the vertex stream frequency back to its default state (which does not use instancing). Because this example used two streams, set both streams as shown below:

pd3dDevice->SetStreamSourceFreq(0,1);
pd3dDevice->SetStreamSourceFreq(1,1);

Indexed Geometry Performance Comparison

While it is not possible to make a single conclusion about how much this technique could reduce the render time in every application, consider the difference in the amount of data streamed into the runtime and the number of state changes that will be reduced if you use the instancing technique. This render sequence takes advantage of drawing multiple instances of the same geometry:

if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
    // Set up the geometry data stream
    pd3dDevice->SetStreamSourceFreq(0,
                (D3DSTREAMSOURCE_INDEXEDDATA | g_numInstancesToDraw));
    pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
                D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

    // Set up the instance data stream
    pd3dDevice->SetStreamSourceFreq(1,
                (D3DSTREAMSOURCE_INSTANCEDATA | 1));
    pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
                D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

    pd3dDevice->SetVertexDeclaration( ... );
    pd3dDevice->SetVertexShader( ... );
    pd3dDevice->SetIndices( ... );

    pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0,
                g_dwNumVertices, 0, g_dwNumIndices/3 );

    pd3dDevice->EndScene();
}

Notice that the render loop is called once, the geometry data is streamed once, and n instances are streamed once. This next render sequence is identical in functionality, but does not take advantage of instancing:

if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
    for(int i=0; i < g_numObjects; i++)
    {
        // Set up the geometry data stream
        pd3dDevice->SetStreamSourceFreq(0,
               (D3DSTREAMSOURCE_INDEXEDDATA | g_numInstancesToDraw));
        pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
                D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

        // Set up the instance data stream
        pd3dDevice->SetStreamSourceFreq(1,
               (D3DSTREAMSOURCE_INSTANCEDATA | 1));
        pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
                D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

        pd3dDevice->SetVertexDeclaration( ... );
        pd3dDevice->SetVertexShader( ... );
        pd3dDevice->SetIndices( ... );

        pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0,
                g_dwNumVertices, 0, g_dwNumIndices/3 );
    }

    pd3dDevice->EndScene();
}

Notice that the entire render loop is wrapped by a second loop to draw each object. Now the geometry data is streamed into the renderer n times (instead of once) and any pipeline states may also be set redundantly for each object drawn. This render sequence is very likely to be significantly slower. Notice also that the parameters to IDirect3DDevice9::DrawIndexedPrimitive have not changed between the two render loops.

Drawing Non-Indexed Geometry

In Drawing Indexed Geometry, vertex buffers were configured to draw multiple instances of indexed geometry with greater efficiency. You can also use IDirect3DDevice9::SetStreamSourceFreq to draw non-indexed geometry. This requires a different vertex buffer layout and has different constraints. To draw non-indexed geometry, prepare your vertex buffers like this:

Figure 2: Non-Indexed Geometry Vertex Buffer Layout

This technique is not supported by hardware acceleration on any device. It is only supported by software vertex processing and will work only with vs_3_0 shaders.

Because this technique works with non-indexed geometry, there is no index buffer. As the diagram shows, the vertex buffer that contains geometry contains n copies of the geometry data. For each instance drawn, the geometry data is read from the first vertex buffer and the instance data is read from the second vertex buffer.

Here are the corresponding vertex buffer declarations:

const D3DVERTEXELEMENT9 g_VBDecl_Geometry[] =
{
{0,  0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
{0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL,   0},
{0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT,  0},
{0, 36, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0},
{0, 48, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
D3DDECL_END()
};

const D3DVERTEXELEMENT9 g_VBDecl_InstanceData[] =
{
{1, 0,  D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1},
{1, 16, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2},
{1, 32, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3},
{1, 48, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4},
{1, 64, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,    0},
D3DDECL_END()
};

These declarations are identical to the declarations made in the indexed geometry example. Once again, the first declaration (for stream 0) defines the geometry data and the second declaration (for stream 1) defines the per-object instance data. When you create the first vertex buffer, be sure to load it with the number of instances of the geometry data that you will be drawing.

Before rendering, you need to set up the divider which tells the runtime how to divide up the first vertex buffer into n instances. Then set the divider using IDirect3DDevice9::SetStreamSourceFreq like this:

// Given n instances, m vertices per instance
float fDivider = n / m;

// Set the divider
pd3dDevice->SetStreamSourceFreq(0, fDivider);
// Bind the stream to the vertex buffer
pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
        D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

// Set up the instance data stream
pd3dDevice->SetStreamSourceFreq(1, m);
pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
        D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

The first call to IDirect3DDevice9::SetStreamSourceFreq says that stream 0 uses fDivider to identify the stride of the data in vertex buffer 1. Recall that the first buffer contains n instances of m vertices. IDirect3DDevice9::SetStreamSourceFreq then binds stream 0 to the geometry vertex buffer.

In the second call, IDirect3DDevice9::SetStreamSourceFreq identifies stream 1 as the source of the instance data. The second parameter is the number of vertices in each object (m). Remember that the instance data stream must always be declared as the second stream. IDirect3DDevice9::SetStreamSourceFreq then binds stream 1 to the vertex buffer that contains the instance data.

In general, the vertex offset (in the vertex buffer) is computed as follows:

VertexOffset = StartVertex / Divider * StreamStride +
               VertexIndex / Divider * StreamStride + StreamOffset

Note that the division in this equation is an integer division. The range of the frequency divider is: 0 < Divider < = 216 - 1

When you are finished rendering the instance data, be sure to reset the vertex stream frequency back to its default state. Because this example used two streams, set both streams as shown below:

pd3dDevice->SetStreamSourceFreq(0,1);
pd3dDevice->SetStreamSourceFreq(1,1);

Non-Indexed Geometry Performance Comparison

The major advantage of this instancing style is that it can be used on non-indexed geometry. While it is not possible to make a single conclusion about how much this technique could reduce the render time in every application, consider the difference in the amount of data streamed into the runtime, and the number of state changes that will be reduced for the following render sequence:

if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
 // Given n instances, m vertices per instance
    float fDivider = n / m;

    // Set the divider
    pd3dDevice->SetStreamSourceFreq(0, fDivider);
    pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
                D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

    // Set up the instance data stream
    pd3dDevice->SetStreamSourceFreq(1, m));
    pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
                D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

    pd3dDevice->SetVertexDeclaration( ... );
    pd3dDevice->SetVertexShader( ... );
    pd3dDevice->SetIndices( ... );

    pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0,
                g_dwNumVertices, 0, g_dwNumIndices/3 );

    pd3dDevice->EndScene();
}

Notice that the render loop is called once. The geometry data is streamed once although there are n instances of the geometry being streamed. The data from the instance vertex buffer is streamed once. This next render sequence is identical in functionality, but does not take advantage of instancing:

if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
    for(int i=0; i < g_numObjects; i++)
    {
     // Given n instances, m vertices per instance
        float fDivider = n / m;

        // Set the divider
        pd3dDevice->SetStreamSourceFreq(0, fDivider);
        pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
                D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

        // Set up the instance data stream
        pd3dDevice->SetStreamSourceFreq(1, m));
        pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
                D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

        pd3dDevice->SetVertexDeclaration( ... );
        pd3dDevice->SetVertexShader( ... );
        pd3dDevice->SetIndices( ... );

        pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0,
                g_dwNumVertices, 0, g_dwNumIndices/3 );
    }

    pd3dDevice->EndScene();
}

Without instancing, the render loop needs to be wrapped by a second loop to draw each object. By eliminating the second render loop, you should expect better performance due to fewer render state changes that are called inside the loop.

Overall, it is reasonable to expect the indexed technique (Drawing Indexed Geometry) to perform better than the non-indexed technique (Drawing Non-Indexed Geometry) because the indexed technique only streams one copy of the geometry data. Notice that the parameters to IDirect3DDevice9::DrawIndexedPrimitive have not changed for any of the render sequences.

See Also

Instancing Sample


Using UVAtlas (Direct3D 9)

Many rendering and content generation techniques require a unique, non-overlapping map of a 2D signal (such as a texture) onto a mesh. Such techniques include:

  • Normal/displacement mapping
  • Texture-space PRT simulations and light maps
  • Surface painting
  • Texture-space lighting

Generating a unique UV mapping manually is often time-consuming and tedious; this is especially true when the input geometry is complex and efficient/low-distortion texture-space utilization is desired.

Figure 1: An example mesh and its corresponding texture atlas

This example shows a mesh (on the left) and the corresponding UV-space normal map (on the right). Notice that the texture atlas contains several groups or clusters of data; each cluster is called a chart and in the example above, displays contains the normal data for a portion of the mesh.

The D3DX UVAtlas APIs automatically generate an optimal, non-overlapping texture atlas. The APIs provide input parameters that allow you to:

  • Minimize texture stretch, distortion, and undersampling.
  • Maximize texture-space packing density for efficient use of memory.
  • Provide an even sampling across the mesh, minimizing discontinuities in sampling frequency.

How UVAtlas Works

The UVAtlas APIs (see UVAtlas Functions) generate a texture atlas by partitioning a surface into charts and packing the charts into a texture atlas. Use D3DXUVAtlasPartition and D3DXUVAtlasPack to perform these steps separately; or use D3DXUVAtlasCreate to partition, parameterize and pack in a single call.

  • Partitioning and Parameterizing a Mesh
  • Using Integrated Metric Tensors to Control Parameterization
  • Using Adjacency Data for User Specified Creases
  • Packing Charts Into an Atlas

Partitioning and Parameterizing a Mesh

First, the mesh is partitioned into charts, then each chart is parameterized into its own [0,1] UV-space. A cylinder can be parameterized by one chart; a sphere on the other hand will require two charts.

Figure 2: A sphere partitioned into two charts

A mesh which can be parameterized with a single chart is classified as "homeomorphic to a disk", meaning you could spread out an infinitely flexible, infinitely stretchable disk over the chart and cover the geometry perfectly. This stretching, called a homeomorphism, is a bidirectional function; which means you can go from one parameterization to the other without losing information.

Very few real-world meshes can be parameterized into two dimensions without separating the mesh into clusters, or charts.

Figure 3: Another example mesh and its corresponding texture atlas

There are two parameters that determine the number of charts created:

  • The maximum number of charts allowed for the atlas
  • The maximum amount of stretch allowed for each chart

The amount of stretch will determine the number of charts that are generated, and the overall quality of the sampling. Stretch ranges from 0.0 (no stretch) to 1.0 (any amount of stretch). D3DXUVAtlasCreate and D3DXUVAtlasPartition return the maximum stretch generated by the algorithm.

Figure 4: Another example mesh and its corresponding texture atlas

Using Integrated Metric Tensors to Control Parameterization

Texture-space prioritization can be specified on a per-triangle basis. Integrated Metric Tensors can be provided to control how triangles are stretched in the resulting texture-space atlas. IMT's can be specified directly or computed based on an input signal using the D3DX IMT computation functions. An integrated metric tensor (or IMT) is a symmetrical 2x2 matrix that describes how a triangle is stretched in the atlas. Each IMT is defined by 3 floats, call them (a,b,c). They can be arranged in a symmetric 2x2 matrix like this:

a b
b c

Then the IMT can be used to find the distance between two vectors. Given two vectors v1 and v2, where :

vector v1
vector v2 = v1 + (s,t)

The distance between v1 and v2 can be calculated as:

sqrt((s, t) * M * (s, t)^T)

In other words, the vector (s,t) could be the magnitude of the stretch in an arbitrary direction in u-v space. In this case, the s vector is a direction from the first to the second vertex, and t is the cross product of the normal and s. For instance:

(1,1) * (1,1) = (2,2)
        (1,1)
IMT(1,1,1) scales by 2

(1,-1) * (1,1) = (0,0)
         (1,1)
IMT(2,0,2) scales by 2 with no shearing

IMT's can be specified directly or computed based on an input signal using the D3DX IMT computation functions: D3DXComputeIMTFromPerVertexSignal, D3DXComputeIMTFromPerTexelSignal, D3DXComputeIMTFromSignal, and D3DXComputeIMTFromTexture_graphics.

Specify IMT data directly if you want to control how texture-space is allocated to individual triangles. By doing so, allocate more area in the atlas to important areas of a mesh (such as a character's face or chest logo, or regions of a scene near a player's walking-path). By specifying IMT's that are multiples of the identity matrix, the resulting triangles will be scaled uniformly in texture space.

For example, given a high-resolution normal map, you can compute IMT to provide more texture-space to areas of higher frequency signal in the normal map. Triangles that are "flat" (that mapped to constant regions of the original normal map) will receive less texture space. Triangles that contain a great deal of normal-map detail will receive more texture area in the final result. You can then resample the normal map into a smaller texture but maintain detail, or you can recompute the normal map with the more optimal UV mapping.

Using Adjacency Data for User Specified Creases

User-defined adjacency information can be provided to the partitioning function to describe pre-defined creases in the mesh, and thus define a chart boundary between adjacent faces. This is a simple way for the caller to specify their own chart partitioning as input into the algorithm, which will further refine charts to bring the stretch under the maximum allowed.

Example

This example illustrates how you might use the UVAtlas APIs and the DirectX Viewer to find and fix discontinuities in your model that can dramatically affect the size of your texture atlas.

Assume you started with some model in your favorite content generation software (this example uses a dwarf head model that was created in Maya). Export the textured model to an .x file and create a texture atlas with D3DXUVAtlasCreate. The resulting texture atlas would look something like this:

Figure 5: Example atlas for a dwarf model

The atlas has 22 charts and a maximum stretch of 0.994.

Now look at the textured model to see how well the texture atlas maps to the geometry. To do this, load the model into the viewer tool:

  • Open the viewer tool from the DirectX Utilities.
  • Load the .x file by clicking the Open button.
  • Enabling the crease viewing option by clicking the view button and selecting Creases from popup.

Here's what you should see:

Figure 6: Textured Mesh in the Viewer tool

Each line is a crease which is an adjacent edge between two charts in the texture atlas. The number of charts generated by the algorithm is caused by slight differences perhaps due to discontinuities in the normals. These small differences can be reduced by welding data, that is, forcing data that is nearly equal to be equal. To weld the normals and the skinweights:

  • Run the DirectX Ops (dxops.exe) tool with the following command line on the mesh (replacing 'modelName.x' with the name of your model):
    Dxops.exe -s "load 'modelName.x'; Optimize n:2.01 w:2.01 uv0:0.01;  save 'newModelName.x';"

This compares the normals and skinweights, and where they differ in value by less than 2.01, the data is made equal. This figure shows a close up of the eye to see the creases before welding (on the left) and the creases after welding (on the right):

Figure 7: Removing creases by welding

In this example, welding removed 86 vertices from the input mesh. With fewer creases in the mesh, you can regenerate the atlas:

Figure 8: New atlas with creases removed

The atlas only has 7 charts and a maximum stretch of approximately 0.0776. The new atlas now fits into a smaller texture (approximately 30% smaller in this example).

Packing Charts Into an Atlas

Once a mesh has been partitioned into individually-parameterized charts, the charts need to be packed efficiently into a single texture map. This is performed as the second step of D3DXUVAtlasCreate or can be invoked explicitly by calling D3DXUVAtlasPack.

Packed charts are separated by a user-specified gutter width. The gutter width is the amount of separation between charts, and allows for bilinear interpolation and mip-mapping to avoid rendering artifacts at chart boundaries. D3DX provides an interface for automatically filling in these gutters - see ID3DXTextureGutterHelper for more information.

Integrating UVAtlas Into Your Pipeline

In addition to being artist-invoked prior to texture painting, these functions can be integrated into an automated art pipeline. For example, a UVAtlas call can be issued automatically after an asset is updated, prior to performing a PRT simulation or normal mapping pass. This avoids any need to manually manual repair of an object's UV mapping if the mesh's topology has been modified.

See the UV Atlas Command-Line Tool (uvatlas.exe) for example usage of the UVAtlas functions.


Programming Tips (Direct3D 9)

This section contains information to help you develop DirectX Graphics applications efficiently. The following topics are covered.

  • Asynchronous Notification
  • Driver Internal Errors
  • Enabling Direct3D Debug Information
  • Multihead
  • Multithreading Issues
  • Performance Optimizations
  • Presenting Multiple Views in Windowed Mode
  • Troubleshooting
  • Working with Device Windows
  • Working with Earlier Drivers
  • Working with Multiple System Monitors
  • Working with Mouse Cursors


Asynchronous Notification (Direct3D 9)

There are number of interesting queries on a driver that an application can make if there is no performance cost. In Direct3D 7 and Direct3D 8, a synchronous query mechanism, GetInfo, worked well for things like statistics, but no performance-critical queries were added. There are other things (like fences) that are inherently asynchronous. This is a simple API to make both synchronous and asynchronous queries. GetInfo will be retired in Direct3D 9.

Create a query using IDirect3DDevice9::CreateQuery. This method takes a D3DQUERYTYPE, which defines what kind of query to make and returns a pointer to an IDirect3DQuery9 object. If the query type is not supported, the call returns an error D3DERR_NOTAVAILABLE. Using the query object, the application submits the query to the runtime using IDirect3DQuery9::Issue, and polls the query status using IDirect3DQuery9::GetData. If the query result is available, S_OK is returned; otherwise, S_FALSE is returned. The application is expected to pass an appropriately sized buffer for the query results.

The application has an option to force the runtime to flush the query down to the driver by using D3DGETDATA_FLUSH with IDirect3DQuery9::GetData. It causes a flush, forcing the driver to see the query. In this case, D3DERR_DEVICELOST is returned if the device becomes lost.

All queries are lost when the device is lost, the application has to re-create them. If the device does not support the query and the pQueryID is NULL, the query creation will fail with D3DERR_INVALIDCALL.

The following table summaries important information about each query type.

QuertyType | Valid issue flag | GetData buffer | Runtime | Implicit beginning of query
D3DQUERYTYPE_VCACHE | D3DISSUE_END | D3DDEVINFO_VCACHE | Retail/Debug | CreateDevice
D3DQUERYTYPE_ResourceManager | D3DISSUE_END | D3DDEVINFO_ResourceManager | Debug only | Present
D3DQUERYTYPE_VERTEXSTATS | D3DISSUE_END | D3DDEVINFO_D3DVERTEXSTATS | Debug only | Present
D3DQUERYTYPE_EVENT | D3DISSUE_END | BOOL | Retail/Debug | CreateDevice
D3DQUERYTYPE_OCCLUSION | D3DISSUE_BEGIN,D3DISSUE_END | DWORD | Retail/Debug | N/A

Flags field for IDirect3DQuery9::Issue:

#define D3DISSUE_END (1 << 0)
// Tells the runtime to issue the end of a query, changing its state to
//   "non-signaled"

#define D3DISSUE_BEGIN (1 << 1) // Tells the runtime to issue the
// beginning of a query.

Flags field for IDirect3DQuery9::GetData:

#define D3DGETDATA_FLUSH (1 << 0) // Tells the runtime to flush
// if the query is outstanding.


Driver Internal Errors (Direct3D 9)

In Direct3D 9, Direct3D will allow the driver to return error codes such as E_OUTOFMEMORY, D3DERR_OUTOFVIDEOMEMORY, and D3DERR_UNSUPPORTEDCOLORARG so that an application would be able to respond to them. However, sometimes the API calls that generated these return types get loaded into a command buffer and are batched up to be sent to the GPU (see Controlling Runtime and Driver Optimizations). In this case, the errors cannot be relayed to the application when action needs to be taken, so the error code is consumed by the runtime and a note is made on the device object that this happened. Later when the application invokes IDirect3DDevice9::Present, IDirect3DDevice9::Present will return D3DERR_DRIVERINTERNALERROR. This is why the best approach for an application to take when receiving a D3DERR_DRIVERINTERNALERROR from IDirect3DDevice9::Present is to destroy and recreate the device.

If you want to try to debug further, here are a couple of suggestions for trying to figure out which API call is generating the error:

  • Because the list of possible return values is not complete, you can try to find which call is failing by surrounding each API call like this:

    TRACE ( "Calling DrawPrimitive" );
d3ddev->DrawPrim(...);
TRACE ( "done\n" );

    The output debug stream should then show the call that is causing the problem.

  • Additionally, for debugging purposes, try calling IDirect3DDevice9::ValidateDevice immediately before each IDirect3DDevice9::DrawPrimitive to see if there is an additional problem with the device driver (unsupported operation, unusable combination of texture formats, etc).

    Note IDirect3DDevice9::ValidateDevice should be used carefully and sparingly because of the amount of validation work the driver needs to perform to return an answer.


Enabling Direct3D Debug Information (Direct3D 9)

Are you trying to find out more information about Direct3D objects during debug? For instance, here's what you typically see when you look at a Direct3D interface in the watch window:

You can enable the core debug objects so that a mirrored object which contains all of the properties of the object can be viewed in the watch window. Simply include the following #define in your code before the D3d9.h file:

#define D3D_DEBUG_INFO

To enable debug information, the #define must get built before the D3d9.h file. If you are running a SDK sample, you can see this in Dxstdafx.h (which affects all the C++ samples). You must also be running the debug Direct3D runtime (which can be enabled from the Control Panel if necessary).

Here's an example using the BasicHLSL Sample.

  1. Add the #define to the Dxstdafx.h file before line 37.
  2. Build a debug project.
  3. Set a breakpoint at line 307 in BasicHLSL.cpp
  4. Run the debugger.

Here is an example of the kind of detailed information you can get about a Direct3D texture object from the watch window:

Note

The object property names are visible and the values are correct only when the debug runtime is enabled. When running against the retail runtime, the values are invalid.

Use the Call Stack for Extended Debug

With Direct3D debug enabled, you can also look at a call stack each time an object is created. This will make your application very slow, but can be used to check for resource leaks. To write out the call stack, set the following registry key to 1:

\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Direct3D\\
D3D9Debugging\\EnableCreationStack

Building your application with debug enabled will give you access to this additional variable:

  LPCWSTR CreationCallStack;

This variable will store the call stack each time that an object is created. This will make your application very slow, but can be used to debug resource leaks.


Multihead (Direct3D 9)

Multihead cards are those that have a common frame buffer and accelerator, independent digital-to-analog converters (DACs), and monitor outputs. Such devices can offer much more usable multiple monitor support than a similar number of heterogeneous display adapters.

Multihead cards are exposed in the API as a single API-level device that can drive several full-screen swap chains. Consequently, all resources are shared with all the heads, and each head has exactly the same capabilities. Each head can be set to independent display modes and can be refreshed (with IDirect3DSwapChain9::Present) at different times. Use IDirect3DDevice9::Present for simultaneous presents.

Each swap chain for a multihead device must be full screen. When a device has entered multihead mode, it must remain full screen. The transition back to windowed mode requires the destruction of the device (except for the normal ALT+TAB-to-minimize operation).

The old method of dividing video memory between the heads and treating each head as a fully independent accelerator will still be a common usage scenario. This proposal does not replace that mechanism unless the application has been specifically coded to function in the Direct3D 9 multihead mode.

Drivers are given adequate knowledge to switch between the two modes of operation.

One head will be called the master head, and all other heads on the same card be called subordinate heads. If more than one multihead adapter is present in a system, the master and its subordinates from one multihead adapter are called a group. Groups are denoted by the adapter ordinal of their master head.

The D3DCAPS9 structure has been updated to expose the following new hardware caps.

UINT NumberOfAdaptersInGroup;
UINT MasterAdapterOrdinal;
UINT AdapterOrdinalInGroup;
  • NumberOfAdaptersInGroup is 1 for conventional adapters, and greater than 1 for the master adapter of a multihead card. The value will be 0 for a subordinate adapter of a multihead card. Each card can have at most one master, but might have many subordinates.
  • MasterAdapterOrdinal indicates which device is the master for this subordinate.
  • AdapterOrdinalInGroup indicates the order in which heads are referenced by the API. The master adapter always has AdapterOrdinalInGroup 0. These values do not correspond to the adapter ordinals passed to the IDirect3D9 methods, but apply only to heads within a group.

This definition allows multihead cards to continue to present multiple adapters as if they were independent cards, just as they did in DirectX 8.

To create a multihead device, specify the behavior flag DAC in IDirect3D9::CreateDevice. The presentation parameters (an array of D3DPRESENT_PARAMETERS) should contain NumberOfAdaptersInGroup elements. The runtime will assign each element to each head in AdapterOrdinalInGroup numerical order. When DAC is set, each presentation parameter must have:

  • The Windowed member set to FALSE (in other words, be full screen).
  • The same value for the EnableAutoDepthStencil member of D3DPRESENT_PARAMETERS.

In addition, if EnableAutoDepthStencil is TRUE, then each of the following fields must have the same value for each D3DPRESENT_PARAMETERS:

  • AutoDepthStencilFormat
  • BackBufferWidth
  • BackBufferHeight
  • BackBufferFormat

If DAC is set, additional calls to IDirect3DDevice9::CreateAdditionalSwapChain are illegal.

If the device was created with the DAC, IDirect3DDevice9::Reset will expect an array of D3DPRESENT_PARAMETERS.

Each D3DPRESENT_PARAMETERS structure passed to IDirect3DDevice9::Reset must be full screen. To switch back to windowed mode, the application must destroy the device and re-create a non-multihead device in windowed mode.

Here is a basic usage scenario:

1. Create multihead device
2. For each swap chain of device:
   3. Call GetBackBuffer for the i-th swapchain
   4. Call SetRenderTarget
   5. Call DrawPrimitive
   6. Optionally call swapchain::Present (or wait until
all swap chains are drawn and present outside of loop)
7. End the for loop
8. Optionally present all swap chains with device::Present

For more information, see IDirect3D9::CreateDevice and IDirect3DDevice9::GetNumberOfSwapChains.


Multithreading Issues (Direct3D 9)

Full-screen Direct3D applications provide a window handle to the Direct3D run time. The window is hooked by the run time. This means that all messages passed to the application's window message procedure have first been examined by the Direct3D run time's own message-handling procedure.

Display mode changes are affected by support routines built into the underlying operating system. When mode changes occur, the system broadcasts several messages to all applications. In Direct3D applications, the messages are received on the window procedure thread, which is not necessarily the same thread that called IDirect3DDevice9::Reset or IDirect3D9::CreateDevice (or the final Release of IDirect3DDevice9, which can cause a display mode change). The Direct3D run time maintains several critical sections internally. Because at least one of these critical sections is held across the mode switch caused by IDirect3DDevice9::Reset or IDirect3D9::CreateDevice, these critical sections are still held when the application receives the mode-change related window messages.

This design has some implications for multithreaded applications. In particular, an application must be sure to strongly segregate its window message handling threads from its Direct3D threads. An application that causes a mode change on one thread but makes Direct3D calls on a different thread in its window procedure is in danger of deadlock.

For these reasons, Direct3D is designed so that the methods IDirect3DDevice9::Reset, IDirect3D9::CreateDevice, IDirect3DDevice9::TestCooperativeLevel, or the final Release of IDirect3DDevice9 can only be called from the same thread that handles window messages.


Performance Optimizations (Direct3D 9)

Every developer who creates real-time applications that use 3D graphics is concerned about performance optimization. This section provides guidelines for getting the best performance from your code.

  • General Performance Tips
  • Databases and Culling
  • Batching Primitives
  • Lighting Tips
  • Texture Size
  • Matrix Transforms
  • Using Dynamic Textures
  • Using Dynamic Vertex and Index Buffers
  • Using Meshes
  • Z-Buffer Performance

General Performance Tips

  • Clear only when you must.
  • Minimize state changes and group the remaining state changes.
  • Use smaller textures, if you can do so.
  • Draw objects in your scene from front to back.
  • Use triangle strips instead of lists and fans. For optimal vertex cache performance, arrange strips to reuse triangle vertices sooner, rather than later.
  • Gracefully degrade special effects that require a disproportionate share of system resources.
  • Constantly test your application's performance.
  • Minimize vertex buffer switches.
  • Use static vertex buffers where possible.
  • Use one large static vertex buffer per FVF for static objects, rather than one per object.
  • If your application needs random access into the vertex buffer in AGP memory, choose a vertex format size that is a multiple of 32 bytes. Otherwise, select the smallest appropriate format.
  • Draw using indexed primitives. This can allow for more efficient vertex caching within hardware.
  • If the depth buffer format contains a stencil channel, always clear the depth and stencil channels at the same time.
  • Combine the shader instruction and the data output where possible. For example:
    // Rather than doing a multiply and add, and then output the data with
//   two instructions:
mad r2, r1, v0, c0
mov oD0, r2

// Combine both in a single instruction, because this eliminates an
//   additional register copy.
mad oD0, r1, v0, c0

Databases and Culling

Building a reliable database of the objects in your world is key to excellent performance in Direct3D. It is more important than improvements to rasterization or hardware.

You should maintain the lowest polygon count you can possibly manage. Design for a low polygon count by building low-polygon models from the start. Add polygons if you can do so without sacrificing performance later in the development process. Remember, the fastest polygons are the ones you don't draw.

Batching Primitives

To get the best rendering performance during execution, try to work with primitives in batches and keep the number of render-state changes as low as possible. For example, if you have an object with two textures, group the triangles that use the first texture and follow them with the necessary render state to change the texture. Then group all the triangles that use the second texture. The simplest hardware support for Direct3D is called with batches of render states and batches of primitives through the hardware abstraction layer (HAL). The more effectively the instructions are batched, the fewer HAL calls are performed during execution.

Lighting Tips

Because lights add a per-vertex cost to each rendered frame, you can improve performance significantly by being careful about how you use them in your application. Most of the following tips derive from the maxim, "the fastest code is code that is never called."

  • Use as few light sources as possible. To increase the overall lighting level, for example, use the ambient light instead of adding a new light source.
  • Directional lights are more efficient than point lights or spotlights. For directional lights, the direction to the light is fixed and doesn't need to be calculated on a per-vertex basis.
  • Spotlights can be more efficient than point lights, because the area outside the cone of light is calculated quickly. Whether spotlights are more efficient or not depends on how much of your scene is lit by the spotlight.
  • Use the range parameter to limit your lights to only the parts of the scene you need to illuminate. All the light types exit fairly early when they are out of range.
  • Specular highlights almost double the cost of a light. Use them only when you must. Set the D3DRS_SPECULARENABLE render state to 0, the default value, whenever possible. When defining materials, you must set the specular power value to zero to turn off specular highlights for that material; just setting the specular color to 0,0,0 is not enough.

Texture Size

Texture-mapping performance is heavily dependent on the speed of memory. There are a number of ways to maximize the cache performance of your application's textures.

  • Keep the textures small. The smaller the textures are, the better chance they have of being maintained in the main CPU's secondary cache.
  • Do not change the textures on a per-primitive basis. Try to keep polygons grouped in order of the textures they use.
  • Use square textures whenever possible. Textures whose dimensions are 256x256 are the fastest. If your application uses four 128x128 textures, for example, try to ensure that they use the same palette and place them all into one 256x256 texture. This technique also reduces the amount of texture swapping. Of course, you should not use 256x256 textures unless your application requires that much texturing because, as mentioned, textures should be kept as small as possible.

Matrix Transforms

Direct3D uses the world and view matrices that you set to configure several internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently - for example, thousands of times per frame - is computationally time-consuming. You can minimize the number of required calculations by concatenating your world and view matrices into a world-view matrix that you set as the world matrix, and then setting the view matrix to the identity. Keep cached copies of individual world and view matrices so that you can modify, concatenate, and reset the world matrix as needed. For clarity in this documentation, Direct3D samples rarely employ this optimization.

Using Dynamic Textures

To find out if the driver supports dynamic textures, check the D3DCAPS2_DYNAMICTEXTURES flag of the D3DCAPS9 structure.

Keep the following things in mind when working with dynamic textures.

  • They cannot be managed. For example, their pool cannot be D3DPOOL_MANAGED.
  • Dynamic textures can be locked, even if they are created in D3DPOOL_DEFAULT.
  • D3DLOCK_DISCARD is a valid lock flag for dynamic textures.

It is a good idea to create only one dynamic texture per format and possibly per size. Dynamic mipmaps, cubes, and volumes are not recommended because of the additional overhead in locking every level. For mipmaps, D3DLOCK_DISCARD is allowed only on the top level. All levels are discarded by locking just the top level. This behavior is the same for volumes and cubes. For cubes, the top level and face 0 are locked.

The following pseudocode shows an example of using a dynamic texture.

DrawProceduralTexture(pTex)
{
    // pTex should not be very small because overhead of
    //   calling driver every D3DLOCK_DISCARD will not
    //   justify the performance gain. Experimentation is encouraged.
    pTex->Lock(D3DLOCK_DISCARD);
    <Overwrite *entire* texture>
    pTex->Unlock();
    pDev->SetTexture();
    pDev->DrawPrimitive();
}

Using Dynamic Vertex and Index Buffers

Locking a static vertex buffer while the graphics processor is using the buffer can have a significant performance penalty. The lock call must wait until the graphics processor is finished reading vertex or index data from the buffer before it can return to the calling application, a significant delay. Locking and then rendering from a static buffer several times per frame also prevents the graphics processor from buffering rendering commands, since it must finish commands before returning the lock pointer. Without buffered commands, the graphics processor remains idle until after the application is finished filling the vertex buffer or index buffer and issues a rendering command.

Ideally the vertex or index data would never change, however this is not always possible. There are many situations where the application needs to change vertex or index data every frame, perhaps even multiple times per frame. For these situations, the vertex or index buffer should be created with D3DUSAGE_DYNAMIC. This usage flag causes Direct3D to optimize for frequent lock operations. D3DUSAGE_DYNAMIC is only useful when the buffer is locked frequently; data that remains constant should be placed in a static vertex or index buffer.

To receive a performance improvement when using dynamic vertex buffers, the application must call IDirect3DVertexBuffer9::Lock or IDirect3DIndexBuffer9::Lock with the appropriate flags. D3DLOCK_DISCARD indicates that the application does not need to keep the old vertex or index data in the buffer. If the graphics processor is still using the buffer when lock is called with D3DLOCK_DISCARD, a pointer to a new region of memory is returned instead of the old buffer data. This allows the graphics processor to continue using the old data while the application places data in the new buffer. No additional memory management is required in the application; the old buffer is reused or destroyed automatically when the graphics processor is finished with it. Note that locking a buffer with D3DLOCK_DISCARD always discards the entire buffer, specifying a nonzero offset or limited size field does not preserve information in unlocked areas of the buffer.

There are cases where the amount of data the application needs to store per lock is small, such as adding four vertices to render a sprite. D3DLOCK_NOOVERWRITE indicates that the application will not overwrite data already in use in the dynamic buffer. The lock call will return a pointer to the old data, allowing the application to add new data in unused regions of the vertex or index buffer. The application should not modify vertices or indices used in a draw operation as they might still be in use by the graphics processor. The application should then use D3DLOCK_DISCARD after the dynamic buffer is full to receive a new region of memory, discarding the old vertex or index data after the graphics processor is finished.

The asynchronous query mechanism is useful to determine if vertices are still in use by the graphics processor. Issue a query of type D3DQUERYTYPE_EVENT after the last DrawPrimitive call that uses the vertices. The vertices are no longer in use when IDirect3DQuery9::GetData returns S_OK. Locking a buffer with D3DLOCK_DISCARD or no flags will always guarantee the vertices are synchronized properly with the graphics processor, however using lock without flags will incur the performance penalty described earlier. Other API calls such as IDirect3DDevice9::BeginScene, IDirect3DDevice9::EndScene, and IDirect3DDevice9::Present do not guarantee the graphics processor is finished using vertices.

Below are ways to use dynamic buffers and the proper lock flags.

    // USAGE STYLE 1
    // Discard the entire vertex buffer and refill with thousands of vertices.
    // Might contain multiple objects and/or require multiple DrawPrimitive
    //   calls separated by state changes, etc.

    // Determine the size of data to be moved into the vertex buffer.
    UINT nSizeOfData = nNumberOfVertices * m_nVertexStride;

    // Discard and refill the used portion of the vertex buffer.
    CONST DWORD dwLockFlags = D3DLOCK_DISCARD;

    // Lock the vertex buffer.
    BYTE* pBytes;
    if( FAILED( m_pVertexBuffer->Lock( 0, 0, &pBytes, dwLockFlags ) ) )
        return false;

    // Copy the vertices into the vertex buffer.
    memcpy( pBytes, pVertices, nSizeOfData );
    m_pVertexBuffer->Unlock();

    // Render the primitives.
    m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, nNumberOfVertices/3)

    // USAGE STYLE 2
    // Reusing one vertex buffer for multiple objects

    // Determine the size of data to be moved into the vertex buffer.
    UINT nSizeOfData = nNumberOfVertices * m_nVertexStride;

    // No overwrite will be used if the vertices can fit into
    //   the space remaining in the vertex buffer.
    DWORD dwLockFlags = D3DLOCK_NOOVERWRITE;

    // Check to see if the entire vertex buffer has been used up yet.
    if( m_nNextVertexData > m_nSizeOfVB - nSizeOfData )
    {
        // No space remains. Start over from the beginning
        //   of the vertex buffer.
        dwLockFlags = D3DLOCK_DISCARD;
        m_nNextVertexData = 0;
    }

    // Lock the vertex buffer.
    BYTE* pBytes;
    if( FAILED( m_pVertexBuffer->Lock( (UINT)m_nNextVertexData, nSizeOfData,
               &pBytes, dwLockFlags ) ) )
        return false;

    // Copy the vertices into the vertex buffer.
    memcpy( pBytes, pVertices, nSizeOfData );
    m_pVertexBuffer->Unlock();

    // Render the primitives.
    m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST,
               m_nNextVertexData/m_nVertexStride, nNumberOfVertices/3)

    // Advance to the next position in the vertex buffer.
    m_nNextVertexData += nSizeOfData;

Using Meshes

You can optimize meshes by using Direct3D indexed triangles instead of indexed triangle strips. The hardware will discover that 95 percent of successive triangles actually form strips and adjust accordingly. Many drivers do this for older hardware also.

D3DX mesh objects can have each triangle, or face, tagged with a DWORD, called the attribute of that face. The semantics of the DWORD are user-defined. They are used by D3DX to classify the mesh into subsets. The application sets per-face attributes using the ID3DXMesh::LockAttributeBuffer call. The ID3DXMesh::Optimize method has an option to group the mesh vertices and faces on attributes using the D3DXMESHOPT_ATTRSORT option. When this is done, the mesh object calculates an attribute table that can be obtained by the application by calling ID3DXBaseMesh::GetAttributeTable. This call returns 0 if the mesh is not sorted by attributes. There is no way for an application to set an attribute table because it is generated by the ID3DXMesh::Optimize method. The attribute sort is data sensitive, so if the application knows that a mesh is attribute sorted, it still needs to call ID3DXMesh::Optimize to generate the attribute table.

The following topics describe the different attributes of a mesh.

Attribute ID

An attribute id is a value that associates a group of faces with an attribute group. This id describes which subset of faces ID3DXBaseMesh::DrawSubset should draw. Attribute ids are specified for the faces in the attribute buffer. The actual values of the attribute ids can be anything that fits in 32 bits, but it is common to use 0 to n where n is the number of attributes.

Attribute Buffer

The attribute buffer is an array of DWORDs (one per face) that specifies which attribute group each face belongs in. This buffer is initialized to zero on creation of a mesh, but is either filled by the load routines or must be filled by the user if more than one attribute with id 0 is desired. This buffer contains the information that is used to sort the mesh based on attributes in ID3DXMesh::Optimize. If no attribute table is present, ID3DXBaseMesh::DrawSubset scans this buffer to select the faces of the given attribute to draw.

Attribute Table

The attribute table is a structure owned and maintained by the mesh. The only way for one to be generated is by calling ID3DXMesh::Optimize with attribute sorting or stronger optimization enabled. The attribute table is used to quickly initiate a single draw primitive call to ID3DXBaseMesh::DrawSubset. The only other use is that progressing meshes also maintain this structure, so it is possible to see what faces and vertices are active at the current level of detail.

Z-Buffer Performance

Applications can increase performance when using z-buffering and texturing by ensuring that scenes are rendered from front to back. Textured z-buffered primitives are pretested against the z-buffer on a scan line basis. If a scan line is hidden by a previously rendered polygon, the system rejects it quickly and efficiently. Z-buffering can improve performance, but the technique is most useful when a scene draws the same pixels more than once. This is difficult to calculate exactly, but you can often make a close approximation. If the same pixels are drawn less than twice, you can achieve the best performance by turning z-buffering off and rendering the scene from back to front.


Presenting Multiple Views in Windowed Mode (Direct3D 9)

In addition to the swap chain that is owned and manipulated through the IDirect3DDevice9 interface, an application can create additional swap chains in order to present multiple views from the same device. The application typically creates one swap chain per view by using the IDirect3DDevice9::CreateAdditionalSwapChain method, and associates each swap chain with a particular window. The application renders images into the back buffers of each swap chain, and then presents them individually.

Only one swap chain at a time can be full-screen on each adapter.


Troubleshooting (Direct3D 9)

This topic lists common categories of problems that you might encounter when writing Direct3D applications, and how to prevent them.

Device Creation

If your application fails during device creation, check for the following common errors.

  • Make sure you check the device capabilities, particularly the render depths.
  • Examine the error code. D3DERR_OUTOFVIDEOMEMORY is always possible.
  • Use the debug DirectX dynamic-link libraries (DLLs) and review output messages under the debugger.

Using Lit Vertices

Applications that use lit vertices should disable the Direct3D lighting engine by setting the D3DRS_LIGHTING render state to FALSE. By default, when lighting is enabled, the system sets the color for any vertex that doesn't contain a normal vector to 0 (black), even if the input vertex contained a nonzero color value. Because lit-vertices don't, by their nature, contain a vertex normal, any color information passed to Direct3D is lost during rendering if the lighting engine is enabled.

Obviously, vertex color is important to any application that performs its own lighting. To prevent the system from imposing the default values, make sure you set D3DRS_LIGHTING to FALSE.

If your application runs but nothing is visible, check for the following common errors.

  • Ensure that your triangles are not degenerate.
  • Ensure that your triangles are not being culled.
  • Make sure that your transformations are internally consistent.
  • Check the viewport settings to be sure they allow your triangles to be seen.

Debugging

Debugging a Direct3D application can be challenging. Try the following techniques, in addition to checking all the return values - a particularly important piece of advice in Direct3D programming, which is dependent on very different hardware implementations.

  • Switch to debug DLLs.
  • Force a software-only device, turning off hardware acceleration even when it is available.
  • Force surfaces into system memory.
  • Create an option to run in a window, so that you can use an integrated debugger.

The second and third options in this list can help you avoid the Win16 lock which can otherwise cause your debugger to hang.

Also, try adding the following entries to Win.ini.

[Direct3D]
debug=3
[DirectDraw]
debug=3

Borland Floating-Point Initialization

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

// Borland floating point initialization
#include <math.h>
#include <float.h>

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

int _matherr(struct _exception  *e)
{
    e;               // Dummy reference to catch the warning
    return 1;        // Error has been handled
}

Parameter Validation

For performance reasons, the debug version of the Direct3D Immediate Mode run time performs more parameter validation than the retail version, which sometimes performs no validation at all. This enables applications to perform robust debugging with the slower debug run-time component before using the faster retail version for performance tuning and final release.

Although several Direct3D Immediate Mode methods impose limits on the values that they can accept, these limits are often only checked and enforced by the debug version of the Direct3D Immediate Mode run time. Applications must conform to these limits, or unpredictable and undesirable results can occur when running on the retail version of Direct3D. For example, the IDirect3DDevice9::DrawPrimitive method accepts a parameter (PrimitiveCount) that indicates the number of primitives that the method will render. The method can only accept values between 0 and D3DMAXNUMPRIMITIVES. In the debug version of Direct3D, if you pass more than D3DMAXNUMPRIMITIVES primitives, the method fails gracefully, printing an error message to the error log, and returning an error value to your application. Conversely, if your application makes the same error when it is running with the retail version of the run time, behavior is undefined. For performance reasons, the method does not validate the parameters, resulting in unpredictable and completely situational behavior when they are not valid. In some cases the call might work, and in other cases it might cause a memory fault in Direct3D. If an invalid call consistently works with a particular hardware configuration and DirectX version, there is no guarantee that it will continue to function on other hardware or with later releases of DirectX.

If your application encounters unexplained failures when running with the retail Direct3D run-time file, test against the debug version and look closely for cases where your application passes invalid parameters. Use the DirectX control panel applet, switch to the debug runtime if necessary, and check the "Break on D3DError" option. This option will force the runtime to use the Windows DebugBreak method in order to force the application to stop when an application bug is detected.


Working with Device Windows (Direct3D 9)

This section lists an issue that you might encounter when working with device windows in Direct3D applications.

  • Direct3D only hooks up the focus windows instead of the device window with the Direct3D message processing function, and only processes the focus window messages. So, the focus window should be the parent of any device window.


Working with Earlier Drivers (Direct3D 9)

This section lists issues that can be encountered when working with Direct3D 9 on drivers written for versions of Direct3D earlier than Direct3D 9.

  • When working with a T&L HAL device, the fog intensity is computed but the absolute value operation is not applied to this value. Rather, the value is left negative if that is what is computed. The best way to avoid this situation is to set up transforms appropriately. A less-preferred method is to make the fog-start and fog-end values negative to match.

To check for a Direct3D 9 driver, look for a nonzero value for D3DDEVCAPS2_STREAMOFFSET in the DevCaps2 member of D3DCAPS9.


Working with Multiple Monitor Systems (Direct3D 9)

The concept of exclusive full-screen mode is retained in Direct3D 9, but it is kept entirely implicit in the IDirect3D9::CreateDevice and IDirect3DDevice9::Reset method calls. Whenever a device is successfully reset or created in full-screen operation, the Direct3D object that created the device is marked as owning all adapters on that system. This state is known as exclusive mode, and at this point the Direct3D object owns exclusive mode. Exclusive mode means that devices created by any other Direct3D9 object can neither assume full-screen operation nor allocate video memory. In addition, when a Direct3D9 object assumes exclusive mode, all devices other than the device that went full-screen are placed into the lost state. For information about how to handle lost devices, see Lost Devices (Direct3D 9).

Along with exclusive mode, the Direct3D9 object is informed of the focus window to be used by the device. Exclusive mode is released when the last full-screen device owned by that Direct3D9 object is either reset to windowed mode or destroyed.

Devices can be divided into two categories when a Direct3D9 object owns exclusive mode. The first category of devices are those that were created by the same Direct3D9 object that created the device that is already full-screen, have the same focus window as the device that is already full-screen, and represent a different adapter from any full-screen device. Devices in this category have no restrictions concerning their ability to be reset or created and are not placed into the lost state. Devices in this category can even be placed into full-screen mode.

Devices not in this category, which would be those created by a different Direct3D9 object, or with a different focus window, or for some adapter with a device already full-screen cannot be reset and remain in the lost state until exclusive mode is lost.

The practical implication is that a multiple monitor application can place several devices in full-screen mode, but only if all these devices are for different adapters, were created by the same Direct3D9 object, and all share the same focus window.

When you create a new device using the same IDirect3D9 object and focus window, your original device will lose its surfaces. You will need to call IDirect3DDevice9::Reset on the first device in order for your application to use it. For example, to create two devices, do the following:

  1. Create Device 1
  2. Create Device 2
  3. Reset Device 1


Working with Mouse Cursors (Direct3D 9)

The mouse cursor methods enable the application to specify a color cursor by providing a surface that contains an image. The system will ensure that this cursor will be updated at half the display rate or more if the application's frame rate is slow. However, the cursor will never be updated more frequently than the display refresh rate.

The mouse cursor position is tied to the system cursor, appropriately scaled for the current display mode spatial resolution, but it can be moved explicitly by the application. This is analogous to the behavior of the Win32 API - supported system mouse cursor. For more information about how to use a mouse cursor in your Direct3D application, see the following reference topics.

  • IDirect3DDevice9::ShowCursor
  • IDirect3DDevice9::SetCursorPosition
  • IDirect3DDevice9::SetCursorProperties

Direct3D ensures that the mouse is supported either by hardware implementations or by the Direct3D run time that performs hardware-accelerated blitting operations when calling IDirect3DDevice9::Present.


Direct3D 9 Tools

Use the following Direct3D 9 tools to compile and/or assemble shader and effects or to link precompiled shader fragments.

  • flink
  • psa
  • vsa

Use the following tool to debug shaders.

  • Shader Debugger to help to debug shaders and effects.

Use the following tool to compile shaders and effects in either Direct3D 9 or Direct3D 10.

  • Effect-Compiler Tool

See Also

Direct3D 9 Graphics


flink

HLSL shader fragments can be linked from the command line using the fragment-linker tool (flink.exe) that is found in (SDK root)\Utilities\.

Syntax

flink [SwitchOptions] Filename

Where:

  • The switch options are:
    /Cc | Output color coded assembly listings
    /D<id>=<text> | Define macro
    /E<name> | Entrypoint name
    /Fc file | Generate assembly code listing file
    /Fh file | Generate header containing object code
    /Fo file | Generate object file
    /Fx file | Generate assembly code and hex listing file
    /Gfa | Avoid flow control constructs
    /Gfp | Prefer flow control constructs
    /Gpp | Force partial precision
    /I<include> | additional include path
    /nologo | Suppress copyright message
    /Od | Disable optimizations
    /Op | Disable preshaders
    /T<profile> Identify the target profile, which is one of the following:
    • Vertex shader profiles are contained in D3DXGetVertexShaderProfile
    • Pixel shader profiles are contained in D3DXGetPixelShaderProfile. ps_1_x is not supported.
    /Vd | Disable validation
    /Vi | display details about the include process
    /Vn<name> | use <name> as variable name in header file
    /Zi | Enable debugging information
    /Zpc | Pack matrices in column-major order
    /Zpr | Pack matrices in row-major order

    You must supply at least one switch option.

  • Filename is the effect filename.

Using Flink

Use flink.exe with to link compiled code fragments; the fragments will be linked in the order specified in the command line. For instance, this example links two fragments (illustrated from the FragmentLinker Sample.

flink /E ProjectionFragment_Animated \\
/E AmbientDiffuseFragment /T vs_1_1 /Fo FragmentLinker.fxo \\
FragmentLinker.fx

See Also

Direct3D 9 Tools


psa

Pixel shaders can be assembled into binary code using the pixel shader (psa.exe) command-line assembler that is found in:

(SDK root)\Utilities\

Syntax

psa [Switch Options] Filename

Where:

  • The available Switch Options are:

    • These switches can be used with any of the compiler tools

    Switch Name | Description
/Cc | Display color-coded assembly listings
/D id=text | Define a macro.
/Fc file | Generate assembly code listing file.
/Fh file | Generate header containing object code.
/Fo file | Generate object file.
/Fx file | Generate assembly code and hexadecimal listing file.
/Gfa | Avoid flow control constructs.
/Gfp | Prefer flow control constructs.
/I path | Additional include path.
/Vd | Disable validation.
/Vi | Display additional details about the include process.
/Vn name | Use name as variable name in header file.
/Zi | Enables HLSL debugging information.
/nologo | Suppress copyright message.
  • Filename is the effect filename.

See Also

Direct3D 9 Tools


vsa

Vertex shaders can be assembled into binary code using the vertex shader (vsa.exe) command-line assembler that is found in:

(SDK root)\Utilities\

Syntax

vsa [SwitchOptions] Filename

Where:

  • The SwitchOptions are:
    Switch Name | Description
    /Cc | Display color-coded assembly listings
    /D id=text | Define a macro.
    /Fc file | Generate assembly code listing file.
    /Fh file | Generate header containing object code.
    /Fo file | Generate object file.
    /Fx file | Generate assembly code and hexadecimal listing file.
    /Gfa | Avoid flow control constructs.
    /Gfp | Prefer flow control constructs.
    /I path | Additional include path.
    /Vd | Disable validation.
    /Vi | Display additional details about the include process.
    /Vn name | Use name as variable name in header file.
    /Zi | Enables HLSL debugging information.
    /nologo | Suppress copyright message.
  • Filename is the effect filename.

Example

Use vsa.exe to assemble precompiled vertex shaders. This code can be written by a developer or it could be the output of a shader compiled by fxc with the /Fc switch. For instance, compiling the HLSLwithoutEffects.vsh file to an assembly vertex shader results in an assembly file that can be compiled by vsa.

fxc /T vs_2_0 /E Ripple /Fc HLSLwithoutEffects.vs HLSLwithoutEffects.vsh

vsa /Fo HLSLwithoutEffects.vso HLSLwithoutEffects.vs

Pixel shaders can be compiled using psa in a similar way.

See Also

Direct3D 9 Tools


Shader Debugger

Microsoft Visual Studio .NET supports debugging assembly-level and high-level language vertex and pixel shaders and effects using the DirectX Extensions for Visual Studio .NET (the shader debugger). Many of the debugger features are listed below. To prepare your machine for shader debugging, see Getting Started Debugging Shaders (Direct3D 9). If you already have the right tools installed, you can also try the Goal 5 - Shader Debugging Tutorial.

The debugger works with the debug version of the runtime, as well as with certain device types. Any vertex or pixel shader can be debugged when using a reference device. Vertex shaders can be debugged, providing they are running on a hardware abstraction layer (HAL) device created for software vertex processing. No debugging support is provided for hardware vertex processing or "pure" HAL devices. For more information about device types, see D3DDEVTYPE.

  • Building with Debug Information
  • Starting the Debugger
  • Breakpoints
  • Viewing Device State
  • Debugging C++ Code and Direct3D Code Simultaneously
  • See Also

Building with Debug Information

To do source-level debugging of a shader, the shader must be built with debug information and it must have an on-disk source file associated with it. You can create such a shader in the following two ways.

  • Compile the shader at build time using Vsa.exe (the vertex shader assembler), Psa.exe (the pixel shader assembler), or Fxc.exe (the high-level language compiler), and specify the /Zi command-line flag.
  • Compile the shader at run time using D3DXAssembleShaderFromFile or D3DXCompileShaderFromFile and specify the D3DXSHADER_DEBUG flag. For more information about the compiler flags, see D3DXSHADER Flags.

For debugging purposes, disable optimizations by supplying the /Od command line flag or the D3DXSHADER_SKIPOPTIMIZATION flag.

If you choose to compile a shader from memory using methods like D3DXAssembleShader or D3DXCompileShader or D3DXCreateEffect, add the #line directive to your shader code to get the debugger to work properly. Here's an example:

#line 2 "currentfile.fx"

It is not necessary to build an application with Visual Studio .NET in order to use the shader debugger. Build your application with any compiler, and then use Visual Studio .NET to debug it by starting your application and using the "Attach To Process" dialog box (which is explained in the next section).

Starting the Debugger

To debug an application, the application must be using the debug version of the Microsoft Direct3D runtime and must have shader debugging enabled. You can configure these options through the Direct3D tab in the Microsoft DirectX control panel applet. The DirectX debug service must also be running on the target computer. This service is installed automatically when you install the Microsoft DirectX extensions for Visual Studio .NET.

  • When using a HAL device, only vertex shaders created for software vertex processing can be debugged. Pixel shaders cannot be debugged at all. No debugging whatsoever is supported for "pure" HAL devices.
  • When using a reference device, any vertex or pixel shader may be debugged. Debugging of "pure" reference devices works the same as it does for "non-pure" reference devices.

There are two techniques for starting the debugger. Both techniques will work on a C++ application; however, a managed code application can only be debugged using the second technique.

Technique 1: Click Debug, Direct3D, Start With Direct3D Debugging (CTRL+ALT+F5) to start the debugger.

Technique 2: You can "attach" to an already running Direct3D process. The easiest way to do this from Visual Studio .NET is as follows:

  1. On the Debug menu, start your application with the Start Without Debugging command.
  2. On the Debug menu, click Processes to open the Processes window.
  3. Select your application from the process list and click the Attach button.

  4. In the Attach to Process dialog box, select Native to debug your C++ code, and select Direct3D to debug your Direct3D code. You can debug both C++ and Direct3D code simultaneously (see Debugging C++ Code and Direct3D Code Simultaneously near the bottom of this topic).

    Visual Studio .NET also supports remote debugging of Direct3D applications. To attach to a Direct3D process on a remote computer, in the Processes dialog box, enter the name of the remote computer in the Name box and then attach to the process the same as for a local process.

Breakpoints

To set a breakpoint in a vertex or pixel shader source file, the shader must have debug information present (see Building with Debug Information). The module window (click on Debug, then Windows and finally Modules) can be used to view all shaders that are currently loaded. When debugging native code, right-click the window and choose Show Modules for All Programs to view the shaders that are loaded.

Line Breakpoints

You can set a breakpoint at a particular line in a shader the same way you would set a breakpoint in C++ source code, that is:

  1. Open the source file in the Visual Studio .NET text editor; move the cursor to the line on which to set the breakpoint; and choose the Toggle Breakpoint command (F9 by default).
  2. Right-click the line in the source code where you want to set the breakpoint and then choose Insert Breakpoint from the shortcut menu.
  3. Select the New Breakpoint command (CTRL+B by default). Using the File tab in the New Breakpoint dialog box, enter the file name and, optionally, the line number of the breakpoint.

Left clicking the margin next to a line in the source code toggles a breakpoint.

Function Breakpoints

Using the Function tab in the Breakpoint Properties dialog box, type the case-sensitive name of the shader function as the name, and set the language to Direct3D Shader. The function name is the name of the shader function stored in the debug information, or the name of the file containing the shader. The module window (open it by clicking on Windows and then select the Windows... menu item) lists all currently loaded shaders and their names. IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene breakpoints work as before.

Conditional Breakpoints

Any of the following types of breakpoints can have a condition, as long as the breakpoint is set to occur when the condition is true (as opposed to when the condition changes):

  • Function
  • File/Line
  • Address

The expression must evaluate to a single-element Boolean result.

Pixel Area Breakpoints

A pixel area breakpoint triggers at the first instruction of any pixel shader that is about to modify a pixel within a given rectangle. Set a pixel area breakpoint by going to the Data tab in the Breakpoint dialog and:

  • Select Direct3D Shader as the language.
  • Enter a breakpoint in the Variable text box in one of these formats:
    • (x,y) : Break when the pixel at (x, y) is being computed.
    • (left,top)-(right,bottom) : Break when any of the pixels in a rectangle is being computed. Standard RECT semantics apply: left and top edges are in the rectangle; right and bottom edges are not.

Alternatively, a pixel area breakpoint can also be created by dragging out a rectangle with the mouse on a render target tool window.

Assembly Code (Address) Breakpoints

Setting a breakpoint on a specific instruction of a shader does not require debug information. You can set an address breakpoint in the following ways.

  • Move the cursor in the Disassembly window to the line containing the instruction on which you want to set the breakpoint, and choose the Toggle Breakpoint command (F9 by default).
  • Right-click the line in the Disassembly window containing the instruction on which to set the breakpoint and choose Insert Breakpoint from the shortcut menu.
  • Select the New Breakpoint command (CTRL+B by default), select the Address tab, select Direct3D Shader from the Language combo box, and enter the address of the instruction that needs the breakpoint.

    The format of an address is xxx:yyy where:

    • xxx is the shader module number
    • yyy is the instruction address

    To find the values for xxx:yyy, open the Disassembly window, find the instruction on which you want to set a breakpoint, and copy the module number:address number from the previous line. The xxx number starts with a "v" for Vertex Shader or "p" for Pixel Shader. Here's an example of the number: P00000009:00000780 (which could be entered as P9:780). This would set a breakpoint in a pixel shader, that is in module 9, at address 780.

BeginScene or EndScene Breakpoints

To set a breakpoint when the application you are debugging reaches IDirect3DDevice9::BeginScene or IDirect3DDevice9::EndScene, select the New Breakpoint command (CTRL+B by default), select the Function tab, select Direct3D Shader from the Language combo box, and type either BeginScene or EndScene as the name of the function.

Stepping

You can step through shader code using the Debug menu's Step Over command (F10 by default). Stepping in Direct3D code will cause the application you are debugging to stop at the next vertex or pixel shader instruction it runs.

Expression Evaluation

When the application you are debugging is stopped in a vertex or pixel shader, or at a BeginScene or EndScene breakpoint, you can use the Watch window to inspect the state of the application you are debugging. You can also quickly view the contents of a register by briefly resting the mouse pointer on the register in the Disassembly window or in your shader source code.

The expression syntax supports register names, swizzles, and the following operators, which all operate per component.

+ - * / == < != <= > >= [] ! || &, &

In addition, the following two intrinsic functions are supported.

  • any( e ) - Returns TRUE if any of the Boolean elements of e are true.
  • all( e ) - Returns TRUE if all of the Boolean elements of e are true.

All types must match exactly. Floating-point literals must have a decimal point; otherwise, they are treated as integers.

Examples

This expression returns TRUE if all of the first three components of r0 are less than the corresponding components of c4.

all( r0.xyz<c4.xyz )

Constant registers are indexed by one plus the x-component of a0.

c[a0.x+1]

Viewing Register Contents

To view the contents of a register in the watch window, use the following expression syntax:

registerName[.swizzle][,format][,w]

Where:

  • registerName is the name of the register to inspect (for example, r0, oPos, t7).
  • swizzle is the optional swizzle specifier, the same as used on a source register in the shader assembly language (for example, v0.xxyy, r2.rgb).
  • format is the optional floating-point format specifier, the same as for C++ debugging. Valid format specifiers are:
    • e - Exponential notation (for example, 1.23e+1)
    • f - Standard notation (for example, 12.3)
    • g - Either 'e' or 'f', whichever is more compact
  • w is an optional specifier that says to divide the first three components by the fourth component before displaying.

Viewing Device State

To view the current values of render states and texture stage states on the device, enter $DeviceState in the Watch window.

Viewing the Current Pixel Position

The coordinates of the pixel currently being rendered by a pixel shader are contained in register vPos (see Position Register). Enter vPos in the watch window to see its value.

Viewing Surface Contents

Viewing the render target - To view the contents of the current render-target surface, open the Render Target window by selecting the Debug menu's Direct3D, Render Target menu options. This window will be updated with the current contents of the render target whenever the application you are debugging enters break mode.

Viewing textures - To view the contents of the texture currently selected into a texture stage, open a Texture window by selecting the appropriate texture stage from the Debug menu's Direct3D, Textures menu. The texture windows will be updated with the current contents of the corresponding texture stage whenever the application you are debugging enters "break" mode.

If the contents of a surface (either the render target or a texture) are not available, the surface's window will show the text as "Unavailable." Possible reasons for a surface being unavailable include:

  • The surface is not lockable. The surface must be created to allow it to be locked for read-only access. To create a lockable back buffer, specify the D3DPRESENTFLAG_LOCKABLE_BACKBUFFER flag in D3DPRESENT_PARAMETERS when calling IDirect3D9::CreateDevice.
  • The surface is a volume texture. The texture windows do not support the display of volume textures in this release.
  • The surface is in an unsupported pixel format. The debugger currently supports the display of most standard RGB and RGBA pixel formats, as well as the DXTn compressed texture formats.
  • The application you are debugging is running on a remote computer. In this release, the surface views are not supported when debugging remotely.

Debugging C++ Code and Direct3D Code Simultaneously

The Visual Studio .NET debugger supports debugging of multiple program types at the same time. Typical C++ debugging uses the "Native" program type. Direct3D debugging uses the "Direct3D" program type. When the application you are debugging stops in C++ code, the current program will be set to Native, and the call stack, watch window, and other debug windows will reflect the state of the Native program. Similarly, when the application you are debugging stops in shader code, the current program will be set to Direct3D, and the debug windows will reflect the state of the Direct3D program. To switch between program types, use the Program combo box on the Debug Location toolbar. Note that when the application you are debugging is stopped in Native code, most of the state of the Direct3D program will be unavailable. The reverse is not true, however. If you stop at a breakpoint in a shader, for example, you can switch to the Native program and see the C++ call stack that caused your shader to be invoked.

For more information about debugging multiple program types simultaneously, see Debugging Multiple Programs.

Debugging without Debug Information

If possible, build your shaders with debug information enabled (see Building with Debug Information). In cases where building with debug information is not feasible, such as for shaders that are built up "on the fly," debugging is possible but is much more difficult. Because source code is not available, source code breakpoints won't work. One approach to debugging without debug information is to set a BeginScene breakpoint, and when that breakpoint is reached, step into the shader code of the first shader run by pressing F10. When you're stepping through disassembly code, you can set breakpoints in the Disassembly window. You can also use the Modules window to view the names of all shaders currently loaded and selectively set breakpoints on them as needed.

See Also

Direct3D 9 Tools


Tutorials and Samples

The SDK provides several sources of sample code.

  • Tutorials are built from the ground up and contain only those API calls necessary to exercise Direct3D functionality.
  • Samples demonstrate the lastest features of Direct3D 9 as well as functionality that is fundamental to using Direct3D. All of the Direct3D samples are built on top of DXUT.
  • The HLSL Workshop uses effects files designed in high-level shader language (HLSL).


Tutorials

The following tutorials demonstrate the basic functionality of Direct3D as well as the DirectX tools provided in the SDK.

  • Direct3D Tutorials
  • HLSL Workshop


Direct3D Tutorials

The introductory tutorials in this section show how to use Direct3D and D3DX in a C/C++ application. The tasks are divided into required steps. The following tutorials are provided:

  • Tutorial 1: Creating a Device
  • Tutorial 2: Rendering Vertices
  • Tutorial 3: Using Matrices
  • Tutorial 4: Creating and Using Lights
  • Tutorial 5: Using Texture Maps
  • Tutorial 6: Using Meshes

The sample code in these tutorials is from source projects whose location is provided in each tutorial. The sample files in these tutorials are written in C++. If you are using a C compiler, you must make the appropriate changes to the files for them to successfully compile. At the very least, you need to add the vtable and this pointers to the interface methods.

Some comments in the included sample code might differ from the source files in the Platform SDK. Changes are made for brevity only and are limited to comments to avoid changing the behavior of the sample code.


Tutorial 1: Creating a Device

To use Direct3D, you first create an application window, then you create and initialize Direct3D objects. You use the component object model (COM) interfaces that these objects implement to manipulate them and to create other objects required to render a scene. The CreateDevice sample project on which this tutorial is based illustrates these tasks by creating a Direct3D device and rendering a blue screen.

This tutorial uses the following steps to initialize Direct3D, render a scene, and eventually shut down.

Steps

  • Step 1 - Creating a Window
  • Step 2 - Initializing Direct3D
  • Step 3 - Handling System Messages
  • Step 4 - Rendering and Displaying a Scene
  • Step 5 - Shutting Down

Note The path of the CreateDevice sample project is:

(SDK root)\Samples\C++\Direct3D\Tutorials\Tut01_CreateDevice


Step 1 - Creating a Window

The first thing any Windows application must do when it is run is to create an application window to display to the user. To do this, the CreateDevice sample project begins execution at its WinMain function. The following sample code performs window initialization.

INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT )
{
    // Register the window class.
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
    GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
    "Direct3D Tutorial", NULL };

    RegisterClassEx( &wc );

    // Create the application's window.
    HWND hWnd = CreateWindow( "Direct3D Tutorial", "Direct3D Tutorial 01: CreateDevice",
    WS_OVERLAPPEDWINDOW, 100, 100, 300, 300,
    GetDesktopWindow(), NULL, wc.hInstance, NULL );

The preceding code sample is standard Windows programming. The sample starts by defining and registering a window class called "Direct3D Tutorial." After the class is registered, the sample code creates a basic top-level window that uses the registered class, with a client area of 300 pixels wide by 300 pixels tall. This window has no menu or child windows. The sample uses the WS_OVERLAPPEDWINDOW window style to create a window that includes Minimize, Maximize, and Close buttons common to windowed applications. (If the sample were to run in full-screen mode, the preferred window style is WS_EX_TOPMOST, which specifies that the created window should be placed above all non-topmost windows and should stay above them, even when the window is deactivated.) When the window is created, the code sample calls standard Win32 functions to display and update the window.

With the application window ready, you can begin setting up the essential Direct3D objects, as described in Step 2 - Initializing Direct3D.


Step 2 - Initializing Direct3D

The CreateDevice sample project performs Direct3D initialization in the InitD3D application-defined function called from WinMain after the window is created. After you create an application window, you are ready to initialize the Direct3D object that you will use to render the scene. This process includes creating the object, setting the presentation parameters, and finally creating the Direct3D device.

After creating a Direct3D object, use the IDirect3D9::CreateDevice method to create a device, and to enumerate devices, types, modes, and so on.

if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
    return E_FAIL;

The only parameter passed to Direct3DCreate9 should always be D3D_SDK_VERSION. This informs Direct3D that the correct header files are being used. This value is incremented whenever a header or other change would require applications to be rebuilt. If the version does not match, Direct3DCreate9 will fail.

By filling in the fields of D3DPRESENT_PARAMETERS you can specify how you want your 3D application to behave. The CreateDevice sample project sets Windowed to TRUE, SwapEffect to D3DSWAPEFFECT_DISCARD, and BackBufferFormat to D3DFMT_UNKNOWN.

D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

The final step is to use the IDirect3D9::CreateDevice method to create the Direct3D device, as illustrated in the following code example.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                  &d3dpp, &g_pd3dDevice ) ) )

The preceding code sample creates the device with the default adapter by using the D3DADAPTER_DEFAULT flag. In most cases, the system will have only a single adapter, unless it has multiple graphics hardware cards installed. Indicate that you prefer a hardware device over a software device by specifying D3DDEVTYPE_HAL for the DeviceType parameter. This code sample uses D3DCREATE_SOFTWARE_VERTEXPROCESSING to tell the system to use software vertex processing. Note that if you tell the system to use hardware vertex processing by specifying D3DCREATE_HARDWARE_VERTEXPROCESSING, you will see a significant performance gain on video cards that support hardware vertex processing.

Now that the Direct3D object has been initialized, the next step is to ensure that you have a mechanism to process system messages, as described in Step 3 - Handling System Messages.


Step 3 - Handling System Messages

After you have created the application window and initialized Direct3D, you are ready to render the scene. In most cases, Windows applications monitor system messages in their message loop, and they render frames whenever no messages are in the queue. However, the CreateDevice sample project waits until a WM_PAINT message is in the queue, telling the application that it needs to redraw all or part of its window.

// The message loop.
MSG msg;
while( GetMessage( &msg, NULL, 0, 0 ) )
{
    TranslateMessage( &msg );
    DispatchMessage( &msg );
}

Each time the loop runs, DispatchMessage calls MsgProc, which handles messages in the queue. When WM_PAINT is queued, the application calls Render, the application-defined function that will redraw the window. Then the Win32 function ValidateRect is called to validate the entire client area.

The sample code for the message-handling function is shown below.

LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg )
    {
        case WM_DESTROY:
            PostQuitMessage( 0 );
            return 0;

        case WM_PAINT:
            Render();
            ValidateRect( hWnd, NULL );
            return 0;
    }

    return DefWindowProc( hWnd, msg, wParam, lParam );
}

Now that the application handles system messages, the next step is to render the display, as described in Step 4 - Rendering and Displaying a Scene.


Step 4 - Rendering and Displaying a Scene

To render and display the scene, the sample code in this step clears the back buffer to a blue color, transfers the contents of the back buffer to the front buffer, and presents the front buffer to the screen.

To clear a scene, call the IDirect3DDevice9::Clear method.

// Clear the back buffer to a blue color
g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0 );

The first two parameters accepted by IDirect3DDevice9::Clear inform Direct3D of the size and address of the array of rectangles to be cleared. The array of rectangles describes the areas on the render-target surface to be cleared.

In most cases, you use a single rectangle that covers the entire rendering target. You do this by setting the first parameter to zero and the second parameter to NULL. The third parameter determines the method's behavior. You can specify a flag to clear a render-target surface, an associated depth buffer, the stencil buffer, or any combination of the three. This tutorial does not use a depth buffer, so D3DCLEAR_TARGET is the only flag used. The last three parameters are set to reflect clearing values for the render target, depth buffer, and stencil buffer. The CreateDevice sample project sets the clear color for the render-target surface to blue (D3DCOLOR_XRGB(0,0,255)). The final two parameters are ignored by the IDirect3DDevice9::Clear method because the corresponding flags are not present.

After clearing the viewport, the CreateDevice sample project informs Direct3D that rendering will begin, then signals that rendering is complete, as shown in the following code fragment:

// Begin the scene
g_pd3dDevice->BeginScene();

// Rendering of scene objects happens here

// End the scene
g_pd3dDevice->EndScene();

The IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene methods signal to the system when rendering is beginning or is complete. You can call rendering methods only between calls to these methods. Even if rendering methods fail, you should call EndScene before calling BeginScene Again.

After rendering the scene, you display it by using the IDirect3DDevice9::Present method.

g_pd3dDevice->Present( NULL, NULL, NULL, NULL );

The first two parameters are a source rectangle and destination rectangle. The sample code in this step presents the entire back buffer to the front buffer by setting these two parameters to NULL. The third parameter sets the destination window for this presentation. Because this parameter is set to NULL, the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is used. The fourth parameter is the DirtyRegion parameter and in most cases should be set to NULL.

The final step for this tutorial is shutting down the application, as described in Step 5 - Shutting Down.


Step 5 - Shutting Down

At some point during execution, your application must shut down. Shutting down a DirectX application not only means that you destroy the application window, but you also deallocate any DirectX objects your application uses, and you invalidate the pointers to them. The CreateDevice sample project calls Cleanup, an application-defined function to handle this when it receives a WM_DESTROY message.

VOID Cleanup()
{
    if( g_pd3dDevice != NULL)
        g_pd3dDevice->Release();
    if( g_pD3D != NULL)
        g_pD3D->Release();
}

The preceding function deallocates the Direct3D objects it uses by calling the IUnknown methods for each object. Because this tutorial follows COM rules, the reference count for most objects should become zero and should be automatically removed from memory.

In addition to shutdown, there are times during normal execution - such as when the user changes the desktop resolution or color depth - when you might need to destroy and re-create the Microsoft Direct3D objects in use. Therefore it is a good idea to keep your application's cleanup code in one place, which can be called when the need arises.

This tutorial has shown you how to create a device. Tutorial 2: Rendering Vertices shows you how to use vertices to draw geometric shapes.


Tutorial 2: Rendering Vertices

Applications written in Direct3D use vertices to draw geometric shapes. Each three-dimensional (3D) scene includes one or more of these geometric shapes. The Vertices sample project creates the simplest shape, a triangle, and renders it to the display.

This tutorial shows how to use vertices to create a triangle with the following steps:

Steps

  • Step 1 - Defining a Custom Vertex Type
  • Step 2 - Setting Up the Vertex Buffer
  • Step 3 - Rendering the Display

Note The path of the Vertices sample project is:

(SDK root)\Samples\C++\Direct3D\Tutorials\Tut02_Vertices

The sample code in the Vertices project is nearly identical to the sample code in the CreateDevice project. The Rendering Vertices tutorial focuses only on the code unique to vertices and does not cover initializing Direct3D, handling Windows messages, rendering, or shutting down.


Step 1 - Defining a Custom Vertex Type

The Vertices sample project renders a 2D triangle by using three vertices. This introduces the concept of the vertex buffer, which is a Direct3D object that is used to store and render vertices. Vertices can be defined in many ways by specifying a custom vertex structure and corresponding custom flexible vertex format (FVF). The format of the vertices in the Vertices sample project is shown in the following code fragment:

struct CUSTOMVERTEX
{
    FLOAT x, y, z, rhw; // The transformed position for the vertex.
    DWORD color;        // The vertex color.
};

The structure above specifies the format of the custom vertex type. The next step is to define the FVF that describes the contents of the vertices in the vertex buffer. The following code fragment defines an FVF that corresponds with the custom vertex type created above.

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE)

D3DFVF describes what type of custom vertex is being used. The sample code above uses the D3DFVF_XYZRHW and D3DFVF_DIFFUSE flags, which tell the vertex buffer that the custom vertex type has a transformed point followed by a color component.

Now that the custom vector format and FVF are specified, the next step is to fill the vertex buffer with vertices, as described in Step 2 - Setting Up the Vertex Buffer.

Note The vertices in the Vertices sample project are transformed. In other words, they are already in 2D window coordinates. This means that the point (0,0) is at the top left corner and the positive x-axis is right and the positive y-axis is down. These vertices are also lit, meaning that they are not using Direct3D lighting but are supplying their own color.


Step 2 - Setting Up the Vertex Buffer

Now that the custom vertex format is defined, it is time to initialize the vertices. The Vertices sample project does this by calling the application-defined function InitVB after creating the required Direct3D objects. The following code fragment initializes the values for three custom vertices.

CUSTOMVERTEX vertices[] =
{
    { 150.0f,  50.0f, 0.5f, 1.0f, 0xffff0000, }, // x, y, z, rhw, color
    { 250.0f, 250.0f, 0.5f, 1.0f, 0xff00ff00, },
    {  50.0f, 250.0f, 0.5f, 1.0f, 0xff00ffff, },
};

The preceding code fragment fills three vertices with the points of a triangle and specifies which color each vertex will emit. The first point is at (150, 50) and emits the color red (0xffff0000). The second point is at (250, 250) and emits the color green (0xff00ff00). The third point is at (50, 250) and emits the color blue-green (0xff00ffff). Each of these points has a depth value of 0.5 and an RHW of 1.0.

The next step is to call IDirect3DDevice9::CreateVertexBuffer to create a vertex buffer as shown in the following code fragment.

if( FAILED( g_pd3dDevice->CreateVertexBuffer( 3*sizeof(CUSTOMVERTEX),
         0 /*Usage*/, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )
    return E_FAIL;

The first two parameters of IDirect3DDevice9::CreateVertexBuffer tell Direct3D the desired size and usage for the new vertex buffer. The next two parameters specify the vector format and memory location for the new buffer. The vector format here is D3DFVF_CUSTOMVERTEX, which is the flexible vertex format (FVF) that the sample code specified earlier. The D3DPOOL_DEFAULT flag tells Direct3D to create the vertex buffer in the memory allocation that is most appropriate for this buffer. The final parameter is the address of the vertex buffer to create.

After creating a vertex buffer, it is filled with data from the custom vertices as shown in the following code fragment.

VOID* pVertices;
if( FAILED( g_pVB->Lock( 0, sizeof(vertices), (void**)&pVertices, 0 ) ) )
    return E_FAIL;

memcpy( pVertices, vertices, sizeof(vertices) );

g_pVB->Unlock();

The vertex buffer is first locked by calling IDirect3DVertexBuffer9::Lock. The first parameter is the offset into the vertex data to lock, in bytes. The second parameter is the size of the vertex data to lock, in bytes. The third parameter is the address of a BYTE pointer, filled with a pointer to vertex data. The fourth parameter tells the vertex buffer how to lock the data.

The vertices are then copied into the vertex buffer using memcpy. After the vertices are in the vertex buffer, a call is made to IDirect3DVertexBuffer9::Unlock to unlock the vertex buffer. This mechanism of locking and unlocking is required because the vertex buffer may be in device memory.

Now that the vertex buffer is filled with the vertices, it is time to render the display, as described in Step 3 - Rendering the Display.


Step 3 - Rendering the Display

Now that the vertex buffer is filled with vertices, it is time to render the display. Rendering the display starts by clearing the back buffer to a blue color and then calling BeginScene.

g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0L );
g_pd3dDevice->BeginScene();

Rendering vertex data from a vertex buffer requires a few steps. First, you need to set the stream source; in this case, use stream 0. The source of the stream is specified by calling IDirect3DDevice9::SetStreamSource.

g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof(CUSTOMVERTEX) );

The first parameter is the stream number and the second parameter is a pointer to the vertex buffer. The third parameter is the offset from the beginning of the stream to the beginning of the vertex data, which is 0 in this example. The last parameter is the number of bytes of each element in the vertex declaration.

The next step is to call IDirect3DDevice9::SetFVF to identify the fixed function vertex shader. Full, custom vertex shaders are an advanced topic, but in this case the vertex shader is only the flexible vertex format (FVF) code. The following code fragment sets the FVF code.

g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );

The only parameter for SetFVF is the fixed vertex function code to define the vertex data layout.

The next step is to use IDirect3DDevice9::DrawPrimitive to render the vertices in the vertex buffer as shown in the following code fragment.

g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 );

The first parameter accepted by DrawPrimitive is a flag that tells Direct3D what type of primitives to draw. This sample uses the flag D3DPT_TRIANGLELIST to specify a list of triangles. The second parameter is the index of the first vertex to load. The third parameter tells the number of primitives to draw. Because this sample draws only one triangle, this value is set to 1.

For more information about different kinds of primitives, see Primitives (Direct3D 9).

The last steps are to end the scene and then present the back buffer to the front buffer. This is shown in the following code fragment.

g_pd3dDevice->EndScene();
g_pd3dDevice->Present( NULL, NULL, NULL, NULL );

After the back buffer is presented to the front buffer, the client window shows a triangle with three different colored points.

This tutorial has shown you how to use vertices to render geometric shapes. Tutorial 3: Using Matrices introduces the concept of matrices and how to use them.


Tutorial 3: Using Matrices

This tutorial introduces the concept of matrices and shows how to use them. The Vertices sample project rendered 2D vertices to draw a triangle. However, in this tutorial you will be working with transformations of vertices in 3D. Matrices are also used to set up cameras and viewports.

Before the Matrices sample project renders geometry, it calls the SetupMatrices application-defined function to create and set the matrix transformations that are used to render the 3D triangle. Typically, three types of transformation are set for a 3D scene. Steps for creating each one of these typical transformations are listed below.

Steps

  • Step 1 - Defining the World Transformation Matrix
  • Step 2 - Defining the View Transformation Matrix
  • Step 3 - Defining the Projection Transformation Matrix

The path of the Matrices sample project is:

(SDK root)\Samples\C++\Direct3D\Tutorials\Tut03_Matrices

The order in which these transformation matrices are created does not affect the layout of the objects in a scene. However, Direct3D applies the matrices to the scene in the following order:

  1. World
  2. View
  3. Projection

The sample code in the Matrices project is nearly identical to the sample code in the Vertices project. The>Using Matrices tutorial focuses only on the code unique to matrices and does not cover initializing Direct3D, handling Windows messages, rendering, or shutting down.


Step 1 - Defining the World Transformation Matrix

The world transformation matrix defines how to translate, scale, and rotate the geometry in the 3D model space.

The following code fragment rotates the triangle on the y-axis and then sets the current world transformation for the Direct3D device.

D3DXMATRIX matWorld;
D3DXMatrixRotationY( &matWorld, timeGetTime()/150.0f );
g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

The first step is to rotate the triangle around the y-axis by calling the D3DXMatrixRotationY method. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second parameter is the angle of rotation in radians.

The next step is to call IDirect3DDevice9::SetTransform to set the world transformation for the Direct3D device. The first parameter accepted by IDirect3DDevice9::SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_WORLD macro to specify that the world transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information about world transformations, see World Transform (Direct3D 9).

After defining the world transformation for the scene, you can prepare the view transformation matrix. Again, note that the order in which transformations are defined is not critical. However, Direct3D applies the matrices to the scene in the following order:

  1. World
  2. View
  3. Projection

Defining the view transformation matrix is described in Step 2 - Defining the View Transformation Matrix.


Step 2 - Defining the View Transformation Matrix

The view transformation matrix defines the position and rotation of the view. The view matrix is the camera for the scene.

The following code fragment creates the view transformation matrix and then sets the current view transformation for the Direct3D device.

D3DXVECTOR3 vEyePt   ( 0.0f, 3.0f,-5.0f );
D3DXVECTOR3 vLookatPt( 0.0f, 0.0f, 0.0f );
D3DXVECTOR3 vUpVec   ( 0.0f, 1.0f, 0.0f );
D3DXMATRIXA16 matView;
D3DXMatrixLookAtLH( &matView, &vEyePt, &vLookatPt, &vUpVec );
g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

The first step is to define the view matrix by calling D3DXMatrixLookAtLH. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second, third, and fourth parameters define the eye point, look-at point, and "up" direction, respectively. Here the eye is set back along the z-axis by five units and up three units, the look-at point is set at the origin, and "up" is defined as the y-direction.

The next step is to call IDirect3DDevice9::SetTransform to set the view transformation for the Direct3D device. The first parameter accepted by IDirect3DDevice9::SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_VIEW flag to specify that the view transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information about view transformations, see View Transform (Direct3D 9).

After defining the world transformation for the scene, you can prepare the projection transformation matrix. Again, note that the order in which transformations are defined is not critical. However, Direct3D applies the matrices to the scene in the following order:

  1. World
  2. View
  3. Projection

Defining the projection transformation matrix is described in Step 3 - Defining the Projection Transformation Matrix.


Step 3 - Defining the Projection Transformation Matrix

The projection transformation matrix defines how geometry is transformed from 3D view space to 2D viewport space.

The following code fragment creates the projection transformation matrix and then sets the current projection transformation for the Direct3D device.

D3DXMATRIX matProj;
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 1.0f, 100.0f );
g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );

The first step is to call D3DXMatrixPerspectiveFovLH to set up the projection matrix. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second parameter defines the field of view, which tells how objects in the distance get smaller. A typical field of view is 1/4 pi, which is what the sample uses. The third parameter defines the aspect ratio. The sample uses the typical aspect ratio of 1. The fourth and fifth parameters define the near and far clipping plane. This determines the distance at which geometry should no longer be rendered. The Matrices sample project has its near clipping plane set at 1 and its far clipping plane set at 100.

The next step is to call IDirect3DDevice9::SetTransform to apply the transformation to the Direct3D device. The first parameter accepted by IDirect3DDevice9::SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_PROJECTION flag to specify that the projection transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information about projection transformations, see the projection transform.

This tutorial has shown you how to use matrices. Tutorial 4: Creating and Using Lights shows how to add lights to your scene for more realism.


Tutorial 4: Creating and Using Lights

Direct3D lights add more realism to 3D objects. When used, each geometric object in the scene will be lit based on the location and type of lights that are used. The sample code in this tutorial introduces the topics of lights and materials.

This tutorial has the following steps to create a material and a light.

Steps

  • Step 1 - Initializing Scene Geometry
  • Step 2 - Setting Up Material and Light

Note The path of the Lights sample project is:

(SDK root)\Samples\C++\Direct3D\Tutorials\Tut04_Lights

The sample code in the Lights project is nearly identical to the sample code in the Matrices project. The Creating and Using Lights tutorial focuses only on the code unique to creating and using lights and does not cover setting up Direct3D, handling Windows messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information about selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information about matrices and transformations, see Tutorial 3: Using Matrices.


Step 1 - Initializing Scene Geometry

One of the requirements of using lights is that each surface has a normal. To do this, the Lights sample project uses a different custom vertex type. The new custom vertex format has a 3D position and a surface normal. The surface normal is used internally by Direct3D for lighting calculations.

struct CUSTOMVERTEX
{
    D3DXVECTOR3 position; // The 3D position for the vertex.
    D3DXVECTOR3 normal;   // The surface normal for the vertex.
};
// Custom flexible vertex format (FVF).
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL)

Now that the correct vector format is defined, the Lights sample project calls InitGeometry, an application-defined function that creates a cylinder. The first step is to create a vertex buffer that stores the points of the cylinder as shown in the following sample code.

// Create the vertex buffer.
if( FAILED( g_pd3dDevice->CreateVertexBuffer( 50*2*sizeof(CUSTOMVERTEX),
                                           0 /*Usage*/, D3DFVF_CUSTOMVERTEX,
                                           D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )
    return E_FAIL;

The next step is to fill the vertex buffer with the points of the cylinder. Note that in the following sample code, each point is defined by a position and a normal.

CUSTOMVERTEX* pVertices;
if( FAILED( g_pVB->Lock( 0, 0, (void**)&pVertices, 0 ) ) ) return E_FAIL;

for( DWORD i=0; i<50; i++ )
{
    FLOAT theta = (2*D3DX_PI*i)/(50-1);
    pVertices[2*i+0].position = D3DXVECTOR3( sinf(theta),-1.0f, cosf(theta) );
    pVertices[2*i+0].normal   = D3DXVECTOR3( sinf(theta), 0.0f, cosf(theta) );
    pVertices[2*i+1].position = D3DXVECTOR3( sinf(theta), 1.0f, cosf(theta) );
    pVertices[2*i+1].normal   = D3DXVECTOR3( sinf(theta), 0.0f, cosf(theta) );
}

After the preceding sample code fills the vertex buffer with the vertices for a cylinder, the vertex buffer is ready for rendering. But first, the material and light for this scene must be set up before rendering the cylinder. This is described in Step 2 - Setting Up Material and Light.


Step 2 - Setting Up Material and Light

To use lighting in Direct3D, you must create one or more lights. To determine which color a geometric object reflects, a material is created that is used to render geometric objects. Before rendering the scene, the Lights sample project calls SetupLights, an application-defined function that sets up one material and one directional light.

  • Creating a Material
  • Creating a Light

Creating a Material

A material defines the color that is reflected off the surface of a geometric object when a light hits it. The following code fragment uses the D3DMATERIAL9 structure to create a material that is yellow.

D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );
mtrl.Diffuse.r = mtrl.Ambient.r = 1.0f;
mtrl.Diffuse.g = mtrl.Ambient.g = 1.0f;
mtrl.Diffuse.b = mtrl.Ambient.b = 0.0f;
mtrl.Diffuse.a = mtrl.Ambient.a = 1.0f;
g_pd3dDevice->SetMaterial( &mtrl );

The diffuse color and ambient color for the material are set to yellow. The call to the IDirect3DDevice9::SetMaterial method applies the material to the Direct3D device used to render the scene. The only parameter that IDirect3DDevice9::SetMaterial accepts is the address of the material to set. After this call is made, every primitive will be rendered with this material until another call is made to IDirect3DDevice9::SetMaterial that specifies a different material.

Now that material has been applied to the scene, the next step is to create a light.

Creating a Light

There are three types of lights available in Direct3D:

  • point lights
  • directional lights
  • spotlights

The sample code creates a directional light, which is a light that goes in one direction. The code also oscillates the direction of the light.

The following code fragment uses the D3DLIGHT9 structure to create a directional light.

D3DXVECTOR3 vecDir;
D3DLight9 light;
ZeroMemory( &light, sizeof(light) );
light.Type = D3DLIGHT_DIRECTIONAL;

The following code fragment sets the diffuse color for this light to white.

light.Diffuse.r = 1.0f;
light.Diffuse.g = 1.0f;
light.Diffuse.b = 1.0f;

The following code fragment rotates the direction of the light around in a circle.

vecDir = D3DXVECTOR3(cosf(timeGetTime()/360.0f),
                     0.0f,
                     sinf(timeGetTime()/360.0f) );
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );

The call to D3DXVec3Normalize normalizes the direction vector used to determine the direction of the light.

A range can be specified to tell Direct3D how far the light will have an effect. This member does not affect directional lights. The following code fragment assigns a range of 1000 units to this light.

light.Range = 1000.0f;

The following code fragment assigns the light to the Direct3D device by calling IDirect3DDevice9::SetLight.

g_pd3dDevice->SetLight( 0, &light );

The first parameter that IDirect3DDevice9::SetLight accepts is the index that this light will be assigned to. Note that if a light already exists at that location, it will be overwritten by the new light. The second parameter is a pointer to the light structure that defines the light. The Lights sample project places this light at index 0.

The following code fragment enables the light by calling IDirect3DDevice9::LightEnable.

g_pd3dDevice->LightEnable( 0, TRUE);

The first parameter that IDirect3DDevice9::LightEnable accepts is the index of the light to enable. The second parameter is a Boolean value that tells whether to turn the light on (TRUE) or off (FALSE). In the sample code above, the light at index 0 is turned on.

The following code fragment tells Direct3D to render lights by calling IDirect3DDevice9::SetRenderState.

g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE );

The first two parameters that IDirect3DDevice9::SetRenderState accepts is which device state variable to modify and what value to set it to. This code sample sets the D3DRS_LIGHTING device variable to TRUE, which has the effect of enabling the rendering of lights.

The final step in this code sample is to turn on ambient lighting by again calling IDirect3DDevice9::SetRenderState.

g_pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0x00202020 );

The preceding code fragment sets the D3DRS_AMBIENT device variable to a light gray color (0x00202020). Ambient lighting will light up all objects by the given color.

For more information about lighting and materials, see Lights and Materials (Direct3D 9).

This tutorial has shown you how to use lights and materials. Tutorial 5: Using Texture Maps shows you how to add texture to surfaces.


Tutorial 5: Using Texture Maps

While lights and materials add a great deal of realism to a scene, nothing adds more realism than adding textures to surfaces. Textures can be thought of as wallpaper that is shrink-wrapped onto a surface. You could place a wood texture on a cube to make the cube look like it is actually made of wood. The Texture sample project adds a banana peel texture to the cylinder created in tutorial 4. This tutorial covers how to load textures, set up vertices, and display objects with texture.

This tutorial implements textures using the following steps:

Steps

  • Step 1 - Defining a Custom Vertex Format
  • Step 2 - Initializing Screen Geometry
  • Step 3 - Rendering the Scene

Note The path of the Texture sample project is:

(SDK root)\Samples\C++\Direct3D\Tutorials\Tut05_Textures

The sample code in the Texture project is nearly identical to the sample code in the Lights project, except that the Texture sample project does not create a material or a light. The Using Texture Maps tutorial focuses only on the code unique to textures and does not cover initializing Direct3D, handling Windows messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information about selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information about matrices and transformations, see Tutorial 3: Using Matrices.


Step 1 - Defining a Custom Vertex Format

Before using textures, a custom vertex format that includes texture coordinates must be used. Texture coordinates tell Direct3D where to place a texture for each vector in a primitive. Texture coordinates range from 0.0 to 1.0, where (0.0, 0.0) represents the top-left side of the texture and (1.0, 1.0) represents the lower-right side of the texture.

The following sample code shows how the Texture sample project sets up its custom vertex format to include texture coordinates.

// A structure for our custom vertex type. Texture coordinates were added.
struct CUSTOMVERTEX
{
    D3DXVECTOR3 position; // The position
    D3DCOLOR    color;    // The color
#ifndef SHOW_HOW_TO_USE_TCI
    FLOAT       tu, tv;   // The texture coordinates
#endif
};

// Custom flexible vertex format (FVF), which describes custom vertex structure
#ifdef SHOW_HOW_TO_USE_TCI
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE)
#else
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
#endif

For more information about texture coordinates, see Texture Coordinates (Direct3D 9).

Now that a custom vertex type has been defined, the next step is to load a texture and create a cylinder, as described in Step 2 - Initializing Screen Geometry.


Step 2 - Initializing Screen Geometry

Before rendering, the Texture sample project calls InitGeometry, an application-defined function that creates a texture and initializes the geometry for a cylinder.

Textures are created from file-based images. The following code fragment uses D3DXCreateTextureFromFile to create a texture from Banana.bmp that will be used to cover the surface of the cylinder.

if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, "Banana.bmp",
&g_pTexture ) ) )
return E_FAIL;

The first parameter that D3DXCreateTextureFromFile accepts is a pointer to the Direct3D device that will be used to render the texture. The second parameter is a pointer to an ANSI string that specifies the filename from which to create the texture. This sample specifies Banana.bmp to load the image from that file. The third parameter is the address of a pointer to a texture object.

When the banana texture is loaded and ready to use, the next step is to create the cylinder. The following code sample fills the vertex buffer with a cylinder. Note that each point has the texture coordinates (tu, tv).

for( DWORD i=0; i<50; i++ )
{
    FLOAT theta = (2*D3DX_PI*i)/(50-1);

        pVertices[2*i+0].position = D3DXVECTOR3( sinf(theta),-1.0f, cosf(theta) );
        pVertices[2*i+0].color    = 0xffffffff;
#ifndef SHOW_HOW_TO_USE_TCI
        pVertices[2*i+0].tu       = ((FLOAT)i)/(50-1);
        pVertices[2*i+0].tv       = 1.0f;
#endif

        pVertices[2*i+1].position = D3DXVECTOR3( sinf(theta), 1.0f, cosf(theta) );
        pVertices[2*i+1].color    = 0xff808080;
#ifndef SHOW_HOW_TO_USE_TCI
        pVertices[2*i+1].tu       = ((FLOAT)i)/(50-1);
        pVertices[2*i+1].tv       = 0.0f;
#endif
}

Each vertex includes position, color, and texture coordinates. The code sample above sets the texture coordinates for each point so that the texture will wrap smoothly around the cylinder.

Now that the texture is loaded and the vertex buffer is ready for rendering, it is time to render the display, as described in Step 3 - Rendering the Scene.


Step 3 - Rendering the Scene

After scene geometry has been initialized, it is time to render the scene. In order to render an object with texture, the texture must be set as one of the current textures. The next step is to set the texture stage states values. Texture stage states enable you to define the behavior of how a texture or textures are to be rendered. For example, you could blend multiple textures together.

The Texture sample project starts by setting the texture to use. The following code fragment sets the texture that the Direct3D device will use to render with IDirect3DDevice9::SetTexture.

g_pd3dDevice->SetTexture( 0, g_pTexture );

The first parameter that IDirect3DDevice9::SetTexture accepts is a stage identifier to set the texture to. A device can have up to eight set textures, so the maximum value here is 7. The Texture sample project has only one texture and places it at stage 0. The second parameter is a pointer to a texture object. The Texture sample project uses the texture object that it created in its InitGeometry application-defined function.

The following code sample sets the texture stage state values by calling the IDirect3DDevice9::SetTextureStageState method.

    // Setup texture. Using textures introduces the texture stage states, which
    //   govern how textures get blended together (in the case of multiple
    //   textures) and lighting information. In this case, you are modulating
    //   (blending) your texture with the diffuse color of the vertices.
    g_pd3dDevice->SetTexture( 0, g_pTexture );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP,   D3DTOP_DISABLE );

#ifdef SHOW_HOW_TO_USE_TCI
    // Note: To use Direct3D texture coordinate generation, use the stage state
    // D3DTSS_TEXCOORDINDEX, as shown below. In this example, you are using
    // the position of the vertex in camera space to generate texture
    // coordinates. The tex coord index (TCI) parameters are passed into a
    // texture transform, which is a 4x4 matrix that transforms the x,y,z
    // TCI coordinates into tu, tv texture coordinates.

    // In this example, the texture matrix is set up to
    // transform the texture from (-1,+1) position coordinates to (0,1)
    // texture coordinate space:
    //    tu =  0.5*x + 0.5
    //    tv = -0.5*y + 0.5
    D3DXMATRIXA16 mat;
    mat._11 = 0.25f; mat._12 = 0.00f; mat._13 = 0.00f; mat._14 = 0.00f;
    mat._21 = 0.00f; mat._22 =-0.25f; mat._23 = 0.00f; mat._24 = 0.00f;
    mat._31 = 0.00f; mat._32 = 0.00f; mat._33 = 1.00f; mat._34 = 0.00f;
    mat._41 = 0.50f; mat._42 = 0.50f; mat._43 = 0.00f; mat._44 = 1.00f;

    g_pd3dDevice->SetTransform( D3DTS_TEXTURE0, &mat );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
            D3DTTFF_COUNT2 );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX,
            D3DTSS_TCI_CAMERASPACEPOSITION );
#endif

The first parameter that IDirect3DDevice9::SetTextureStageState accepts is the stage index for the state variable to be set. This code sample changes the values for the texture at stage 0, so it puts a zero here. The next parameter is the texture state to set. For a list of all valid texture states and their meaning, see D3DTEXTURESTAGESTATETYPE. The next parameter is the value to which the texture state will be set. The value that you place here is based on the texture stage state value that you are modifying.

After setting up the desired values for each texture stage state, the cylinder can be rendered and texture will be added to the surface.

Another way to use texture coordinates is to automatically generate them. This is done by using a texture coordinate index (TCI). The TCI uses a texture matrix to transform the (x,y,z) TCI coordinates into (tu, tv) texture coordinates. In the Texture sample project, the position of the vertex in camera space is used to generate texture coordinates.

The first step is to create the matrix that will be used for the transformation, as demonstrated in the following code fragment.

D3DXMATRIX mat;
mat._11 = 0.25f; mat._12 = 0.00f; mat._13 = 0.00f; mat._14 = 0.00f;
mat._21 = 0.00f; mat._22 =-0.25f; mat._23 = 0.00f; mat._24 = 0.00f;
mat._31 = 0.00f; mat._32 = 0.00f; mat._33 = 1.00f; mat._34 = 0.00f;
mat._41 = 0.50f; mat._42 = 0.50f; mat._43 = 0.00f; mat._44 = 1.00f;

After the matrix is created, it must be set by calling IDirect3DDevice9::SetTransform, as shown in the following code fragment.

g_pd3dDevice->SetTransform( D3DTS_TEXTURE0, &mat );

The D3DTS_TEXTURE0 flag tells Direct3D to apply the transformation to the texture located at texture stage 0. The next step that this sample takes is to set more texture stage state values to get the desired effect. That is done in the following code fragment.

g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
            D3DTTFF_COUNT2 );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX,
            D3DTSS_TCI_CAMERASPACEPOSITION );

The texture coordinates are set up, and now the scene is ready to be rendered. Notice that the coordinates are automatically created for the cylinder. This particular setup gives the effect of the texture being laid over the rendering screen after the geometric shapes have been rendered.

For more information about textures, see Direct3D Textures (Direct3D 9).


Tutorial 6: Using Meshes

Complicated geometry is usually modeled using 3D modeling software, after which the model is saved to a file. An example of this is the .x file format. Direct3D uses meshes to load the objects from these files. Meshes are somewhat complicated, but D3DX contains functions that make using meshes easier. The Meshes sample project introduces the topic of meshes and shows how to load, render, and unload a mesh.

This tutorial shows how to load, render, and unload a mesh using the following steps.

Steps

  • Step 1 - Loading a Mesh Object
  • Step 2 - Rendering a Mesh Object
  • Step 3 - Unloading a Mesh Object

The path of the Meshes sample project is: (SDK root)\Samples\C++\Direct3D\Tutorials\Tut06_Meshes

The sample code in the Meshes project is nearly identical to the sample code in the Lights project, except that the code in the Meshes project does not create a material or a light. This tutorial focuses only on the code unique to meshes and does not cover setting up Direct3D, handling Windows messages, rendering, or shutting down.


Step 1 - Loading a Mesh Object

A Direct3D application must first load a mesh before using it. The Meshes sample project loads the tiger mesh by calling InitGeometry>, an application-defined function, after loading the required Direct3D objects.

A mesh needs a material buffer that will store all the materials and textures that will be used. The function starts by declaring a material buffer as shown in the following code fragment.

LPD3DXBUFFER pD3DXMtrlBuffer;

The following code fragment loads the mesh.

// Load the mesh from the specified file
if( FAILED( D3DXLoadMeshFromX( "Tiger.x", D3DXMESH_SYSTEMMEM,
            g_pd3dDevice, NULL, &pD3DXMtrlBuffer, NULL,
            &g_dwNumMaterials, &g_pMesh ) ) )
    {
    // If model is not in current folder, try parent folder
    if( FAILED( D3DXLoadMeshFromX( "..\\Tiger.x",
            D3DXMESH_SYSTEMMEM, g_pd3dDevice, NULL,
            &pD3DXMtrlBuffer, NULL, &g_dwNumMaterials,
            &g_pMesh ) ) )
        {
            MessageBox(NULL, "Could not find tiger.x",
                       "Meshes.exe", MB_OK);
            return E_FAIL;
        }
    }

The first parameter is a pointer to a string that tells the name of the DirectX file to load. This sample loads the tiger mesh from Tiger.x.

The second parameter specifies how to create the mesh. The sample uses the D3DXMESH_SYSTEMMEM flag, which is equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM. Both of these flags put the index buffer and vertex buffer for the mesh in system memory.

The third parameter is a pointer to a device that will be used to render the mesh.

The fourth parameter is a pointer to an ID3DXBuffer object. This object will be filled with information about neighbors for each face. This information is not required for this sample, so this parameter is set to NULL.

The fifth parameter also takes a pointer to an ID3DXBuffer object. After this method is finished, this object will be filled with D3DXMATERIAL structures for the mesh.

The sixth parameter is a pointer to the number of D3DXMATERIAL structures placed into the ppMaterials array after the method returns.

The seventh parameter is the address of a pointer to a mesh object, representing the loaded mesh.

After loading the mesh object and material information, you need to extract the material properties and texture names from the material buffer.

The Meshes sample project does this by first getting the pointer to the material buffer. The following code fragment uses the ID3DXBuffer::GetBufferPointer method to get this pointer.

D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer();

The following code fragment creates new mesh and texture objects based on the total number of materials for the mesh.

g_pMeshMaterials = new D3DMATERIAL9[g_dwNumMaterials];
g_pMeshTextures  = new LPDIRECT3DTEXTURE9[g_dwNumMaterials];

For each material in the mesh the following steps occur.

The first step is to copy the material, as shown in the following code fragment.

g_pMeshMaterials[i] = d3dxMaterials[i].MatD3D;

The second step is to set the ambient color for the material, as shown in the following code fragment.

g_pMeshMaterials[i].Ambient = g_pMeshMaterials[i].Diffuse;

The final step is to create the texture for the material, as shown in the following code fragment.

// Create the texture.
if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice,
   d3dxMaterials[i].pTextureFilename, &g_pMeshTextures[i] ) ) )
    g_pMeshTextures[i] = NULL;
}

After loading each material, you are finished with the material buffer and need to release it by calling IUnknown.

pD3DXMtrlBuffer->Release();

The mesh, along with the corresponding materials and textures are loaded. The mesh is ready to be rendered to the display, as described in Step 2 - Rendering a Mesh Object.


Step 2 - Rendering a Mesh Object

In step 1 the mesh was loaded and is now ready to be rendered. It is divided into a subset for each material that was loaded for the mesh. To render each subset, the mesh is rendered in a loop. The first step in the loop is to set the material for the subset, as shown in the following code fragment.

g_pd3dDevice->SetMaterial( &g_pMeshMaterials[i] );

The second step in the loop is to set the texture for the subset, as shown in the following code fragment.

g_pd3dDevice->SetTexture( 0, g_pMeshTextures[i] );

After setting the material and texture, the subset is drawn with the ID3DXBaseMesh::DrawSubset method, as shown in the following code fragment.

g_pMesh->DrawSubset( i );

The ID3DXBaseMesh::DrawSubset method takes a DWORD that specifies which subset of the mesh to draw. This sample uses a value that is incremented each time the loop runs.

After using a mesh, it is important to properly remove the mesh from memory, as described in Step 3 - Unloading a Mesh Object.


Step 3 - Unloading a Mesh Object

After any DirectX program finishes, it needs to deallocate any DirectX objects that it used and invalidate the pointers to them. The mesh objects used in this sample also need to be deallocated. When it receives a WM_DESTROY message, the Meshes sample project calls Cleanup, an application-defined function, to handle this.

The following code fragment deletes the material list.

if(g_pMeshMaterials)
delete[] g_pMeshMaterials;

The following code fragment deallocates each individual texture that was loaded and then deletes the texture list.

if(g_pMeshTextures)
{
    for(DWORD i = 0; i < g_dwNumMaterials; i++
    {
        if(g_pMeshTextures[i])
            g_pMeshTextures[i]->Release();
    }
delete[] g_pMeshTextures;

The following code fragment deallocates the mesh object.

// Delete the mesh object
if(g_pMesh)
    g_pMesh->Release();

This tutorial has shown you how to load and render meshes. This is the last tutorial in this section.


HLSL Workshop

The high-level shader language (HLSL) Workshop is a set of tutorials that make it easy to learn how to generate HLSL shaders.

HLSL Tutorials

These tutorials are .fx files that offer a step-by-step approach to learning how to use vertex, pixel, and texture shaders in HLSL to create the following functionality:

  • Goal 1: Hemispheric Lighting Tutorial
  • Goal 2: Vertex Animation Tutorial
  • Goal 3: Environment Mapping
  • Goal 4: Procedural Texture Tutorial

Launching The Shader Debugger

While running these tutorials, you may find it helpful to know how to launch the shader debugger to interactively debug your shaders. Here is one additional tutorial that will show you how to launch the debugger and start your debug session:

  • Goal 5: Shader Debugging Tutorial


Goal 1 - Hemispheric Lighting Tutorial

In this lesson you'll be implementing the hemispheric lighting term of the lighting equation. Before starting on the solution, look at this page for an explanation of the theory (Hemispheric Lighting Explained) as you work through the tutorial. If you get stuck, refer to the Goal1_Solution.fx file inside the solutions directory for the suggested answer. Most of the steps can be implemented in many different ways, so don't worry if your code is different from the solution.

The hemispheric lighting goal is divided into three tasks:

  1. Use the occlusion term stored per vertex to modulate the hemisphere term.
  2. Calculate the hemisphere light value.
  3. Change the sky and ground colors.

Extra Credit: Make the skull translucent where the occlusion term is low (you'll need to set alpha blend states).

Setup

Preparation

Open Goal1.fx. If you have the SDK installed, the .fx file is located at:

(SDK root)\Samples\C++\Direct3D\Tutorials\HLSLWorkshop\

Description

The default render technique is Hemisphere, which uses only the hemispheric lighting term of the lighting equation. Since you'll be implementing hemispheric lighting in this lesson, this term is currently calculated using placeholder values; therefore, your render view should show a flat, dark, gray skull surface:

Task 1: Use the Occlusion Term Stored per Vertex to Modulate the Hemisphere Term

Preparation

Locate Goal 1A in the code and follow the instructions.

Description

The occlusion term is a weight that was calculated in a offline pass of the model that is the percentage of the hemisphere that is blocked by other parts of the model. In the term provided, a value of 0 means that the vertex is not occluded by any geometry (all light will be received) versus a value of 1 which means that the vertex is completely blocked from light.

Multiplying by the result of 1 - Occ will darken the hemisphere light in relation to how much this vertex is affected by a hemisphere light.

Solution

Hemi *= (1 - Occ);

After modulating by the occlusion term, the model appears shadowed in occluded areas:

Task 2: Calculate the Hemisphere Light Value

Preparation

Locate Goal 1B in the code and follow the instructions.

Description

A hemisphere light is made up of two colors, sky and ground, that are interpolated between based on the normal; that is, areas with normals pointing towards the sky are "sky"-colored, and areas pointed towards the "ground" are more "ground"-colored.

An easy way to implement a hemisphere light is to linearly interpolate between the sky color and the ground color based on the angle between the normal and sky direction. The angle can easily be calculated by doing a dot product between the normal and sky direction. This results in a -1 to 1 value that, when remapped to 0 to 1, is perfect for linearly interpolating between the two colors.

Solution

float LerpFactor = (dot(Normal, DirToSky) + 1) / 2;

Both Normal and DirToSky should be normalized (unit) vectors.

After taking into account the angle between sky and ground colors, the model reflects the white sky color on areas pointed upward and the black ground color on areas pointed downward:

Task 3: Change the Sky and Ground Colors

Preparation

Locate Goal 1C in the code and follow the instructions.

Description

Experiment with a few values for sky and ground. The hemisphere light is used to simulate an environment that is dominated by one color at the north and south poles of a "sphere" surrounding the object. One hemisphere is the sky color and the other is the ground color. An example of this is blue for the sky and green for the ground. This will simulate basic radiosity of a scene for an object sitting on a green surface like grass with a blue sky overhead. Note that the default color values are stored at the top of the file.

Solution

float4 GroundColor              = { 0.1f, 0.4f, 0.0f, 1.0f };    // ground
float4 SkyColor                 = { 0.5f, 0.5f, 0.9f, 1.0f };    // sky

Notice how the new sky and ground colors affect the model:

Because the selected technique Hemisphere only uses the hemispheric term of the lighting equation, the model shading is very dark. Try scrolling through the other techniques to see how the different components of the lighting equation affect the model; notice that all the techniques which start with Hemisphere include the hemispheric lighting term you implemented. The following image, rendered using the Hemisphere technique, shows the model under complete illumination:

That completes Goal 1. Feel free to try the extra credit problem or move on to Goal 2 when ready.


Hemispheric Lighting Explained

Hemispheric lighting divides scene lighting into two spheres: an upper hemisphere and a lower hemisphere. Each vertex uses its normal to determine whether it is more visible to the upper or the lower hemisphere. Once the visibility is determined, per-vertex lighting is interpolated from the two hemisphere colors to produce more realistic object lighting. See Goal 1 - Hemispheric Lighting Tutorial.

Why Use Hemispheric Lighting?

Compare the two objects below. The difference between the lighting on the two objects is that the one on the right has a hemispheric component.

In the image on the right, notice the color difference between the top and the bottom of the object. The top is brighter with a bluish tint because it is more influenced by the sky color. The bottom is darker with a greenish tint because it is more influnced by the ground color.

How Does It Work?

Here is an example of a vertex "p" that is influenced by two hemispheres. This diagram shows two hemispheres: the top one is blue, and the bottom one is green. The polygon in the center of the sphere is the one we are lighting. The angle theta is the angle between the vertex normal and the up vector (a vector pointed (0,1,0)).

Hemispheric lighting takes the sky and ground color and blends them together based on the value of theta like this:

The resulting hemisperic component can then be combined with other per-vertex components (such as ambient, diffuse, or specular components).

This example also includes an occlusion term that identifies which vertices are occluded (or blocked) from the hemispheric lighting. A value of 1 means that the vertex is completely occluded from the light; a value of 0 means the vertex is not blocked from the light. In this example, the occlusion term is a per-vertex property, and was supplied in the per-vertex model data.

An easy way to implement a hemisphere light is to interpolate between the sky color and the ground color based on the angle between the normal and sky direction. The angle can easily be calculated by doing a dot product between the normal and sky direction. This results in a -1 to 1 value that, when remapped to 0 to 1, is perfect for interpolating between the two colors.


Goal 2: Vertex Animation Tutorial

In this lesson you'll be using a programmable vertex shader to animate the vertices of the model. Animating vertices using the fixed function pipeline would require either updating the vertex positions stored in the vertex buffer, or changing tranformation matrices for each vertex. Because smooth animation would require making these changes for every frame, both of these approaches are prohibitively slow for most applications; if, however, the animation is performed in a programmable vertex shader, the animation can be performed during the transformation process at minimal expense. As before, the given solutions are just suggested implementations, and your answers may vary.

The vertex animation goal contains a single task: Use the Time variable to modify geometry.

Extra Credit: Use sin(float3) to create a rippling skull.

Setup

Preparation

Open Goal2.fx. If you have the SDK installed, the .fx file is located at:

(SDK root)\Samples\C++\Direct3D\Tutorials\HLSLWorkshop\

Description

The default render technique is HemisphereDiffuseSpecular, which uses the full hemispheric lighting equation developed in the previous lesson:

Task 1: Use the Time Variable to Modify Geometry

Preparation

Locate Goal 2A in the code and follow the instructions.

Description

You can put the current time in seconds in any float variable with the TIME semantic like the Time variable declared above. Offset is just the vertex's model space coordinate, and can be used to distinguish different vertices so that any motion generated at one vertex is not the same as all vertices (that is, it can be used to offset the sine evaluation so that each point is at a different point in the sine equation).

One good method of animating things is using sine or cosine. This can be used to generate waves or other interesting interference patterns.

A couple of HLSL features will be very useful for this task. First, most of the intrinsic functions are defined for both scalar and vector types (that is, if you pass a vector to the sine function it will return a vector containing the sine of each vector component). Second, a single component scalar type will automatically be promotion cast to multiple component types when the function returns.

You probably do not want to add or subtract too large a value per vertex. Multiplying the result of sine or cosine by 0.1 is a good start for the skull model.

Solution

In particular, this task doesn't have any right or wrong implementations. Here are a few values which give interesting results:

return sin(Time);
return sin(Time * Offset) * 0.1;
return sin(Time + Offset) * 0.1;
return float3( sin(Time + Offset.x), sin(3*Time + Offset.x), 0) * 0.5;

return (Normal*(sin(Time)+1))*0.5;
// For this solution, you'll need to pass "Normal" into the function

The computed value is added to the vertex's transformed position inside the vertex shader, resulting in a periodic animation:

This completes Goal 2. Feel free to try the extra credit problem or move on to Goal 3 when ready.


Goal 3 - Environment Mapping

In this lesson you'll be implementing environment mapping to simulate ray-traced reflections. Before starting on the solution, look over the Environment Mapping Explained for an explanation of the theory, and refer back as needed as you work through the code. If you get stuck, refer to the Goal3_Solution.fx file inside the solutions directory for the suggested answer. Most of the steps can be implemented in many different ways, so don't worry if your code is different from the solution.

The environment mapping goal is divided into four tasks:

  1. Create a texture and a sampler for the environment map.
  2. Do a cubemap texture lookup.
  3. Calculate the reflection vector.
  4. Adjust reflectivity.

Extra Credit:

  • Add a fresnel term.
  • Change the environment map to per-pixel instead of per-vertex.

Setup

Preparation

Open Goal3.fx. If you have the software development kit (SDK) installed, the .fx file is located at:

(SDK root)\Samples\C++\Direct3D\Tutorials\HLSLWorkshop\

Description

The default render technique is HemisphereDiffuseSpecular, which uses the full hemispheric lighting equation developed in lesson 1; however, the pixel shader has been modified to use the environment map in place of the diffuse color. Since you'll be adding support for environment mapping in this lesson, the placeholder code evaluates to black, leaving only subtle white highlights from the specular contribution:

Note that the animation calculation added in the previous lesson has been commented out to make things easier.

Task 1: Create a Texture and a Sampler for the Environment Map

Preparation

Locate Goal 3A in the code and follow the instructions.

Description

Texture variables are the .fx file representation of the texture interfaces. Texture parameters also have annotations that specify what type of texture and where the texture should come from. This information is read by the application, which then creates a texture using that information and sets the interface back into the effect for use. In this case, the sample looks for type and name annotations in order to correctly load the texture.

The sampler variable is the HLSL .fx representation of how to do lookups. The texture intrinsics require a sampler, because a sample encompasses the concept of the texture and the method in which to do the lookup (that is, types of filtering, and so on). In .fx files, samplers can also have sampler_state blocks that specify the state to be loaded into the device whenever that sampler is used.

Note These blocks are ignored if D3DXCompileShader or fxc is used.

Note

Create a texture variable named EnvironmentMap. Also create two string annotations:

  1. "type" with the value "CUBE"
  2. "name" with the value "lobbycube.dds" (the environment map to use)

Create a samplerCUBE variable called Environment. Add a sampler_state block that sets the following state:

  1. Texture to (EnvironmentMap)
  2. MipFilter to LINEAR;
  3. MinFilter to LINEAR;
  4. MagFilter to LINEAR;

Solution

texture EnvironmentMap
<
    string type = "CUBE";
    string name = "lobbycube.dds";
>;

samplerCUBE EnvironmentSampler = sampler_state
{
    Texture = (EnvironmentMap);
    MipFilter = LINEAR;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
};

Task 2: Do a Cubemap Texture Lookup

Preparation

Locate Goal 3B in the code and follow the instructions.

Description

The cubemap contains the view of the environment from the object's perspective along the six positive and negative axes. By sampling this texture and applying the result to the model's surface, the model will appear to reflect the environment.

Note

Use the provided CubeTexcoord and the texCUBE intrinsic to do the texture lookup.

Solution

return texCUBE(EnvironmentSampler, CubeTexcoord);

The environment can now be seen reflected from the object:

Note that the reflection does not take the viewer's position into account (as you'll notice if you move the camera). This will be fixed in the next step.

Task 3: Calculate the Reflection Vector

Preparation

Locate Goal 3C in the code and follow the instructions.

Description

The reflection vector is used to find the ray of light leaving a particular point in the environment, bouncing off the surface of the object, and entering the camera.

Note

A good way to start is just to return the Normal until you make sure the cube map lookup is working. Next you can use the reflect intrinsic to reflect the ViewToPos vector around the Normal vector. Both the ViewToPos and Normal vectors should be normalized before calculating reflection (which has already been done for you in the vertex shader).

Solution

return reflect(ViewToPos, Normal);

The environment mapping appears much more accurate with the correct reflection vector:

Note that the environment mapping is still not quite right - upon close inspection you will notice that the surface reflection appears slightly warped when moving the model around. This is a result of calculating the cubemap sample coordinates per-vertex and interpolating the result across the fragment. Instead, the normal and view vector could be interpolated across the fragment and used to calculate environment mapping per-pixel. For this workshop, per-vertex approximation is good enough, and per-pixel environment mapping is left to the user as an extra credit exercise. As a general rule, moving calculations from the vertex shader to the pixel shader gives greater accuracy at the expense of performance.

Task 4: Adjust Reflectivity

Preparation

Locate Goal 3D in the code and follow the instructions.

Description

Most shiny objects are not completely reflective. Some percentage of the final color is a reflection of the environment and the remaining contribution comes from the material's diffuse properties. Factor in the diffuse color to decrease reflectivity.

Note

Linearly interpolate between the diffuse color calculated within the vertex shader (In.Diff) and the environment map color sampled from the cubemap. A good reflectivity value for this scene is 0.25

Solution

OutColor = lerp(In.Diff, Environment, 0.25);

The environment now appears as a subtle reflection on top of the diffuse color:

Now that you have everything working, you might want to uncomment the animation calculation and to see how the reflections give added visual cues to the animated deformations.

This completes Goal 3. Feel free to try the extra credit problems or move on to Goal 4 when ready.


Environment Mapping Explained

This sample uses high-level shader language (HLSL) and effects to apply a cubic environment map using a pixel shader. A vertex shader is also used trivially to transform the vertex data to projection space. The shaders and the helper functions are written in HLSL. An effect encapsulates the sampler state, the texture state, and a technique that invokes the vertex and pixel shaders.

How an Environment Map Works

An environment map, sometimes referred to as a reflection map, is a method for applying environment reflections to a curved surface. A cubic environment map, is a texture map that contains six 2D textures, one for each direction from a point (see Cubic Environment Mapping (Direct3D 9)). By applying an environment map, an object can be made to appear like it has a highly smooth surface (such as an object made out of metal or glass). This example illustrates the difference between two objects: one object lit with normal diffuse lighting, and one that has a environment map applied.

Figure 1. Standard ambient/diffuse lighting | Figure 2. With an environment map and identical lighting

The skull in Figure 1 appears to have a flat finish; there are no reflections from the environment and no glossy or specular highlights. In contrast, Figure 2 contains an environment map that makes the skull appear to have a highly reflective, glossy surface.

How This Example Works

An environment map relies on a reflection vector to sample the texture. The reflection vector leaves the point being textured at an angle form the normal that is equivalent to the angle between the view vector to the point. This is shown below.

Generating the Reflection Vector

The reflection vector will be used as a lookup (in other words, as texture coordinates) for the texture sampling. The vertex shader calculates the reflection vector with the help of the CalcReflectionVector HLSL function as shown here.

// Generate a reflection vector to lookup in a reflection cube-map
Out.CubeTexcoord = CalcReflectionVector(EyeToVertex, Normal);

The helper function uses the reflect (Direct3D 9 HLSL) HLSL intrinsic function to generate a reflection vector from the view vector and the vertex normal. The last thing the helper function does is normalize the resulting vector by calling the normalize (Direct3D 9 HLSL) intrinsic function.

float3 CalcReflectionVector(float3 ViewToPos, float3 Normal)
{
    return normalize(reflect(ViewToPos, Normal));
}

You may want to test your normals to see that they are correct, by simply returning the normal with this function. This will produce a texture image on your object that is incorrect, but it will help verify the normal data. Once this works, add the reflect and normalize intrinsic functions to create correct environmental mapping.

Environment Map Lookup

The environment map lookup is a cubic texture sample. The texture sample requires the input texture coordinate (passed into the helper function by CubeTexcoord), and the sampler that we declared earlier. The sampling is done with the help of the HLSL intrinsic function texCUBE (Direct3D 9 HLSL), which takes the 3D coordinates, and returns a 4D color value.

float4 CubeMapLookup(float3 CubeTexcoord)
{
    return 0.25 * texCUBE(EnvironmentSampler, CubeTexcoord);
}

Lastly, once the texture is sampled and a color is returned, this will be added to the existing pixel color in the pixel shader. The 0.25 factor is an arbitrary number chose to scale down the influence of the sampled color. This is done so that the appearance of the surface is not completely reflective.

Technique

In the render loop, an application sets the current technique ID3DXEffect::SetTechnique. This technique contians a single pass which calls a vs_2_0 vertex shader and a ps_2_0 pixel shader.

technique TEnvironmentMap
{
    pass P0
    {
        VertexShader = compile vs_2_0 VS();
        PixelShader = compile ps_2_0 PS();
    }
}

Pixel Shader

The pixel shader is also very simple, thanks to the CubeMapLookup helper function. The pixel shader is passed in the output of the vertex shader, and then returns a single color, marked by the COLOR semantic just after the functions argument list.

The first line of the pixel shader sums the diffuse and specular color to make the final color. The second line adds an additional color that is returned by the CubeMapLookup helper function; this is the cubic environment map sample that results from looking up the texture coordinates that were calculated by the vertex shader.

struct VS_OUTPUT
{
    float4 Pos  : POSITION;
    float4 Diff : COLOR0;
    float4 Spec : COLOR1;
    float3 VolTexcoord : TEXCOORD0;
    float3 CubeTexcoord : TEXCOORD1;
};
float4 PS ( VS_OUTPUT In) : COLOR
{
    float4 OutColor;

    OutColor = In.Diff + In.Spec;

    OutColor += CubeMapLookup(In.CubeTexcoord);

    return OutColor;
}


Goal 4 - Procedural Texture Tutorial

In this lesson you'll be using the HLSL to generate a volume texture procedurally. If you get stuck, refer to the Goal4_Solution.fx file inside the solutions directory for the suggested answer. Most of the steps can be implemented in many different ways, so don't worry if your code is different from the solution.

The procedural texture goal is divided into two tasks:

  1. Do a volume texture lookup.
  2. Generate a procedural texture.

Extra Credit: Use if statements to create a volume checkerboard texture.

Setup

Preparation

Open Goal4.fx. If you have the SDK installed, the .fx file is located at:

(SDKRoot)\Samples\C++\Direct3D\Tutorials\HLSLWorkshop\

Description

The default render technique is HemisphereDiffuseSpecular, which uses the full hemispheric lighting equation developed in Goal 1 - Hemispheric Lighting Tutorial. In addition, the model shows the environment mapping developed in the previous lesson (Goal 3 - Environment Mapping):

Note that the animation calculation added in lesson 2 has been commented out to make things easier.

Task 1: Do a volume texture lookup.

Preparation

Locate Goal 4A in the code and follow the instructions.

Description

Simply sample from the volume texture at the provided coordinate. Assume for now that the texture has already been procedurally generated, although this will actually be done during the next step.

Use the provided VolTexcoord and the tex3D (Direct3D 9 HLSL) intrinsic function to do the texture lookup. Unlike the cubemap lookup (from lesson 2), it is easier to scale down the values of the volume map in the function that generates the volume instead of doing it here, so no scale should be required.

Solution

return tex3D(VolumeTexture, VolTexcoord);

The volume texture currently contains a solid yellow color, which yields the following render output when the sampled texture color is added to the diffuse color:

Task 2: Generate a procedural texture.

Preparation

Locate Goal 4B in the code and follow the instructions.

Description

Use the D3DXFillVolumeTextureTX function to execute this function for every texel in the volume texture. The height, width, depth, and function name are all described in the texture definition. The input is the position of the texel in the texture. In this case it is a three-dimensional coordinate that ranges from 0 to 1 on all axes (x = width, y = height, z = depth). The return value is the color stored at the texel position specified by the input position.

The noise (Direct3D 9 HLSL) intrinsic is a good start for a procedural texture. Even by itself it can give a nice grainy texture. One thing to remember about the noise (Direct3D 9 HLSL) function is that it is a good idea to scale up the access to it, because the range of noise on inputs of 0 to 1 is not as interesting as that of 0 to 500. You get a more random-looking set of values then. The noise (Direct3D 9 HLSL) function outputs values between 0 and 1, so you might want to scale the return value down to limit the effect.

Solution

return noise(Pos * 500) * 0.5f;

The speckles added by the procedural texture give the appearance of metal shavings within a glossy paint layer:

This completes Goal 4 of the shader workshop. The tutorials are designed to make it easy to experiment with the code. Don't be afraid to experiment with different values for noise to see if you can create other interesting procedural textures.


Goal 5 - Shader Debugging Tutorial

This tutorial will launch the debugger and show you how to debug a vertex shader.

If you are having trouble getting the debugger to work, see Goal 5 - Shader Debugging Tutorial to understand the tools you must have installed. Once you have completed the tutorial, many of the debugger features are listed in the Getting Started Debugging Shaders (Direct3D 9).

The shader debugger tutorial is divided into several tasks:

  1. Task 1: Launching Visual Studio .NET
  2. Task 2: Opening a Visual Studio .NET project
  3. Task 3: Building a Debug Project
  4. Task 4: Starting the debugger
  5. Task 5: Setting a breakpoint
  6. Task 6: Viewing the disassembly code
  7. Task 7: Setting conditional breakpoints

Task 1: Launching Visual Studio .NET

Launch Visual Studio .NET (either version 2002 or 2003).

If neither of these versions is available, you need to install Visual Studio .NET. Go to Setting Up the Tools for install instructions.

Task 2: Opening a Visual Studio .NET project

  1. From the File menu, click Open Solution.
  2. In the file open dialog box, open the file BasicHLSL which is installed by the SDK into the following default location:
    C:\DX90SDK\Samples\C++\Direct3D\BasicHLSL\BasicHLSL

    If you cannot find BasicHLSL you may need to install the latest version of the DirectX SDK. For instructions, see Install DirectX9.

Task 3: Building a Debug Project

  1. From the Build menu, click Configuration Manager to make sure Debug is selected.
  2. Remove the first comments in the following two lines:
    //#define DEBUG_VS   // Uncomment this line to debug vertex shaders
//#define DEBUG_PS   // Uncomment this line to debug pixel shaders

    The lines should now look like this:

    #define DEBUG_VS   // Uncomment this line to debug vertex shaders
#define DEBUG_PS   // Uncomment this line to debug pixel shaders

    This sets the correct shader flags so that the shaders can be debugged.

  3. From the Build menu, click Build Solution to build the debug project.

Task 4: Starting the debugger

From the Debug menu, click Direct3D then Start With Direct3D Debugging to launch the debugger.

Visual Studio .NET window with Direct3D Debugging selected

This is also available with shortcut keys CTRL+ALT+F5.

Task 5: Setting a breakpoint

A breakpoint can be set in the code window.

  1. From the File menu, click Open.
  2. Select the BasicHLSL.fx file.
  3. Once the file has opened, click on a line of code (line 92 in this example) where you want to break and press the F9 key.

    This is what you will see when the debugger breaks. The breakpoint is marked by the filled circle to the left of line 92.

    You can now step through one line of code at a time by hitting F10. You can check the contents of any variable or register by placing the mouse over the variable and waiting for the value to pop up.

See Viewing Register Contents or Viewing_Device_State for more options for viewing state.

Task 6: Viewing the disassembly code

Disassembly code is a combination of the HLSL shader statements, and the assembly instructions generated by the HLSL compiler. From the Debug menu, click Windows then Disassembly to open the disassembly window.

With the shader paused at the breakpoint, you can hold the mouse over individual registers to see the contents, or even drag and drop a register into the watch window to look at the contents.

Task 7: Setting conditional breakpoints

Once a breakpoint is set, you may need a mechanism for stopping at this breakpoint only if a certain condition is met; for example, after some number of vertices have been processed, or only if a certain normal vector value is seen. This is called a conditional breakpoint because the break only occurs on this condition. Here is an example of how to set one.

  1. First right click on the breakpoint and select Properties.
  2. When the Breakpoint Properties dialog box opens, click the Condition... button.

  3. In the text box on the Breakpoint Conditions dialog box, enter an expression that evaluates to a Boolean result.

The conditional expression in this example is (Output.Diffuse.a == 1), which means that the debugger will only break on line 92 when the alpha component of the diffuse color is 1. (Since we set alpha to this value, this will always cause a break.) Conditional breakpoints offer a powerful method for fine tuning breakpoints, so that you can look at a particular subset of conditions while debugging.

See Getting Started Debugging Shaders (Direct3D 9) for more options for setting breakpoints and for debugging shader and Direct3D code simultaneously.


Samples

The samples in this section show how to use Direct3D and D3DX in a C/C++ application. Once you have mastered the tutorials, you are ready to jump into the samples. Some of these samples demonstrate the latest features of Direct3D 9. Other samples demonstrate existing functionality that is fundamental to using Direct3D.

Samples

These samples demonstrate the newest techniques incorporated into DirectX. Although DirectX samples include Visual C++ project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly.

  • Antialias Sample
  • IrradianceVolume Sample
  • BasicHLSL Sample
  • Blobs Sample
  • CompiledEffect Sample
  • Config System Sample
  • CustomUI Sample
  • DepthOfField Sample
  • EffectParam Sample
  • EmptyProject Sample
  • EnhancedMesh Sample
  • FragmentLinker Sample
  • HDRCubeMap Sample
  • HDRFormats Sample
  • HDRLighting Sample
  • HLSLwithoutEffects Sample
  • Instancing Sample
  • LocalDeformablePRT Sample
  • MeshFromObj Sample
  • MultiAnimation Sample
  • OptimizedMesh Sample
  • ParallaxOcclusionMapping Sample
  • PixelMotionBlur Sample
  • PostProcess Sample
  • ProgressiveMesh Sample
  • PRTSimulator (prtcmdline.exe)
  • PRT Demo Sample
  • IrradianceVolume Sample
  • ShadowMap Sample
  • ShadowVolume Sample
  • SimpleSample Sample
  • SkinnedMesh Sample
  • StateManager Sample
  • Text3D Sample
  • UV Atlas Command-Line Tool

Follow the instructions for Sample Code contained in the license agreements within the following folder:

(SDK root)\Documentation\License Agreements


Antialias Sample

Multisampling attempts to reduce aliasing by mimicking a higher resolution display using multiple sample points to determine each pixel's color. This sample shows how the various multisampling techniques supported by your video card affect the scene's rendering. Although multisampling effectively combats aliasing, under particular situations it can introduce visual artifacts of its own. As illustrated by the sample, centroid sampling seeks to eliminate one common type of multisampling artifact. Support for centroid sampling is supported by the pixel shader 2.0 model and later.

Note

To better see the subtle pixel-level details explored by this sample, it might be helpful to zoom in on the screen with the magnifier tool. To launch the tool, type magnify in the Run dialog.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Antialias
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\Antialias.exe

Aliasing and Antialiasing

Raster displays use a finite number of pixels to display the scene; the greater the display resolution, the more accurately the scene can be represented. Visible artifacts exist in scenes where pixels can not adequately represent high-frequency data. This is most apparent at mesh edges, where straight-line data is approximated by a fixed number of pixels, creating a stairstep pattern; this form of aliasing is often called "jaggies," and becomes especially apparent when the polygon is in motion along the screen. Figure 1 shows aliasing in the sample's Triangles scene when multisampling is disabled.

Figure 1: Stairstep pattern on polygon edges is a common type of aliasing artifact.

Aliasing is a natural consequence of rasterization. For a review of raster displays and polygon rasterization, see Directly Mapping Texels to Pixels. As long as individual pixels are large enough to be distinguished from neighboring pixels, then there is no perfect way to eliminate aliasing. Ultimately, it is best to make pixels so small and so close together that aliasing can't be noticed. Be aware that inkjet printers also produce raster output, but it's nearly impossible to find any aliasing on a printout. This is because the common resolution for a square inch of paper is 300x300 dots per inch (dpi). The common resolution for a square inch on a computer display is 72x72 pixels. Comparatively, there are more than 17 times as many dots on a printed page than on a monitor. Of course, the other way to make the pixels appear smaller is to increase your viewing distance from the monitor. This appears to make the "jaggies" disappear once you back up far enough. At a certain point, you would be unable to distinguish between a cluster of 4 pixels and a pixel that was 4 times larger but had the same average color.

Following this logic, one way to combat aliasing is with oversampling. Oversampling is a technique that renders the scene at a higher resolution than the display resolution. For example, if your display resolution is 800x600 pixels and you render the scene at 1600x1200, each pixel is responsible for displaying a 2x2 region of the scene texture. The best way to approximate a 2x2 region is the mathematical average of all 4 colors. It has the advantage of noticeably reducing aliasing artifacts in your scene; however, it requires a larger back buffer and, therefore, a higher fill cost. Oversampling is not implemented by Direct3D (nor is it recommended due to the disadvantages just mentioned).

Another technique for combatting aliasing is multisampling. Multisampling reduces the overhead of oversampling, by emulating the sub-pixel averaging behavior without actually computing each sub-pixel's color.

Rasterization compares the location of the edges of a polygon against the location of the center of a pixel (the sampling point). If the polygon covers the center of the pixel, then the polygon determines the pixel's color. Multisampling extends rasterization by using a pattern of sampling points instead of the pixel's center (see Figure 2).

Figure 2: Single point-sample pixel color vs. four-point multisampled pixel color.

During multisampling, the final pixel color is a combination of the sampled pixel color and the number of samples that are covered by the polygon. In the top half of Figure 2, the polygon covers the single sampling point so the pixel color is 100 percent of the polygon's color. In the bottom half of Figure 2, only two of the four sampling points are covered by the polygon, so the polygon color contributes 50 percent of the pixel color.

During multisampling, the rasterization process tests multiple sample points inside each pixel so it might seem that multisampling is just as expensive as oversampling. However, multisampling doesn't run the pixel pipeline at every sampling point. Instead, a single pixel sample determines the color at the pixel center, and the percentage of sampling points covered by the polygon is multiplied by the pixel color. The result is that multisampling increases the accuracy of the pixel color without increasing the amount of sampling that is necessary by oversampling. Figure 3 shows how multisampling greatly reduces the "jaggies" seen in the same scene from Figure 1:

Figure 3: Multisampling reduces the noticeability of aliasing.

One important point to note is that Direct3D does not specify the sampling point patterns, only the number of sampling points (as shown in Figure 4). That means that the exact same scene under the exact same multisampling settings could appear slightly different depending on the graphics card used.

Figure 4: Multisampling patterns from various vendors.

Direct3D does not define the layout of sample points, only the number of sample points; hardware vendors decide patterns for supported multisampling modes. A selection of valid 4-sample multisampling patterns is shown above.

Centroid Sampling

As mentioned earlier, a key point to the efficiency of multisampling is that the pixel pipeline is only run once per pixel per polygon. The screen location used to determine the polygon's color is typically the center of the pixel, but this can lead to a problem: if a polygon covers one or more sample points but does not cover the pixel's center, the polygon's color will be determined at a point which does not actually lie on the polygon (see Figure 5):

Figure 5: The polygon covers two of the four sampling points and will therefore contribute 50 percent of the pixel's color.

Normally, this isn't a problem; however, if the polygon is textured you should be aware that the sampled texels could lie outside of the polygon's UV boundaries. Developers often pack several small textures onto a large texture, sometimes called an "atlas" texture, in order to minimize texture changes (for example, light maps are often stored this way). If the atlas texture features high-contrast differences, sampling at the pixel's center can introduce artifacts at the polygon edges. This is most visible when the polygon is rotated to be parallel with the view vector. Stated another way, if the polygon is at a high glancing angle, then the iterated texture coordinate at the pixel's center could be well beyond the polygon's UV boundaries.

Try running the sample's Triangles scene with the multisampling type set to D3DMULTISAMPLE_NONE and texture filtering set to D3DTEXF_POINT. You should not be able to see any non-white pixels under the Texturing Artifacts label. Now enable multisampling and notice that the outline of a triangle appears, as shown in Figure 6:

Figure 6: Example of multisampling texturing artifacts (left) when rendering a triangle with this texture (right).

The left side of Figure 6 shows the texturing artifacts that can happen when texture coordinates get interpolated beyond the polygon's UV boundary. In this case, the polygon covers two of the four sampling points but does not cover the pixel's center. The right side of Figure 6 shows the applied to the triangle that highlights the texturing artifacts. Black texels are outside the triangle's UV coordinate boundaries. The triangle is textured such that texels that are contained or crossed by the triangle's UV boundaries are white, and all other texels are black; therefore, the triangle will be invisible against the white background except where texels beyond the UV boundary are being sampled. Note that it's normal for linear and anisotropic filtering to sample from texels outside the UV boundary; this follows directly from how bilinear filtering works.

The texturing artifacts are visible when using point filtering with multisampling because multisampling extends the rasterized area of the triangle to include all pixels in which sampling points are covered, even when the pixel center is not. The solution to this problem is centroid sampling, which adjusts the position used for determining polygon color to be the center of all the sampling points covered by the polygon. The solution to this problem is centroid sampling, which is shown in Figure 7:

Figure 7: Multisampling versus centroid multisampling.

Figure 7 contrasts a four-point multisampling pattern (on the left) with a four-point centroid multisampling pattern (on the right). Polygon coverage is indicated by the gray shaded region. The four-point sampling pattern is shown with blue dots and the texture sampling location is the red dots.

When centroid sampling is enabled, the sampled pixel position used for determining polygon color is adjusted to be the center of the sampling points covered by the polygon. This guarantees that a centroid-sampled location will always lie within the polygon being rendered. Place a check in the Centroid sampling checkbox and notice that the Texturing Artifacts label is again blank, indicating that centroid sampling is constraining the iterated texture coordinates to the triangle's UV boundary. Centroid sampling is automatically enabled for each pixel shader input that has a color semantic (see Shader Semantic Syntax). Alternately, you can enable centroid sampling on any HLSL pixel shader input by appending the centroid semantic as shown here:

//--------------------------------------------------------------------------------------
// Texture - Point sampled (centroid)
//--------------------------------------------------------------------------------------
float4 TexturePointCentroidPS( float4 TexCoord : TEXCOORD0_centroid ) : COLOR0
{
    return tex2D( PointSampler, TexCoord );
}

Similarly, to enable centroid sampling within an assembly shader, append the centroid semantic to the declaration:

dcl_texcoord0_centroid v0

Be aware that centroid sampling does not influence pixel rate-of-change calculations. This means that mipmap levels are still chosen from rate-of-change calculations at pixel centers. Also note that centroid sampling should primarily be used with atlas textures as described above; under the typical texture usage where the entire texture maps directly to the mesh, centroid sampling will actually introduce slight texturing errors.

The sample's Spheres scene and the sample's Quads scene contain low-tessellated and high-tessellated meshes textured with a checker pattern. Try playing with various multisampling, filtering, and centroid sampling settings to see how the adjustments influence the scene.

References

  • Mitchell, Jason. DirectX 9 High Level Shading Language. Siggraph 2004 presentation.
  • Burrows, Mike et al. Advanced Visual Effects with Direct3D. Game Developers Conference 2004 presentation.


BasicHLSL Sample

This sample shows a simple example of the high-level shader language (HLSL) using an effect interface.

Path

Source: | (SDK root)\Samples\C++\Direct3D\BasicHLSL
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\BasicHLSL.exe

Sample Overview

This sample simply loads a mesh, creates an effect from a file, and then uses the effect to render the mesh. The effect that is used is a simple vertex shader that animates the vertices based on time.

How the Sample Works

First the sample loads the geometry with D3DXLoadMeshFromX and calls D3DXComputeNormals to create mesh normals if there aren't any. It then calls OptimizeInplace() to optimize the mesh for the vertex cache, then loads the textures using D3DXCreateTextureFromFile. Next, the sample calls D3DXCreateEffectFromFile to compile the effect text file to a ID3DXEffect* interface called m_pEffect.

Note that the D3DXCreateEffectFromFile takes flags which are needed to debug shaders with the Visual Studio .NET shader debugger. Debugging vertex shaders requires either a reference device or software vertex processing. Debugging a pixel shader requires a reference device.

The D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flags set various source code debugging options. Setting these flags will cause slower rendering since the shaders will be unoptimized and forced into software. All that is needed to turn these flags on with the sample code is to uncomment the #define DEBUG_VS or #define DEBUG_PS line from near the top of the file. This will also force the device into software processing by adding some code to CMyD3DApplication::ConfirmDevices. See Shader Debugger for more information about debugging shaders.

In CMyD3DApplication::Render, the sample sets the technique to use with a call to ID3DXEffect::SetTechnique and passes a D3DXHANDLE to the technique that was obtained upon initialization with a call to ID3DXBaseEffect::GetTechniqueByName. It is possible to pass a string name instead of a handle, but using a handle improves performance since this high frequency call does not have to spend time on a string compare.

The sample then sets variables used by the technique such as the World*View*Projection matrix and the time variable with various ID3DXEffect::Set* calls. To render, the sample calls ID3DXEffect::Begin which returns the number of passes required by the technique, then loops through each pass calling m_pEffect->Pass(iPass) and rendering the mesh with ID3DXBaseMesh::DrawSubset. When all the passes are done, it calls ID3DXEffect::End.


Blobs Sample

This sample mimics a metaball effect in screen space using a pixel shader. True metaball techniques deform surfaces according to pushing or pulling modifiers, and are commonly used to model liquid effects like the merging of water droplets. Metaball effects can be computationally expensive, however, so this sample implements a 3D metaball effect in 2D image space with a pixel shader.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Blobs
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\Blobs.exe

Sample Overview

Metaballs (also called Blinn blobs after James Blinn who formulated the technique) are included with most modeling software as an easy way to create smooth surfaces from a series of enclosed volumes (called blobs) which merge together; the apparent flow between blobs makes the technique particularly well suited for particle systems which model liquids.

The underlying technique is based on isosurfaces, which are 3D equations that define a closed volume. For instance, x2 + y2 + z2 = 1 defines a sphere of radius 1 centered at the origin. This idea can be extended to arbitrary 3D functions. That is, an isosurface is defined by the set of all points along a continuous function which are equal to an arbitrary constant value. Individual metaballs are often implemented as spheres defined by Gaussian distributions where the highest value exists at the sphere's center and all values above an arbitrary threshold are defined to be inside the sphere. Subtracting the threshold from the Gaussian height gives a surface height of zero at the blob edge. Since the surface is completely defined according to this threshold, the values of overlapping spheres can be added to produce a new surface. Figure 1 shows the smooth curve which results from the addition of two Gaussian curves.

Figure 1: Addition of Gaussian curves produces smooth blending

For a true metaball effect, these calculations would be made in 3D space. Instead, this sample performs the computation in 2D screen space, which gives a nice visual effect requiring few computations. However, one limitation you may notice is that accuracy is lost when blobs in the background merge with blobs near the camera as they align along the view vector.

How the Sample Works

The individual blobs are described according to world-space position, size, and color. Before each frame is rendered, the blob positions are animated in FrameMove and then FillBlobVB projects each blob into screen-space and fills the vertex buffer with corresponding billboard quads. The vertex format of these billboards is shown below:

struct VS_OUTPUT
{
    float4 vPosition : POSITION;    // Screen-space position of the vertex
    float2 tCurr     : TEXCOORD0;   // Texture coordinates for Gaussian sample
    float2 tBack     : TEXCOORD1;   // Texture coordinates of vertex position on render target
    float2 sInfo     : TEXCOORD2;   // Z-offset and blob size
    float3 vColor    : TEXCOORD3;   // Blob color
};

The coordinates stored in tCurr are used to sample a 2D Gaussian texture which defines the sphere. The coordinates stored in tBack are used to sample data from previously-rendered blobs, and could also be used to blend against a background texture. These pre-transformed vertices are handed directly to the BlobBlenderPS pixel shader:

PS_OUTPUT BlobBlenderPS( VS_OUTPUT Input )
{
    PS_OUTPUT Output;
    float4 weight;

    // Get the new blob weight
    DoLerp( Input.tCurr, weight );

    // Get the old data
    float4 oldsurfdata = tex2D( SurfaceBufferSampler, Input.tBack );
    float4 oldmatdata  = tex2D( MatrixBufferSampler, Input.tBack );

    // Generate new surface data
    float4 newsurfdata = float4((Input.tCurr.x-0.5) * Input.sInfo.y,
                                (Input.tCurr.y-0.5) * Input.sInfo.y,
                                0,
                                1);
    newsurfdata *= weight.r;

    // Generate new material properties
    float4 newmatdata = float4(Input.vColor.r,
                               Input.vColor.g,
                               Input.vColor.b,
                               0);
    newmatdata *= weight.r;

    // Additive blending
    Output.vColor[0] = newsurfdata + oldsurfdata;
    Output.vColor[1] = newmatdata + oldmatdata;

    return Output;
}

The DoLerp helper function performs a bilinear filtered texture sample since bilinear filtering of floating-point textures is typically not implemented by the graphics driver. Each blob billboard is rendered to a set of temporary textures, one to store accumulated color data and one to store accumulated surface normal data:

Figure 2: Surface normal buffer Figure 3: Color buffer

The blended normal and color data are used by the BlobLightPS pixel shader for a final lighting pass which samples into an environment map based on the averaged surface normal:

float4 BlobLightPS( VS_OUTPUT Input ) : COLOR
{
    static const float aaval = THRESHOLD * 0.07f;

    float4 blobdata = tex2D( SourceBlobSampler, Input.tCurr);
    float4 color = tex2D( MatrixBufferSampler, Input.tCurr);

    color /= blobdata.w;

    float3 surfacept = float3(blobdata.x/blobdata.w,
                              blobdata.y/blobdata.w,
                              blobdata.w-THRESHOLD);
    float3 thenorm = normalize(-surfacept);
    thenorm.z = -thenorm.z;

    float4 Output;
    Output.rgb = color.rgb + texCUBE( EnvMapSampler, thenorm );
    Output.rgb *= saturate ((blobdata.a - THRESHOLD)/aaval);
    Output.a=1;

    return Output;
}

Which yields the final composite image:


CompiledEffect Sample

This sample shows how an ID3DXEffect object can be compiled when the project is built and loaded directly as a binary file at run time.

Path

Source: | (SDK root)\Samples\C++\Direct3D\CompiledEffect
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\CompiledEffect.exe

Overview

Large-scale projects may contain dozens or even hundreds of shader and effect files. Compiling these files at run time can cause a noticeable delay during initialization, and this delay is incurred each and every time the project is run. In spite of this, it is beneficial to compile at run time when developing or debugging effect files as this allows more debugging flexibility.

Once development and/or debugging of these shaders are completed, these files can be compiled as part of your project build process. Since these files will only need to be compiled when changes are made, no additional build time is spent on effect files which have already been debugged and compiled.

The process illustrated in this sample is identical, whether compiling a complete effect object or individual shaders. All that would change would be the shader profile passed to the compiler on the command line.

How the Sample Works

The code is virtually identical to the HLSLwithoutEffects Sample except for a couple important differences:

  • The call to D3DXCreateEffectFromFile is passed the filename of the compiled effect CompiledEffect.fxo instead of the filename of the effect source CompiledEffect.fx.
  • No debugging flags are passed to D3DXCreateEffectFromFile. Instead, flags are passed to the effect compiler to enable shader debugging. The choice of compiler flags depends on the Visual Studio .NET build configuration chosen.

The program used to compile shaders at build time is fxc. This command-line utility ships with the SDK, and wraps the ID3DXEffectCompiler calls (which are called to compile the shader). You could create your own shader compiler fairly easily using the ID3DXEffectCompiler, but fxc should be flexible enough for most needs. The commands used to build release and debug versions of a typical .fx file are:

Release: | fxc /Tfx_2_0 /FoMyEffect.fxo MyEffect.fx
Debug: | fxc /Od /Zi /Tfx_2_0 /FoMyEffect.fxo MyEffect.fx

Run fxc without any arguments for usage information.

Build Environment Configuration

Here are the steps taken to configure the build environment. These steps should be performed for every effect file you want to be compiled as part of the build process:

  1. Open the CompiledEffect sample inside Visual Studio .NET.
  2. From within the Solution Explorer window, right click on CompiledEffect.fx and select Properties from the context menu.
  3. Select Configuration Properties/Custom Build Step to view the custom build step directives. The specific compile command issued depends on the project build configuration, as you can verify by scrolling through the Configuration combo box.


Config System Sample

The Config System sample showcases a configuration system using a database of hardware device models. The sample detects the hardware on the system, and then looks up the database to find custom behavior defined for those existing devices.

Path

Source: | (SDK root)\Samples\C++\Direct3D\ConfigSystem
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\ConfigSystem.exe

Sample Overview

The Config System sample is a demonstration of a database-driven application configuration system. Today, several shipping games, such as Halo PC, Microsoft Flight Simulator, Microsoft Combat Flight Simulator, and Rise of Nations are already taking advantage of this versatile and powerful system. 3D graphic cards have a set of capabilities that they support to make better-looking images. Realistically, not every card supports the exact same set of capabilities; therefore, applications need to check each card for the capabilities it supports. In Direct3D, device capabilities are reported in the capability structure, or cap bits for short, that can be obtained by calling IDirect3DDevice9::GetDeviceCaps. The cap bits structure details what the device can and cannot support. Usually, the cap bits provide a fast and easy way to know what rendering features an application can utilize.

However, the cap bits are not always accurate or complete. Devices may mistakenly report cap bits which they actually do not support, or which are broken. Furthermore, a capability may be enabled at the expense of severe performance penalty. In this case, many developers prefer to have a steady performance over a particular feature. To overcome these issues associated with the cap bits, an application developer could test all supported hardware models during development, then record the list of hardware that the application has trouble with (as well as the specific problems each device has) in a database. This allows an application to detect the host system hardware at run time. If the hardware model is found, the database provides the detail as to what special actions the application must take to take advantage of the hardware.

How the Sample Works

The sample demonstrates a database-driven configuration system with three code components:

  • The configuration system client makes use of the system as well as handling necessary sample code, such as rendering and animation routines. This is located in Main.cpp.
  • The configuration database implements the configuration database as a Component Object Model (COM) object. The database object handles parsing of the configuration file. This is located in ConfigDatabase.cpp.
  • The configuration manager encapsulates access to the database and provides efficient access to the properties. This is located in ConfigManager.cpp.

The sample represents a simple game. When the sample is run, the user is in a closed room with several balls on the ground. The user can shoot additional balls and watch them bounce around. At the bottom of the screen, a list of properties is listed. These properties are parsed and loaded from the configuration database file based on the display and audio devices that the sample detects. The existence of these properties affects how the sample runs (for instance, how it renders or handles sound).

Graphics Card Capabilities

A collection of the capabilities exposed by current drivers of graphics hardware available on the market today are available as separate files in the DirectX SDK.

See the Graphics Card Capabilities sample in the DirectX Sample Browser for more details.

The Database

In the sample, the configuration database file is a text file. Each line is either a statement or keyword that affects parsing, a property definition, or a comment that starts with a double slash. When parsing the database, the text letter case is ignored. The file contains three sections:

  • Section 1: Hardware Requirements
  • Section 2: Named Property Sets
  • Section 3: Hardware Devices in the Database

Section 1: Hardware Requirements

The first section lists the hardware requirement of the sample. It starts with the Requirements statement followed by one or more properties, or property-value assignments. The section ends with a break statement as shown below:

Requirements
    OS=Win98
    CpuSpeed=733
    Memory=128
    VideoMemory=64
    DirectX=4.9.0.902
    DiskSpace=100
    break

Here are the values for each of the requirements:

Requirement Property | Description
OS | Operating system version. Supported values, in ascending order, are: Win95, Win98, WinME, Win2k, WinXP, and Win2003.
CpuSpeed | Processor speed in megahertz.
Memory | Amount of system memory in megabytes.
VideoMemory | Amount of video memory in megabytes.
DirectX | DirectX version on the system in this format: #.#.#.#, where # denotes a decimal digit
DiskSpace | Amount of available disk space in megabytes. This requirement is here for illustrative purposes only and is not checked by the sample.

Section 2: Named Property Sets

The second section is a list of named property sets. A property set groups related custom properties under one name. Each property set is a set of custom properties followed by a break statement. It starts with the PropertySet statement followed by one or more properties, or property-value assignments. The section ends with a break statement as shown below:

PropertySet = "MyPropSet"
    CustomPropertyName1          // Name
    CustomPropertyName2 = Value  // Name/Value
    break

Each property set begins with the name of the property set enclosed in quotes; this example contains two custom properties. A custom property is a name/value pair, or simply a name by itself. It is defined and applied to devices by the application and it serves as a flag to signal the application that a special action should be taken when dealing with the devices to which this custom property is applied.

Note As you can see in the previous example, comments can be included by using a double forward slash notation (//).

A property set can refer to other property sets as shown here:

PropertySet = "SmallPropSet"
    CustomPropertyName1          // Name
    CustomPropertyName2 = Value  // Name/Value
    break

PropertySet = "BigPropSet"
    PropertySet = "SmallPropSet" // BigPropSet includes SmallPropSet's properties
    CustomPropertyName3          // Name
    CustomPropertyName4 = Value  // Name/Value
    break

The PropertySet statement is used in place of a custom property name, and its value is the name of the property set to include, in quotes. It is as if BigPropSet were defined like this:

PropertySet = "BigPropSet"
    CustomPropertyName1          // Name
    CustomPropertyName2 = Value  // Name/Value
    CustomPropertyName3          // Name
    CustomPropertyName4 = Value  // Name/Value
    break

Section 3: Hardware Devices in the Database

The third section lists the hardware device entries included in the database. In the sample, the database contains audio and display devices. The device entries are organized by vendors and device ids. Each entry must follow one of the following four formats:

Format 1: Vendor Definition

The vendor definition looks like this:

AudioVendor = 0x1102 "Audio card vendor name"       // For audio vendor
DisplayVendor = 0x10b4  "Display card vendor name"  // For display vendor

A vendor string follows the hexadecimal number vendor id with the vendor's name.

Format 2: Device Definition

The device definition looks like this:

0x1015 = "Device Name"

The device hexadecimal number is followed by a string with the device name. You can use "unknown" for the device string to represent all other devices from the current vendor that are not found in the database.

Format 3: Custom Property Definition

A custom property or reference to a named property must be defined like this:

PropertyName1             // Name
PropertyName2 = Value     // Name/Value
PropertySet = "MyPropSet" // Apply all properties included in MyPropSet

The first example (without a value pair) is useful for enabling or disabling a particular feature, such as specular lighting. The second property (with a value pair) is useful when a parameter needs to be set to a different value for some devices. The third form is a reference to the previously named property set MyPropSet, as if all properties in the previously named property set were listed.

Format 4: Conditional Property Definition

A conditional property is a custom property (and/or named property set references) embedded in an if block, and are only applied when the specified condition is true. Additionally, you may nest if blocks. Here is an example:

if identifier operator value
    PropertyName3 = Value
    PropertySet = "MyPropSet"
endif

Where identifier can be one of the following:

Identifier | Value | Description
ram | Number in decimal or hexadecimal (begins with 0x) | Amount of system memory.
videoram | Number in decimal or hexadecimal (begins with 0x) | Amount of video memory.
SubSysID | Number in decimal or hexadecimal (begins with 0x) | The subsystem id of the hardware device.
Revision | Number in decimal or hexadecimal (begins with 0x) | The revision number of the hardware device.
driver | Full version format, defined as #.#.#.#, where # denotes a number in decimal or hexadecimal | The device's driver version.
guid | A globally unique identifier (GUID) in the format of ########-####-####-####-############ where each # denotes a hexadecimal digit | The device's GUID.
OS | One of the following: Win95, Win98, Win98SE, WinME, Win2k, WinXP | The computer's operating system.
Any DWORD members of D3DCAPS9 | Number in decimal or hexadecimal (begins with 0x) | Values such as Caps, Caps2, and so on.

And where operator can be one of the following:

= or == | True if the two operands are equal in value.
<> or != | True if the two operands are not equal in value.
>= | True if the left operand is greater than or equal to the right one in value.
<= | True if the left operand is less than or equal to the right one in value.
> | True if the left operand is greater than the right one in value.
< | True if the left operand is less than the right one in value.
& | Performs a bit-wise AND operation with the two operands and returns the result.

Do not use quotes around the identifier or its value.

Parsing the Device Database

The sample separately parses the device's audio and display properties from the database. The following discussion describes parsing of display device properties, though the process also applies to audio device properties.

To match for a specific hardware device, the parser first searches for a display vendor statement with a matching vendor id. Once a matching vendor definition is found, the parser skips vendor definitions after the matching definition. This is done because sometimes a vendor has several vendor ids, and they are defined with several vendor definition lines. Next, the parser looks for any and all custom properties after the vendor definition but before a device definition. The properties found here will be applied to all devices from that particular vendor. Therefore, properties that apply to all devices from a particular vendor should be placed immediately after the vendor definition when constructing the database.

After parsing the vendor-wide properties, the parser continues to search for a device definition line. The parser then searches all the properties. The parser stops when it finds a break statement. It does not stop when it finds another device definition. This behavior is useful as it becomes easy to add properties that apply to multiple devices.

The following is an example database that defines properties for devices from a particular vendor:

DisplayVendor = 0x1101 "Display Vendor Name"
DisplayVendor = 0x1102 "Display Vendor Name"
    DisableSpecular        // Disable specular lighting
0x1001 = "Card Model 1"
    ForceShader=14         // Restrict shader to 1.4 or lower
0x1002 = "Card Model 2"
    MaximumResolution=1024 // Max resolution 1024x768
    break
0x1003 = "Card Model 3"
Unknown = "Unknown"
    UseAnisotropicFilter   // Use anisotropic filtering
    break

In the above example, three devices from a display vendor are defined. The vendor has two known vendor ids: 0x1101 and 0x1102. DisableSpecular appears before any device definition for this vendor; therefore, it applies to all devices from this vendor.

Specifying a Default for All Devices

The database can specify a default set of properties to apply to all devices from all vendors, whether or not they are included in the database. To do this, the database can include two ApplyToAll property sets. One appears before the hardware vendor definitions, and the other appears after. The syntax of an ApplyToAll property set is as follows:

ApplyToAll
    Property1
    Property2
    break

ApplyToAll property sets, like any other property set, should end with a break statement. The first ApplyToAll block is parsed before the hardware vendor section is; therefore, the first block defines default properties that can be overridden by vendor-specific or device-specific properties and the second ApplyToAll is parsed after parsing the hardware vendor section so the second block defines default properties that cannot be overridden.

Custom Properties Implemented by the Sample

Custom properties are designed and supported by the application. The sample implements a list of common custom properties to demonstrate typical uses and the affect that properties can have on application behavior. The sample also lists a number of additional properties not implemented in the sample, but which may be valuable to other previously-released applications. These serve the purpose of indicating the types of problems hardware and drivers can have.

The custom properties which are implemented by the sample are detailed below:

Property | Value | Description
MaximumResolution | 640, 800, 1024, etc. | This limits the maximum resolution used by the sample by specifying the width of the resolution. For instance, to limit resolution to 800 x 600, use MaximumResolution=800.
UseFixedFunction | None | Use the fixed function pipeline. When this property is not present, the renderer uses programmable shaders. In the sample, fixed-function uses per-vertex lighting, while pixel shader 2.0 or higher uses per-pixel lighting. The visual difference is dramatic.
ForceShader | 0, 11, 12, 13, 14, 20, A2, B2, 30 | Use a particular pixel shader version, even if the graphic device supports a newer version. For instance, to force the renderer to use ps_1_4, use ForceShader=14. In the sample, pixel shader 2.0 or higher uses per-pixel lighting. The visual difference is dramatic.
UseAnisotropicFilter | None | Use anisotropic filtering for textures.
DisableSpecular | None | Warn the user about the presence of known prototype cards. When this is present, the sample brings up a message box to inform the user.
UnsupportedCard | None | This property is used to disallow running the sample with cards below specification. When this is present, the sample brings up a message box to inform the user, then terminates.
OldDriver | None | This property is used to warn the application user that the display driver is older than the version tested by the developer. The sample brings up a message box to inform the user.
InvalidDriver | None | This property is used to disallow running the sample with display drivers that are known to cause severe problems with the application. When this is present, the sample brings up a message box to inform the user, then terminates.
OldSoundDriver | None | This property is used to warn the application user that the sound driver is older than the version tested by the developer. The sample brings up a message box to inform the user.
InvalidSoundDriver | None | This property is used to disallow running the sample with sound drivers that are known to cause severe problems with the application. When this is present, the sample brings up a message box to inform the user, then terminates.
UMA | None | This property is used to alert the application that the display card on the system is a Unified Memory Architecture (UMA) card. A UMA display card uses part of the system memory as its video memory. When this property is present, the amount of available video memory on the system is calculated from the system memory size.

The following properties are included in and parsed from the database, but not implemented by the sample.

Property | Value | Description
LinearTextureAddressing | None | When this is defined, non-square textures use texture coordinates that have not been normalized.
DoNotUseMinMaxBlendOp | None | When this is defined, the display device does not handle minimum or maximum blending mode properly, so these should be avoided.
DisableDriverManagement | None | With this property, the device should be created with D3DCREATE_DISABLE_DRIVER_MANAGEMENT so that resource management is done by Direct3D, not the driver.
DisableAlphaRenderTargets | None | When this is defined, the application should not allow render targets with an alpha channel.
DisableRenderTargets | None | All render targets should be disabled.
EnableStopStart | None | The sound card supports calling a IDirectSoundCaptureBuffer8::Start or IDirectSoundCaptureBuffer8::Stop method at a high frequency.

Loading and Accessing the Database

When an application needs to access the content of the database, it calls the static method IConfigDatabase::Create, which initializes and returns an IConfigDatabase object. The application should then call the IConfigDatabase::Load method, passing in the following parameters:

  • the configuration database file path
  • a SOUND_DEVICE structure with information about the sound device on the system
  • a D3DADAPTER_IDENTIFIER9 structure with similar information about the display device on the system
  • the display cap bits as returned by Direct3D
  • the amount of system and video memory
  • the processor speed

IConfigDatabase::Load parses the configuration database file and saves the requirements and relevant custom properties based on the detected display and sound devices. Internally, IConfigDatabase saves this information as a property name/value pair. Once the operation is complete, the application can query for available requirements or custom properties and obtain the string pairs.

Because the properties control how the application renders, the application will very likely need to check the value of properties in a rendering loop. Because comparing strings is not as efficient as comparing two numbers, it is generally not a good idea for the rendering loop to query properties directly from IConfigDatabase. The CConfigManager helper class acts as a code layer on top of IConfigDatabase. This application-customized class provides detection for hardware on the system. It also queries its IConfigDatabase for properties, then stores the property values in its member variables. During rendering, the application can check the value of the member variables to determine the appropriate behavior instead of querying string pairs from IConfigDatabase.

Running in Safe Mode

The sample also demonstrates a simple implementation of safe mode. Safe mode is a mode in which the application runs everything in the lowest possible settings, such as the lowest resolution or disabling any feature that is not supported by every video card. In safe mode, the sample saves the state of the application in a file in case the application unexpectedly ends (allowing the status data to persist outside of the application lifetime). To do this, the sample creates an empty file at startup (called Launch.sta) and deletes this file before it exits. The sample writes this file to the following path:

Drive:\Document and Settings\username\Local Settings\Application Data\ConfigSystem

Note that username as used in the previous path is the log-in name of the current user. The following folder is used by applications local to the system to store information for the current user.

Drive\Document and Settings\username\Local Settings\Application Data

This path can be obtained by calling SHGetFolderPath with CSIDL_LOCAL_APPDATA. The sample uses this path instead of the application executable directory because it is the best practice to write user-specific data to a location that is specific to the user. Not every user will have access to the executable directory all the time. Therefore, writing user-specific data to the executable directory should be avoided.

When the sample is launched and before it writes Launch.sta, it determines whether Launch.sta already exists or not. If it does exist, then the implication is that the previous launch of the application encountered an unrecoverable problem and could not exit normally. This is a good indication to turn on safe mode so that the application can minimize the chance of a recurring problem.

Summary

A configuration system using a database allows applications to precisely define the behavior to employ for a specific hardware device. It is worth noting that the properties in the database are defined by the client application, and the application is free to extend the database by adding more properties as it requires, or adding more hardware vendors or devices as newer hardware becomes available. For applications that get patched or updated, the most up-to-date configuration database file can accompany the patch to ensure that customers with newer hardware can still benefit from the system.


CustomUI Sample

This sample is a simple demonstration of the UI subsystem implemented by DXUT. DXUT provides the common code and infrastructure found in most Direct3D applications. One area of DXUT is user interface support. DXUT contains commonly used control objects, such as buttons and check boxes, that both windowed and full screen Direct3D applications can use to implement their user interfaces.

Path

Source: | (SDK root)\Samples\C++\Direct3D\CustomUI
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\CustomUI.exe

How the Sample Works

This sample demonstrates how an application that uses DXUT can take advantage of the framework's user interface support. DXUT supports the following control types:

Control type | Class that implements it
Statics | CDXUTStatic
Buttons | CDXUTButton
Radio buttons | CDXUTRadioButton
Check boxes | CDXUTCheckBox
Combo boxes | CDXUTComboBox
Sliders | CDXUTSlider
Edit boxes | CDXUTEditBox
Edit boxes with IME capability | CDXUTIMEEditBox

All of the DXUT controls work similarly to Windows controls. They are implemented entirely from scratch and do not use HWND or any Windows control underneath. They are also rendered with Direct3D, and therefore can be used by both windowed and full screen Direct3D applications.

The CDXUTIMEEditBox is an edit box with IME (Input Method Editor) functionality. When entering text with CDXUTIMEEditBox, the user can switch input language to one of the East Asian languages supported (Japanese, Korean, Simplified Chinese, and Traditional Chinese). When typing, CDXUTIMEEditBox renders IME windows with Direct3D, and it also supresses the default IME windows so that they will not corrupt the application window in full screen mode.

This sample starts by defining two CDXUTDialog objects: g_HUD and g_SampleUI. A CDXUTDialog serves as a container that encapsulates one or more controls. It sits between the application and the controls, so that the application can pass messages and rendering calls to CDXUTDialog, and CDXUTDialog will ensure that all of its controls receive the messages and get rendered properly. The controls themselves are designed to be used with a CDXUTDialog, not stand-alone. Applications are not limited to one CDXUTDialog object. They can use more at once, as this sample does.

The first thing the the sample has to do to initialize the CDXUTDialog objects is set the event callback function with the SetCallback method. As the user interacts with the UI controls, the controls can notify the sample about important events, so that it can respond accordingly. At this time the sample also initializes additional fonts that it will need. This is done with the SetFont method.

The next step that the sample has to do is create the controls it needs. This is achieved by calling the CDXUTDialog's AddXXX methods, such as AddButton. In the sample, g_HUD contains 4 buttons that provide standard functionalities that Direct3D samples have: view whitepaper, toggle between full screen and windowed mode, toggle between HAL and REF, and change 3D device settings. g_SampleUI contains the rest of the controls, which are sample-specific. After a control is added, its appearance can be modified. This is demonstrated in the sample as it modifies the appearance of the static controls as well as the combo box and IME-capable edit box.

Next, in OnResetDevice, are a number of calls to the CDXUTDialog's and controls' SetSize and SetLocation methods. This is because when the user resizes the application window, some dialogs and controls need to be resized and repositioned as well. It is worth noting that the CDXUTDialog's location is relative to the application window, while a control's location is relative to the CDXUTDialog it belongs.

To render the user interface, the sample calls the OnRender method of the two CDXUTDialog objects in its OnFrameRender function. CDXUTDialog will render the controls it contains in the correct order.

The final step required to make the UI work is passing messages to the controls. This lets them receive keyboard and mouse events from the user. In MsgProc, the sample calls CDXUTDialog's MsgProc method to pass down the messages. It is very important that if CDXUTDialog's MsgProc returns true indicating that the message has been handled, the sample sets *pbNoFurtherProcessing to true and returns immediately. Failure to do so will cause a message to be processed more than once, and this can cause undesirable behavior for certain Input Method Editor (IME) messages, such as double windows.

Event Callback

Certain events happen as the user interacts with the UI controls, such as checking or unchecking a check box, selecting a new item in a combo box, selecting a new item in a radio button group, etc. The application may be interested in such events, and it can be notified with the CDXUTDialog event callback mechanism. In the sample, a callback function, OnGUIEvent, is defined and passed as the parameter to the CDXUTDialog::SetCallback method. As a result, this function will get called whenever the user performs an interesting action with a UI control. The actions that can trigger a callback are:

  • Clicking a button (CDXUTButton)
  • Selecting a new item in a combo box (CDXUTComboBox)
  • Selecting a new item in a radio button group (CDXUTRadioButton)
  • Changing the check state of a check box (CDXUTCheckBox)
  • Changing the value of a slider (CDXUTSlider)
  • Pressing Enter in an edit box (CDXUTEditBox and CDXUTIMEEditBox)
  • In the callback, the type of event, the ID of the control that fired the event, and the control object are available to the application. The sample responds to the callback by retrieving content of the firing control and displaying it on screen.

Further Reading

For more information please refer to the technical articles entitled Installing and Using Input Method Editors and Using an Input Method Editor in a Game.


DepthOfField Sample

This sample shows several techniques for creating a depth-of-field effect in which objects are only in focus at a given distance from the camera and out of focus at other distances. Rendering objects out of focus adds realism to the scene. The methods it shows are reasonably cheap to perform on most hardware, and the depth of field post processing can easily be combined with other post process techniques such as image-based motion blur or high dynamic range (HDR) lighting.

Path

Source: | (SDK root)\Samples\C++\Direct3D\DepthOfField
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\DepthOfField.exe

Background

In CMyD3DApplication::InitDeviceObjects it loads the geometry with D3DXLoadMeshFromX and calls D3DXComputeNormals to create mesh normals if there aren't any. It then calls ID3DXMesh::OptimizeInplace to optimize the mesh for the vertex cache. It then loads the textures using D3DXCreateTextureFromFile.

CMyD3DApplication::RestoreDeviceObjects does the following:

  • Sets up the camera class. The camera class encapsulates handling mouse and keyboard input and updating the view matrix accordingly.
  • Calls D3DXCreateTexture to create a D3DUSAGE_RENDERTARGET A8R8G8B8 texture with the same height and width as the back buffer. If that fails, it tries again but without the D3DUSAGE_RENDERTARGET flag.
  • Creates a ID3DXRenderToSurface with D3DXCreateRenderToSurface to help render to the texture on cards that don't support render targets.
  • Loads the D3DX effect file into a ID3DXEffectxxx, and caches the D3DXHANDLE to all the parameters that it will set every frame.
  • Initializes effect parameters that don't change every frame, such as the material properties and render target texture, using ID3DXBaseEffect::SetVector and ID3DXBaseEffect::SetTexture.
  • Finds the first valid technique in the effect for the current device.
  • Creates a quad of vertices to be used in the post-processing pass. The quad has 6 sets of texture coords defined. Each set of texture coordinates is slightly shifted so when they are used in post process the pixel shader effect will be a blur. Note that the entire set of texture coordinates aren't used in every technique. How this quad is used will be explained below in more detail.
  • Scales the effect's kernel TwelveKernelBase from pixel space (where 1.0 means 1 pixel) to texture coordinate space and stores the result into a separate array labeled TwelveKernel.

In CMyD3DApplication::FrameMove it simply calls FrameMove() on the camera class so it can move the view matrix according the user input over time.

CMyD3DApplication::Render essentially does 2 things:

  1. It first renders the scene into a render target while it simultaneously calculates the blur factor and stores this in the alpha channel of the render target. An alpha value of 0 means that specific pixel is not blurry while an alpha value of 1 means that specific pixel is blurry.
  2. It then uses this render target with depth information stored in the alpha channel and renders a full screen quad to execute a pixel shader for each pixel in the final surface.

In more detail, the first part of CMyD3DApplication::Render uses the technique WorldWithBlurFactor which uses the vs_1_1 vertex shader called WorldVertexShader. This vertex shader transforms vertex position into screen space, performs a simple N dot L lighting equation, copies texture coordinates, and computes the blur factor based on the depth. The blur factor is calculated with these equations:

fBlurFactor = dot(float4(vViewPosition, 1.0), vFocalPlane)*fHyperfocalDistance;
Output.Diffuse.a = fBlurFactor*fBlurFactor;

This equation calculates the distances from a point to a plane and scales the result by some factor. The hyperfocal distance is a factor that is the distance from clear to blurry. The blur factor is then squared and capped at 0.75f so that the center pixel is always weighted in the blurred image, thus reducing artifacts.

The technique WorldWithBlurFactor then uses a ps_1_1 pixel shader called WorldPixelShader which simply modulates the diffuse vertex color with the mesh's texture color. This could be done with texture blending if desired.

The second part of CMyD3DApplication::Render is where the blur actually happens. It uses one of five techniques to show off essentially 2 different pixel shader blur techniques.

The techniques UsePS20ThirteenLookups and UsePS20SevenLookups both use the ps_2_0 pixel shader called DepthOfFieldManySamples (but compile it using different parameters). The pixel shader is fairly simple: for a fixed number of samples it uses an array of values, called TwelveKernel, to offset the original UV texture coords and calls tex2D() with this new UV on a texture which is the render target created above. The kernel is defined to be two hexagons: one a single pixel out and the other two pixels out with close to "equal" spacing between the points in order to get the best blurring. For each sample it keeps a running sum of the color with this equation:

Blurred += lerp(Original.rgb, Current.rgb, saturate(Original.a*Current.a));

After all the samples have been taken, it returns this color divided by number of samples.

The other techniques UsePS20SixTexcoords,UsePS11FourTexcoordsNoRings, and UsePS11FourTexcoordsWithRings all are similar. Unlike the above, they don't use a kernel to offset the texture coordinates but instead use separate sets of texture coords that are precomputed. These texture coordinates are created in the application function called CMyD3DApplication::SetupQuad and each set is offset to create a blur when used in a very similar way as done above in DepthOfFieldManySamples. The advantage to this method is that it can be done with ps_1_1 hardware.

The difference between UsePS11FourTexcoordsNoRings, and UsePS11FourTexcoordsWithRings is that UsePS11FourTexcoordsWithRings linearly interpolates between the center pixel's RGB and the 3 jitter pixel's RGB based on the alpha value (the blur factor) of the center pixel. If one of the jitter pixels is not blurry while the center pixel is blurry, then the jitter pixel is incorrectly averaged in. However, UsePS11FourTexcoordsNoRings linearly interpolates between the center pixel's RGB and the 3 jitter pixel's RGB based on the value of center pixel's alpha multiplied by the jitter pixel alpha. Since 0 means no blur, this means that if one of the jitter pixels is not blurry while the center pixel is blurry then 0 * 1 = 0 so that the jitter pixel is not averaged in, causing a better result without artifacts.

For example, here is an original unblurred scene:

By pressing I, the sample will visually show you the blur factor of the scene. White means that pixel is not blurry (alpha=0.0f), and black means that pixel is blurry (alpha=1.0f).

Here's what the final scene looks like:


EffectParam Sample

The EffectParam sample demonstrates two D3DX effect system features: parameter blocks and parameter sharing (see Sharing Effect Parameters> and Use Parameter Blocks to Manage Effect Parameters). Parameter blocks group multiple Setxxx API calls and associate them with an effect handle. An application can then use the parameter block to make all those state changes with a single API call. Parameter sharing synchronizes parameters in multiple effects; each time an application updates a parameter in one effect, that parameter is updated in all the other shared effects.

Path

Source: | (SDK root)\Samples\C++\Direct3D\EffectParam
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\EffectParam.exe

How the Sample Works

This sample renders a scene that consists of seven mesh objects. The meshes are arranged in a circular ring. The user can rotate either the front mesh, or the ring to bring another mesh to the front. Each mesh has one or more materials, and each mesh can specify the effect file to render each material with.

A mesh is encapsulated by the CEffectMesh class, which wraps the ID3DXMesh interface. The class is mainly a helper class for setting up mesh materials. When loading a mesh, D3DX returns an array of materials used by the mesh. Each material has several attributes that define the appearance of the material, such as diffuse color, specular color, texture name, and the effect file used to render the material. D3DX does not set up materials automatically when loading meshes. It is up to the application to do so. CEffectMesh takes care of this task when an instance is created.

Each material is represented as a CMeshMaterial. This class contains three data members representing the needed data when rendering this material: the texture object, the effect object, and a handle for setting the effect's parameters.

To create a mesh, CEffectMesh::Create is called with the name of the mesh file. The sample calls D3DXLoadMeshFromX to create an ID3DXMesh interface and material information. Then, for each material, it checks for the associated effect instance. The effect instance (D3DXEFFECTINSTANCE) specifies the effect file name for rendering the material, optional effect parameters and their default values. If an effect instance exists for this material, then an ID3DXEffect interface is created from the effect file. Next, the sample creates a parameter block that contains the effect parameters. This is done by first calling ID3DXEffect::BeginParameterBlock. This call indicates to the effect object that it should record all subsequent set calls, until ID3DXEffect::EndParameterBlock is called. When ID3DXEffect::EndParameterBlock is called, the effect returns a D3DXHANDLE for the parameter block. From this point on, when the parameter block is applied (with ID3DXEffect::ApplyParameterBlock), the effect looks at the parameters inside the block, and sets the values for each of the parameters. The result is as if the application called this series of set methods. For instance, if an effect has two float4 parameters called Diffuse and Specular, a parameter block can be created to include these two parameters like this:

D3DXVECTOR4 vDiffuse;
D3DXVECTOR4 vSpecular;
D3DXHANDLE  hBlock;

// Initialize vDiffuse and vSpecular

pEffect->BeginParameterBlock();
pEffect->SetVector( "Diffuse", &vDiffuse );
pEffect->SetVector( "Specular", &vSpecular );
hBlock = pEffect->EndParameterBlock();

After this code is run, hBlock contains two parameters, Diffuse and Specular, and the recorded value of vDiffuse and vSpecular. Now, whenever the application does this:

// Apply the parameter block

pEffect->ApplyParameterBlock(hBlock);

The result is equivalent to the following, assuming vDiffuse and vSpecular still have the correct values:

pEffect->SetVector( "Diffuse", &vDiffuse );
pEffect->SetVector( "Specular", &vSpecular );

After the parameter block is created, the sample creates a new CMeshMaterial object to encapsulate the material. An effect may have more than one parameter, but CMeshMaterial only uses one D3DXHANDLE because parameter blocks allow the sample to use a single handle to represent multiple parameters.

For materials without an effect instance, a default effect is used for rendering those materials, and a parameter block is created for the standard Direct3D material attributes; that is, ambient, diffuse, specular, emissive, and specular power.

Parameter Sharing

When loading an effect, an application can optionally supply an ID3DXEffectPool pointer. An application passes NULL for the pool to indicate that there is no parameter sharing between effects. When a valid ID3DXEffectPool is passed, parameters declared with shared usage are shared between multiple effects. When the value of the parameter changes in one effect, every effect that shares this parameter will also see the change. To the application, it is as if there is only one instance of the parameter, used by all effects. For instance, if two effects are created with the same ID3DXEffectPool, and they both have a shared parameter named WorldViewProjection, then updating WorldViewProjection on one effect changes its value as seen by the other effect.

In the EffectParam sample, the parameters that are declared with the shared usage are the world, view, and projection matrices (or combinations of them). Because all materials of a mesh use the same transformation, it makes sense to share them among the effects so that the sample only needs to set each matrix once per mesh rendered, instead of once per material. The sample allows the user to enable or disable parameter sharing to see its impact on performance. During rendering of a mesh, the sample always sets the transformation matrices once in the default effect. When the share option is enabled, all effects of the mesh see the correct matrices and are able to transform vertices appropriately. This means that all parts of the mesh are rendered regardless of their materials (Figure 1). When the option is set to disable, the updated matrices are only seen by the default effect. All other effects never see up-to-date values in the matrices, unless they are set by other effects. Because the sample does not do this, only materials rendered by the default effect are visible (Figure 2).

Figure 1. Parameter sharing enabled. All materials are rendered correctly.

Figure 2. Parameter sharing disabled. Only materials rendered by the default effect are correctly transformed.


EmptyProject Sample

Starting point for new Direct3D applications.

Path

Source: | (SDK root)\Samples\C++\Direct3D\EmptyProject
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\EmptyProject.exe

Sample Overview

This sample is a bare-bones Direct3D application provided as a convenient starting point for your own project.

How the Sample Works

This sample uses DXUT to initialize and run a basic Direct3D application. Functions are included as stubs with implementation left for the user.

See Also

SimpleSample Sample


EnhancedMesh Sample

The EnhancedMesh sample demonstrates mesh tessellation in Direct3D. Mesh tessellation subdivides mesh triangles. This produces a mesh with finer geometry details which can produce better lighting results even with per-vertex lighting. Mesh tessellation is often used to implement a LOD technique where meshes closer to the viewer are rendered with more details, and meshes further away are rendered with less detail.

Path

Source: | (SDK root)\Samples\C++\Direct3D\EnhancedMesh
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\EnhancedMesh.exe

How the Sample Works

The sample can run in one of two modes: hardware tessellation or software tessellation. The user can set the tessellation level to different values and see how the mesh changes in reaction to the level adjustment.

When running in hardware tessellation mode, the sample tessellates the mesh by calling IDirect3DDevice9::SetNPatchMode which sets the number of tessellation segments into which the device will tessellate each mesh segment. For instance, specifying 3.0 will cause each original segment in the input mesh to be tessellated into three segments. This tessellation happens in real-time, after the mesh draw calls in the render loop.

When running in software tessellation mode, the sample does not rely on the hardware to do on-the-fly tessellation. Therefore, the sample must process the mesh and obtain the desired detail level before rendering it. The code achieves this by calling D3DXTessellateNPatches which takes an input mesh and a segment count, and then outputs another mesh that represents the tessellated version of the input mesh. The sample can then render this tessellated mesh using any standard mechanism.


FragmentLinker Sample

This FragmentLinker sample shows how to use the ID3DXFragmentLinker interface. Shader source code can be split into a series of shader fragments, that are compiled separately and linked together to form a complete shader. This linking stage is very efficient, making it suitable for run-time use. In this way a Direct3D application can custom-build an appropriate shader for the current graphics card.

Path

Source: | (SDK root)\Samples\C++\Direct3D\FragmentLinker
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\FragmentLinker.exe

How the Sample Works

Large-scale Direct3D applications commonly employ a large set of redundant shaders covering every supported fallback case for a given technique (often generated by uniform parameters) from which the appropriate shader for the current graphics hardware is selected at run time. This approach can result in a large amount of compiled shaders being included with the application, only a small fraction of which are ever used on a given machine. Using shader fragments, the desired shader for the current graphics card can be built at run time.

This sample links together one of two vertex shader fragments that handle projection (vertex animated or static) and one of two vertex shader fragments that handle vertex lighting (diffuse enabled or ambient only). These fragments are compiled once during initialization and are then linked together at run time.

There are only a few steps that need to be followed when using shader fragments in your application:

  1. Create the ID3DXFragmentLinker interface using the D3DXCreateFragmentLinker function.
  2. Load and compile the shader fragments by calling D3DXGatherFragments, D3DXGatherFragmentsFromFile, or D3DXGatherFragmentsFromResource.
  3. Add the compiled fragments to the linker's internal list with a call to ID3DXFragmentLinker::AddFragments. This list defines the complete set of all fragments, from which a subset will be linked to create a shader.
  4. Retrieve handles of the fragments you want linked through calls to ID3DXFragmentLinker::GetFragmentHandleByIndex or ID3DXFragmentLinker::GetFragmentHandleByName.
  5. Link together a subset of the added fragments by passing fragment handles to the ID3DXFragmentLinker::LinkVertexShader, ID3DXFragmentLinker::LinkPixelShader, or ID3DXFragmentLinker::LinkShader method. These methods create an interface to a compiled shader that can be used for rendering.

The sample application performs the above steps upon device creation within the OnCreateDevice function:

// Create the fragment linker interface
V_RETURN( D3DXCreateFragmentLinker( pd3dDevice, 0, &g_pFragmentLinker ) );

// Compile the fragments to a buffer. The fragments must be linked
// together to form a shader before they can be used for rendering.
V_RETURN( DXUTFindDXSDKMediaFileCch(
    strPath, MAX_PATH, L"FragmentLinker.fx" ) );
V_RETURN( D3DXGatherFragmentsFromFile(
    strPath, NULL, NULL, 0, &g_pCompiledFragments, NULL ) );

// Build the list of compiled fragments
V_RETURN( g_pFragmentLinker->AddFragments(
    (DWORD*)g_pCompiledFragments->GetBufferPointer() ) );

// Store the fragment handles
CDXUTComboBox* pComboBox = NULL;
pComboBox = g_SampleUI.GetComboBox( IDC_LIGHTING );
pComboBox->RemoveAllItems();
pComboBox->AddItem( L"Ambient", (void*) g_pFragmentLinker
                 ->GetFragmentHandleByName( "AmbientFragment" ) );
pComboBox->AddItem( L"Ambient & Diffuse", (void*) g_pFragmentLinker
                 ->GetFragmentHandleByName( "AmbientDiffuseFragment" ) );

pComboBox = g_SampleUI.GetComboBox( IDC_ANIMATION );
pComboBox->RemoveAllItems();
pComboBox->AddItem( L"On", (void*) g_pFragmentLinker
                 ->GetFragmentHandleByName( "ProjectionFragment_Animated" ) );
pComboBox->AddItem( L"Off", (void*) g_pFragmentLinker
                 ->GetFragmentHandleByName( "ProjectionFragment_Static" ) );

// Link the desired fragments to create the vertex shader
V_RETURN( LinkVertexShader() );

The final linking step is performed within the LinkVertexShader helper function. In addition to being called upon device creation, this function is also called whenever the user changes a fragment combobox selection. The currently selected fragments are retrieved from the user interface controls, the shader is quickly linked, and the new shader is passed to the effect file:

HRESULT LinkVertexShader()
{
    HRESULT hr;
    ID3DXBuffer *pCode;
    DWORD *pShaderCode;
    IDirect3DDevice9 *pd3dDevice = DXUTGetD3DDevice();

    const int NUM_FRAGMENTS = 2;
    D3DXHANDLE aHandles[ NUM_FRAGMENTS ] = {0};
    aHandles[ 0 ] =
        (D3DXHANDLE) g_SampleUI.GetComboBox(IDC_ANIMATION)->GetSelectedData();
    aHandles[ 1 ] =
        (D3DXHANDLE) g_SampleUI.GetComboBox(IDC_LIGHTING)->GetSelectedData();

    SAFE_RELEASE( g_pLinkedShader );

    // Link the fragments together to form a shader
    V_RETURN( g_pFragmentLinker->LinkShader(
        "vs_1_1", 0, aHandles, NUM_FRAGMENTS, &pCode, NULL ) );
    pShaderCode = (DWORD*) pCode->GetBufferPointer();
    V_RETURN( pd3dDevice->CreateVertexShader( pShaderCode, &g_pLinkedShader));
    V_RETURN( D3DXGetShaderConstantTable( pShaderCode, &g_pConstTable ) );

    SAFE_RELEASE( pCode );

    // Set global variables
    V_RETURN( pd3dDevice->SetVertexShader( g_pLinkedShader ) );

    if (g_pConstTable)
    {
        g_pConstTable->SetVector(
            pd3dDevice, "g_vMaterialAmbient", &g_vMaterialAmbient );
        g_pConstTable->SetVector(
            pd3dDevice, "g_vMaterialDiffuse", &g_vMaterialDiffuse );
        g_pConstTable->SetVector(
            pd3dDevice, "g_vLightColor",      &g_vLightColor );
        g_pConstTable->SetVector(
            pd3dDevice, "g_vLightPosition",   &g_vLightPosition );
    }

    return S_OK;
}

Resources

The syntax for writing shader fragments is detailed in Writing Shader Fragments and in the Fragment Declaration Syntax (Direct3D 9 HLSL).

More in-depth coverage of the process behind compiling and linking shader fragments is found in Building And Rendering Fragments.


HDRCubeMap Sample

This sample demonstrates cubic environment-mapping with floating-point textures and high dynamic range lighting. In Direct3D 9, floating-point formats have become available for textures. These formats can store color values higher than 1.0, which can make lighting effects more realistic on the environment-mapped mesh when the material absorbs part of the light.

Note that not all cards support all features for the environment-mapping and high dynamic range lighting techniques.

Path

Source: | (SDK root)\Samples\C++\Direct3D\HDRCubeMap
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\HDRCubeMap.exe

Sample Overview

The sample shows off two rendering techniques: cubic environment-mapping and high dynamic range lighting. Cubic environment-mapping is a technique in which the environment surrounding a 3D object are rendered into a cube texture map, so that the object can use the cube map to achieve complex lighting effects without memory intensive lighting calculations. High dynamic range (HDR) lighting is a technique to render highly realistic lighting effects by using floating-point textures and high-intensity lights. The floating-point texture formats are introduced in Direct3D 9. Unlike traditional textures in integer format, floating-point textures are capable of storing a wide range of color values. Because color values in floating-point textures don't get clamped to [0, 1], much like lights in real-world, these textures can be used to achieve greater realism.

The scene that HDRCubeMap renders is an environment-mapped mesh, along with several other objects making up the environment around the mesh. The mesh has a reflectivity setting adjustable from 0 to 1, where 0 means the mesh absorbs light completely, and 1 means it absorbs no light and reflects all. The lights used in the scene consist of four point lights, whose intensity is adjustable by the user.

Implementation

The scene that the sample renders consists of these objects:

  • A room mesh. This includes the walls, floor, and ceiling.
  • Four small sphere meshes representing light sources.
  • A mesh in the center of the room with the environment map applied to it.
  • Two bi-plane meshes. These orbit around the environment-mapped mesh and are reflected on the environment map. They give the visual cue that the environment map is dynamic, and changes as the surrounding environment changes.

When the sample loads, it creates two cubic textures, one in A8R8G8B8 format and the other in A16B16G16R16F format. When rendering, the sample uses one of these to construct an environment map based on the user's choice. This is done to show the visual difference between integer and floating-point textures when used with high dynamic range lighting. A stencil surface with a size equal to the size of a cube texture face is also created at this time. This stencil surface will be used as the stencil buffer when the sample renders the scene onto the cube texture. The sample also creates an effect object that contains all of the shaders and techniques needed for rendering the scene. The camera used in the sample is a CModelViewerCamera. This camera always looks at the origin, where the environment-mapped mesh is. The user can move the camera position around the mesh and rotate the mesh with mouse control. The camera object computes the view and projection matrices for rendering, as well as the world matrix for the environment-mapped mesh.

The Rendering Code

The rendering of the sample happens in three functions: RenderSceneIntoCubeMap, Render, and RenderScene, using vertex and pixel shaders.

RenderScene is the function that does the actual work of rendering the scene onto the current render target. This is called both to render the scene onto the cube texture and onto the device backbuffer. It takes three parameters: a view matrix, a projection matrix, and a flag indicating whether it should render the environment-mapped mesh. The flag is needed because the environment-mapped mesh is not drawn when constructing the environment map. The rest of the function is straightforward. It first updates the effect object with the latest transformation matrices, as well as the light position in view space. Then, it renders every mesh object in the scene by using an appropriate technique for each one.

RenderSceneIntoCubeMap's job is rendering the entire scene (minus the environment-mapped mesh) onto the cube texture. First, it saves the current render target and stencil buffer, and sets the stencil surface for the cube texture as the device stencil buffer. Next, the function iterates through the six faces of the cube texture. For each face, it sets the appropriate face surface as the render target. Then, it computes the view matrix to use for that particular face, with the camera at the origin looking out in the direction of the cube face. It then calls RenderScene with bRenderEnvMappedMesh set to false, passing along the computed view matrix and a special projection matrix. This projection matrix has a 90 degree field of view and an aspect ratio of 1, since the render target is a square. After this process is complete for all six faces, the function restores the old render target and stencil buffer. The environment map is now fully constructed for the frame.

Render is the top level rendering function called once per frame by DXUT. It first calls FrameMove for the camera object, so that the matrices managed by the camera can be updated. Next, it calls RenderSceneIntoCubeMap to construct the cube texture to reflect the environment for that frame. After that, it renders the scene by calling RenderScene with the view and projection matrices from the camera, and bRenderEnvMappedMesh set to true.

The Shaders

All of the rendering in this sample are done by programmable shaders, divided into three effect techniques: RenderLight, RenderHDREnvMap, and RenderScene.

The RenderLight technique is used for rendering the spheres representing the light sources. The vertex shader does a usual world-view-projection transformation, then assigns the light intensity value to the output diffuse. The pixel shader propagates the diffuse to the pipeline.

The RenderHDREnvMap technique is used for rendering the environment-mapped mesh in the scene. Besides transforming the position from object space to screen space, the vertex shader computes the eye reflection vector (the reflection of the eye-to-vertex vector) in view space. This vector is passed to the pixel shader as a cubic texture coordinate. The pixel shader samples the cube texture, applies the reflectivity to the sampled value, and returns the result to the pipeline.

The RenderScene technique is used to render everything else. Objects rendered by this technique employ per-pixel diffuse lighting. The vertex shader transforms the position from object to screen space. Then, it computes the vertex position and normal in view space and passes them to the pixel shader as texture coordinates. The pixel shader uses this information to perform per-pixel lighting. A for-loop is used to compute the amount of light received from the four light sources. The diffuse term of the pixel is computed by taking the dot product of the normal and the unit vector from the pixel to the light. The attenuation term is computed as the reciprocal of the square of the distance between the pixel and the light. These two terms are then modulated to represent the amount of light the pixel receives from one of the light sources. Once this process is done for all lights in the scene, the values are summed and modulated with the light intensity and the texel to form the output.

High Dynamic Range Realism

Prior to Direct3D 9, only integer texture formats are supported by Direct3D. When a texture of this type is used, if a color value is higher than 1.0, it is clamped to 1.0 before being written so that the value can fit in an 8-bit integer. This means that when the cube texture is written, its texel color values will have a maximum of 1.0. When this texture is later used for environment-mapping on a material that is not 100 percent reflective (say, only 30 percent reflective), even the brightest texels in the texture will end up showing at 0.3 on the mesh, regardless of how high the original light intensity is. Consequently, realism is compromised. This is demonstrated in the figure below.

When Direct3D 9's new floating-point cube texture is used with lights whose intensity is higher than 1, the texture is capable of storing color values higher than 1.0, thus preserving true luminance even after the reflectivity multiplication. The figure below shows this.

Alternatives

It is possible to achieve a high level of realism in a high dynamic range lighting environment without using floating-point cube textures. An application can accomplish this by applying the material reflectivity multiplier when constructing the cubic environment map. Then, during rendering, the pixel shader will sample the cube texture and output the value straight back to the pipeline. This method works around color clamping by scaling before the clamping instead of after. The drawback of this method is that if the scene has multiple environment-mapped objects with different reflectivity, a different environment map will generally need to be rendered for each of these objects.


HDRFormats Sample

High dynamic range lighting effects require the ability to work with color values beyond the 0 to 255 range, usually by storing high range color data in textures. Floating point texture formats are the natural choice for HDR applications, but they may not be available on all target systems. This sample shows how high dynamic range data can be encoded into integer formats for compatibility across a wide range of devices.

Path

Source: | (SDK root)\Samples\C++\Direct3D\HDRFormats
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\HDRFormats.exe

Sample Overview

High dynamic range lighting techniques add realism to your application; furthermore, these techniques are fairly straightforward to implement, integrate well into an existing render pipeline, and require a modest amount of processing time; however, most HDR techniques rely in floating-point texture formats, which may not be available on the target system. One way to enable HDR techniques on devices without floating-point texture support is to encode high range floating-point data into an integer format, decoding on-the-fly as needed.

Be aware that integer textures are not perfect replacements for floating-point textures; the disadvantages of integer encoding are a loss of precision and/or a loss a range from the floating-point source, plus a performance hit resulting from the encoding/decoding process. This encoding/decoding happens seemlessly within the pixel shaders, so it's not prohibitively expensive, but it does use some of the available shader instruction count and can cause a slight frame-rate drop. For static elements, such as a skyboxes, the encoding can be done once during initialization, saving some cycles during run-time.

Implementation

The application uses two high dynamic range techniques: tone mapping and blooming. If you are not familiar with how these techniques work or want more information about high dynamic range images in general, look at HDR Lighting programming guide first, and view the HDRLighting and HDRCubeMap samples included with the SDK.

For the techniques used in this sample, the ability to store HDR data in textures is critical. The scene must be rendered to an HDR render target, the environment map texture needs to be HDR, and the temporary textures used to measure scene luminance all need to store HDR data. A device which supports floating-point textures will offer the best performance and simplest implementation, but with a little extra work integer textures can be used to store HDR data. This sample implements two encoding schemes:

RGB16

Using a 16-bit per channel integer format, 65536 discrete values are available to store per-channel data. This encoding is a simple linear distribution of those 65536 values between 0.0f and an arbitrary maximum value (100.0f for this sample). The alpha channel is unused. Here is the formula for decoding the floating-point value from an encoded RGB16 color:

decoded.rgb = encoded.rgb dot max_value

RGBE8

This encoding is more sophisticated than RGB16 and allows for a far greater range of color data by using a logarithmic distribution. Each channel stores the mantissa of the color component, and the alpha channel stores a shared exponent. The added flexibility of this encoding comes at the cost of extra computation. Here is the formula for decoding the floating-point value from an encoded RGBE8 color:

decoded.rgb = encoded.rgb * 2encoded.a

The images below show the textures used to render the scene in top-down order according to when they're used. Images with a blue border contain high dynamic range data, shown here with RGBE8 encoding.

The process of rendering the scene is nearly identical between the native floating-point texture mode and the encoded integer texture modes. Pixel shaders which read from high dynamic range textures simply require an extra decoding step when reading from encoded integer textures and require a similar encoding step when writing HDR data to integer textures. By using uniform arguments to the shader, the same shader can be compiled differently and used by every encoding scheme. For example, here is the pixel shader that lights the model:

//-----------------------------------------------------------------------------
// Name: ScenePS
// Type: Pixel Shader
// Desc: Environment mapping and simplified hemispheric lighting
//-----------------------------------------------------------------------------
float4 ScenePS( SceneVS_Output Input,
                uniform bool RGBE8,
                uniform bool RGB16 ) : COLOR
{
    // Sample the environment map
    float3 vReflect = reflect( Input.ViewVec_World, Input.Normal_World );
    float4 vEnvironment = texCUBE( CubeSampler, vReflect );

    if( RGBE8 )
        vEnvironment.rgb = DecodeRGBE8( vEnvironment );
    else if( RGB16 )
        vEnvironment.rgb = DecodeRGB16( vEnvironment );

    // Simple overhead lighting
    float3 vColor = saturate( MODEL_COLOR * Input.Normal_World.y );

    // Add in reflection
    vColor = lerp( vColor, vEnvironment.rgb, MODEL_REFLECTIVITY );

    if( RGBE8 )
        return EncodeRGBE8( vColor );
    else if( RGB16 )
        return EncodeRGB16( vColor );
    else
        return float4( vColor, 1.0f );
}


HDRLighting Sample

This sample demonstrates some HDR lighting effects using floating-point textures. Integer texture formats have a limited range of discrete values, which results in lost color information under dynamic lighting conditions; conversely, floating-point formats can store very small or very large color values, including values beyond the displayable 0.0 to 1.0 range. This flexibility allows for dynamic lighting effects, such as blue-shifting under low lighting and blooming under intense lighting. This sample also employs a simple light adaptation model, under which the camera is momentarily overexposed or underexposed to changing light conditions.

HDR Lighting Sample screen shot

Path

Source: | (SDK root)\Samples\C++\Direct3D\HDRLighting
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\HDRLighting.exe

Why This Sample Is Interesting

Light in the real world has a very high ratio between highest and lowest luminances; this ratio is called dynamic range and is approximately 1012:1 for viewable light in everyday life, from sun to starlight; however, the human visual system is only capable of a dynamic range around 1000:1 at a particular exposure. In order to see light spread across a high dynamic range, the human visual system automatically adjusts its exposure to light, selecting a narrow range of luminances based on the intensity of incoming light. This process is not instantaneous, as you'll notice when entering a dark building on a sunny day, or vice versa. This delayed exposure adjustment is referred to as light adaptation, and can be simulated in a real-time application.

Computer displays and print media have a dynamic range around 100:1, so compromises will have to be made when trying to display a scene with a higher dynamic range; this sample borrows from a technique originally developed for use in photography called tone mapping, which describes the process of mapping an HDR image into a low dynamic range space. Tone mapping effectively produces the same effect as the automatic exposure control which happens in the human visual system.

Finally, when a bright light strikes a lens, certain aberrations naturally occur, including bloom and star effects shown in the following image. If high-intensity light values are not discarded during the render process, these effects can be produced after the scene has been rendered to add an additional level of realism to the image. Because these are post-process effects, the time required to produce them depends only on the screen resolution, regardless of scene or lighting complexity.

Scene with glare effects

Overview

This sample uses Direct3D 9 floating-point textures to store HDR lighting information for the scene. Integer texture formats are clamped from 0.0f to 1.0f in the pixel shader, but floating-point textures are allowed to contain any value, bound only to the constraints of available bits for mantissa and exponent.

The algorithms described in this sample are based very closely on the lighting effects implemented in the following references.

  • Kawase, Masaki. "Real-Time High Dynamic Range Image-Based Lighting".
  • Reinhard, Erik, Mike Stark, Peter Shirley, and James Ferwerda. "Photographic Tone Reproduction for Digital Images". ACM Transactions on Graphics (TOG), Proceedings of the 29th Annual Conference on Computer Graphics and Interactive Techniques (SIGGRAPH), pp. 267-276. New York, NY: ACM Press, 2002.

How the Sample Works

For this sample, scene objects are textured with normal integer format textures, but the sphere objects representing lights are shaded with a high range of values, effectively creating emissive lights. All objects in the scene are shaded using an illumination model that calculates ambient, diffuse, and specular lighting based on the position and intensity of the lights; because these lights be assigned high values, the resulting colors of illuminated objects can extend far beyond the 1.0f cutoff. If a floating-point texture is not used to capture these HDR values, this light data will be lost, and the scene will appear overexposed, as in the following figure.

Scene without tone mapping

If, instead, the scene is rendered onto a floating-point surface, the HDR information will be stored and the scene can then be tone mapped to an appropriate low dynamic range for display, as shown in the following figure.

Scene with tone mapping

The following figure shows the top-level flow diagram for the sample. The scene is first rendered onto a floating-point texture, which has the same dimensions as the backbuffer. Because the scene will be sampled several times to create the post-processing effects, a good first step is to scale down the scene to minimize the number of pixels the shaders must sample. This has the added benefit of making post-process effects larger when their associated textures are scaled up to full size. The scaled scene texture is processed to measure the average luminance of the scene. Using this average luminance value, it is possible to determine which pixels in the scene will be bright after the scene has been tone mapped to a low dynamic range. By excluding all color data in the scene except brightly-lit areas, a bright-pass filtered copy of the scene is created that can be used as the source of post-process lighting effects.

Flow diagram for high dynamic range sample

The scene in this sample is rendered using a pixel shader to control the ambient, diffuse, and specular contribution of each light at every pixel. Because the lights for the featured scene are very bright, most of the pixels have per-channel color components above the 0.0 to 1.0 range displayable by the graphics card. Therefore, this texture appears mostly white when viewed directly. However, the color information above 1.0 is not lost, but simply needs to be tone-mapped into the 0.0 to 1.0 range. During a final pass, the scene is tone-mapped to the desired luminance range, and the post-process image effects are blended on top of the scene to create the final image.

User's Guide

Calculating Luminance

Before your program can scale the intensity of your scene, it will need to determine how bright the scene is to begin with. The goal is to calculate a good estimate for the average scene luminance while minimizing the amount of time spent making the calculation. The calculation can be sped up by reducing the number of sampled texels, but you risk missing bright areas with a sparse test pattern. The approach used in this sample is to first scale the scene by 1/4 x 1/4, using the average of each 4 x 4 block of texels to down-sample. This scaled texture is also used to create the source textures for the lighting effects, so it is important that the scale operation is precise, to avoid flickering artifacts as the camera moves around the scene.

The process used to measure the average scene luminance and perform tone mapping is featured in the whitepaper Photographic Tone Reproduction for Digital Images, from which the following luminance equation is taken.

Equation for average luminance

The average scene luminance used for later calculations is the antilogarithm of the average log values for all sampled pixels. Delta contains a small value to handle the case of pure black texels. This equation is implemented using four pixel shader passes called from the MeasureLuminance method, as follows:

  1. Sample average log() values into a 64 x 64 texture.
  2. Downscale to 16 x 16.
  3. Downscale to 4 x 4.
  4. Downscale to 1 x 1 and perform an exp() operation on the result.

By keeping the calculation result inside a 1 x 1 texture, the calculations which require the average luminance value can be done completely on the video card without requiring any AGP transfers.

Exposure Control

Exposure control is the process of finding an appropriate low dynamic range view of the HDR scene. In a physical lens system, the aperture is adjusted to limit the amount of light entering the system. The process used in computer graphics to emulate exposure control is commonly called tone mapping, which refers to the process of mapping an HDR image space onto a low dynamic range space suitable for video display. Unlike exposure control, all the high range data is available for use when tone mapping; so, depending on the operator used, the image may contain more detail from bright and dark areas simultaneously than would be possible using a traditional camera.

After the average scene luminance has been calculated, the HDR scene texture can be scaled according to a target average luminance, represented by alpha in the following equation:

Equation for luminance scaled to target average luminance

This equation simply produces a linear scaling of the scene luminance centered around the target average luminance for the final scene; however, the resulting values have not yet been compressed to fit within the low dynamic range of 0.0 to 1.0 viewable on the monitor. The following tone mapping operator performs the desired compression.

Equation for tone mapping operator

Light Adaptation

The human visual system does not adjust instantly for changing light conditions, and this behavior can be easily simulated by slightly extending the tone-mapping calculations. The luminance value to which the user is currently adapted is used instead of the average scene luminance within the tone-mapping equations. This adapted luminance value is stored in a 1 x 1 texture and is adjusted each frame to slowly track the measured scene luminance, as shown in the following code snippet:

float fNewAdaptation = fAdaptedLum + (fCurrentLum - fAdaptedLum) * ( 1 - pow( 0.98f, 30 * g_fElapsedTime ) );

For example, if the camera is stationary, the adapted luminance will eventually match the measured luminance, resulting in tone-mapped output identical to the output when adaptation is disabled. However, if the camera is moved to focus on an area of different lighting magnitude, the image will appear over- or underexposed while the viewer adjusts to the new lighting conditions. The adaptation model used in this sample is not intended to be a realistic model of human adaptation, which can take longer than a half hour for full dark adaptation.

Bright-Pass Filter

Tone mapping is performed in two places within the code: once in Render as part of the final shader pass to compose the glare textures onto the scene, and once as part of the bright-pass filter. The bright-pass filter uses tone mapping to first determine what areas of the final scene image will be bright, and then it excludes the remaining data. Because HDR lighting effects are relative to the current exposure, these effects can be performed on a tone-mapped image and added directly to the scene output. This procedure offers the advantage of being able to use integer textures for glare generation.

As shown in the following code snippet, the bright-pass filter first maps the scene to a desired middle gray target luminance before subtracting out the dark areas. The tone mapping operator which transforms the scene luminance to the 0.0 to 1.0 range is modified slightly from the last equation. Instead of dividing the luminance by one plus the luminance, an offset value replaces one in the equation. As this offset value increases, the relative separation between bright and dark regions of the scene also increases.

// Determine what the pixel's value will be after tone mapping occurs
vSample.rgb *= g_fMiddleGray/(fAdaptedLum + 0.001f);

// Subtract out dark pixels
vSample.rgb -= BRIGHT_PASS_THRESHOLD;

// Clamp to 0
vSample = max(vSample, 0.0f);

// Map the resulting value into the 0 to 1 range. Higher values for
// BRIGHT_PASS_OFFSET will isolate lights from illuminated scene
// objects.
vSample.rgb /= (BRIGHT_PASS_OFFSET+vSample);

Bloom Effect

Before the bloom is performed, the bright-pass filtered image is scaled and blurred down to 1/8 x 1/8 scale of the original scene texture. The bloom pass is simply a two-pass separable horizontal and vertical Gaussian blur of the scaled bright-pass filtered scene. As shown in the following figure, the texture is first blurred along the horizontal, then the horizontally-blurred texture is blurred along the vertical to complete the process. As part of the final scene pass, the bloom texture is scaled to the size of the back buffer using bilinear filtering and added directly to the output of the scene.

Star Effect

The star effect may require as many as three passes to render each of the star lines. The star patterns used in this sample require as many as eight lines, resulting in a potential cost of 24 passes to render fully. The GlareDef.h file defines characteristics for the various star types, including the number of lines, line directions, and chromatic offsets. As shown in the following figure, once all the individual directional lines have been rendered, the average texel value across the individual line textures is used to create the final composite star texture. This composite texture is scaled and added directly to the final scene image.


HDRDemo Sample

Path

Source: | (SDK root)\Samples\C++\Direct3D\HDRDemo
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\HDRDemo.exe

Sample Overview

This sample application is intended to complement existing HDR (High Dynamic Range) samples by showing the many intermediary processing steps that make up a typical HDR rendering path in a Direct3D application. Whilst implementing HDR rendering is not the most complex of algorithms, it does have a large number of steps involved in the composition of the final image displayed to the user.

The above screenshot shows a typical view of the application. To correctly interpret the display, follow the white-on-red arrows linking each of the cells together - they indicate the order in which the steps are completed. The image that would normally be shown to the end-user is the largest cell in the bottom-right of the window.

The above image shows a different view of the sample program, this time with no HDR information. Note that the four cells across the top of the image are all black.

The above image shows a view containing a substantial amount of HDR information. Note that the brighter parts have a slight glow to them (corresponding to the contents of the four cells at the top of the image) and that the background is noticeably darker than the previous image.

The above screenshot show a much more typical scene - one where there is a mixture of normal colours (in the 0.0-1.0 range) and "over bright" HDR values. Because much of the image is relatively dark the luminance mapping is biased towards an exposure to suit a lower range of values. The result is that the few areas of HDR information are over exposed - appearing as white in the final image. Due to the exposure being adapted to the darker source image, the final image is composed such that it's brightness is increased. Because of this the cube and background colour appear much brighter than in the source image.

Implementation

There are four main stages to a HDR rendering path, all demonstrated by this sample and explained in the following sections:

Initial image rendering

The first step requires that a source image is generated - and is also the simplest step. A floating point render target is used to store values outside of the usual 0.0 to 1.0 (or 0 to 255) range common in traditional Direct3D applications. It is worth comparing the results shown in this cell with the contents of the final image. Exposure adjustments and luminance calculations can make substantial, but subtle, differences. Because the results of this stage will be stored in a high-precision format, any scaling introduced later on in the rendering should produce less noticeable banding or resolution artefacts common with lower-precision rendering.

This sample application uses three faces of the cube at the middle of the scene to produce values greater than 1.0. The remaining three faces are coloured within the normal range, so as to provide some comparison. A better way to produce HDR values in a scene might be to use bright light sources (and associated algorithms).

Computing the average luminance for the scene

In order to push as much of the work onto the GPU (which is specifically designed to process graphics-related work) a series of down sampling steps are used to compute the overall luminance. Each of the 6 steps reduces the dimensions by a factor of 3 until a 1x1 texture stores a single pixel representing the average luminance across the whole of the source image.

The luminance value is later used to scale the intensity of the final image - a generally bright scene will get darkened and vice versa.

Post-processing effects

Even with a correct luminance measurement it is quite possible for areas of the image to still be over-exposed. When viewed through a lens (a camera for example) this excess light energy can be subject to reflection/refraction effects. This can result in a slight blurring around the edges of the over-exposed area, an effect that is simulated by the post-processing stage.

This effect is applied to pixels that are greater than or equal to a specific "Bright Pass Threshold". This threshold can be controlled by a slider in the sample's GUI. The first (left-most) cell in the above image shows the initial HDR image with only those pixels that are greater than, or equal to, the bright-pass threshold. A lower threshold will result in more of the initial image being visible in this cell.

In order to blur an image a pixel shader is required to read multiple samples from the source before writing to the destination, and as such can be particularly fill-rate intensive for the GPU. To remedy this performance problem, the first two stages of the post-processing pipeline down sample the input so as to reduce the number of pixels that will be considered by the blurring stages. The final number of pixels submitted to the blurring filter is 1/16th of the initial image.

An advantage of this down-sampling is that when the post-processing results (the right-most cell in the above image) are sampled into the final image, that each pixel covers a larger area meaning that the application can do less work and still achieve noticeable effects. Conversely, aliasing/resolution artefacts can be introduced unless texture filtering is used.

Post-processing effects

The final image, shown in the bottom right of the screen, takes the results of the aforementioned three stages and computes the correct image. This image will be tone mapped according to the computed luminance, and also include the results of the post-processing blurring around over-exposed elements. Due to the way that the components are additively combined, the bright (over-exposed) areas of the original image appear to "bleed" colour into the properly exposed areas.

Application performance

It is worth noting that this application was specifically developed as an educational sample - visually demonstrating how the many steps and processes of a HDR rendering path work. Because of this, it hasn't been aggressively optimized for real-time performance.

From a performance perspective there are two interesting aspects to this sample:

Firstly, it is a good example of a GPU bound (and more specifically fill-rate bound) application. The vast majority of the work done on any given frame is offloaded to the GPU. Consequently, performance noticeably reflects the hardware installed. As an experiment, try zooming in/out (mouse scroll wheel) and examining the frame-rate in the bottom-left of the final image. When the scene is suitably zoomed out and covers a small area of the final image the frame rate should be significantly higher than when the scene is zoomed in and covers all of the final image.

Secondly, the source code for this sample makes particular use of the D3DPERF_BeginEvent and D3DPERF_EndEvent API calls. The calls allow PIX for Windows to group related calls together, making the interpretation of call streams a lot more intuitive. Using PIX to record a replayable call-stream capture should yield information similar to the following screenshot - the "User Event" sections are the result of the aforementioned API calls:

See Also

HDRLighting

HDRFormats


HLSLwithoutEffects Sample

HLSLwithoutEffects demonstrates using HLSL to write vertex shaders without using the D3DX effect interfaces. HLSL is a language that closely resembles C syntax and constructs. By writing shaders in HLSL instead of assembly language, developers can take advantage of not only the features and elements of the language they are already familiar with, but also the great optimization capabilities offered by the D3DX shader compiler.

Path

Source: | (SDK root)\Samples\C++\Direct3D\HLSLwithoutEffects
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\HLSLwithoutEffects.exe

How HLSLwithoutEffects Works

The scene that this sample renders consists of a square grid of triangles lying on the XZ plane. In each frame, the vertices of this grid will move up or down along the Y direction based on a function of their distance to the origin and time. The vertices are also lit using another function of the distance and time. The time is incremented for each frame. Because the Y coordinate and color of the vertices are generated in each frame, they do not need to be stored. Therefore, the vertex declaration only contains a D3DXVECTOR2 for the X and Z coordinates.

During initialization, the sample calls D3DXCompileShaderFromFile to read the shader function from a file and compile it into binary shader code. After this process, an ID3DXBuffer containing the shader code and a ID3DXConstantTable that allows the application to get and set the global variables of the shader are created. Then, the sample calls IDirect3DDevice9::CreateVertexShader with the shader code to obtain a IDirect3DDevice9 object that can be passed to the device.

In FrameMove, the sample uses the ID3DXConstantTable interface to set the shader's global variables mViewProj and fTime in order to update the view + projection transformation and time parameter for the shader. At render time, the sample calls IDirect3DDevice9::SetVertexShader to enable vertex shader rendering on the device. When IDirect3DDevice9::DrawIndexedPrimitive is called after that, the vertex shader will be invoked once for every vertex processed.

In the sample, the vertex shader is written in a text file called HLSLwithoutEffects.vsh. In this file, there are two global variables and a shader function called Ripple. Ripple takes a float2 as input (for X and Z of the vertex) and outputs two float4 representing the screen-space position and vertex color. The Y coordinate is generated using this formula:

Y = 0.1 * sin( 15 * L * sin(T) );

L is the distance between the vertex and the origin before the Y adjustment, so it has the value of sqrt(X2 + Z2), because the vertices are lying on the XZ plane. T is the fTime global variable.

The color of the vertex will be some shade of gray based on this formula:

C = 0.5 - 0.5 * cos( 15 * L * sin(T) );

C will be the value used for all red, green, blue, and alpha and will range from 0 to 1, giving the vertex a color of black to white, respectively. The result looks like ripples with width changing back and forth between narrow and wide and with proper shading based on the slope.

General controls defined in the sample:

Key | Action
W/S | Move forward/backward
Q,E,A,D | Strafe
F2 | Change device
Esc | Quit


Instancing Sample

This sample demonstrates the instancing feature available with Direct3D 9. A vs_3_0 device is required for the hardware version of this feature. The sample also shows alternate ways of achieving results similar to hardware instancing, but for adapters that do not support vs_3_0. The shader instancing technique shows the benefits of efficient batching of primitives.

Note On graphics hardware that does not support vs_2_0, the sample will run as a reference device.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Instancing
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\Instancing.exe

How the Sample Works

The sample demonstrates four different rendering techniques to achieve the same result: to render many nearly identical boxes (objects with small numbers of polygons) in the scene. The boxes differ by their position and color.

The user can vary the number of boxes in the scene between one and 1000. Use the sample to monitor performance as the number of boxes increases. As you change the number of boxes, the vertex and index buffer resources are recreated by OnCreateBuffers and OnDestroyBuffers.

Technique 1: Hardware Instancing

Hardware instancing requires a vs_3_0-capable device. The instance-specific data is stored in a second vertex buffer. The rendering is implemented in the sample application's OnRenderHWInstancing method. IDirect3DDevice9::SetStreamSourceFreq is used with D3DSTREAMSOURCE_INDEXEDDATA to specify the number of boxes and with D3DSTREAMSOURCE_INSTANCEDATA to specify the frequency of the instance data (in this case, frequency equals one).

Drawing the scene is accomplished as follows:

pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, 4 * 6, 0, 6 * 2 );

Technique 2: Shader Instancing (with Draw Call Batching)

This is the most efficient technique that does not use the hardware to perform the instancing. One call to IDirect3DDevice9::DrawIndexedPrimitive handles multiple primitives at once. The instance data is stored in a system memory array, which is then copied into the vertex shader's constants at draw time. Since vs_2_0 only guarantees 256 constants, it is not possible for the entire array of instance data to fit at once. This sample's .fx file can only batch-process 120 constants (one float4 is required for box position, and one float4 is required for box color). Rendering is performed in the sample's OnRenderShaderInstancing method.

int nRenderBoxes = min( nRemainingBoxes, g_nNumBatchInstance );
...
pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, nRenderBoxes * 4 * 6, 0, nRenderBoxes * 6 * 2 );

This method would also work on a vs_1_1 part, although not as efficiently because vs_1_1 only guarantees 96 constants. This means that batching is nearly three times more efficient on vs_2_0 hardware than on vs_1_1 hardware, but even on vs_1_1 hardware, batching still outperforms no batching.

Technique 3: Constants Instancing (without Draw Call Batching)

This technique is somewhat similar to Technique 2 without the batching (batch size = 1). It will render one box at a time, by first setting its position and color and then calling DrawIndexedPrimitive. The technique is implemented in the sample's OnRenderConstantsInstancing method.

Technique 4: Stream Instancing

As in Technique 1, this technique uses a second vertex buffer to store instance data. Instead of setting vertex shader constants to update the position and color for each box, this technique changes the offset in the instance stream buffer and draws one box at a time. The technique is implemented in the sample's OnRenderStreamInstancing method.

CPU- vs. GPU-bound

When the sample renders a large number of boxes, only Techniques 1 and 2 are GPU-bound, while Techniques 3 and 4 waste many CPU cycles by making numerous calls per frame to DrawIndexedPrimitive.

The performance numbers for rendering a large number of boxes show that only the first two techniques are GPU-bound, while the last two techniques waste a lot of CPU cycles by making numerous calls to DrawIndexedPrimitive per frame. To better illustrate the penalty from being CPU-bound in a real world application, the sample has the Goal option which simulates a secondary task (in a game, this could be AI or physics) competing for CPU. The sample queries the time elapsed since the last frame and if there is time remaining inside the goal time/frame, the sample allows time to pass to represent game logic. It reports the amount of time used in the Remaining for logic statistic. This is the percentage of CPU cycles that are available to spend on non-rendering algorithms such as game logic or physics; the higher the percentage, the better. If the scene is loaded with 1000 boxes, it was observed that the efficient techniques have 2x better CPU efficiency than the CPU-bound techniques. In other words, using Techniques 3 and 4 to render many instances will starve other tasks of CPU time.

The following table summarizes hardware and memory requirements for different rendering techniques:

Rendering Technique | Requires vs_3_0 Card | CPU-bound | Requires Additional Vertex Buffer | Requires Additional Shader Constant Buffer
Hardware Instancing | Yes | No | Yes | No
Shader Instancing | No | No | No | Yes
Constants Instancing | No | Yes | No | Yes
Stream Instancing | No | Yes | Yes | No

See Also

Efficiently Drawing Multiple Instances of Geometry (Direct3D 9)


LocalDeformablePRT Sample

This sample demonstrates a simple usage of locally-deformable precomputed radiance transfer (LDPRT). This implementation does not require an offline simulator for calculating PRT coefficients; instead, the coefficients are calculated from a thickness texture. This allows an artist to create and tweak subsurface scattering PRT data in an intuitive way.

Path

Source: | (SDK root)\Samples\C++\Direct3D\LocalDeformablePRT
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\LocalDeformablePRT.exe

Sample Overview

This sample shows what is likely the easiest non-trivial implementation of a PRT technique (it doesn't even use the offline simulator). The animated bat in the scene is textured with a thickness map. The alpha channel of the albedo texture stores this scalar value - the higher the value the more backlight is allowed to transmit through the wings. Each color channel is also influenced by a shader constant that allows selective tinting of transmitted light. Because this is a true PRT effect, the entire lighting environment can be used for illumination.

For simplicity, the per-pixel transfer function is globally set to the standard diffuse, clamped, cosine kernel (for N dot L lighting above the tangent plane and a scaled N dot L lobe mirrored across the tangent plane for subsurface contribution). Far more local control over light transport is possible with the addition of coefficient data per vertex or per texel; however, the simplicity and accessibility of the demonstrated technique make it worth considering even without further improvements.

Technical Overview

PRT enables complex lighting transport effects like soft self-shadowing, colored interreflections, and subsurface scattering (that is, translucency). LDPRT is no exception, and is built upon the same concepts as standard PRT, so it's helpful to have a basic understanding of the math behind PRT before investigating this sample (such as used in PRT Demo Sample, Precomputed Radiance Transfer (Direct3D 9), and PRT Equations (Direct3D 9)).

LDPRT differs from standard PRT by employing a single coefficient per spherical harmonic (SH) order; this ensures that the transfer function has radial symmetry around the normal. This radial symmetry allows for very quick rotations and makes LDPRT suitable for use on animated meshes. The decrease in coefficients naturally results in constraints on possible transfer functions, but this is largely mitigated by selecting proper normals for the coefficients (see the reference page ID3DXPRTEngine::ComputeLDPRTCoeffs for remarks about shading normals). D3DX can also generate LDPRT coefficients and shading normals from a given set of PRT coefficients, resulting in a surprisingly good LDPRT approximation to the PRT original. See the PRTDemo sample for a comparison of PRT and LDPRT techniques on a variety of scenes.

The LDPRT technique employed within the LocalDeformablePRT sample is actually easier to implement than a standard PRT solution because it doesn't necessitate running a simulator to generate transfer coefficients. The values that control the transmitted light are taken directly from a texture map and are therefore particularly easy to tweak in an intuitive way.

Implementation

This specific implementation of LDPRT requires very minimal additional art requirements; the unused alpha channel in the albedo texture was painted to contain the transmission factor of subsurface light. This can be thought of as the thickness of the textured object, where higher values indicate a thinner material (and therefore more transmitted light). To display the full usefulness of LDPRT, vertex blending (also known as "skinning") data was added to the mesh within the 3D modeling application. This model also uses a normal map to store normal offset values; the perturbed normals add apparent texture to the surface and are used as the shading normals for LDPRT calculations (demonstrating the compatibility of LDPRT with other surface lighting techniques).

Application Initialization

On startup, the sample:

  • Loads the skybox cubemap and computes the spherical harmonic projection of the lighting environment.
  • Generates four cubemaps to store the first 16 SH basis functions (each color channel stores a unique basis function). Note that this sample only uses SH bases through order 2, but the sample supports through order 3 for simple extension.
  • Loads the mesh hierarchy and prepares the matrix palette. (For more information on vertex blending see SkinnedMesh Sample.)
  • Loads the effect file and required textures.

Frame Rendering

At the beginning of every frame, the SH lighting environment is calculated from a weighted combination of the light probe and the adjustable spotlight:

void UpdateLightingEnvironment()
{
    // Gather lighting options from the HUD
    g_vLightDirection = g_LightControl.GetLightDirection();
    g_fLightIntensity = g_SampleUI.GetSlider( IDC_LIGHT_SLIDER )->GetValue() / 100.0f;
    g_fEnvIntensity = g_SampleUI.GetSlider( IDC_ENV_SLIDER )->GetValue() / 1000.0f;

    // Create the spotlight
    D3DXSHEvalConeLight( D3DXSH_MAXORDER, &g_vLightDirection, D3DX_PI/8.0f,
                         g_fLightIntensity, g_fLightIntensity, g_fLightIntensity,
                         m_fRLC, m_fGLC, m_fBLC);

    float fSkybox[3][D3DXSH_MAXORDER*D3DXSH_MAXORDER];

    // Scale the light probe environment contribution based on input options
    D3DXSHScale( fSkybox[0], D3DXSH_MAXORDER, g_fSkyBoxLightSH[0], g_fEnvIntensity );
    D3DXSHScale( fSkybox[1], D3DXSH_MAXORDER, g_fSkyBoxLightSH[1], g_fEnvIntensity );
    D3DXSHScale( fSkybox[2], D3DXSH_MAXORDER, g_fSkyBoxLightSH[2], g_fEnvIntensity );

    // Combine the environment and the spotlight
    D3DXSHAdd( m_fRLC, D3DXSH_MAXORDER, m_fRLC, fSkybox[0] );
    D3DXSHAdd( m_fGLC, D3DXSH_MAXORDER, m_fGLC, fSkybox[1] );
    D3DXSHAdd( m_fBLC, D3DXSH_MAXORDER, m_fBLC, fSkybox[2] );
}

The remaining LDPRT work happens inside the pixel shader:

float4 PS( VS_OUTPUT In, uniform bool bNdotL ) : COLOR0
{
    // Albedo
    float4 Color = tex2D( AlbedoSampler, In.TexCoord );

    // Normal map
    float3 Normal = tex2D( NormalMapSampler, In.TexCoord );
    Normal *= 2;
    Normal -= 1;

    // Move the normal from tangent space to world space
    float3x3 mTangentFrame = { In.Binormal, In.Tangent, In.Normal };
    Normal = mul( Normal, mTangentFrame );

    if( bNdotL )
    {
    // Basic N dot L lighting
    Color *= g_fLightIntensity * saturate( dot( Normal, g_vLightDirection ) );
    }
    else
    {
    // 1 channel LDPRT, 3 channel lighting loading Ylm coeffs from cubemaps
    Color *= LDPRTCoeffLighting( In.TexCoord, Normal );
    }

    return Color;
}

The shader is first responsible for determining the shading normal for the LDPRT calculations. In this case, the normal stored in the standard normal map is used as the shading normal; because the lighting calculations in this sample are conducted in world space, a tangent frame is constructed within the vertex shader and passed to the pixel shader for transforming the perturbed normal into world space. As shown, the LDPRT illumination is calculated within the LDPRTCoeffLighting helper function:

float4 LDPRTCoeffLighting(float2 vTexCoord, float3 vSHCoeffDir)
{
    float4 vExitRadiance[3] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    float4 vTransferVector[4], vYlm[4];
    Ylm(vSHCoeffDir, vYlm);

    // A 4 channel texture can hold a cubics worth of LDPRT coefficients.
    float4 vLDPRTCoeffs = { 1,  2.0/3.0, 0.25, 0};
    BuildSHTransferVector(vLDPRTCoeffs, vYlm, vTransferVector);

    // Calculate sub-surface contribution

    // Negating the odd-order coefficients will mirror the lobe across the tangent plane
    vLDPRTCoeffs.y *= -1;
    float4 vTransferVectorBehind[4];
    BuildSHTransferVector(vLDPRTCoeffs, vYlm, vTransferVectorBehind);

    // The alpha channel of the albedo texture is being used to store how 'thin'
    // the material is, where higher values allow more light to transmit.
    // Although each color channel could have a separate thickness texture, we're
    // simply scaling the amount of transmitted light by a channel scalar.
    float4 vAlbedo = tex2D( AlbedoSampler, vTexCoord );
    for( int i=0; i < 4; i++ )
    {
        vTransferVectorBehind[i] *= vAlbedo.a;
    }

    // Red
    vExitRadiance[0] += g_vLightCoeffsR[0] * (vTransferVector[0] + g_vColorTransmit.r * vTransferVectorBehind[0]);
    vExitRadiance[0] += g_vLightCoeffsR[1] * (vTransferVector[1] + g_vColorTransmit.r * vTransferVectorBehind[1]);
    vExitRadiance[0] += g_vLightCoeffsR[2] * (vTransferVector[2] + g_vColorTransmit.r * vTransferVectorBehind[2]);
    vExitRadiance[0] += g_vLightCoeffsR[3] * (vTransferVector[3] + g_vColorTransmit.r * vTransferVectorBehind[3]);

    // Green
    vExitRadiance[1] += g_vLightCoeffsG[0] * (vTransferVector[0] + g_vColorTransmit.g * vTransferVectorBehind[0]);
    vExitRadiance[1] += g_vLightCoeffsG[1] * (vTransferVector[1] + g_vColorTransmit.g * vTransferVectorBehind[1]);
    vExitRadiance[1] += g_vLightCoeffsG[2] * (vTransferVector[2] + g_vColorTransmit.g * vTransferVectorBehind[2]);
    vExitRadiance[1] += g_vLightCoeffsG[3] * (vTransferVector[3] + g_vColorTransmit.g * vTransferVectorBehind[3]);

    // Blue
    vExitRadiance[2] += g_vLightCoeffsB[0] * (vTransferVector[0] + g_vColorTransmit.b * vTransferVectorBehind[0]);
    vExitRadiance[2] += g_vLightCoeffsB[1] * (vTransferVector[1] + g_vColorTransmit.b * vTransferVectorBehind[1]);
    vExitRadiance[2] += g_vLightCoeffsB[2] * (vTransferVector[2] + g_vColorTransmit.b * vTransferVectorBehind[2]);
    vExitRadiance[2] += g_vLightCoeffsB[3] * (vTransferVector[3] + g_vColorTransmit.b * vTransferVectorBehind[3]);

    return float4( dot(vExitRadiance[0], 1),
                   dot(vExitRadiance[1], 1),
                   dot(vExitRadiance[2], 1),
                   1 );
}

This function first generates the required rotated SH basis functions by calling the Ylm helper function, which relies on the SH cubemap textures generated on initialization. The shader then builds the LDPRT coefficients; this sample's shader uses the coefficients { 1, 2.0/3.0, 0.25, 0 } that describe the second-order, clamped cosine kernel. More complex light transport would use coefficients stored in the vertex or a texture map. Next, the BuildSHTransferVector function multiplies the LDPRT coefficients against the basis functions to create the transfer vector vTransferVector; this first vector gathers the direct lighting contribution. By negating the odd-order coefficients, the resulting second transfer vector vTransferVectorBehind is a mirror of the first across the tangent plane, and therefore gathers the subsurface lighting contribution. The subsurface vector is then scaled against the thickness factor at that pixel. Finally, the subsurface transmission is scaled per color channel and both transfer vectors are convolved against the lighting environment. The resulting radiance calculation is output as the pixel color.

See Also

Precomputed Radiance Transfer (Direct3D 9), PRT Equations (Direct3D 9)


MeshFromObj Sample

This sample shows how an ID3DXMesh object can be created from mesh data stored in a Wavefront Object file ( .obj). It's convenient to use .x files when working with ID3DXMesh objects since D3DX can create and fill a mesh object directly from a .x file. It's also easy to initialize a mesh object with data gathered from any file format or memory resource.

Path

Source: | (SDK root)\Samples\C++\Direct3D\MeshFromObj
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\MeshFromObj.exe

Sample Overview

The ID3DXMesh interface is a handy way to manage complex meshes. It allows you to divide the mesh into subsets, usually according to separate material types. When rendering the mesh you can loop through subsets, setting the proper render state for the current material. The interface treats the complex mesh as a single object while still offering the flexibility of rendering with several different textures or shaders.

The interface implements member functions for optimizing how internal mesh data is sorted. This leads to fewer state changes during rendering and increased vertex cache performance. In addition, the related interfaces ID3DXPatchMesh, ID3DXPMesh, and ID3DXSPMesh support other specialized cases.

ID3DXMesh can encapsulate any mesh that can be rendered using indexed triangle lists, and therefore does not rely on any particular file format. The purpose of this sample is to show how an ID3DXMesh object can be created from arbitrary mesh data.

Implementation

ID3DXMesh objects contain a vertex buffer and an associated index buffer. Each ID3DXMesh object is rendered as an indexed triangle list, so a call to DrawSubset is functionally the same as retrieving the internal vertex and index buffers and calling IDirect3DDevice9::DrawIndexedPrimitive using the D3DPT_TRIANGLELIST primitive type. To fill an ID3DXMesh object with mesh data you simply need to fill the internal vertex and index buffers. When creating a mesh directly from a .x file using D3DXLoadMeshFromX, setting the vertex format and populating the vertex and index buffers are handled automatically. If you use a different mesh file format (than .x) you will need to set up the vertex and index buffers yourself.

For this sample, the .obj format was chosen for its simplicity, but the lesson extends to any file format or memory resource layout. In fact, the most important snippet of sample code is the portion which deals with loading an ID3DXMesh object once the mesh data has already been imported:

// Create the encapsulated mesh
ID3DXMesh* pMesh = NULL;
V_RETURN( D3DXCreateMesh( m_Indices.GetSize() / 3, m_Vertices.GetSize(),
                          D3DXMESH_MANAGED | D3DXMESH_32BIT, VERTEX_DECL,
                          pd3dDevice, &pMesh ) );

// Copy the vertex data
VERTEX* pVertex;
V_RETURN( pMesh->LockVertexBuffer( 0, (void**) &pVertex ) );
memcpy( pVertex, m_Vertices.GetData(), m_Vertices.GetSize() * sizeof(VERTEX) );
pMesh->UnlockVertexBuffer();
m_Vertices.RemoveAll();

// Copy the index data
DWORD* pIndex;
V_RETURN( pMesh->LockIndexBuffer( 0, (void**) &pIndex ) );
memcpy( pIndex, m_Indices.GetData(), m_Indices.GetSize() * sizeof(DWORD) );
pMesh->UnlockIndexBuffer();
m_Indices.RemoveAll();

// Copy the attribute data
DWORD* pSubset;
V_RETURN( pMesh->LockAttributeBuffer( 0, &pSubset ) );
memcpy( pSubset, m_Attributes.GetData(), m_Attributes.GetSize() * sizeof(DWORD) );
pMesh->UnlockAttributeBuffer();
m_Attributes.RemoveAll();

The code above locks and fills the internal vertex and index buffers, much the same way these buffers would be accessed if used independently of the ID3DXMesh interface. This code also fills the optional attribute buffer. Each face in the mesh can be given an attribute, which is the number of the subset to which it belongs; during a call to ID3DXMesh::DrawSubset( DWORD AttribId ), those faces with an attribute that matches the attribute id will be rendered. If rendering the entire mesh, the application simply needs to loop through all the subsets. The attribute ids divide a mesh into groups which are rendered separately. For this sample, the mesh is divided into material groups which allows an application to render each subset with the correct material properties.

Here's the code to render a subset of the mesh, showing how the texture, illumination variables, and shaders are adjusted for the particular material prior to rendering the subset:

void RenderSubset( UINT iSubset )
{
    HRESULT hr;
    UINT iPass, cPasses;

    // Retrieve the ID3DXMesh pointer and current material from the MeshLoader helper
    ID3DXMesh* pMesh = g_MeshLoader.GetMesh();
    Material* pMaterial = g_MeshLoader.GetMaterial( iSubset );

    // Set the lighting variables and texture for the current material
    V( g_pEffect->SetValue( g_hAmbient, pMaterial->vAmbient, sizeof(D3DXVECTOR3) ) );
    V( g_pEffect->SetValue( g_hDiffuse, pMaterial->vDiffuse, sizeof(D3DXVECTOR3) ) );
    V( g_pEffect->SetValue( g_hSpecular, pMaterial->vSpecular, sizeof(D3DXVECTOR3) ) );
    V( g_pEffect->SetTexture( g_hTexture, pMaterial->pTexture ) );
    V( g_pEffect->SetFloat( g_hOpacity, pMaterial->fAlpha ) );
    V( g_pEffect->SetFloat( g_hSpecularPower, pMaterial->fShininess ) );

    V( g_pEffect->SetTechnique( pMaterial->hTechnique ) );
    V( g_pEffect->Begin(&cPasses, 0) );

    for (iPass = 0; iPass < cPasses; iPass++)
    {
        V( g_pEffect->BeginPass(iPass) );

        // Render the mesh with the applied technique
        V( pMesh->DrawSubset( iSubset ) );

        V( g_pEffect->EndPass() );
    }
    V( g_pEffect->End() );
}

The next section demonstrates how to import mesh data from a .obj file. Note that the simple parser created for this sample is not intended to be a complete parser for the .obj format nor any of its extensions.

Loading the geometry from file

Wavefront Object (*.obj) files are an ASCII format for describing meshes composed of triangle lists. Vertices may contain texture coordinates and normals. Object files may also contain a reference to an MTL (*.mtl) file, which defines materials containing illumination variables and texture filenames. Mesh faces can be assigned a material to allow separate components of the mesh to retain individual material properties. Each line of the file begins with a token which indicates the type of information stored on that line:

token | Comment (ignored)
v float float float | Vertex position v (position x) (position y) (position z)
vn float float float | Vertex normal vn (normal x) (normal y) (normal z)
vt float float | Texture coordinate vt (tu) (tv)
f int int int | f (v) (v) (v) Faces are stored as a series of three vertices in clockwise order. Vertices are described by their position, optional texture coordinate, and optional normal, encoded as indices into the respective component lists.
f int/int int/int int/int | f (v)/(vt) (v)/(vt) (v)/(vt)
f int/int/int int/int/int int/int/int | f (v)/(vt)/(vn) (v)/(vt)/(vn) (v)/(vt)/(vn)
mtllib string | Material file (MTL) mtllib (filename.mtl) References the MTL file for this mesh. MTL files contain illumination variables and texture filenames.
usemtl string | Material selection usemtl (material name) Faces which are listed after this point in the file will use the selected material

The mesh files are parsed within the CMeshLoader::LoadGeometryFromOBJ, which builds a vertex buffer, an index buffer, and an attribute buffer. After the file is completely parsed, these buffers can be copied into an empty ID3DXMesh object. LoadGeometryFromOBJ builds vertex position, texture coordinate, and vertex normal lists directly from file input. When a mesh face element is encountered within the input file, the vertex components are retrieved from the respective component lists.

Since multiple vertices may share the same position but have different texture coordinates or vertex normals, a little extra work must be done when storing vertices, otherwise duplicate vertices will be added to the vertex buffer (in which case there's no point to having an index buffer). To make this check relatively quick, vertices are stored in a hash table cache according to their position index as they are added to the vertex buffer. This cache is checked for duplicates by CMeshLoader::AddVertex for each new face. After the mesh has been completely loaded from file, this vertex cache is destroyed by calling the CMeshLoader::DeleteCache.

Most .obj files will also reference a .mtl file, which contains named material sets. The parser builds a list of materials it expects to find within the .mtl file, and keeps track of which material is selected as each mesh face is read. This material index is also used as the attribute number for a given face; these attribute numbers divide the mesh faces into material type subsets. Although the material groupings may be scattered throughout the .obj file, the vertex buffer will be reordered into material subsets as part of the call to ID3DXMesh::Optimize, so no additional sorting is required of the parser.

Loading the Materials from file

If an MTL file was referenced within the Object file, it's parsed immediately after the Object file. The MTL file format uses an ASCII encoding very similar to .obj files, using these tokens:

Token | Comment (ignored)
newmtl string | Material newmtl (material name). Begins a new material description.
Ka float float float | Ambient color Ka (red) (green) (blue)
Kd float float float | Diffuse color Kd (red) (green) (blue)
Ks float float float | Specular color Ks (red) (green) (blue)
d float Tr float | Transparency Tr (alpha)
Ns int | Shininess Ns (specular power)
illum int | Illumination model illum (1 / 2); 1 if specular disabled, 2 if specular enabled.
map_Kd string | Texture map_Kd (filename)

When the .obj file is parsed and new material names are encountered, material structures containing default values are created and added to the material list. When the .mtl file is parsed, these structures are retrieved from the material list and filled with the correct values. In addition, a default material is created to contain all the faces which aren't otherwise assigned a material. These conventions guarantee that all faces will be assigned a material and missing material descriptions will be filled with default values.

Texture filenames are stored within the material structures, and the corresponding textures are created upon device creation. When creating textures, the material list is scanned for duplicate texture filenames to ensure that materials which use the same texture point to a single created instance. After the .mtl file has been parsed, each item in the material list will correspond to a subset in the ID3DXMesh object. As described above, this material list is iterated through in combination with corresponding mesh subsets when rendering the entire mesh.


MultiAnimation Sample

This sample demonstrates mesh animation with multiple animation sets using high-level shader language (HLSL) skinning and the D3DX animation controller. The animation controller blends animation sets together to ensure a smooth transition when moving from one animation to another.

MultiAnimation sample screenshot

Path

Source: | (SDK root)\Samples\C++\Direct3D\MultiAnimation
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\MultiAnimation.exe

Overview

This sample shows how an application can render 3D animation utilizing D3DX animation support. D3DX has APIs that handle the loading of the mesh to be animated, as well as the blending of multiple animations. The animation controller supports animation tracks for this purpose, and allows transitioning from one animation to another smoothly. The sample is divided into two parts: the animation class library and the application.

The animation class library is a general-purpose library that sits between the application and D3DX. It encapsulates the details of loading the mesh from a .x file and manipulating its frame hierarchy to prepare it for rendering, as well as rendering the animated mesh using a vertex shader and a matrix palette for indexed skinning. It is designed to be reusable and customizable.

The application portion contains code specific only to this sample. It uses the animation class library to create instances of the Tiny character, which are animated according to the action they perform. Each instance can be controlled by either the user or the sample. This portion also handles collision detection among instances of Tiny, out of bound detection, and behavior management for instances that are controlled by the sample.

The Application

The application portion of this sample consists of two parts. The first part is the CTiny class. It handles the behavior of the animated mesh in the sample loaded from the tiny_4anim.x file. The second part contains CMyD3DApplication and all of the code that is normally generated by the DirectX application wizard.

In this sample, Tiny can be controlled by either the user or the application (default). When Tiny is controlled by the application, the following happens: First, a random location on the floor is chosen and a move speed (run or walk) is determined. Next, Tiny is turned at the current position toward the new destination and is moved in that direction. After Tiny arrives at the new destination, there is a brief period of idle time before another location is selected where to move Tiny, and the whole process repeats. There can be more than one instance of Tiny. Collision detection is done for the instances, so they can block each other's movement.

The CTiny class has a CAnimInstance member, a class defined by the animation library. CTiny uses this member and its animation controller to perform the animation tasks necessary. In this sample, Tiny has three sets of animation: Loiter, Walk, and Run. The animation controller of Tiny supports two animation tracks. Most of the time, one of these two tracks is active with an animation set. When Tiny's action calls for a change of animation (for instance, going from loitering to walking, or stopping from running), enable the second track with the new animation set to play and set a transition period to complete the transition from the first track to the second. Then, as time is advanced, the animation controller will generate the correct frame matrices that reflect the transition smoothly by interpolating between the two tracks. After the transition period passes, the first track is disabled, and the second track plays the new animation in which Tiny is seen.

CTiny also takes advantage of the callback system to play the footstep sound at appropriate instances in the animation. At initialization time, CTiny sets up a structure, CallbackDataTiny, containing the data to pass to the callback handler. The structure has three members: m_dwFoot indicates which foot is triggering the sound, m_pvCameraPos points to the camera position when the callback is made, and m_pvTinyPos points to the world space coordinates of Tiny. This data is used to determine which sound to play (left or right), and how loud it should be. The sample defines a class called CBHandlerTiny, derived from ID3DXAnimationCallbackHandler, that contains the callback handler function to be called by the animation controller. The callback handler function, HandleCallback, retrieves the data passed as a CallbackDataTiny structure then plays a DirectSound buffer with the appropriate volume based on the values in the CallbackDataTiny structure.

In FrameMove, the sample iterates through the array of CTiny instances and calls Animate on each one of them. This updates the behaviors of all instances, changing them if needed.

The rendering code of the application is relatively simple. It first sets up the view and projection matrices based on the camera position and orientation, then it renders the mesh object representing the floor. Next, it goes through the array of Tiny instances and calls AdvanceTime and Draw on each one of them. AdvanceTime makes the animation controller update the frame hierarchy's matrices, then Draw renders the instance using the updated matrices. Finally, the code renders the informational text as necessary.

The Animation Class Library

The library consists of the following structures and classes:

  • CMultiAnim
  • CAnimInstance
  • CMultiAnimAllocateHierarchy
  • MultiAnimFrame Structure
  • MultiAnimMC Structure

CMultiAnim

This class is the heart of the library. Its function is to encapsulate the mesh hierarchy loaded from a .x file. It can also create instances of the animating mesh, of the type CAnimInstance, that share the mesh hierarchy from the .x file. These instances are associated with the CMultiAnim object that creates them.

In its initialization method, CMultiAnim::Setup, CMultiAnim determines the maximum size of the matrix palette based on the version of the vertex shader present. It then loads the mesh hierarchy from the given .x file and creates an effect object from the given .fx file that contains the vertex shader with which the mesh is rendered. The frames of the mesh hierarchy and the animation controller are created in this process.

The frames consist of a tree structure representing the hierarchy of the bones, as well as the mesh objects. This structure is shared by all associated instances.

The animation controller is associated with the mesh hierarchy frames. The animation controller that CMultiAnim holds is not used for animation. Instead, when a new animation instance is created, the animation controller is cloned and the new animation controller is owned by the new instance. The application uses an instance's own animation controller to control its animation. Because each instance has its own copy of animation controller, it can animate independent of all other instances.

When the ID3DXAnimationController::AdvanceTime method of an animation controller in an animation instance is called, the animation controller will update the transformation matrix for each frame in the mesh hierarchy. The frames are then used in the rendering of the instance.

CAnimInstance

This class represents an animation entity, or an animation instance. Each animation instance has its own animation controller, which allows the instances to be animated independent of each other. Each instance is also associated with a CMultiAnim object, which holds the mesh hierarchy that is shared by all associated instances. The following table lists the methods that are the most interesting for animation control and which are used extensively by the application when animating and rendering.

Method Name | Description
GetAnimController | Returns the animation controller for this instance, of type ID3DXAnimationController. With the animation controller, the application can set the animation it needs to play.
SetWorldTransform | Sets the top level world transformation matrix for this instance. When the animation time advances, each frame in the mesh hierarchy is recursively transformed by this world transformation to bring it to the correct world space coordinate and orientation.
AdvanceTime | Advances the local animation time for this instance with an optional callback handler. The time advancement causes the animation controller to update the bone positions for this instance. The animation controller will also invoke the callback handler if the keyed event is reached.
ResetTime | Resets the local time for this instance.
Draw | Renders this instance with the HLSL vertex shader. This is normally called after calling AdvanceTime so that the frames are set up properly for rendering.

When an animation instance is rendered, it uses the effect object of its associated CMultiAnim to set the rendering parameters, including the vertex shader. The vertex shader function is responsible for skinning the mesh, transforming the position to screen space, and computing the color. The skinning portion is done by the function VS_Skin. This function is located in the vertex shader file Skin.vsh. The file contains an array of float4x3 named amPalette, which represents the matrix palette for skinning meshes, and the VS_Skin skinning function. VS_Skin is designed to be invoked by another vertex shader function, so an application can call it in its own vertex shader function to handle the skinning process. VS_Skin takes the object space position and normal, up to three blending weights (the last blending weight is computed by subtracting the sum of all other weights from 1), and up to four indices for the matrix palette. The function then transforms the position and normal up to four times with the corresponding matrices in the matrix palette and blending weights, and adds the result together to form the world space position and normal.

CMultiAnimAllocateHierarchy

This class inherits from ID3DXAllocateHierarchy. Its purpose is to handle the allocation and deallocation of resources during the loading and releasing of a mesh hierarchy. In this sample, CMultiAnimAllocateHierarchy initializes all members of new frames and mesh containers in CreateFrame and CreateMeshContainer called during the mesh hierarchy creation. In DestroyFrame and DestroyMeshContainer, it frees up all resources allocated in CreateFrame and CreateMeshContainer, respectively.

CreateMeshContainer does a little more work than simply allocating and copying. It also has to do the following:

  • Create all of the textures used by the mesh.
  • Initialize the mesh container's bone offset array, given by pSkinInfo.
  • Obtain the palette size that the mesh has to work with, and call ConvertToIndexedBlendedMesh to create a working mesh that is compatible with the palette size.

MultiAnimFrame Structure

This structure is derived from D3DXFRAME. It represents a single frame, or bone, in a mesh hierarchy. A frame may contain siblings or children. The entire mesh hierarchy is structured similar to a tree. The application can add members to a structure derived from D3DXFRAME as necessary. In this sample, no additional members are needed.

MultiAnimMC Structure

This structure is derived from D3DXMESHCONTAINER. It contains a mesh object attached to the mesh hierarchy along with relevant data for the mesh. A mesh hierarchy can contain any number of mesh containers. In this sample, additional members are defined as listed in the following table.

Type | Name | Description
LPDIRECT3DTEXTURE9 * | m_apTextures | Array of Direct3D texture objects used by the mesh.
LPD3DXMESH | m_pWorkingMesh | A copy of the mesh compatible with the matrix palette size available.
D3DXMATRIX* | m_amxBoneOffsets | Array of matrices representing the bone offsets. This information is obtained from the pSkinInfo member, copied here for convenience.
D3DXMATRIX** | m_apmxBonePointers | Array of pointers to matrix. They point to the TransformationMatrix of various frames of this mesh hierarchy. This array provides an easy mapping from bone index to bone matrix.
DWORD | m_dwNumPaletteEntries | Size of the matrix palette that this mesh uses when rendering. The size cannot exceed the maximum palette size allowed by our vertex shader due to limited registers, and it also cannot be larger than the number of bones in this mesh.
DWORD | m_dwMaxNumFaceInfls | Maximum number of bones that may affect a single face. This value is obtained from ID3DXSkinInfo::ConvertToIndexedBlendedMesh. The vertex shader needs this value when rendering in order to know when to compute the last weight.
DWORD | m_dwNumAttrGroups | Number of attribute groups in working mesh. An attribute group is a subset of the mesh that can be drawn in a single draw call. If the working palette size is not large enough to render the mesh in its entirety, it needs to be broken down into separate attribute groups. This is done by ID3DXSkinInfo::ConvertToIndexedBlendedMesh.
LPD3DXBUFFER | m_pBufBoneCombos | Contains the bone combination table, in the form of an array of D3DXBONECOMBINATION structures. There is one D3DXBONECOMBINATION for each attribute group. It identifies the subset of the mesh (vertices, faces, and bones) that can be drawn in a single draw call.

User's Guide

The following general controls are defined in the sample.

Key | Action
Q | Move camera down.
E | Move camera up.
W | Move camera forward.
A | Move camera left.
S | Move camera backward.
D | Move camera right.
N | Next view
P | Previous view
R | Reset camera
F2 | Bring up Direct3D Settings menu.
Alt+Enter | Toggle full screen.
Esc | Quit

The following controls are valid when you are viewing a specific mesh instance.

Key | Action
C | Take control
W | Move forward
A,D | Turn
W+Shift | Hold for run mode

Pitfalls and Alternatives

Some of what this sample does can be done differently, with different trade-offs.

Because all instances of Tiny share the same frame hierarchy matrices, the sample must advance time on a specific instance and render it before moving on to another instance. Generally, this does not present a problem. However, if an application wishes to update the matrices for all of the instances first then render them, it can make new animation controllers point to a different set of matrices when cloning. This way, each animation controller has its own set of matrices to work with, and overwriting will not occur, at the expense of more memory usage.

It is also worth noting that the matrix palette in the skinning vertex shader is an array of matrices, and naturally takes up a significant number of constant registers. An application may experience the problem of insufficient constant registers for other use. The application can work with a smaller-sized matrix palette by setting the MATRIX_PALETTE_SIZE_DEFAULT shader #define to a smaller value when creating the effect object in CMultiAnim. The drawback of this approach is that the mesh may contain more subsets that need to be drawn separately.

Note that this sample specifically demonstrates rendering animated meshes. It does not handle static meshes, although the code can be extended to do that.

Another task that the sample only does partially is the complete preservation of animation controllers' states when the Direct3D device is released and re-created. This generally happens when the application switches from HAL to REF device (see Device Types (Direct3D 9)), or vice versa, or from one Direct3D device to the other on a dual-monitor system. In MultiAnimation, when the Direct3D device is released, all animation controllers are also released. The animation controllers are then re-created when the sample initializes the new Direct3D device. This presents a problem, because animation states stored in animation controllers are lost. The sample loses the knowledge of what animation each track is playing, what tracks are enabled, and the speed and weight of each track before the old device is released. To remedy this issue, an application should, before releasing Direct3D objects in its cleanup function (DeleteDeviceObjects for MultiAnimation), retrieve the animation controllers' states and save them in a buffer. Then, after it re-creates the animation controllers that it needs (in InitDeviceObjects for MultiAnimation), it should restore the animation controllers' states from the buffer. For each animation controller, the following states should be saved.

  • Current time of the animation controller, obtained with ID3DXAnimationController::GetTime.
  • Name of the animation set that each track is playing. Obtain this information by calling ID3DXAnimationController::GetTrackAnimationSet, then ID3DXAnimationSet::GetName.
  • Track description of all tracks. Use ID3DXAnimationController::GetTrackDesc to obtain this description.
  • Current events for all tracks, if there are events running. This can be retrieved with ID3DXAnimationController::GetCurrentTrackEvent and ID3DXAnimationController::GetEventDesc.
  • All keyed track events. To receive every event keyed, first call ID3DXAnimationController::GetUpcomingTrackEvent with hEvent set to NULL. This returns an event handle to the keyed event to happen next. Then, pass the handle to ID3DXAnimationController::GetEventDesc to obtain the description for this event. After that, take the handle received from the previous ID3DXAnimationController::GetUpcomingTrackEvent call and call ID3DXAnimationController::GetUpcomingTrackEvent again with it. This gives you the handle to the second keyed event. Repeat this process to receive all keyed events.
  • Current priority blend for the animation controller, by calling ID3DXAnimationController::GetPriorityBlend.
  • Current priority blend event, if one is running, by calling ID3DXAnimationController::GetCurrentPriorityBlend and ID3DXAnimationController::GetEventDesc.
  • All keyed priority blend events. This is done by calling ID3DXAnimationController::GetUpcomingPriorityBlend and ID3DXAnimationController::GetEventDesc. The way to handle all events is similar to handling keyed events in the tracks.

For reasons of simplicity, MultiAnimation does not preserve all of its animation controllers' states, but rather it saves only the animation set that its current track is playing. Consequently, if the Direct3D device object is released and re-created during an animation transition, the animation will not appear the same after the transition as before; it will appear as if the transition has been completed. In addition, all keyed events will not be restored after re-initialization.


OptimizedMesh Sample

This OptimizedMesh Sample sample demonstrates the different types of meshes D3DX can load and optimize, as well as the different types of underlying primitives it can render. An optimized mesh has its vertices and faces reordered so that rendering performance can be improved.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Meshes\OptimizedMesh
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\OptimizedMesh.exe

How the Sample Works

The sample can be divided into two areas: loading and rendering.

Loading

The loading code first initializes the mesh from data in the mesh file and calls OptimizeMeshData three times, each with a different optimization type. The optimization types used are D3DXMESHOPT_ATTRSORT, D3DXMESHOPT_VERTEXCACHE, and D3DXMESHOPT_STRIPREORDER. The optimization type is passed to ID3DXMesh::Optimize which reorders the mesh's vertices and faces accordingly.

After the meshes are set up, OptimizeMeshData creates a number of index buffers to hold the face information in the form of triangle strips. First, it calls D3DXConvertMeshSubsetToSingleStrip once for each material in the mesh. This returns an index buffer that represents the mesh triangles of that material with a single triangle strip. This index buffer can then be used to render the mesh. Next, OptimizeMeshData calls D3DXConvertMeshSubsetToStrips for each material in the mesh, and returns an index buffer representing a series of triangle strips. To return a single triangle strip, call D3DXConvertMeshSubsetToSingleStrip instead.

After the loading is complete, the sample has three sets of mesh data. Each set of mesh data includes an ID3DXMesh optimized with a different flag, one index buffer per material that represents the triangle subset as a single strip, and one index buffer per material that represents the subset as a series of strips.

Rendering

The rendering code is simpler compared to the loading code, because the mesh data sets have already been set up during the load time and are ready for use directly with rendering calls. To render, the sample calls DrawMeshData. This function takes a mesh data set and performs the rendering with it. Based on the current optimization setting, the appropriate mesh data set is passed to DrawMeshData.

Inside DrawMeshData, the mesh is rendered according to the primitive type selected by the user. For triangle lists, the mesh object's ID3DXBaseMesh::DrawSubset is called once per material, because the mesh stores its geometry as triangle lists internally. For strips, DrawMeshData sets up primitive sources by calling IDirect3DDevice9::SetStreamSource and SetIndices(). The index buffer that is passed to IDirect3DDevice9::SetIndices is one of the index buffers created in OptimizeMeshData. If the mesh is to be rendered with a single triangle strip, the index buffer returned by D3DXConvertMeshSubsetToSingleStrip is used. If multiple triangle strips are desired, the buffer returned by D3DXConvertMeshSubsetToStrips is used instead. Once the vertex and index data are properly initialized, DrawMeshData renders the mesh by calling IDirect3DDevice9::DrawIndexedPrimitive.


ParallaxOcclusionMapping Sample

This sample donated by ATI Technologies (www.ati.com) presents the parallax occlusion mapping algorithm which employs per-pixel ray-tracing for dynamic lighting of surfaces in real-time on the GPU. The method uses a high precision algorithm for approximating view-dependent surface extrusion for a given height field to simulate motion parallax and perspective-correct depth. Additionally, the method allows generation of soft shadows in real-time for surface occlusions. This sample includes an automatic level-of-detail system for in-shader complexity scaling. The full algorithm is described in 'Dynamic Parallax Occlusion Mapping with Approximate Soft Shadows' paper by N. Tatarchuk, ATI Research, Inc., to appear in ACM Symposium on Interactive 3D Graphics and Games, 2006.

The GDC slides can be found at:

ATI Developer: Techology Papers and Presentations

"Practical Parallax Occlusion Mapping for Highly Detailed Surface Rendering"

N. Tatarchuk, ATI Research, Inc. ATI Technologies, GDC 2006.

Path

Source: | (SDK root)\Samples\C++\Direct3D\ParallaxOcclusionMapping
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\ParallaxOcclusionMapping.exe


PixelMotionBlur Sample

Motion blur adds realism to the scene. It has the perceptual effect of creating high-speed motion. Instead of rendering the geometry multiple times with different alpha values to create a blur effect, this sample shows off a realistic image-based motion blur effect. While the scene is rendered, the shaders record the per-pixel velocity relative to the previous frame. This per-pixel velocity is then used in a post-process pass to blur the pixels in the final image.

Path

Source: | (SDK root)\Samples\C++\Direct3D\PixelMotionBlur
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\PixelMotionBlur.exe

Background

In CMyD3DApplication::InitDeviceObjects, the sample:

  1. Loads the geometry with D3DXLoadMeshFromX.
  2. Calls D3DXComputeNormals to create mesh normals if there aren't any.
  3. Calls ID3DXMesh::OptimizeInplace to optimize the mesh for the vertex cache.
  4. Loads the textures using D3DXCreateTextureFromFile.
  5. Sets up the structures to describe the scenes.
  6. Sets up the camera.

In CMyD3DApplication::RestoreDeviceObjects, the sample:

  • Uses D3DXCreateTexture to create a D3DFMT_A8R8G8B8 render target that is the same size as the back buffer. This render target will be used by the pixel shader to render the scene's RGB color.
  • Uses D3DXCreateTexture to create two more render targets that are the same size as the back buffer, but are instead floating point 16 bits per channel D3DFMT_G16R16F. These textures are used by the pixel shader to render the pixel's velocity. One of these textures will hold the per-pixel velocity of the previous frame and the other will hold the per-pixel velocity of the current frame. The usage of these render targets are explained in more detail below.
  • Uses D3DXCreateEffectFromFile to load the .fx file into an ID3DXEffect and it caches the D3DXHANDLE to all the parameters that it will use every frame.
  • Creates a quad of vertices to be used in the post-processing pass. The quad has a single set of texture coordinates defined. These texture coordinates are set up so that the texels of the render target will map directly to pixels. How this quad is used is explained in more detail below.
  • Clears all of the render targets and sets some ID3DXEffect parameters to default values.

In CMyD3DApplication::FrameMove, the sample:

  • Calls FrameMove on the camera class so it can move the view matrix according the user input over time.
  • Swaps the pointers of the current frame's per-pixel velocity texture and the last frame's per-pixel velocity texture.
  • Animates the objects in the scene, based on a simple function of time.
  • Calls Sleep based on a user's setting. This simulates time spent doing complex graphics, artificial intelligence (AI), physics, networking, etc. This is useful in this sample to slow down the frame rate and thus have more motion between each frame.

The sample essentially does two things in CMyD3DApplication::Render:

  1. Renders the scene's RGB into one render target, m_pFullScreenRenderTargetSurf, while it simultaneously renders the pixel's velocity into a second render target, m_pCurFrameVelocitySurf. This is possible only if the device caps report NumSimultaneousRTs greater than one; otherwise, this will need to be done in two passes.
  2. Does a post-process pass. It renders a full-screen quad to execute a pixel shader for each pixel. The pixel shader uses the render target with velocity information to blur the color of the pixel using a filter, based on the direction of pixel's velocity.

In more detail, the first part of CMyD3DApplication::Render uses the technique WorldWithVelocity, which uses a vs_2_0 vertex shader called WorldVertexShader. This vertex shader transforms vertex position into screen space, performs a simple N • L lighting equation, copies texture coordinates, and computes the velocity of the vertex by transforming the vertex by both the current and previous [world * view * projection] matrix and taking the difference. The difference will be the amount that this vertex has moved in screen space since the last frame. This per-vertex velocity is passed to the pixel shader by TEXCOORD1.

The technique WorldWithVelocity then uses a ps_2_0 pixel shader called WorldPixelShader, which modulates the diffuse vertex color with the mesh's texture color and writes this to COLOR0 and also writes the velocity of the pixel per frame in COLOR1. The render target for COLOR1 is D3DFMT_G16R16F, a floating point, 16-bits-per-channel texture. This render target records the amount the pixel has moved in screen space. The x direction change is the red channel, and the y direction change is in the green channel. The interpolation from per-vertex velocity to per-pixel velocity is done automatically because the velocity is passed to the pixel shader using a texture coordinate.

The second part of CMyD3DApplication::Render is where the motion blur actually happens. It uses the technique called PostProcessMotionBlur to do the post-process motion blur. The technique PostProcessMotionBlur uses a ps_2_0 pixel shader called PostProcessMotionBlurPS. This pixel shader does two texture look-ups to get the per-pixel velocity of the current frame (from CurFrameVelocityTexture) and of the last frame (from LastFrameVelocityTexture). If it just used the current frame's pixel velocity, then it wouldn't blur where the object was in the last frame because the current velocity at those pixels would be 0. Instead, you could filter neighboring pixels to see if any have a nonzero velocity. This requires a large number of texture look-ups which are limited and also may not work if the object has moved too far. So instead, the shader uses the larger of the current velocity or the last frame's velocity.

Once it has chosen the value to use as the pixel's velocity, it samples twelve times along the direction of the pixel's velocity. While sampling, it accumulates the color and divides by the number of samples to get the average color of all the samples and writes this as the final color for that pixel.

For example, here is an original unblurred scene:

And here's what a blurred scene looks like:

What are the pitfalls of this technique? Because the final post-process pixel shader is blurring the whole scene at once without knowledge of object edges, artifacts will arise if objects are occluded because the blur kerne l from one object will sample color from another nearby object. For example:

Also, it will be noticeable if the pixels in an object have moved too far since the last frame.

To correct this, you can either increase the frame rate so that the pixels do not move as far between frames, or reduce the blur factor.


PostProcess Sample

This sample demonstrates some interesting image-processing effects that can be achieved interactively. Traditionally, image processing takes a significant amount of processor power on the host CPU, and is usually done offline. With pixel shaders, these effects can now be performed on the hardware more efficiently, allowing them to be applied in real time.

Note that the techniques shown here require pixel shader 2.0 and floating-point textures. Thus, not all cards support all of the postprocessing techniques.

Path

Source: | (SDK root)\Samples\C++\Direct3D\PostProcess
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\PostProcess.exe

Post Processing Effects

Image-processing techniques can improve the quality and realism of a scene, as well as achieve some specific effects, such as scene-wide blurring. In Direct3D, image processing is usually performed as a postprocess after the rendering is completed. An application first renders its scene onto a texture, then processes the texture with a pixel shader to produce a different image with the enhancement or alteration. The use of pixel shaders makes this operation very efficient, so it can be performed in real time.

Postprocess effects can achieve interesting results particularly when a sequence of one or more postprocesses are applied to the original scene. Four such postprocess effects are included in this sample:

  • Blur - Combine a pixel color with surrounding pixel colors to blur the focus.
  • Bloom - Magnify bright spots in the image, as well as the area around the bright spots.
  • Depth of Field - Blur a pixel based on the pixel's depth or z value. Pixels very far away or very close get blurred.
  • Edge Glow - Use object normals to find an object's edge, and then use blur to help create a glow on the edges.

How the Sample Works

The scene contains a mesh object that can either be textured or environment-mapped, and a background in the form of a skybox cube. The sample can be divided into two parts: the first part renders scene data into three source render targets, and the second part uses pixel shaders to implement 2D effects into three destination render targets.

Part 1 of the sample renders per-pixel data into three scene render targets: 0, 1, and 2.

Part 2 of the sample may use source material from the three scene render targets and the source render targets (0,1,2), and renders a full-screen quad with a pixel shader into the destination render targets (3,4,5). The six render targets in Part 2 are organized into three swap chains indicated by the curved arrows in the figure. When a pixel shader completes, the destination render target is swapped with its respective source render target. As a result, this sample can be used to cascade postprocessed effects. For instance, [Color] Monochrome is a postprocess effect that samples the color source texture (target 3), converts it to grayscale, then outputs the result to the other texture in the swap chain for the color channel (target 6).

Not all postprocess effects require all three render targets. However, using three render targets provides more options for the postprocess effects. Most of the time, the color render target gets updated and replaced. However, allowing other textures to be replaced gives more flexibility. Creative postprocess effects that change the normal and position textures are possible with the sample's architecture. The number of postprocess effects that can be rendered is only limited by system resources.

Running the Sample

When the sample is run, the user sees a typical Direct3D sample window and a Select Post Process Effects dialog that looks like this:

At the top of the dialog are two list controls. The first list displays the post-process effects that are available. The second list displays the active effects. After a scene is rendered, the active post-process effects are applied to the scene image in the order listed before displaying the result to the user. When the user modifies the active list, the visual change to the scene is immediately reflected.

Below the lists are buttons for changing the order the effects are applied. The button also clears the list. In the parameter section, some effects (such as bright pass) have parameters that the user can tweak to generate different visual appearances. The user can highlight an active post-process to adjust its parameters, if it has any.

At the bottom is the predefined post-process combinations that demonstrate how the different post-process effects can be used together to achieve even more interesting results.

The Effect Files

Each postprocess is implemented in one D3DX effect file. One technique, called PostProcess, exists in each file that is selected when its postprocess effect is needed. The technique can have one or more passes. Each pass specifies a pixel shader that does the actual work of image processing when invoked. The technique can have an integer annotation, named nRenderTarget, that specifies to which texture the pixel shader output should go. Assign it a value of 0, 1, or 2 to indicate that the pixel shader output is to be written to the color, normal, or position texture, respectively. If this annotation is missing, the output is assumed for the color texture.

The passes can optionally have two floating-point annotations named fScaleX and fScaleY. These two values specify the amount that the output image is scaled before written to the render target. After a postprocess scales the image to a size smaller than the render target texture, all subsequent postprocesses work with that image size until it is scaled again. This can have a significant performance boost, because the pixel shaders have fewer pixels to process. A common postprocessing practice is to scale down the image, apply postprocess effects to the sub-area of the texture, then scale up the result image to the original size. The performance gain from having fewer pixels to process usually far exceeds the penalty of performing the extra steps of scaling.

In the effect file, there are six texture objects with samplers from which the postprocess pixel shader will sample. g_txSrcColor, g_txSrcNormal, and g_txSrcPosition contain the colors, normals, and camera space positions from the result of the previous postprocess. g_txSceneColor, g_txSceneNormal, and g_txScenePosition are the result from the scene renderer. For the first postprocess in the sequence, these two sets of textures will be identical.

Often, the postprocess pixel shader will need to sample a source texture multiple times for a single destination pixel, each at a different location near the destination pixel. When this is the case, the effect file declares a kernel which is an array of texel offsets (float2) from the destination pixel. The effect file then defines another equally-sized array of float2. This second array has a string annotation, named ConvertPixelsToTexels, that contains the name of the first kernel array. When the sample loads the effect file and sees this annotation, it will translate the offsets from pixel coordinates to texel coordinates, which are compatible with the texture sampling functions such as tex2D (Direct3D 9 HLSL). When the source texels are sampled, the offsets in the kernel are added to the texture coordinates to obtain the texel values near the destination pixel.

Some effects use parameters that the user can adjust. For instance, the Bright Pass effect has parameters that the user can tweak to give different visual appearances. Each PostProcess technique can define one or more annotations for this purpose. The maximum number of parameters supported by a single technique is four.

Annotation Name | Type | Description
Parameter0 | string | Contains the name of the variable that the user can adjust.
Parameter0Def | float4 | Default value for Parameter0. This is always a float4. If fewer than four floats are needed, use Parameter0Size to specify it.
Parameter0Size | int | Specifies how many components of Parameter0 are used. If this is 2, then only the first two components (x and y) are used.
Parameter0Desc | string | A string that describes this parameter.

The Sample Code

In the sample code, each postprocess effect type is represented by a CPostProcess class. This class encapsulates the effect files and provides a mechanism to activate the effect technique and change its parameters. At initialization, an array of CPostProcess objects is created, one for each postprocess effect file.

In the active postprocess effect list, each entry is represented by the CPProcInstance class. This class merely contains an index to the CPostProcess array to indicate the effect and the parameters to apply to this postprocess.

The Render method in the sample first renders the scene onto a set of render target textures. Three render targets are used simultaneously here for color, normal, and position. After that is complete, it calls PerformPostProcess, which handles every aspect of applying postprocesses to the scene image. After PerformPostProcess returns, the code calls IDirect3DDevice9::StretchRect to copy the postprocessing result to the device backbuffer so that the user can see the final image.

The postprocess work is done in two functions: PerformPostProcess and PerformSinglePostProcess.

The first thing that PerformPostProcess does is to set up a quad that defines how the rendering is done for the postprocess. Next, it creates a vertex buffer containing the quad created above. Then, it simply iterates through the active effect list and calls PerformSinglePostProcess for each entry in the list.

PerformSinglePostProcess applies a postprocess effect once to a render target texture. First, it initializes the textures and parameters for the effect. Then, it goes into a loop to render all passes of the technique. For each pass, it checks the scaling values and makes the necessary adjustment to the quad. After that, it renders the quad onto the render target texture with a IDirect3DDevice9::DrawPrimitive call. Finally, it swaps the render target texture with the corresponding source texture so that the next postprocess will have the correct textures from which to read and to which to write.

The following section lists the postprocesses included by this sample with a description of what each does.

Post Processes

Name | Implementation File | Description
[Color] Monochrome | PP_ColorMonochrome.fx | Converts the color image to monochrome.
[Color] Gaussian Blur Horizontal | PP_ColorGBlurH.fx | Performs Gaussian blur horizontally. The pixel shader achieves this by sampling several texels to the left and right of the source texture coordinate and performing a weighted average among the samples.
[Color] Gaussian Blur Vertical | PP_ColorGBlurV.fx | Performs Gaussian blur vertically. The pixel shader achieves this by sampling several texels to the top and bottom of the source texture coordinate and performing a weighted average among the samples.
[Color] Bloom Horizontal | PP_ColorBloomH.fx | Performs Gaussian blur horizontally and magnifies the image at the same time.
[Color] Bloom vertical | PP_ColorBloomV.fx | Performs Gaussian blur vertically and magnifies the image at the same time.
[Color] Bright Pass | PP_ColorBrightPass.fx | Performs a bright pass on the image. The Luminance is adjustable.
[Color] Tone Mapping | PP_ColorToneMapping.fx | Performs tone mapping on the image. The Luminance is adjustable.
[Color] Edge Detection | PP_ColorEdgeDetect.fx | Performs edge detection based on the color texture. For each pixel shader pass, the shader samples the texel at texcoord and its four neighboring texels. Then, it computes the differences between the texel and each of its neighbors. Finally, the shader sums the four absolute values of the differences and outputs it. The end result is that if a pixel has significantly different color from its neighbors, the postprocess result pixel will look bright.
[Color] Down Filter 4x | PP_ColorDownFilter4.fx | Performs a down-filtering pass. The dimension to work with scales to 0.25 times the original. A down filter shrinks the image.
[Color] Up Filter 4x | PP_ColorUpFilter4.fx | Performs an up-filtering pass. The dimension to work with scales to 4 times the original. An up filter enlarges the image.
[Color] Combine | PP_ColorCombine.fx | Adds the result from previous postprocesses and the original scene together and outputs the sum.
[Color] Combine 4x | PP_ColorCombine4.fx | Adds the result from previous postprocesses and the original scene together and outputs the sum, as well as performing a 4x up-filtering pass.
[Normal] Edge Detection | PP_NormalEdgeDetect.fx | Performs an edge detection similar to [Color] Edge Detection except that this technique compares the normals of the neighboring texels instead of colors. An advantage of this method over the colored-based one is that texture patterns will not be treated as edges.
DOF Combine | PP_DofCombine.fx | Performs a linear interpolation between the result texel from previous postprocesses and the original image based on the z coordinate at the pixel. A vector parameter representing the focal plane is used to determine the weights from the two source textures.
Normal Map | PP_NormalMap.fx | Takes the normal (texel on the normal texture) at the pixel and outputs it as the color. This is simply provided as a way of visualizing normals in a scene.
Position Map | PP_PositionMap.fx | Takes the position (texel on the position texture) at the pixel and outputs the z value as the color. This is simply provided as a way of visualizing depth information in a scene.

Blur

Blur is a very common image-based effect, and it is also rather straightforward. First, a down filter is performed to reduce the number of pixels that will be drawn (and therefore improve performance). Then, one horizontal blur and one vertical blur are performed. If more blurring is desired, repeat the blur effects. Finally, an up filter is performed to get the result image to the original size.

Bloom

The visual effect that bloom achieves is that bright spots in a scene get magnified and brighten the area around those spots. In order to achieve this, two passes of down filter are first performed. Because bringing out the bright spots does not require much detail, two passes of down filter boost the performance without sacrificing quality. Next, a bright pass is done. This postprocess picks up the areas in the image that are above a certain threshold, makes them white, then makes the rest of the image black. After that, two alternating passes each of horizontal bloom and vertical bloom are performed. Finally, two passes of up filter are performed, then the result is combined with the original image. Note that the second up filter pass and the combine are done in a single effect, [Color] Combine 4x.

Depth of Field

The depth of field (DOF) effect blurs the pixel of the image based on the z distance at that pixel. The steps that are needed to perform this are identical to that for the blur effect, except that a DOF Combine effect is added to the end of the sequence. Before the DOF combine, there are two textures available from which to sample: the blurred image from previous postprocesses and the original unblurred image. The DOF Combine examines the z coordinate at each pixel and computes a color by linearly interpolating between the two textures.

Edge Glow

This effect is very similar to bloom in concept, which is to take an image, make a part of it colored and everywhere else black, then combine with the original image. In this case, the area where it is emphasized is around the edges in the scene. First, a normal-based edge detection is performed. This produces white lines along the edges in the image (where normals change dramatically between neighboring pixels). Then, a blur effect is performed, by down-filtering, blurring, and up-filtering. Finally, the result is combined with the original image to produce the effect of glow along the edges. Note that the up-filtering and the final combination are done in a single effect.


ProgressiveMesh Sample

This ProgressiveMesh sample shows how an application can use the D3DX progressive mesh functionality to simplify meshes for faster rendering. A progressive mesh is a specialized mesh object that can increase or decrease its geometry complexity, thereby providing flexibility when drawing the mesh so that performance can be maintained at a steady level. This feature is useful when providing LOD support.

Note The simplification algorithm used to generate progressive meshes is based on Hugues Hoppe's SIGGRAPH papers.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Meshes\ProgressiveMesh
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\ProgressiveMesh.exe

How the Sample Works

The functionalities of progressive meshes are provided by ID3DXPMesh. This mesh interface is similar to ID3DXMesh with additional methods for managing the mesh's complexity. To generate a progressive mesh, call D3DXGeneratePMesh. The progressive mesh can be used just like a regular mesh. To render it, the sample loops through its materials and calls ID3DXBaseMesh::DrawSubset to send the geometry subset to the device. To adjust the progressive mesh's level of detail (LOD), the sample calls ID3DXPMesh::SetNumVertices passing it the desired number of vertices. A progressive mesh will simplify or enhance its geometry to match the number of vertices as closely as possible.

The sample also shows an optimization technique for progressive meshes by trimming multiple progressive meshes. Trimming limits the maximum and minimum number of vertices or faces a progressive mesh can have. The sample divides the range (maximum - minimum) of the progressive mesh vertices into ten sub-ranges. After the sub-ranges are computed, the sample creates ten progressive meshes by calling ID3DXPMesh::ClonePMeshFVF on the original mesh. Then the sample calls ID3DXPMesh::TrimByVertices on each progressive mesh using a different sub-range. After setting the range of vertices, the sample calls ID3DXPMesh::OptimizeBaseLOD to optimize the mesh's vertex and index buffers. Whenever the user changes the vertex count, the new vertex count is checked against the range of the optimized progressive mesh set, and the mesh whose range contains the desired vertex count is selected by calling ID3DXPMesh::SetNumVertices.

The advantage of using multiple meshes is that adjusting LOD is more efficient than using a single progressive mesh. The performance load of changing LOD is directly proportional to the difference in complexity (represented by vertex count in this sample). Simplifying a mesh by reducing the number of vertices by ten takes less time than reducing the vertex count by 100. That is why this sample achieves better performance by trimming several progressive meshes, each of which covers a smaller LOD range.


PRT Simulator (prtcmdline.exe)

This is a PRT simulator tool that is run from the command line.

Syntax

prtcmdline.exe [/s] [/v] *.xml...

Where:

Switch Options | Description | Default Value
[/s] | Optionally searches in the specified directory and all subdirectoies of each filename. | Do not search
[/v] | Optional verbose output. Useful for debugging | Minimal text output.
*.xml ... | Specifies one or more .xml files to read. Each .xml file specifies the options for running the simulator. The filename should contain a directory path. Wildcards are supported. The example shows a sample .xml file called Options.xml. | You must supply at least one .xml file.

Example

This is an example options file for the PRTCmdLine sample. Change the values as desired, but keep the ordering of the nodes unchanged.

<Options>
  <Input>
    <Mesh>
      <MeshFile>PRT Demo\wall_with_pillars.x</MeshFile>
      <IsBlockerMesh>0</IsBlockerMesh>
      <Translate.x>0.000000</Translate.x>
      <Translate.y>0.000000</Translate.y>
      <Translate.z>0.000000</Translate.z>
      <Scale.x>1.000000</Scale.x>
      <Scale.y>1.000000</Scale.y>
      <Scale.z>1.000000</Scale.z>
      <Yaw>0.000000</Yaw>
      <Pitch>0.000000</Pitch>
      <Roll>0.000000</Roll>
      <SHMaterial>
        <Diffuse.r>1.000000</Diffuse.r>
        <Diffuse.g>1.000000</Diffuse.g>
        <Diffuse.b>1.000000</Diffuse.b>
        <Absorption.r>0.003000</Absorption.r>
        <Absorption.g>0.003000</Absorption.g>
        <Absorption.b>0.046000</Absorption.b>
        <EnableSubsurfaceScattering>0</EnableSubsurfaceScattering>
        <RelativeIndexOfRefraction>1.300000</RelativeIndexOfRefraction>
        <ReducedScattering.r>2.000000</ReducedScattering.r>
        <ReducedScattering.g>2.000000</ReducedScattering.g>
        <ReducedScattering.b>2.000000</ReducedScattering.b>
      </SHMaterial>
    </Mesh>
  </Input>
  <Settings>
    <Order>6</Order>
    <NumRays>1024</NumRays>
    <NumBounces>1</NumBounces>
    <LengthScale>25.000000</LengthScale>
    <NumChannels>3</NumChannels>
    <Compression>
      <EnableCompression>1</EnableCompression>
      <NumClusters>1</NumClusters>
      <Quality>2</Quality>
      <NumPCA>24</NumPCA>
    </Compression>
    <MeshTessellation>
      <EnableTessellation>0</EnableTessellation>
      <RobustMeshRefine>1</RobustMeshRefine>
      <RobustMeshRefineMinEdgeLength>0.000000</RobustMeshRefineMinEdgeLength>
      <RobustMeshRefineMaxSubdiv>2</RobustMeshRefineMaxSubdiv>
      <AdaptiveDL>1</AdaptiveDL>
      <AdaptiveDLMinEdgeLength>0.030000</AdaptiveDLMinEdgeLength>
      <AdaptiveDLThreshold>0.000080</AdaptiveDLThreshold>
      <AdaptiveDLMaxSubdiv>3</AdaptiveDLMaxSubdiv>
      <AdaptiveBounce>0</AdaptiveBounce>
      <AdaptiveBounceMinEdgeLength>0.030000</AdaptiveBounceMinEdgeLength>
      <AdaptiveBounceThreshold>0.000080</AdaptiveBounceThreshold>
      <AdaptiveBounceMaxSubdiv>3</AdaptiveBounceMaxSubdiv>
    </MeshTessellation>
  </Settings>
  <Output>
    <OutputConcatPRTMesh>meshConcat.x</OutputConcatPRTMesh>
    <OutputConcatBlockerMesh>blockerConcat.x</OutputConcatBlockerMesh>
    <OutputTessellatedMesh>tesslatedMesh.x</OutputTessellatedMesh>
    <BinaryXFile>0</BinaryXFile>
    <OutputPRTBuffer>prtbuffer.prt</OutputPRTBuffer>
    <OutputCompPRTBuffer>prtCompBuffer.pca</OutputCompPRTBuffer>
  </Output>
</Options>

You can define any number of <Mesh> objects. They will be concatenated together, and saved to <OutputConcatPRTMesh> and <OutputConcatBlockerMesh>.

You can define have any number of <SHMaterial> objects for each mesh. They are read in order and will be used for the corresponding attribute mesh subset. If only 1 SHMaterial is defined, it will be used for all materials in the mesh.

If the <Output> node is missing, the tool will pick good defaults based on the file name of this XML file which can be useful for batch processing.

See Also

Precomputed Radiance Transfer (Direct3D 9)


PRT Demo Sample

This sample demonstrates how to use ID3DXPRTEngine, a precomputed radiance transfer (PRT) simulator that uses low-order spherical harmonics. The sample then demonstrates how to compress the results with Clustered principal component analysis (CPCA) and view the compressed results with arbitrary lighting in real time using a vs_1_1 shader.

SHPRTVertex sample screenshot

Path

Source: | (SDK root)\Samples\C++\Direct3D\PRTDemo
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\PRTDemo.exe

Why This Sample Is Interesting

PRT using low-order spherical harmonic basis functions has a number of advantages over typical diffuse (N • L) lighting. Area light sources and global effects such as interreflections, soft shadows, self shadowing, and subsurface scattering can be rendered in real time after a precomputed light transport simulation. CPCA allows the results of the simulator to be compressed so the shader does not need as many constants or per-vertex data.

Overview

The basic idea is first to run a PRT simulator offline as part of the art content creation process and save the compressed results for later real-time use. The light transport simulator models global effects that would typically be very difficult to do in real time. The real-time engine evaluates the lights in terms of spherical harmonic basis functions and sums them up into a single set of spherical harmonic basis coefficients describing the entire lighting environment. It then uses a vertex shader to arrive at the vertex's diffuse color by combining the compressed simulator results and the lighting environment. Because the offline simulator did the work of computing the interreflections and soft shadows, this technique is visually impressive, efficient, and can be used for real-time lighting.

For more detail about the math behind PRT, clustered principal component analysis (CPCA), and spherical harmonics, see PRT Equations (Direct3D 9) and the following references.

  • Sloan, Peter-Pike, Jan Kautz, and John Snyder. "Precomputed Radiance Transfer for Real-Time Rendering in Dynamic, Low-Frequency Lighting Environments". ACM Transactions on Graphics (TOG), Proceedings of the 29th Annual Conference on Computer Graphics and Interactive Techniques (SIGGRAPH), pp. 527-536. New York, NY: ACM Press, 2002.
  • Sloan, Peter-Pike, Jesse Hall, John Hart, and John Snyder. "Clustered Principal Components for Precomputed Radiance Transfer". ACM Transactions on Graphics (TOG), Vol. 22, Issue 3 (SIGGRAPH), pp. 382-391. New York, NY: ACM Press, July 2003.
  • Green, Robin. "Spherical Harmonic Lighting: The Gritty Details". Game Developers' Conference, San Jose, CA, March 2003.

See Also

Precomputed Radiance Transfer (Direct3D 9), PRT Equations (Direct3D 9)


IrradianceVolume Sample

This sample donated by ATI Technologies (www.ati.com) builds upon the PRT Demo Sample and adds preprocessing of the scene to create a volume of radiance samples stored in an octree. This technique allows a PRT object to use the local lighting environment as it moves through a scene. This sample includes a default data set for user experimentation but can be changed to use your own data sets.

The sample is both a subset and an extension of the content presented at GDC. It does not include any support for gradients and does conventional trilinear interpolation. The PRT object is rendered using compression, which means the constant requirements are drastically reduced from the numbers on slide 46 - they are identical to the requirements in the PRTDemo sample (the slides can be found on the developer web site at www.ati.com).

The GDC slides can be found at:

Irradiance Volumes for Games

Oat, Chris Oat (ATI Research). ATI Technologies, GDC 2005.

Path

Source: | (SDK root)\Samples\C++\Direct3D\IrradianceVolume
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\IrradianceVolume.exe

See Also

Precomputed Radiance Transfer (Direct3D 9), PRT Equations (Direct3D 9)


ShadowMap Sample

This sample demonstrates one popular shadowing technique called shadow mapping. A shadow map (in the form of a floating-point texture) is written with the scene's depth information with the camera placed at the light's position. Once generated, the shadow map is projected onto the scene during rendering. The depth values in the scene are compared with those in the shadow map. If they do not match for a particular pixel, then that pixel is in shadow. Shadow mapping is a very efficient real-time shadow casting technique.

Note

This sample requires ps_2_0 which supports floating-point textures. On cards that do not support ps_2_0, the sample will revert to a reference device which will degrade performance, but is useful for verifying functionality.

Path

Source: | (SDK root)\Samples\C++\Direct3D\ShadowMap
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\ShadowMap.exe

How the Sample Works

Rendering real-time shadows has been an advanced topic in computer graphics. Shadows enhance the realism of the scene and give better spatial cue to the viewers. The two most common shadow-rendering techniques are shadow volumes and shadow maps. The major advantage of using shadow maps over shadow volumes is efficiency since a shadow map only requires the scene to be rendered twice. There is no geometry-processing needed and no extra mesh to generate and render. An application using shadow maps can therefore maintain good performance regardless of the complexity of the scene.

The concept of shadow mapping is straightforward. First, the scene is rendered to a texture from the light's perspective. This texture is called a shadow map and is generated from specialized vertex and pixel shaders. For each pixel, the pixel shader writes the pixel depth instead of the pixel color. When the scene is rendered, the distance between each pixel and the light is compared to the corresponding depth saved in the shadow map. If they match, then the pixel is not in shadow. If the distance in the shadow map is smaller, the pixel is in shadow, and the shader can update the pixel color accordingly. The most suitable type of light to use with shadow maps is a spotlight since a shadow map is rendered by projecting the scene onto it.

During initialization, the sample creates a texture of the format D3DFMT_R32F to be used for the shadow map. The format is chosen because the shadow map only requires one channel, and 32-bits will provide good precision. Rendering is done in two parts: the first part constructs the shadow map, and the second part renders the scene with shadows.

Constructing the Shadow Map

The shadow map is constructed by rendering the scene with the shadow map texture as the render target. The shaders used for this process are VertShadow and PixShadow. VertShadow transforms the input coordinates to projected light space (the projected coordinates as if the camera is looking out from the light). The vertex shader passes the projected z and w to the pixel shader, as texture coordinates, so that the pixel shader has a unique z and w for each pixel. PixShadow outputs z / w to the render target. This value represents the depth of the pixel in the scene, and has a range from 0 to 1. At the near clip plane, it is 0; at the far clip plane, it is 1. When the rendering completes, the shadow map contains the depth values for each pixel.

Rendering with the Shadow Map

The shadowed scene is rendered with two shaders: VertScene and PixScene. VertScene transforms position to projected coordinates and passes the texture coordinates to the pixel shader. In addition, it outputs: the vertex coordinates in view space, the vertex normal in view space, and the vertex coordinates in projected light space. The first two are used for lighting computation. The vertex coordinate in projected light space is the shadow map coordinate. The coordinate is obtained by transforming the world position to light view-space using a view matrix as if the camera is looking out from the light, then transforming the position by the projection matrix for the shadow map.

The pixel shader tests each pixel to see if it is in shadow. First, a pixel is tested to see if it is within the cone of light from the spotlight using the dot product of the light direction and the light-to-pixel vector. If the pixel is within the cone, the shader checks to see if its in shadow. This is done by converting the range of vPosLight (between 0 and 1 to match a texture address range), inverting y (positive y direction is down rather than up when addressing a texture), and then using the coordinate to perform a shadow map look-up.

For each texture lookup, the pixel shader does a 2-by-2 percentage closest filtering (by fetching from each of the four closest texels). For each texel fetched, the texel value is compared to the current pixel depth from the light, or vPosLight.z / vPosLight.w. If the value from the shadow map is smaller, then the pixel is in shadow and the lighting amount for this texel is 0. Otherwise, the lighting amount for this texel is 1. After this is done for all four texels, a bilinear-interpolation is done to calculate the lighting factor for the pixel. The light source will be scaled by this factor to provide the darkening effect of the shadow.

Limitations

One of the limitations is that the shadows generated with shadow maps do not have sharp edges like some shadows in real life, or shadows generated with shadow volumes. Shadows with shadow maps generally have aliasing near the shadow edges that can be noticeable when viewed close-up, as shown in the figure below. This is an inherent behavior of shadow mapping, because it is an image-based technique. Filtering helps reduce the aliasing, but it cannot completely eliminate the artifact.

Another type of artifact with shadow maps is caused by the limited precision of depth values. Shadow mapping technique compares two depth values to detect shadows. When the shadow caster and the shadow receiver are close to each other, the limited precision for depth values may not be sufficient to accurately compare the depths of the two objects. Consequently, area that is in shadow may be mistakenly rendered with light, and vice versa, as illustrated in the figure below.

In addition, shadow maps do not work well with point light sources. However, this can be overcome by using a cube texture whose faces form 6 shadow maps around the light source. When constructing the shadow map in this setup, the application first renders the scene 6 times, with each pass rendering depth information onto one face of the cube texture. Then, the scene can be rendered using the cube shadow map.


ShadowVolume Sample

The sample demonstrates one common technique for rendering real-time shadows called shadow volumes. The shadows in the sample work by extruding faces of the occluding geometry (that are facing away from light) to form a volume that represents the shadowed area in 3D space. The stencil buffer is used as a mask for rendering additional geometry, and is updated as geometry is rendered.

Rendering real-time shadows has been an advanced topic in 3D computer graphics. This sample implements the shadow volume technique using the stencil buffer and a vertex shader. First, the occluding geometry is examined, and a different geometry (that represents the shadow volume) is created. When rendering the scene, the shadow volume geometry is rendered with a vertex-extruding vertex shader using the depth-fail stencil technique. The stencil buffer is updated during this process. Using the stencil buffer as a mask, pixels that lie in the shadow volume do not receive lighting. The depth-fail shadow technique requires that the shadow volume must be a closed volume.

The sample supports up to 6 lights and can render the scene three ways:

  • With shadows as you would normally view the scene.
  • With shadows and the shadow volume.
  • With the shadow volume only, but no shadows. This option renders a color code for each pixel based on the complexity of the shadow volume at each pixel (i.e., how many times a pixel is rendered with the shadow volume).

Path

Source: | (SDK root)\Samples\C++\Direct3D\ShadowVolume
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\ShadowVolume.exe

How the Sample Works

A shadow volume of an object is the region in the scene that is covered by the shadow of the object caused by a particular light source. When rendering the scene, all geometry that lies within the shadow volume should not be lit by the particular light source. A closed shadow volume consists of three parts: a front cap, a back cap, and the side. The front and back caps can be created from the shadow-casting geometry: the front cap from light-facing faces and the back cap from faces facing away from light. In addition, the back cap is translated a large distance along the direction of light, to make the shadow volume long enough to cover enough geometry in the scene. The side is usually created by first determining the silhouette edges of the shadow-casting geometry then generating faces that represent the silhouette edges extruded for a large distance along the light direction. Figure 1 shows different parts of a shadow volume.

Figure 1: Creation of a shadow volume. The front cap (blue) and back cap (red) are created from the occluder's geometry. The back cap is translated to prolong the shadow volume, and the side faces (purple) are generated to enclose the shadow volume.

This sample demonstrates a specific implementation of shadow volumes. Instead of determining the silhouette and generating the shadow volume geometry on the CPU, the sample first generates a mesh that can represent the shadow volume of the occluding geometry regardless of light direction and uses a vertex shader to perform vertex extrusion as the shadow volume mesh is rendered. The underlying idea is that for triangles that face the light, we can use them as-is for the front cap of the shadow volume. For triangles that face away from the light, their vertices are translated a large distance along the light direction at each vertex, then they can be used as the back cap. However, a problem occurs at silhouette edges where one triangle faces the light and its neighbor faces away from the light. In this situation, each triangle causes its vertices to be processed differently, and it must be determined how the vertices that are shared by the two triangles should be handled.

To solve this, the two triangles are split by duplicating the shared vertices so that each triangle has its own unique three vertices. When the common edge between the triangles becomes a silhouette edge, one triangle stays where it is and the other moves along the light direction. This, however, creates a gap between the two triangles, but a closed shadow volume cannot have any gap or hole. This can be fixed by adding a quad to the shadow volume mesh between the two triangles. The edge that is shared by the two triangles gets split, and then the four vertices define the quad. Before extrusion, the quad is degenerate because the triangles are next to each other. However, when the triangles are far apart, the quad is stretched and automatically forms the side of the shadow volume. Figure 2 illustrates this process.

Figure 2: The process of splitting two faces. Left: The two faces share vertices A and B. Center: Generate vertices A' (duplicate of A) and B' (duplicate of B) and then let one of the faces reference them. Right: Generate a quad using vertices A, A', B, and B'. For illustration purpose, A' and B' are drawn at a distance from A and B. In actuality, A and A' are coincident in the mesh's vertex buffer, and so are B and B'. The newly created quad would therefore be degenerate.

Generating the Shadow Volume Mesh

The biggest advantage of generating a static mesh for the shadow volume and having a vertex shader extrude its vertices is that very few CPU cycles are required to render shadows. The shadow volume mesh, once generated, does not need to change no matter where the light position is because the vertex shader can extrude vertices in the correct direction as it receives the vertices from the sample. The function that generates shadow volumes is called GenerateShadowMesh. This function takes an input mesh and outputs a different mesh that represents the shadow volume for the input mesh. There are several things that this function does in order to generate the proper shadow volume for the input mesh.

For every edge in the input mesh, the function must split it up into two edges, effectively separating the two faces that share the edge. Then, it creates a quad (or two triangles) that connects the two split edges. Figure 3 visualizes this process. By default, these quads are degenerate, because the split edges are co-linear. However, when one face is extruded and the other is not, the quad between them gets stretched and forms the side of the shadow volume.

Figure 3: Mesh faces (green) are split, and then quads (red) are inserted.

The algorithm that creates the shadow volume mesh works by iterating through the faces in the input mesh. For each face iterated, three things happen.

  • First, three new vertices and one new face are generated for the shadow volume mesh. Each face must have its own unique three vertices because the faces are separated by degenerate quads.
  • Then, the normal of the new vertices are computed to be the normal of the new face, as illustrated in figure 4. The reason that this is necessary is because vertex extrusion is done by a vertex shader, and vertex shaders only see vertex normals, not face normals. By setting the vertex normals to match their face normals, the vertex shader will correctly extrude vertices when the faces they belong are facing away from the light.
  • Finally, the three edges of a face are added to an edge mapping table. An edge mapping entry contains one source edge, representing the edge in the input mesh, and two output edges, representing the split edges in the output mesh. Essentially, the table records the edges in the source mesh and what edges they split into in the output mesh. This information is needed when the quads are generated later. For each edge of the added face, the algorithm looks through the edge mapping table, and if it cannot find an existing entry for the source edge, it creates one and initializes the source edge and one output edge of the edge mapping entry. However, if it finds that the source edge already has an entry in the table, then it has the four vertices of the quad for this edge, so it adds the two faces for the quad to the output mesh and remove the edge mapping entry from the table.

Figure 4: Vertex normals are set up to be identical as the face normals.

At this point, the output mesh contains all of the faces that are in the input mesh, and every edge in the input mesh has been converted to a quad in the output mesh. There is also a list of edges in the mapping table that represents the edges that are not shared in the input mesh. The existence of these edges implies that the input mesh has holes in it, and the holes must be patched so that the shadow mesh becomes a closed volume. This is essential for rendering the shadows with the depth-fail stencil technique. The patching algorithm looks through the mapping table and finds two edges that share a vertex in the original mesh. Then it patches the hole by generating a new face and three new vertices out of the two neighboring edges' vertices. After that, the code generates two quads to connect the patch face to the existing geometry of the output mesh. This process is illustrated in figure 5.

Figure 5: Creating a colsed volume shadow mesh.

Rendering Shadows

At the top level, the rendering steps look like the following:

  • If ambient lighting is enabled, render the entire scene with ambient only.
  • For each light in the scene, do these:
    • Disable depth-buffer and frame-buffer writing.
    • Prepare the stencil buffer render states for rendering the shadow volume.
    • Render the shadow volume mesh with a vertex extruding shader. This sets up the stencil buffer according to whether or not the pixels are in the shadow volume.
    • Prepare the stencil buffer render states for lighting.
    • Prepare the additive blending mode.
    • Render the scene for lighting with only the light being processed.

The lights in the scene must be processed separately because different light positions require different shadow volumes, and thus different stencil bits get updated. Here is how the code processes each light in the scene in details. First, it renders the shadow volume mesh without writing to the depth buffer and frame buffer. These buffers need to be disabled because the purpose of rendering the shadow volume is merely setting the stencil bits for pixels covered by the shadow, and the shadow volume mesh itself should not be visible in the scene. The shadow mesh is rendered using the depth-fail stencil shadow technique and a vertex extruding shader. In the shader, the vertex's normal is examined. If the normal points toward the light, the vertex is left where it is. However, if the normal points away from the light, the vertex is extruded to infinity. This is done by making the vertex's world coordinates the same as the light-to-vertex vector with a W value of 0. The effect of this operation is that all faces facing away from the light get projected to infinity along the light direction. Since faces are connected by quads, when one face gets projected and its neighbor does not, the quad between them is no longer degenerate. It is stretched to become the side of the shadow volume. Figure 6 shows this.

Figure 6: The faces of the shadow volume that face away from light (left, shown in red) have their vertices extruded by the vertex shader to create a volume that encloses area covered by shadows (right).

When rendering the shadow mesh with the depth-fail technique, the code first renders all back-facing triangles of the shadow mesh. If a pixel's depth value fails the depth comparison (usually this means the pixel's depth is greater than the value in the depth buffer), the stencil value is incremented for that pixel. Next, the code renders all front-facing triangles, and if a pixel's depth fails the depth comparison, the stencil value for the pixel is decremented. When the entire shadow volume mesh has been rendered in this fashion, the pixels in the scene that are covered by the shadow volume have a non-zero stencil value while all other pixels have a zero stencil. Lighting for the light being processed can then be done by rendering the entire scene and writing out pixels only if their stencil values are zero.

Figure 7: The depth-fail technique.

Figure 7 illustrates the depth-fail technique. The orange block represents the shadow receiver geometry. Regions A, B, C, D and E are five areas in the frame buffer where the shadow volume is rendered. The numbers indicate the stencil value changes as the front and back faces of the shadow volume are rendered. In region A and E, both the front and back faces of the shadow volume fail the depth test, and therefore both cause the stencil value to change. For region A, the orange shadow receiver is causing the depth test to fail, and for region E, the cube's geometry is failing the test. The net result is that stencil values in this region stay at 0 after all faces are rendered. In region B and D, the front faces pass the depth test while the back faces fail, so the stencil values are not changed with the front faces, and the net stencil changes are 1. In region C, both the front and back faces pass the depth test, and so neither causes the stencil values to change, and the stencil values stay at 0 in this region. When the shadow volume is completely rendered, only the stencil values in regions B and D are non-zero, which correctly indicates that regions B and D are the only shadowed areas for this particular light.

Performance Considerations

Performing vertex extrusion in a vertex shader provides some advantages. Once the shadow volume mesh is generated for a mesh geometry, the application can send the mesh to the 3D device for rendering without modifying it in any way, thus removing the need to perform silhouette determination on the host CPU. However, this technique is not without its shortcoming. The static shadow volume mesh tends to have more vertices than the visible geometry. This is because the geometry needs to have its faces separated and quads generated to produce a valid, closed shadow volume. A completely welded mesh would have a shadow mesh with three times the number of vertices. The increase in vertex count could be so significant that it actually reduces performance by processing them in the vertex shader. Applications are encouraged to implement alternative techniques, such as silhouette determination on the CPU, and then compare the performance result to reach a reasonable conclusion about which technique should be used for each shadow-casting object in the scene.

It is beneficial to use separate meshes for the shadow-casting geometry and its shadow volume. If the additional vertices and faces reside in the original mesh, the application would unnecessarily need to process the extra vertices when rendering the geometry, even when these vertices do not serve any purpose during this process. These extra vertices would also come with the vertex data that do not get used when rendering the shadow, such as texture coordinates and material colors. For the situation when less accurate shadows are adequate, a less-detailed version of the mesh can be used for shadow volume rendering.

Using separate meshes may increase the memory requirement for the geometry. This is the case in the sample, because ID3DXMesh is used for the mesh objects. However, applications can eliminate the need for additional memory by directly utilizing vertex buffers, index buffers, and vertex streams. First, the scene mesh's vertex buffer needs to be split into multiple vertex buffers so that one vertex buffer contains the positions and normals, while other vertex buffers contain the rest of the vertex data, such as material attributes, texture coordinates, and blending parameters. When rendering the geometry, the application must set up multiple vertex streams, one for each vertex buffer. Next, after the shadow volume mesh is generated, the application must reorder its vertex buffer and fix-up its index buffer, so that all vertices that are originally in the input mesh come before the newly created ones. When this is done, the input mesh's vertex buffer for positions and normals would be identical to the first half of the shadow mesh's vertex buffer. Therefore, the input mesh's vertex buffer can be released and the mesh can simply reference the shadow mesh's vertex buffer. Note that the two meshes still require different index buffers. See figure 8 for a visualization of this buffer-sharing arrangement.

Figure 8: Sharing vertex data between the scene mesh and shadow volume mesh. The scene mesh here (enclosed by the green rectangle) has N vertices that span across two distinct vertex buffers, one for positions and normals (shown in red) and the other for everything else (shown in blue). The shadow volume mesh (enclosed by the orange rectangle) has a vertex count higher than the scene mesh. Therefore, its vertex buffer (in red) contains more than N vertices, of which the first N vertices are shared by the scene mesh.

The drawback of using this technique is that the application must manage the vertex and index buffers of the meshes on its own, and can no longer make use of the ID3DXMesh interface for these. Each application should weigh this trade-off based on its own needs and goals.

Finally, there is another area that could call for some performance optimization. As shown earlier, the rendering algorithm with shadow volumes requires that the scene be rendered in multiple passes (one plus the number of lights in the scene, to be precise). Every time the scene is rendered, the same vertices get sent to the device and processed by the vertex shaders. This can be avoided if the application employs deferred lighting with multiple rendertargets. With this technique, the application renders the scene once and outputs a color map, a normal map, and a position map. Then, in subsequent passes, it can retrieve the values in these maps in the pixel shader and apply lighting based on the color, normal and position data it reads. The benefit of doing this is tremendous. Each vertex in the scene only has to be processed once (during the first pass), and each pixel is processed exactly once in subsequent passes, thus ensuring that no overdraw happens in these passes.

Shadow Volume Artifact

It is worth noting that a shadow volume is not a flawless shadow technique. Aside from the high fill-rate requirement and silhouette determination, the image rendered by the technique can sometimes contain artifacts near the silhouette edges, as shown in figure 9. The prime source of this artifact lies in the fact that when a geometry is rendered to cast shadow onto itself, its faces are usually entirely in shadow or entirely lit, depending on whether the face's normal points toward the light. Lighting computation, however, uses vertex normals instead of face normals. Therefore, for a face that is near-parallel to the light direction, it will either be all lit or all shadowed, when in truth, only part of it might really be in shadow. This is an inherent flaw of stencil shadow volume technique, and should be a consideration when implementing shadow support. The artifact can be reduced by increasing mesh details, at the cost of higher rendering time for the mesh. The closer to the face normal that the vertex normals get, the less apparent the artifact will be. If the application cannot reduce the artifact down to an acceptable level, it should also consider using other types of shadow technique, such as shadow mapping or pre-computed radiance transfer.

Figure 9: Shadow volume artifact near the silhouette edges.

Figure 10: Displaying the shadow volume reveals that the jagged edge is caused by faces that are treated as being entirely in shadow when they are actually only partially shadowed.


SimpleSample Sample

Starting point for new Direct3D samples.

Path

Source: | (SDK root)\Samples\C++\Direct3D\SimpleSample
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\SimpleSample.exe

Sample Overview

This sample can be used as a basic starting point for creating a Direct3D sample.

How the Sample Works

This sample uses DXUT to demonstrate common tasks such as device initialization, device reset, and the render loop. It provides the basis for other Direct3D samples.

See Also

EmptyProject Sample


SkinnedMesh Sample

The SkinnedMesh sample illustrates mesh animation with skinning using D3DX. Skinning is an animation technique that takes data organized in a skeletal-mesh hierarchy and applies geometry blending to transform mesh vertices. The geometry blending generates smooth surfaces with fewer artifacts.

Path

Source: | (SDK root)\Samples\C++\Direct3D\SkinnedMesh
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\SkinnedMesh.exe

Sample Overview

Direct3D and D3DX can be used to animate meshes. Applications can load X files containing animation data, then control and render the animated meshes. This sample demonstrates five skinning techniques: fixed-function non-indexed, fixed-function indexed, software, assembly shader, and HLSL shader. Each technique has its advantages and disadvantages, and application developers should weigh these and choose the appropriate techniques for the needs of their application.

Skinning is a popular animation technique that is modeled like a human body. Skinning uses a set of interconnected bones (or frames) that form a hierarchy. Moving or rotating the bones cause the mesh surface to move or rotate. The mesh surface is analagous to the skin of the human body. Each point (or vertex) on the mesh surface is associated with a number of bones. Its position is determined by the position of the associated bones. For instance, consider the hierarchy in figure 1 that describes a human limb:

Clavicle
  Upper Arm
    Forearm
      Hand
        Finger0
        Finger1
        Finger2
        Finger3
        Finger4

Figure 1. The hierarchy of a human limb.

The skin at the elbow is influenced by the upper arm bone and the forearm bone. If the upper arm remains stationary and the forearm moves, the elbow skin position is affected; the same is true when holding the forearm stationary and moving the upper arm. It can be concluded that the skin at the elbow is associated with both the upper arm and forearm bones. Transforming vertices with multiple matrices are done with geometry blending. Each matrix has a blending weight ranging from 0 to 1, with the sum of all blending weights equal to 1. The blending operation is carried out by first transforming the vertex with each matrix, yielding several transformed vertex coordinates. Then, these coordinates are interpolated based on the corresponding blending weights. Vertices can have different blending weights even if they are influenced by the same bones. This geometry blending allows surfaces to stay smooth when animated.

Furthermore, any movement by an ancestor bone may affect the skin position. For instance, if both the upper arm and forearm bones remain stationary (that is, no rotation), and the clavicle bone moved, the skin between the upper arm bone and the forearm bone should change position. This explains why the child bones are modeled in a hierarchy to generate this dependency.

Figure 2. The effect of bone offset transformation on the character's left forearm.

  • Left: The character as it is stored on the disk.
  • Middle: The bone offset transformation changes the vertex coordinates from the mesh space to bone space.
  • Right: Now that vertices are in bone space, animation transformation can be performed. In this case, a rotation is applied to the forearm.

How the Sample Works

The first step in loading a mesh is to call D3DXLoadMeshHierarchyFromXInMemory. This call is similar to D3DXLoadMeshHierarchyFromX, in that they both load a mesh from an X file into memory. However, D3DXLoadMeshHierarchyFromXInMemory returns the mesh in the form of a hierarchy tree composed of bones (or frames). This form matches how the mesh is structured in the X file. In D3DX, an animatable mesh is composed from a frame hierarchy. At the very top, there is a root frame. The root frame has one or more child frames, each child frame has its own child frames, and so forth.

A frame in the hierarchy is represented by a structure derived from a D3DXFRAME. An application may store private information with each frame by deriving the format of each hierarchy node from D3DXFRAME. D3DXFRAME, as shown in figure 3, provides the bare minimum data required by the hierarchy. Each frame has a name, a transformation matrix, and a mesh container for the geometry data. Each frame also contains a link to a sibling and a child frame.

typedef struct _D3DXFRAME {
    LPSTR Name;
    D3DXMATRIX TransformationMatrix;
    LPD3DXMESHCONTAINER pMeshContainer;
    struct _D3DXFRAME *pFrameSibling;
    struct _D3DXFRAME *pFrameFirstChild;
} D3DXFRAME, *LPD3DXFRAME;

Figure 3. D3DXFRAME is the building block of a mesh hierarchy.

The SkinnedMesh sample derives D3DXFRAME and augments the struct with another matrix named a combination matrix which will be used when advancing the animation.

In a hierarchy, some frames will have valid container values, which are the mesh geometry data. When rendering the mesh, the container is drawn regardless of its location in the mesh hierarchy. Similar to a frame, an application should define its own mesh container type by deriving from a D3DXMESHCONTAINER, shown in figure 4.

typedef struct _D3DXMESHCONTAINER {
    LPSTR Name;
    D3DXMESHDATA MeshData;
    LPD3DXMATERIAL pMaterials;
    LPD3DXEFFECTINSTANCE pEffects;
    DWORD NumMaterials;
    DWORD *pAdjacency;
    LPD3DXSKININFO pSkinInfo;
    struct _D3DXMESHCONTAINER *pNextMeshContainer;
} D3DXMESHCONTAINER, *LPD3DXMESHCONTAINER;

Figure 4. A standard mesh container.

All data fields in a D3DXMeshContainer also exist for an ordinary mesh, except for Name and pSkinInfo. Name is a unique string that identifies the mesh container in the hierarchy and pSkinInfo holds bone matrices information. This information consists of the bones by which each vertex is influenced, and is important when setting up the mesh into attribute groups.

In addition to returning a mesh hierarchy, D3DXLoadMeshHierarchyFromX returns an ID3DXAnimationController interface associated with the mesh frames. The animation controller controls the flow of the animation available to the mesh; use it specify what animation sequences to play and how fast each sequence plays.

Because the two fundamental structures of a frame hierarchy are often derived and defined by the application itself, the application has to define functions that handle the allocation and deallocation of the frames and mesh containers. ID3DXAllocateHierarchy is an interface that describes how the application can define such allocation and deallocation functions. To use it, an application first defines a class derived from ID3DXAllocateHierarchy. Then, implement the four methods declared by the interface: ID3DXAllocateHierarchy::CreateFrame, ID3DXAllocateHierarchy::DestroyFrame, ID3DXAllocateHierarchy::CreateMeshContainer, and ID3DXAllocateHierarchy::DestroyMeshContainer. The create methods allocate a new instance of frame or mesh container struct, allocate other resources as necessary, initialize the struct fields, and return the object instance back to the caller.

The destroy methods should free all resources allocated during the creation of the frame or mesh container, including the frame or mesh container instance itself. In the SkinnedMesh sample, CreateMeshContainer also initializes the application-defined fields in the mesh container structure. The structure is shown in figure 5.

struct D3DXMESHCONTAINER_DERIVED: public D3DXMESHCONTAINER
{
    LPDIRECT3DTEXTURE9*  ppTextures;

    // SkinMesh info
    LPD3DXMESH           pOrigMesh;
    LPD3DXATTRIBUTERANGE pAttributeTable;
    DWORD                NumAttributeGroups;
    DWORD                NumInfl;
    LPD3DXBUFFER         pBoneCombinationBuf;
    D3DXMATRIX**         ppBoneMatrixPtrs;
    D3DXMATRIX*          pBoneOffsetMatrices;
    DWORD                NumPaletteEntries;
    bool                 UseSoftwareVP;
    DWORD                iAttributeSW;
};

Figure 5. A derived mesh container.

After retrieving the bone offset matrices from pSkinInfo, CreateNeshContainer calls GenerateSkinnedMesh to set up the mesh hierarchy for animating and rendering. GenerateSkinnedMesh divides the mesh vertices into groups based on the skinning method used, which makes rendering the mesh optimal.

After D3DXLoadMeshHierarchyFromX returns, the sample calls SetupBoneMatrixPointers. This function traverses the frame hierarchy to search for mesh containers. When it finds a mesh container, it calls SetupBoneMatrixPointersOnMesh to initialize the ppBoneMatrixPtrs member of the mesh container. This member is an array of matrix pointers, where each element in the array points to a particular frame matrix. This array provides a quick lookup for frame matrices by frame index. Because the hierarchy is structured as a tree, performing an index-to-matrix lookup is not a straightforward process. This matrix serves as a helper lookup table for efficiency.

Rendering the Mesh

Rendering the animated mesh is a two-step process: setting up the matrices and the actual rendering. To set up the matrices, ID3DXAnimationController::AdvanceTime is called first. This method takes a TimeDelta parameter that indicates how much to advance since the last call, then it updates the frame hierarchy's transformation matrices with matrices that correspond to the bone positions at that instance of time. These matrices contain transformation with respect to their parent frames, consisting of a scaling plus rotation plus translation transformation. Next, the sample calls UpdateFrameMatrices. This function updates the frame hierarchy's combined transformation matrix. The combined transformation matrix holds the product of all of the ancestor frames' matrices, including the frame's own matrix. Recall that bones are influenced by their parent bones, and the parent bones are influenced by the grandparent bones, and so forth. Combining all influencing matrices makes the combined transformation matrix absolute, or relative to the world, which is more suitable for rendering. UpdateFrameMatrices achieves this by recursively traversing the hierarchy tree. For each frame, it writes the product of the transformation matrix and the parent's matrix to the combined transformation matrix. Then it calls UpdateFrameMatrices on its sibling and first child nodes, passing its parent matrix to the sibling and passing its own combined transformation matrix as the parent matrix for the children.

The actual rendering, like all other samples, starts in OnFrameRender. The rendering of the mesh is done by the DrawFrame. This function takes a pointer to a frame node, draws the frame's mesh if one exists, then recursively calls itself again with the frame's sibling and children. The result is that all mesh containers in the frame hierarchy will be drawn when the top DrawFrame returns. When a frame holds a valid mesh container, DrawFrame calls the DrawMeshContainer, which is where all the mesh rendering takes place.

DrawMeshContainer renders the mesh in different ways:

  • Rendering with Fixed-Function Non-Indexed Skinning
  • Rendering with Fixed-Function Indexed Skinning
  • Rendering with Shader-Based Skinning
  • Rendering with Software Skinning

Rendering with Fixed-Function Non-Indexed Skinning

When this skinning technique is active, the device can load up to four world matrices at a time and transform the vertices influenced by those four matrices. After these vertices are rendered, a different set of matrices can be loaded, and vertices influenced by the second set of matrices can be rendered. This rendering process continues until all faces of the mesh are rendered. GenerateSkinnedMesh calls ID3DXSkinInfo::ConvertToBlendedMesh which divides a mesh's faces into attribute groups. Each attribute group identifies geometry influenced by a particular set of four matrices. At render time, each attribute group can be rendered with a single IDirect3DDevice9::DrawIndexedPrimitive.

For non-indexed skinning, DrawMeshContainer loops through each attribute group in the mesh and renders one attribute group at a time. The mesh is set up so that each attribute group is influenced by up to four matrices. Before the vertices can be sent to the device, the influencing matrices first need to be sent to the device. To set the matrices, IDirect3DDevice9::SetTransform is called with the transformation type D3DTS_WORLDMATRIX(i), where i ranges from a minimum of 0 to a maximum of 3. The matrices that the function sends to the device for a particular attribute group are obtained from pBoneCombinationBuf of the mesh container. This member points to a buffer containing an array of type D3DXBONECOMBINATION. Each D3DXBONECOMBINATION identifies the bone matrices influencing this attribute group. With this information, the sample knows which four matrices to load on the device to properly render an attribute group. Before actually setting the matrices, however, the matrices need to have the bone offset matrices applied to them. Recall that bone offset matrices transform the vertices from the mesh's default pose on the disk to the parent bone's frame of reference. Therefore, a matrix that gets sent to the device is the product of the bone matrix and the frame's combined transformation matrix. After loading the matrices, the faces of the attribute group can be rendered by calling ID3DXBaseMesh::DrawSubset.

Rendering with Fixed-Function Indexed Skinning

With the fixed-function indexed skinning, the device has a matrix palette. The size of the palette can be obtained from the device capability information. The application can load as many matrices as the palette could hold. Each vertex in the mesh has up to four indices to identify the matrices in the palette that influence the vertex. In the sample, the code uses a maximum 12-matrix palette. Using a larger palette is more efficient, but using a smaller palette makes the code compatible with more devices. To obtain a mesh suitable for indexed skinning, GenerateSkinnedMesh calls ID3DXSkinInfo::ConvertToIndexedBlendedMesh (which is similar to ID3DXSkinInfo::ConvertToBlendedMesh) but it takes a palette size and divides the mesh vertices into attribute groups to work with the matrix palette. Each attribute group is influenced by one specific set of matrices that can fit in the palette, and can be drawn with a single IDirect3DDevice9::DrawIndexedPrimitive.

The render code for indexed skinning looks extremely similar to the non-indexed case. GenerateSkinnedMesh loops through the attribute groups and sets up the matrices to send to the device, just as it would for non-indexed skinning. Here, each attribute group identifies the vertices influenced by a particular set of matrices in the palette. In the D3DXBONECOMBINATION array, each element identifies the bone matrices with which to load the palette when rendering this attribute group. After the matrices are set, this attribute group's faces are rendered with a call to ID3DXBaseMesh::DrawSubset.

Rendering with Shader-Based Skinning

Shader-based skinning is, in concept, similar to fixed-function indexed skinning. Instead of using the hardware-supported matrix palette, the application uses shader constants to load the matrices. Then, the vertex shader can read in the matrix values and perform the skinning transformation. The sample supports two types of shader-based skinning: assembly and HLSL. Virtually, the only difference between the two is how the shader is written. Similar to fixed-function indexed skinning, GenerateSkinnedMesh computes the number of constants required for the palette, then calls ID3DXSkinInfo::ConvertToBlendedMesh to obtain a mesh that is attribute-sorted by palette. It is worth noting that each matrix in the palette only requires three shader constants because the fourth column is always (0, 0, 0, 1) and does not need to be explicitly stored.

Shader-based skinning is a form of indexed skinning. Instead of loading the matrices with IDirect3DDevice9::SetTransform, they are loaded as shader constants. The sample computes the matrices to send to the device in exactly the same manner as in the fixed-function indexed case. When sending the matrices, the sample calls IDirect3DDevice9::SetVertexShaderConstantF when using an assembly shader, or ID3DXBaseEffect::SetMatrixArray when using an HLSL shader. After this is done and the shader is set up, the attribute group can be rendered with DrawSubset.

Rendering with Software Skinning

Software skinning, as the name suggests, performs the skinning work completely in software. The process takes an input mesh and the bone matrices, carries out the transformation and blending, then writes the result into another mesh. This resulting geometry represents the animation pose desired and can be sent to the device for rendering. The biggest drawback of software skinning is performance. Software skinning is inherently slow because it is done by software instead of the efficient hardware. However, software skinning is also the only technique that is guaranteed to work regardless of the device on which the application runs. (Note that other skinning techniques can also work on all devices by using software vertex processing. However, software skinning can be useful in certain situations, such as performing a hit test on the animated mesh.) To set up for software skinning, the sample allocates an array of matrices to function as the software matrix palette. During rendering, this matrix array will be filled with skinning matrices and used to animate the mesh.

Essentially, software skinning can be thought of as the indexed skinning with an infinitely large palette (or as large as the system memory allows) done completely in software. All matrices can be loaded simultaneously for rendering. In the sample, DrawMeshContainer computes all matrices for the mesh and stores the result in a matrix array. ID3DXSkinInfo::UpdateSkinnedMesh implements software skinning on a set of source vertices using the passed transformation matrices and fills a set of output vertices with animated coordinates. When it returns, the MeshData member of the mesh container holds a skinned and animated mesh; the entire mesh can now be drawn by calling DrawSubset. The code still has to draw each attribute group at a time if the mesh contains multiple materials.


StateManager Sample

This sample demonstrates how to implement a set of callbacks using the ID3DXEffectStateManager to measure the number and types of state changes in a render loop managed by the effect system. The sample also demonstrates how to use the callbacks to override the default state managment, which gives an application the option of implementing a custom approach to state filtering. An application that is CPU-bound is very likely to improve performance dramatically by controlling the amount of redundant state changes that occur in a complex render loop.

Path

Source: | (SDK root)\Samples\C++\Direct3D\StateManager
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\StateManager.exe

Prerequisites:

How The Sample Works

This sample renders a scene composed of several mesh objects including a gazebo, trees, rocks, terrain, and a skybox. Each mesh may be composed of multiple materials (snow, wood, etc). Each material is implemented by a different effect. Because of the scene complexity, the render sequence has many state changes to render the variety of materials and objects. The render sequence is created after calling these functions in OnCreateDevice:

  • BuildSceneFromX - This method loads the scene .x file, which specifies each of the meshes and their world transform. Each mesh then loads it's corresponding materials, which consists of an effect instance and the associated textures (if any).
  • QueueAndSortRenderables - This method does two things. First, it adds to the render queue all the state changes necessary to render the scene. Second, it reorders the queue according to the type of device, and the state manager.
  • SetStateManager - This method propogates the state manager to each of the effects in preparation for rendering.

The sample demonstrates the benefits of filtering redundant state changes with a per device. When a device is created (IDirect3D9::CreateDevice), the type of device is specified with D3DDEVTYPE. A pure device (created with D3DCREATE_PUREDEVICE) filters a smaller subset of possible state change commands. It is very fast because is essentially streams the pipeline commands striaght to the hardware. A pure device does not do any validation of parameters, and does little or no redundant state filtering. In constrast, a non-pure device (created without D3DCREATE_PUREDEVICE) will check each state change for redundancy, and discard them. This reduces the amount of work that the device will need to perform.

The ID3DXEffectStateManager makes it possible to write custom user handlers for state changes. You can measure the number of state changes, that are happening, or even write handlers that perform custom processing (such as filtering out redundant state changes. This is precisely what the StateManager sample does. When you run the sample, it defaults to: running a pure device, and filtering redundant states with ID3DXEffectStateManager. This is done by creating a CPureDeviceStateManager class which derives from ID3DXEffectStateManager.

CPureDeviceStateManager counts the state changes, filters redundant IDirect3DDevice9::SetRenderState, IDirect3DDevice9::SetSamplerState and IDirect3DDevice9::SetTextureStageState commands, and invokes the corresponding Direct3D command. The number of redundant state changes that were filtered is returned to the application.

For instance:

State Changes | Filtered State Changes | Number of Rocks | % Reduction in State Changes
120 | 38 | 1 | -31
7971 | 3856 | 200 | -48

Another Performance Tip: Reordering The Render Sequence

In addition to filtering redundant state changes, another option to improve performance is to re-order the render sequence. This can have an impact especially on a non-pure device, or in a scenario that is more limited by the amount of matrix transforms that are set (as opposed to the number of materials used). For example, here is a render sequence that is ordered by each mesh object:

// Render each mesh object
For each instance of mesh x
    Setup transforms (ID3DXEffect SetMatrix)
    For each material of mesh x
        Set up material (ID3DXEffect Begin/BeginPass)
        Draw

This is the same sequence re-ordered by material:

// Render each effect to minimize state changes
For each material y
    Set up material (ID3DXEffect Begin/Begin Pass)
    For each instance of material y
      Set up transforms (ID3DXEffect SetMatrix)
      Draw

Each sequence is better in some situations and worse in others. An application that has lots of materials may reduce the number of redundant state changes by ordering by material.

For further information about measuring the performance of a CPU bound scenario using similar techniques to a profiler, see Accurately Profiling Direct3D API Calls (Direct3D 9).


Text3D Sample

The Text3D sample shows how to draw 2D text in a 3D scene. This is useful for displaying statistics or game menus, for example.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Text3D
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\x86 or x64\Text3D.exe

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

This sample uses ID3DXFont to display 2D text in a 3D scene. The source code for the class is of most interest to this sample. The class uses Microsoft Windows Graphics Device Interface (GDI) to load a font and output each letter to a bitmap. That bitmap, in turn, is used to create a texture.

When the DrawText function is called, a vertex buffer is filled with polygons that are textured using the font texture created as mentioned above. The polygons may be drawn as a 2D overlay which may be useful for printing statistics.


UV Atlas Command-Line Tool (uvatlas.exe)

UVAtlas.exe is a command line example tool that uses the D3DX UVAtlas and IMT computation functions to generate an optimal, unique texture parameterization for an input mesh.

Syntax

uvatlas.exe [options] [filename1] [filename2] ...

Options

These switch are optional:

Optional Switches | Description | Default Value
[/n int] | Maximum number of charts to generate. This value is a positive integer >= 0. | 0
[/st float] | The maximum amount of stretch. This value is a positive float that ranges from no stretch (0.0) to any amount of stretch (1.0). | 0.16667
[/g float] | The gutter width (width between charts in texels). | 2.0
[/w int] | Texture width | 512
[/h int] | Texture height | 512
[/uvi int] | Specifies the output D3DDECLUSAGE_TEXCOORD index for the UVAtlas data. | 0
[/ta] | Generate topological adjacency, where triangles are marked adjacent if they share edge vertices. Mutually exclusive with /ga and /fa. | Do not generate topological adjacency.
[/ga] | Generate geometric adjacency, where triangles are marked adjacent if edge vertices are positioned within 1e-5 of each other. Mutually exclusive with /ta and /fa. | Do not generate geometric adjacency.
[/fa file] | Load adjacency array entries directly into memory from a binary file. Mutually exclusive with /ta and /ga. | N/A
[/fe file] | Load false-edge adjacency-array entries directly into memory from a binary file. An edge that is not false is indicated by -1, while a false-edge is indicated by any other value, e.g. 0 or the original adjacency value. This enables the parameterization of meshes containing quads and higher order polygons, and the internal edges of each polygon will not be cut during the parameterization process. | N/A
[/ip file] | Calculate the Integrated Metric Tensor (IMT) array for the mesh using a PRT buffer in file. | Must provide one filename.
[/it file] | Calculate the IMT for the mesh using a texture map in file. | Must provide one filename.
[/iv usage] | Calculate the IMT for the mesh using a per-vertex data from the mesh. The usage parameter lets you select which part of the mesh to use. It must be one of NORMAL, COLOR, TEXCOORD, TANGENT, or BINORMAL. | COLOR
[/t] | Create a separate mesh in uv space and append _texture to the mesh file. | Do not create a separate mesh.
[/c] | Modify the mesh materials to show which chart each triangle is in. | Do not display.
[/rt file] | Resamples a texture using the new UVAtlas parameterization. The resampled texture is saved to a filename with "_resampled" appended. | Defaults to reading old texture parameterization from D3DDECLUSAGE_TEXCOORD[0] in original mesh. Use /rtu and /rti to override this.
[/rtu usage] | Specifies the vertex data usage for texture resampling. It must be one of NORMAL, POSITION, COLOR, TEXCOORD, TANGENT, or BINORMAL. | TEXCOORD
[/rti int] | Specifies the usage index for texture resampling. | 0
[/o file] | Output mesh filename. Using this option disables batch processing. | Original filename with "_result" appended.
[/f] | Overwrite the original file with the output. | Off
[/s] | Search for files in sub-directories | No search

Filenames

These switches are required:

Required Switches | Description | Default Value
[filenames*] | Specifies the files to generate atlases for. Wildcards and quotes are supported. At least one source file must be provided. | N/A

Example

For example, to generate a unique texture atlas for the airplane model:

uvatlas /t /o mesh.x airplane.x

See Also

UVAtlas Functions, Using UVAtlas (Direct3D 9)


Reference

This section contains the reference pages for the Direct3D API. Information is contained in the following sections:

  • Direct3D Reference
  • D3DX Reference
  • HLSL Shader Reference (Direct3D 9 HLSL)
  • Asm Shader Reference
  • Effect Reference
  • X File Reference
  • DDS File Reference

See Also

X File Reference (Legacy)


Direct3D Reference

This section contains reference information for the API elements provided by Direct3D. Reference material is divided into the following categories.

  • D3D Interfaces
  • D3D Functions
  • Macros
  • D3D Structures
  • D3D Enumerations
  • D3D Constants

See Also

Reference


D3D Interfaces

This section contains reference information for the Component Object Model (COM) interfaces provided by Microsoft Direct3D. The following interfaces are used with Direct3D.

  • ID3DXFile
  • ID3DXFileData
  • ID3DXFileEnumObject
  • ID3DXFileSaveData
  • ID3DXFileSaveObject
  • IDirect3D9
  • IDirect3D9Ex
  • IDirect3DBaseTexture9
  • IDirect3DCubeTexture9
  • IDirect3DDevice9
  • IDirect3DDevice9Ex
  • IDirect3DIndexBuffer9
  • IDirect3DPixelShader9
  • IDirect3DQuery9
  • IDirect3DResource9
  • IDirect3DStateBlock9
  • IDirect3DSurface9
  • IDirect3DSwapChain9
  • IDirect3DSwapChain9Ex
  • IDirect3DTexture9
  • IDirect3DVertexBuffer9
  • IDirect3DVertexDeclaration9
  • IDirect3DVertexShader9
  • IDirect3DVolume9
  • IDirect3DVolumeTexture9


IDirect3D9

Applications use the methods of the IDirect3D9 interface to create Microsoft Direct3D objects and set up the environment. This interface includes methods for enumerating and retrieving capabilities of the device.

IDirect3D9 Members

Method | Description
IDirect3D9::CheckDepthStencilMatch | Determines whether a depth-stencil format is compatible with a render-target format in a particular display mode.
IDirect3D9::CheckDeviceFormat | Determines whether a surface format is available as a specified resource type and can be used as a texture, depth-stencil buffer, or render target, or any combination of the three, on a device representing this adapter.
IDirect3D9::CheckDeviceFormatConversion | Tests the device to see if it supports conversion from one display format to another.
IDirect3D9::CheckDeviceMultiSampleType | Determines if a multisampling technique is available on this device.
IDirect3D9::CheckDeviceType | Verifies whether a hardware accelerated device type can be used on this adapter.
IDirect3D9::CreateDevice | Creates a device to represent the display adapter.
IDirect3D9::EnumAdapterModes | Queries the device to determine whether the specified adapter supports the requested format and display mode. This method could be used in a loop to enumerate all the available adapter modes.
IDirect3D9::GetAdapterCount | Returns the number of adapters on the system.
IDirect3D9::GetAdapterDisplayMode | Retrieves the current display mode of the adapter.
IDirect3D9::GetAdapterIdentifier | Describes the physical display adapters present in the system when the IDirect3D9 interface was instantiated.
IDirect3D9::GetAdapterModeCount | Returns the number of display modes available on this adapter.
IDirect3D9::GetAdapterMonitor | Returns the handle of the monitor associated with the Direct3D object.
IDirect3D9::GetDeviceCaps | Retrieves device-specific information about a device.
IDirect3D9::RegisterSoftwareDevice | Registers a pluggable software device. Software devices provide software rasterization enabling applications to access a variety of software rasterizers.

Remarks

The IDirect3D9 interface is obtained by calling the Direct3DCreate9 function.

The LPDIRECT3D9 and PDIRECT3D9 types are defined as pointers to the IDirect3D9 interface.

typedef struct IDirect3D9 *LPDIRECT3D9, *PDIRECT3D9;

See Also

D3D Interfaces

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3D9::CheckDepthStencilMatch

Determines whether a depth-stencil format is compatible with a render-target format in a particular display mode.

HRESULT CheckDepthStencilMatch(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  D3DFORMAT AdapterFormat,
  D3DFORMAT RenderTargetFormat,
  D3DFORMAT DepthStencilFormat
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
AdapterFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the display mode into which the adapter will be placed.
RenderTargetFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the render-target surface to be tested.
DepthStencilFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the depth-stencil surface to be tested.

Return Values

If the depth-stencil format is compatible with the render-target format in the display mode, this method returns D3D_OK. D3DERR_INVALIDCALL can be returned if one or more of the parameters is invalid. If a depth-stencil format is not compatible with the render target in the display mode, then this method returns D3DERR_NOTAVAILABLE.

Remarks

This method is provided to enable applications to work with hardware requiring that certain depth formats can only work with certain render-target formats.

The behavior of this method has been changed for DirectX 8.1. This method now pays attention to the D24x8 and D32 depth-stencil formats. The previous version assumed that these formats would always be useable with 32- or 16-bit render targets. This method will now return D3D_OK for these formats only if the device is capable of mixed-depth operations.

The following code fragment shows how you could use IDirect3D9::CheckDeviceFormat to validate a depth stencil format.

BOOL IsDepthFormatOk(D3DFORMAT DepthFormat,
                          D3DFORMAT AdapterFormat,
                          D3DFORMAT BackBufferFormat)
{

    // Verify that the depth format exists
    HRESULT hr = pD3D->CheckDeviceFormat(D3DADAPTER_DEFAULT,
                                         D3DDEVTYPE_HAL,
                                         AdapterFormat,
                                         D3DUSAGE_DEPTHSTENCIL,
                                         D3DRTYPE_SURFACE,
                                         DepthFormat);

    if(FAILED(hr)) return FALSE;

    // Verify that the depth format is compatible
    hr = pD3D->CheckDepthStencilMatch(D3DADAPTER_DEFAULT,
                                      D3DDEVTYPE_HAL,
                                      AdapterFormat,
                                      BackBufferFormat,
                                      DepthFormat);

    return SUCCEEDED(hr);

}

The preceding call will return FALSE if DepthFormat cannot be used in conjunction with AdapterFormat and BackBufferFormat.

Requirements

Header: Declared in D3D9.h.


IDirect3D9::CheckDeviceFormat

Determines whether a surface format is available as a specified resource type and can be used as a texture, depth-stencil buffer, or render target, or any combination of the three, on a device representing this adapter.

HRESULT CheckDeviceFormat(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  D3DFORMAT AdapterFormat,
  DWORD Usage,
  D3DRESOURCETYPE RType,
  D3DFORMAT CheckFormat
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
AdapterFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the display mode into which the adapter will be placed.
Usage
[in] Requested usage options for the surface. Usage options are any combination of D3DUSAGE and D3DUSAGE_QUERY constants (only a subset of the D3DUSAGE constants are valid for IDirect3D9::CheckDeviceFormat; see the table on the D3DUSAGE page).
RType
[in] Resource type requested for use with the queried format. Member of D3DRESOURCETYPE.
CheckFormat
[in] Format of the surfaces which may be used, as defined by Usage. Member of D3DFORMAT.

Return Values

If the format is compatible with the specified device for the requested usage, this method returns D3D_OK.

D3DERR_INVALIDCALL is returned if Adapter equals or exceeds the number of display adapters in the system, or if DeviceType is unsupported.

D3DERR_NOTAVAILABLE is returned if the format is not acceptable to the device for this usage.

Remarks

Here are some examples using IDirect3D9::CheckDeviceFormat to check for hardware support of:

  • An off-screen plain surface format - Specify Usage = 0 and RType = D3DRTYPE_SURFACE.
  • A depth-stencil format - The following snippet tests for the passed in depth-stencil format:
    BOOL IsDepthFormatExisting( D3DFORMAT DepthFormat, D3DFORMAT AdapterFormat )
{
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          D3DUSAGE_DEPTHSTENCIL,
                                          D3DRTYPE_SURFACE,
                                          DepthFormat);

    return SUCCEEDED( hr );
}

    See Selecting a Device (Direct3D 9) for more detail on the enumeration process.

  • Can this texture be rendered in a particular format - Given the current display mode, this example shows how to verify that the texture format is compatible with the specific back-buffer format:
    BOOL IsTextureFormatOk( D3DFORMAT TextureFormat, D3DFORMAT AdapterFormat )
{
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          0,
                                          D3DRTYPE_TEXTURE,
                                          TextureFormat);

    return SUCCEEDED( hr );
}
  • Alpha blending in a pixel shader - Set Usage to D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING. Expect this to fail for all floating-point render targets.
  • Autogeneration of mipmaps - Set Usage to D3DUSAGE_AUTOGENMIPMAP. If the mipmap automatic generation fails, the application will get a non-mipmapped texture. Calling this method is considered a hint, so this method can return D3DOK_NOAUTOGEN (a valid success code) if the only thing that fails is the mipmap generation. For more information about mipmap generation, see Automatic Generation of Mipmaps (Direct3D 9).

Requirements

Header: Declared in D3D9.h.


IDirect3D9::CheckDeviceFormatConversion

Tests the device to see if it supports conversion from one display format to another.

HRESULT CheckDeviceFormatConversion(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  D3DFORMAT SourceFormat,
  D3DFORMAT TargetFormat
);

Parameters

Adapter
[in] Display adapter ordinal number. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
DeviceType
[in] Device type. Member of the D3DDEVTYPE enumerated type.
SourceFormat
[in] Source adapter format. Member of the D3DFORMAT enumerated type.
TargetFormat
[in] Target adapter format. Member of the D3DFORMAT enumerated type.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value is D3DERR_INVALIDCALL. The method will return D3DERR_NOTAVAILABLE when the hardware does not support conversion between the two formats.

Remarks

Using IDirect3D9::CheckDeviceType to test for compatibility between a back buffer that differs from the display format will return appropriate values. This means that the call will reflect device capabilities. If the device cannot render to the requested back buffer format, the call will still return D3DERR_NOTAVAILABLE. If the device can render to the format, but cannot perform the color-converting presentation, the return value will also be D3DERR_NOTAVAILABLE. Applications can discover hardware support for the presentation itself by calling IDirect3D9::CheckDeviceFormatConversion. No software emulation for the color-converting presentation itself will be offered.

IDirect3D9::CheckDeviceFormatConversion can also be used to determine which combinations of source surface formats and destination surface formats are permissible in calls to IDirect3DDevice9::StretchRect.

Color conversion is restricted to the following source and target formats.

  • The source format must be a FOURCC format or a valid back buffer format. For a list of these, see FourCC Formats and BackBuffer or Display Formats.
  • The target format must be one of these unsigned formats:
    D3DFMT_X1R5G5B5 | D3DFMT_A1R5G5B5 | D3DFMT_R5G6B5
    D3DFMT_R8G8B8 | D3DFMT_X8R8G8B8 | D3DFMT_A8R8G8B8
    D3DFMT_A2R10G10B10 | D3DFMT_A16B16G16R16 | D3DFMT_A2B10G10R10
    D3DFMT_A8B8G8R8 | D3DFMT_X8B8G8R8 | D3DFMT_A16B16G16R16F
    D3DFMT_A32B32G32R32F

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::ColorFill


IDirect3D9::CheckDeviceMultiSampleType

Determines if a multisampling technique is available on this device.

HRESULT CheckDeviceMultiSampleType(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  D3DFORMAT SurfaceFormat,
  BOOL Windowed,
  D3DMULTISAMPLE_TYPE MultiSampleType,
  DWORD* pQualityLevels
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns FALSE when this value equals or exceeds the number of display adapters in the system. See Remarks.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
SurfaceFormat
[in] Member of the D3DFORMAT enumerated type that specifies the format of the surface to be multisampled. For more information, see Remarks.
Windowed
[in] bool value. Specify TRUE to inquire about windowed multisampling, and specify FALSE to inquire about full-screen multisampling.
MultiSampleType
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, identifying the multisampling technique to test.
pQualityLevels
[out] The number of quality stops available for a given multisample type. This can be NULL if it is not necessary to return the values.

Return Values

If the device can perform the specified multisampling method, this method returns D3D_OK. D3DERR_INVALIDCALL is returned if the Adapter or MultiSampleType parameters are invalid. This method returns D3DERR_NOTAVAILABLE if the queried multisampling technique is not supported by this device. D3DERR_INVALIDDEVICE is returned if DeviceType does not apply to this adapter.

Remarks

This method is intended for use with both render-target and depth-stencil surfaces because you must create both surfaces multisampled if you want to use them together.

The following code fragment shows how you could use IDirect3D9::CheckDeviceMultiSampleType to test for devices that support a specific multisampling method.

if( SUCCEEDED(pD3D->CheckDeviceMultiSampleType( pCaps->AdapterOrdinal,
                                pCaps->DeviceType, BackBufferFormat,
                                FALSE, D3DMULTISAMPLE_3_SAMPLES, NULL ) ) &&
         SUCCEEDED(pD3D->CheckDeviceMultiSampleType( pCaps->AdapterOrdinal,
                                pCaps->DeviceType, DepthBufferFormat,
                                FALSE, D3DMULTISAMPLE_3_SAMPLES, NULL ) ) )
    return S_OK;

The preceding code will return S_OK if the device supports the full-screen D3DMULTISAMPLE_3_SAMPLES multisampling method with the surface format.

Requirements

Header: Declared in D3D9.h.


IDirect3D9::CheckDeviceType

Verifies whether a hardware accelerated device type can be used on this adapter.

HRESULT CheckDeviceType(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  D3DFORMAT DisplayFormat,
  D3DFORMAT BackBufferFormat,
  BOOL Windowed
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to enumerate. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, indicating the device type to check.
DisplayFormat
[in] Member of the D3DFORMAT enumerated type, indicating the format of the adapter display mode for which the device type is to be checked. For example, some devices will operate only in 16-bits-per-pixel modes.
BackBufferFormat
[in] Back buffer format. For more information about formats, see D3DFORMAT. This value must be one of the render-target formats. You can use IDirect3DDevice9::GetDisplayMode to obtain the current format. For windowed applications, the back buffer format does not need to match the display mode format if the hardware supports color conversion. The set of possible back buffer formats is constrained, but the runtime will allow any valid back buffer format to be presented to any desktop format. There is the additional requirement that the device be operable in the desktop mode because devices typically do not operate in 8 bits per pixel modes. Full-screen applications cannot do color conversion. D3DFMT_UNKNOWN is allowed for windowed mode.
Windowed
[in] Value indicating whether the device type will be used in full-screen or windowed mode. If set to TRUE, the query is performed for windowed applications; otherwise, this value should be set FALSE.

Return Values

If the device can be used on this adapter, D3D_OK is returned. D3DERR_INVALIDCALL is returned if Adapter equals or exceeds the number of display adapters in the system. D3DERR_INVALIDCALL is also returned if IDirect3D9::CheckDeviceType specified a device that does not exist. D3DERR_NOTAVAILABLE is returned if the requested back buffer format is not supported, or if hardware acceleration is not available for the specified formats.

Remarks

A hal device type requires hardware acceleration. Applications can use CheckDeviceType to determine if the needed hardware and drivers are present to support a hal device.

Full-screen applications should not specify a DisplayFormat that contains an alpha channel. This will result in a failed call. Note that an alpha channel can be present in the back buffer but the two display formats must be identical in all other respects. For example, if DisplayFormat = D3DFMT_X1R5G5B5, valid values for BackBufferFormat include D3DFMT_X1R5G5B5 and D3DFMT_A1R5G5B5 but exclude D3DFMT_R5G6B5.

The following code fragment shows how you could use CheckDeviceType to test whether a certain device type can be used on this adapter.

if(SUCCEEDED(pD3Device->CheckDeviceType(D3DADAPTER_DEFAULT,
                                        D3DDEVTYPE_HAL,
                                        DisplayFormat,
                                        BackBufferFormat,
                                        bIsWindowed)))

     return S_OK;
// There is no HAL on this adapter using this render-target format.
// Try again, using another format.

This code returns S_OK if the device can be used on the default adapter with the specified surface format.

Using IDirect3D9::CheckDeviceType to test for compatibility between a back buffer that differs from the display format will return appropriate values. This means that the call will reflect device capabilities. If the device cannot render to the requested back-buffer format, the call will still return D3DERR_NOTAVAILABLE. If the device can render to the format, but cannot perform the color-converting presentation, the return value will also be D3DERR_NOTAVAILABLE. Applications can discover hardware support for the presentation itself by calling IDirect3D9::CheckDeviceFormatConversion. No software emulation for the color-converting presentation itself will be offered.

Requirements

Header: Declared in D3D9.h.


IDirect3D9::CreateDevice

Creates a device to represent the display adapter.

HRESULT CreateDevice(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  HWND hFocusWindow,
  DWORD BehaviorFlags,
  D3DPRESENT_PARAMETERS * pPresentationParameters,
  IDirect3DDevice9 ** ppReturnedDeviceInterface
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type that denotes the desired device type. If the desired device type is not available, the method will fail.
hFocusWindow
[in] The focus window alerts Direct3D when an application switches from foreground mode to background mode. See Remarks.
  • For full-screen mode, the window specified must be a top-level window.
  • For windowed mode, this parameter may be NULL only if the hDeviceWindow member of pPresentationParameters is set to a valid, non-NULL value.
BehaviorFlags
[in] Combination of one or more options that control device creation. For more information, see D3DCREATE.
pPresentationParameters

Pointer to a D3DPRESENT_PARAMETERS structure, describing the presentation parameters for the device to be created. If BehaviorFlags specifies D3DCREATE_ADAPTERGROUP_DEVICE, pPresentationParameters is an array. Regardless of the number of heads that exist, only one depth/stencil surface is automatically created.

[in, out] For Windows 2000 and Windows XP, the full-screen device display refresh rate is set in the following order:
  1. User-specified nonzero ForcedRefreshRate registry key, if supported by the device.
  2. Application-specified nonzero refresh rate value in the presentation parameter.
  3. Refresh rate of the latest desktop mode, if supported by the device.
  4. 75 hertz if supported by the device.
  5. 60 hertz if supported by the device.
  6. Device default.

An unsupported refresh rate will default to the closest supported refresh rate below it. For example, if the application specifies 63 hertz, 60 hertz will be used. There are no supported refresh rates below 57 hertz.

pPresentationParameters is both an input and an output parameter. Calling this method may change several members including:

  • If BackBufferCount, BackBufferWidth, and BackBufferHeight are 0 before the method is called, they will be changed when the method returns.
  • If BackBufferFormat equals D3DFMT_UNKNOWN before the method is called, it will be changed when the method returns.

ppReturnedDeviceInterface
[out, retval] Address of a pointer to the returned IDirect3DDevice9 interface, which represents the created device.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_DEVICELOST, D3DERR_INVALIDCALL, D3DERR_NOTAVAILABLE, D3DERR_OUTOFVIDEOMEMORY.

Remarks

This method returns a fully working device interface, set to the required display mode (or windowed), and allocated with the appropriate back buffers. To begin rendering, the application needs only to create and set a depth buffer (assuming EnableAutoDepthStencil is FALSE in D3DPRESENT_PARAMETERS).

When you create a Direct3D device, you supply two different window parameters: a focus window (hFocusWindow) and a device window (the hDeviceWindow in D3DPRESENT_PARAMETERS). The purpose of each window is:

  • The focus window alerts Direct3D when an application switches from foreground mode to background mode (via Alt-Tab, a mouse click, or some other method). A single focus window is shared by each device created by an application.
  • The device window determines the location and size of the back buffer on screen. This is used by Direct3D when the back buffer contents are copied to the front buffer during IDirect3DDevice9::Present.

This method should not be run during the handling of WM_CREATE. An application should never pass a window handle to Direct3D while handling WM_CREATE. Any call to create, release, or reset the device must be done using the same thread as the window procedure of the focus window.

Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and at least one of these vertex processing flags must be specified when calling this method.

Back buffers created as part of the device are only lockable if D3DPRESENTFLAG_LOCKABLE_BACKBUFFER is specified in the presentation parameters. (Multisampled back buffers and depth surfaces are never lockable.)

The methods IDirect3DDevice9::Reset, IUnknown, and IDirect3DDevice9::TestCooperativeLevel must be called from the same thread that used this method to create a device.

D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9::CreateDevice, IDirect3DDevice9::Reset, and IDirect3DDevice9::CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling IDirect3D9::CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified.

If you attempt to create a device on a 0x0 sized window, IDirect3D9::CreateDevice will fail.

Requirements

Header: Declared in D3D9.h.

See Also

Direct3DCreate9, D3DDEVICE_CREATION_PARAMETERS, IDirect3DDevice9::Reset, Multihead (Direct3D 9)


IDirect3D9::EnumAdapterModes

Queries the device to determine whether the specified adapter supports the requested format and display mode. This method could be used in a loop to enumerate all the available adapter modes.

HRESULT EnumAdapterModes(
  UINT Adapter,
  D3DFORMAT Format,
  UINT Mode,
  D3DDISPLAYMODE* pMode
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to enumerate. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
Format
[in] Allowable pixel formats. See Remarks.
Mode
[in] Represents the display-mode index which is an unsigned integer between zero and the value returned by IDirect3D9::GetAdapterModeCount minus one.
pMode
[out] A pointer to the available display mode of type D3DDISPLAYMODE. See Remarks.

Return Values

  • If the device can be used on this adapter, D3D_OK is returned.
  • If the Adapter equals or exceeds the number of display adapters in the system, D3DERR_INVALIDCALL is returned.
  • If either surface format is not supported or if hardware acceleration is not available for the specified formats, D3DERR_NOTAVAILABLE is returned.

Remarks

An application supplies a display mode and a format to IDirect3D9::EnumAdapterModes which returns a display mode. This method could be used in a loop to enumerate all available display modes.

The application specifies a format and the enumeration is restricted to those display modes that exactly match the format (alpha is ignored). Allowed formats (which are members of D3DFORMAT) are as follows:

  • D3DFMT_A1R5G5B5
  • D3DFMT_A2R10G10B10
  • D3DFMT_A8R8G8B8
  • D3DFMT_R5G6B5
  • D3DFMT_X1R5G5B5
  • D3DFMT_X8R8G8B8

In addition, IDirect3D9::EnumAdapterModes treats pixel formats 565 and 555 as equivalent, and returns the correct version. The difference comes into play only when the application locks the back buffer and there is an explicit flag that the application must set in order to accomplish this.

Requirements

Header: Declared in D3D9.h.


IDirect3D9::GetAdapterCount

Returns the number of adapters on the system.

UINT GetAdapterCount();

Parameters

None.

Return Values

A UINT value that denotes the number of adapters on the system at the time this IDirect3D9 interface was instantiated.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3D9::GetAdapterIdentifier


IDirect3D9::GetAdapterDisplayMode

Retrieves the current display mode of the adapter.

HRESULT GetAdapterDisplayMode(
  UINT Adapter,
  D3DDISPLAYMODE * pMode
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
pMode
[in, out] Pointer to a D3DDISPLAYMODE structure, to be filled with information describing the current adapter's mode.

Return Values

If the method succeeds, the return value is D3D_OK.

If Adapter is out of range or pMode is invalid, this method returns D3DERR_INVALIDCALL.

Remarks

IDirect3D9::GetAdapterDisplayMode will not return the correct format when the display is in an extended format, such as 2:10:10:10. Instead, it returns the format X8R8G8B8.

Requirements

Header: Declared in D3D9.h.


IDirect3D9::GetAdapterIdentifier

Describes the physical display adapters present in the system when the IDirect3D9 interface was instantiated.

HRESULT GetAdapterIdentifier(
  UINT Adapter,
  DWORD Flags,
  D3DADAPTER_IDENTIFIER9 * pIdentifier
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter. The minimum value for this parameter is 0, and the maximum value for this parameter is one less than the value returned by IDirect3D9::GetAdapterCount.
Flags
[in] Flags sets the WHQLLevel member of D3DADAPTER_IDENTIFIER9. Flags can be set to either 0 or D3DENUM_WHQL_LEVEL. If D3DENUM_WHQL_LEVEL is specified, this call can connect to the Internet to download new Microsoft Windows Hardware Quality Labs (WHQL) certificates.
pIdentifier
[out] Pointer to a D3DADAPTER_IDENTIFIER9 structure to be filled with information describing this adapter. If Adapter is greater than or equal to the number of adapters in the system, this structure will be zeroed.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if Adapter is out of range, if Flags contains unrecognized parameters, or if pIdentifier is NULL or points to unwriteable memory.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3D9::GetAdapterCount


IDirect3D9::GetAdapterModeCount

Returns the number of display modes available on this adapter.

UINT GetAdapterModeCount(
  UINT Adapter,
  D3DFORMAT Format
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
Format
[in] Identifies the format of the surface type using D3DFORMAT. Use IDirect3D9::EnumAdapterModes to see the valid formats.

Return Values

This method returns the number of display modes on this adapter or zero if Adapter is greater than or equal to the number of adapters on the system.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3D9::EnumAdapterModes


IDirect3D9::GetAdapterMonitor

Returns the handle of the monitor associated with the Direct3D object.

HMONITOR GetAdapterMonitor(
  UINT Adapter
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.

Return Values

Handle of the monitor associated with the Direct3D object.

Remarks

As shown in the following code fragment, which illustrates how to obtain a handle to the monitor associated with a given device, use IDirect3DDevice9::GetDirect3D to return the Direct3D enumerator from the device and use IDirect3DDevice9::GetCreationParameters to retrieve the value for Adapter.

    if( FAILED( pDevice->GetCreationParameters(  &Parameters ) ) )
        return D3DERR_INVALIDCALL;

    if( FAILED( pDevice->GetDirect3D(&pD3D) ) )
        return D3DERR_INVALIDCALL;

    hMonitor = pD3D->GetAdapterMonitor(Parameters.AdapterOrdinal);

    pD3D->Release();

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetCreationParameters, IDirect3DDevice9::GetDirect3D


IDirect3D9::GetDeviceCaps

Retrieves device-specific information about a device.

HRESULT GetDeviceCaps(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  D3DCAPS9 * pCaps
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type. Denotes the device type.
pCaps
[out] Pointer to a D3DCAPS9 structure to be filled with information describing the capabilities of the device.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_INVALIDDEVICE, D3DERR_OUTOFVIDEOMEMORY, and D3DERR_NOTAVAILABLE.

D3DERR_NOTAVAILABLE will be returned if the desktop is locked (i.e. the D3D driver is unavailable under the protected desktop). The application should retry periodically. The WM_ACTIVATEAPP message can be used to detect when the desktop returns from protected status.

Remarks

The application should not assume the persistence of vertex processing capabilities across Direct3D device objects. The particular capabilities that a physical device exposes may depend on parameters supplied to IDirect3D9::CreateDevice. For example, the capabilities may yield different vertex processing capabilities before and after creating a Direct3D Device Object with hardware vertex processing enabled. For more information see the description of D3DCAPS9.

Requirements

Header: Declared in D3D9.h.


IDirect3D9::RegisterSoftwareDevice

Registers a pluggable software device. Software devices provide software rasterization enabling applications to access a variety of software rasterizers.

HRESULT RegisterSoftwareDevice(
  void * pInitializeFunction
);

Parameters

pInitializeFunction
[in] Pointer to the initialization function for the software device to be registered.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL. The method call is invalid. For example, a method's parameter may have an invalid value: D3DERR_OUTOFVIDEOMEMORY.

Remarks

If the user's computer provides no special hardware acceleration for 3D operations, your application might emulate 3D hardware in software. Software rasterization devices emulate the functions of color 3D hardware in software. A software device runs more slowly than a hal. However, software devices take advantage of any special instructions supported by the CPU to increase performance. Instruction sets include the AMD 3DNow! instruction set on some AMD processors and the MMX instruction set supported by many Intel processors. Direct3D uses the 3D-Now! instruction set to accelerate transformation and lighting operations and the MMX instruction set to accelerate rasterization.

Software devices communicate with Direct3D through an interface similar to the hardware device driver interface (DDI).

Software devices are loaded by the application and registered with the IDirect3D9 object. Direct3D uses the software device for rendering.

The Direct3D Driver Development Kit (DDK) provides the documentation and headers for developing pluggable software devices.

Requirements

Header: Declared in D3D9.h.


IDirect3D9Ex

Applications use the methods of the IDirect3D9Ex interface (which inherits from IDirect3D9) to create Microsoft Direct3D 9Ex objects and set up the environment. This interface includes methods for enumerating and retrieving capabilities of the device and is available when the underlying device implementation is compliant with Windows Vista.

IUnknown
IDirect3D9
IDirect3D9Ex
CreateDeviceEx | Creates a device to represent the display adapter.
EnumAdapterModesEx | Returns the actual display mode info based on the given mode index.
GetAdapterDisplayModeEx | Retrieves the current display mode and rotation settings of the adapter.
GetAdapterLUID | This method returns a unique identifier for the adapter that is specific to the adapter hardware.
GetAdapterModeCountEx | Returns the number of display modes available.

The LPDIRECT3D9EX and PDIRECT3D9EX types are defined as pointers to the IDirect3D9Ex interface:

typedef struct IDirect3D9Ex *LPDIRECT3D9EX, *PDIRECT3D9EX;


IDirect3D9Ex::CreateDeviceEx

Creates a device to represent the display adapter.

HRESULT CreateDeviceEx(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  HWND hFocusWindow,
  DWORD BehaviorFlags,
  D3DPRESENT_PARAMETERS* pPresentationParameters,
  D3DDISPLAYMODEEX *pFullscreenDisplayMode,
  IDirect3DDevice9Ex **ppReturnedDeviceInterface
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Specifies the type of device. See D3DDEVTYPE. If the desired device type is not available, the method will fail.
hFocusWindow
[in] The focus window alerts Direct3D when an application switches from foreground mode to background mode. For full-screen mode, the window specified must be a top-level window. For windowed mode, this parameter may be NULL only if the hDeviceWindow member of pPresentationParameters is set to a valid, non-NULL value.
BehaviorFlags
[in] Combination of one or more options (see D3DCREATE) that control device creation.
pPresentationParameters
[in, out] Pointer to a D3DPRESENT_PARAMETERS structure, describing the presentation parameters for the device to be created. If BehaviorFlags specifies D3DCREATE_ADAPTERGROUP_DEVICE, this parameter is an array. Regardless of the number of heads that exist, only one depth/stencil surface is automatically created.

This parameter is both an input and an output parameter. Calling this method may change several members including:

  • If BackBufferCount, BackBufferWidth, and BackBufferHeight are 0 before the method is called, they will be changed when the method returns.
  • If BackBufferFormat equals D3DFMT_UNKNOWN before the method is called, it will be changed when the method returns.
pFullscreenDisplayMode
[in, out] The display mode for when the device is set to fullscreen. See D3DDISPLAYMODEEX (DirectX 9Ex only). If BehaviorFlags specifies D3DCREATE_ADAPTERGROUP_DEVICE, this parameter is an array.
ppReturnedDeviceInterface
[out, retval] Address of a pointer to the returned IDirect3DDevice9Ex, which represents the created device.

Return Values

This method returns S_OK when rendering device along with swapchain buffers are created successfully. D3DERR_DEVICELOST is returned when any error other than invalid caller input is encountered.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3D9Ex


IDirect3D9Ex::EnumAdapterModesEx

This method returns the actual display mode info based on the given mode index.

HRESULT EnumAdapterModesEx(
  UINT Adapter,
  CONST D3DDISPLAYMODEFILTER* pFilter,
  UINT Mode,
  D3DDISPLAYMODEEX* pMode
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to enumerate. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
pFilter
[in] See D3DDISPLAYMODEFILTER (DirectX 9Ex only).
Mode
[in] Represents the display-mode index which is an unsigned integer between zero and the value returned by GetAdapterModeCount minus one.
pMode
[out, retval] A pointer to the available display mode of type D3DDISPLAYMODEEX (DirectX 9Ex only).

Return Values

  • If the device can be used on this adapter, D3D_OK is returned.
  • If the Adapter equals or exceeds the number of display adapters in the system, D3DERR_INVALIDCALL is returned.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3D9Ex


IDirect3D9Ex::GetAdapterDisplayModeEx

Retrieves the current display mode and rotation settings of the adapter.

HRESULT GetAdapterDisplayModeEx(
  UINT Adapter,
  D3DDISPLAYMODEEX * pMode,
  D3DDISPLAYROTATION * pRotation
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
pMode
[in, out] Pointer to a D3DDISPLAYMODEEX (DirectX 9Ex only) structure containing data about the display mode of the adapter. As opposed to the display mode of the device, which may not be active if the device does not own full-screen mode. Can be set to NULL.
pRotation
[in, out] Pointer to a D3DDISPLAYROTATION (DirectX 9Ex only) indicating the type of screen rotation the application will do. The value returned through this pointer is important when the D3DPRESENTFLAG_NOAUTOROTATE flag is used; otherwise, it can be set to NULL.

Return Values

If the method succeeds, the return value is D3D_OK.

If Adapter is out of range or pMode is invalid, this method returns D3DERR_INVALIDCALL.

Remarks

IDirect3D9Ex::GetAdapterDisplayModeEx will not return the correct format when the display is in an extended format, such as 2:10:10:10. Instead, it returns the format X8R8G8B8.

To windowed applications, S_PRESENT_MODE_CHANGED returned from IDirect3DDevice9Ex::PresentEx or IDirect3DDevice9Ex::CheckDeviceState is the indication of display mode change happened and current display mode might have different format. To avoid a color converting Present blt, windowed applications have the option of getting new display mode info via this method and adjust its swapchain format accordingly. It will return D3DERR_NOTAVAILABLE if this head is no longer part of the desktop or monitor is disconnected.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3D9Ex


IDirect3D9Ex::GetAdapterLUID

This method returns a unique identifier for the adapter that is specific to the adapter hardware. Applications can use this identifier to define robust mappings across various APIs (Direct3D 9, DXGI).

HRESULT GetAdapterLUID(
  UINT Adapter,
  LUID *pLUID
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter from which to retrieve the LUID.
pLUID
[in] A unique identifier for the given adapter. See LUID.

Return Values

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3D9Ex


IDirect3D9Ex::GetAdapterModeCountEx

Returns the number of display modes available.

UINT GetAdapterModeCountEx(
  UINT Adapter,
  CONST D3DDISPLAYMODEFILTER* pFilter
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter from which to retrieve the display mode count.
pFilter
[in] Specifies the characteristics of the desired display mode. See D3DDISPLAYMODEFILTER (DirectX 9Ex only).

Return Values

The number of display modes available. A return of value zero from this method is an indication that no such display mode is supported or simply this monitor is no longer available.

Remarks

Events such as display mode changes on other heads of the same hardware, monitor change or its connection status change, and desktop extension/unextension could all affect the number of display mode available.

To fullscreen applications, S_PRESENT_MODE_CHANGED returned from IDirect3DDevice9Ex::PresentEx or IDirect3DDevice9Ex::CheckDeviceState is the indication of display mode setting failure due to those events.

To increase the chance of setting a currently available display mode successfully, fullscreen applications should try to requery the available display mode list upon receiving S_PRESENT_MODE_CHANGED.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3D9Ex


IDirect3DBaseTexture9

Applications use the methods of the IDirect3DBaseTexture9 interface to manipulate texture resources including cube and volume textures.

IDirect3DResource9
IDirect3DBaseTexture9
IDirect3DCubeTexture9
IDirect3DTexture9
IDirect3DVolumeTexture9

IDirect3DBaseTexture9 Members

Method | Description
IDirect3DBaseTexture9::GenerateMipSubLevels | Generate mipmap sublevels.
IDirect3DBaseTexture9::GetAutoGenFilterType | Get the filter type that is used for automatically generated mipmap sublevels.
IDirect3DBaseTexture9::GetLevelCount | Returns the number of texture levels in a multilevel texture.
IDirect3DBaseTexture9::GetLOD | Returns a value clamped to the maximum level-of-detail set for a managed texture (this method is not supported for an unmanaged texture).
IDirect3DBaseTexture9::SetAutoGenFilterType | Set the filter type that is used for automatically generated mipmap sublevels.
IDirect3DBaseTexture9::SetLOD | Sets the most detailed level-of-detail for a managed texture.

Remarks

The IDirect3DBaseTexture9 interface assigned to a particular stage for a device is obtained by calling the IDirect3DDevice9::GetTexture method.

The LPDIRECT3DBASETEXTURE9 and PDIRECT3DBASETEXTURE9 types are defined as pointers to the IDirect3DBaseTexture9 interface.

typedef struct IDirect3DBaseTexture9 *LPDIRECT3DBASETEXTURE9, *PDIRECT3DBASETEXTURE9;

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DBaseTexture9::GenerateMipSubLevels

Generate mipmap sublevels.

VOID GenerateMipSubLevels();

Parameters

None.

Return Values

No return value.

Remarks

An application can generate mipmap sublevels at any time by calling IDirect3DBaseTexture9::GenerateMipSubLevels. To have mipmap sublevels generated automatically at texture creation time (see Automatic Generation of Mipmaps (Direct3D 9)), specify D3DUSAGE_AUTOGENMIPMAP during IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateCubeTexture, and IDirect3DDevice9::CreateVolumeTexture. For more information about usage constants, see D3DUSAGE.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DBaseTexture9::GetAutoGenFilterType, IDirect3DBaseTexture9::SetAutoGenFilterType


IDirect3DBaseTexture9::GetAutoGenFilterType

Get the filter type that is used for automatically generated mipmap sublevels.

D3DTEXTUREFILTERTYPE GetAutoGenFilterType();

Parameters

None.

Return Values

Filter type. See D3DTEXTUREFILTERTYPE. A texture must be created with D3DUSAGE_AUTOGENMIPMAP to use this method. Any other usage value will cause this method to return D3DTEXF_NONE.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, CubeTexture, and volumetexture filter caps. For more information about texture types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::SetAutoGenFilterType


IDirect3DBaseTexture9::GetLevelCount

Returns the number of texture levels in a multilevel texture.

DWORD GetLevelCount();

Parameters

None.

Return Values

A DWORD value indicating the number of texture levels in a multilevel texture.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9

Requirements

Header: Declared in D3D9.h.


IDirect3DBaseTexture9::GetLOD

Returns a value clamped to the maximum level-of-detail set for a managed texture (this method is not supported for an unmanaged texture).

DWORD GetLOD();

Parameters

None.

Return Values

A DWORD value, clamped to the maximum level-of-detail value (one less than the total number of levels). Calling IDirect3DBaseTexture9::GetLOD on an unmanaged texture is not supported and will result in a D3DERR error code being returned.

Requirements

Header: Declared in D3D9.h.


IDirect3DBaseTexture9::SetAutoGenFilterType

Set the filter type that is used for automatically generated mipmap sublevels.

HRESULT SetAutoGenFilterType(
  D3DTEXTUREFILTERTYPE FilterType
);

Parameters

FilterType
[in] Filter type. See D3DTEXTUREFILTERTYPE. This method will fail if the filter type is invalid or not supported.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver does not support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. IDirect3DBaseTexture9::SetAutoGenFilterType will fail unless the driver sets the appropriate D3DPTFILTERCAPS_MINFxxx caps. These values are specified in the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9. For more information about texture filter types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. In this case, no failure is returned. For more information about usage constants, see D3DUSAGE.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::GetAutoGenFilterType


IDirect3DBaseTexture9::SetLOD

Sets the most detailed level-of-detail for a managed texture.

DWORD SetLOD(
  DWORD LODNew
);

Parameters

LODNew
[in] Most detailed level-of-detail value to set for the mipmap chain.

Return Values

A DWORD value, clamped to the maximum level-of-detail value (one less than the total number of levels). Subsequent calls to this method will return the clamped value, not the level-of-detail value that was previously set.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DBaseTexture9::SetLOD is used for level-of-detail control of managed textures. This method returns 0 on nonmanaged textures.

IDirect3DBaseTexture9::SetLOD communicates to the Direct3D texture manager the most detailed mipmap in the chain that should be loaded into local video memory. For example, in a five-level mipmap chain, setting LODNew to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time.

More specifically, if the texture was created with the dimensions of 256x256, setting the most detailed level to 0 indicates that 256 x 256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128 x 128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

Requirements

Header: Declared in D3D9.h.


IDirect3DCubeTexture9

Applications use the methods of the IDirect3DCubeTexture9 interface to manipulate a cube texture resource.

IDirect3DResource9
IDirect3DBaseTexture9
IDirect3DCubeTexture9

IDirect3DCubeTexture9 Members

Method | Description
IDirect3DCubeTexture9::AddDirtyRect | Member of the D3DCUBEMAP_FACES enumerated type, identifying the cube map face.
IDirect3DCubeTexture9::GetCubeMapSurface | Retrieves a cube texture map surface.
IDirect3DCubeTexture9::GetLevelDesc | Specifies a level of a mipmapped cube texture.
IDirect3DCubeTexture9::LockRect | Locks a rectangle on a cube texture resource.
IDirect3DCubeTexture9::UnlockRect | Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.

Remarks

The IDirect3DCubeTexture9 interface can be obtained by calling the IDirect3DDevice9::CreateCubeTexture method or one of the D3DXCreateCubeTexturexxx functions.

This interface inherits additional functionality from the IDirect3DBaseTexture9 interface.

This interface, like all COM interfaces, inherits additional functionality from the IUnknown interface.

The LPDIRECT3DCUBETEXTURE9 and PDIRECT3DCubeTexture9 types are defined as pointers to the IDirect3DCubeTexture9 interface.

typedef struct IDirect3DCubeTexture9 *LPDIRECT3DCUBETEXTURE9, *PDIRECT3DCubeTexture9;

See Also

IDirect3DDevice9::CreateCubeTexture, D3DXCreateCubeTexture, D3DXCreateCubeTextureFromFile, D3DXCreateCubeTextureFromFileEx, D3DXCreateCubeTextureFromFileInMemory, D3DXCreateCubeTextureFromFileInMemoryEx, D3DXCreateCubeTextureFromResource, D3DXCreateCubeTextureFromResourceEx

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DCubeTexture9::AddDirtyRect

Adds a dirty region to a cube texture resource.

HRESULT AddDirtyRect(
  D3DCUBEMAP_FACES FaceType,
  CONST RECT * pDirtyRect
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying the cube map face.
pDirtyRect
[in] Pointer to a RECT structure, specifying the dirty region. Specifying NULL expands the dirty region to cover the entire cube texture.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when IDirect3DCubeTexture9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. The destination surface of IDirect3DDevice9::UpdateSurface is also marked dirty automatically.

Using D3DLOCK_NO_DIRTY_UPDATE and explicitly specifying dirty regions can be used to increase the efficiency of IDirect3DDevice9::UpdateTexture. Using this method, applications can optimize what subset of a resource is copied by specifying dirty regions on the resource. However, the dirty regions may be expanded to optimize alignment.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DCubeTexture9::GetLevelDesc, IDirect3DCubeTexture9::LockRect, IDirect3DCubeTexture9::UnlockRect


IDirect3DCubeTexture9::GetCubeMapSurface

Retrieves a cube texture map surface.

HRESULT GetCubeMapSurface(
  D3DCUBEMAP_FACES FaceType,
  UINT Level,
  IDirect3DSurface9 ** ppCubeMapSurface
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.
ppCubeMapSurface
[out] Address of a pointer to an IDirect3DSurface9 interface, representing the returned cube texture map surface.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.


IDirect3DCubeTexture9::GetLevelDesc

Retrieves a description of one face of the specified cube texture level.

HRESULT GetLevelDesc(
  UINT Level,
  D3DSURFACE_DESC * pDesc
);

Parameters

Level
[in] Specifies a level of a mipmapped cube texture.
pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing one face of the specified cube texture level.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

The D3DSURFACE_DESC structure contains Width and Height members, which describe the size of one face in the cube. To get the size of the entire cube, multiply six (the number of cube faces) by the product of Width and Height.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::LockRect, IDirect3DCubeTexture9::UnlockRect


IDirect3DCubeTexture9::LockRect

Locks a rectangle on a cube texture resource.

HRESULT LockRect(
  D3DCUBEMAP_FACES FaceType,
  UINT Level,
  D3DLOCKED_RECT * pLockedRect,
  CONST RECT * pRect,
  DWORD Flags
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.
pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure, describing the region to lock.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT structure. Specifying NULL for this parameter expands the dirty region to cover the entire cube texture.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
You may not specify a subrect when using D3DLOCK_DISCARD. For a description of the flags, see D3DLOCK.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if one or more of the arguments is invalid.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when IDirect3DCubeTexture9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

Cube textures created with D3DPOOL_DEFAULT are not lockable. Cube textures created in video memory are lockable when created with USAGE_DYNAMIC.

The only lockable format for a depth-stencil texture is D3DFMT_D16_LOCKABLE.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::GetLevelDesc, IDirect3DCubeTexture9::UnlockRect


IDirect3DCubeTexture9::UnlockRect

Unlocks a rectangle on a cube texture resource.

HRESULT UnlockRect(
  D3DCUBEMAP_FACES FaceType,
  UINT Level
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::LockRect


IDirect3DDevice9

Applications use the methods of the IDirect3DDevice9 interface to perform DrawPrimitive-based rendering, create resources, work with system-level variables, adjust gamma ramp levels, work with palettes, and create shaders.

IDirect3DDevice9 Members

Method | Description
IDirect3DDevice9::BeginScene | Begins a scene.
IDirect3DDevice9::BeginStateBlock | Signals Direct3D to begin recording a device-state block.
IDirect3DDevice9::Clear | Clears one or more surfaces such as a render target, Multiple Render Targets (Direct3D 9)multiple render targets
IDirect3DDevice9::ColorFill | Allows an application to fill a rectangular area of a D3DPOOL_DEFAULT surface with a specified color.
IDirect3DDevice9::CreateAdditionalSwapChain | Creates an additional swap chain for rendering multiple views.
IDirect3DDevice9::CreateCubeTexture | Creates a cube texture resource.
IDirect3DDevice9::CreateDepthStencilSurface | Creates a depth-stencil resource.
IDirect3DDevice9::CreateIndexBuffer | Creates an index buffer.
IDirect3DDevice9::CreateOffscreenPlainSurface | Create an off-screen surface.
IDirect3DDevice9::CreatePixelShader | Creates a pixel shader.
IDirect3DDevice9::CreateQuery | Creates a status query.
IDirect3DDevice9::CreateRenderTarget | Creates a render-target surface.
IDirect3DDevice9::CreateStateBlock | Creates a new state block that contains the values for all device states, vertex-related states, or pixel-related states.
IDirect3DDevice9::CreateTexture | Creates a texture resource.
IDirect3DDevice9::CreateVertexBuffer | Creates a vertex buffer.
IDirect3DDevice9::CreateVertexDeclaration | Create a vertex shader declaration from the device and the vertex elements.
IDirect3DDevice9::CreateVertexShader | Creates a vertex shader.
IDirect3DDevice9::CreateVolumeTexture | Creates a volume texture resource.
IDirect3DDevice9::DeletePatch | Frees a cached high-order patch.
IDirect3DDevice9::DrawIndexedPrimitive | Based on indexing, renders the specified geometric primitive into an array of vertices.
IDirect3DDevice9::DrawIndexedPrimitiveUP | Renders the specified geometric primitive with data specified by a user memory pointer.
IDirect3DDevice9::DrawPrimitive | Renders a sequence of nonindexed, geometric primitives of the specified type from the current set of data input streams.
IDirect3DDevice9::DrawPrimitiveUP | Renders data specified by a user memory pointer as a sequence of geometric primitives of the specified type.
IDirect3DDevice9::DrawRectPatch | Draws a rectangular patch using the currently set streams.
IDirect3DDevice9::DrawTriPatch | Draws a triangular patch using the currently set streams.
IDirect3DDevice9::EndScene | Ends a scene that was begun by calling IDirect3DDevice9::BeginScene.
IDirect3DDevice9::EndStateBlock | Signals Direct3D to stop recording a device-state block and retrieve a pointer to the state block interface.
IDirect3DDevice9::EvictManagedResources | Evicts all managed resources, including both Direct3D and driver-managed resources.
IDirect3DDevice9::GetAvailableTextureMem | Returns an estimate of the amount of available texture memory.
IDirect3DDevice9::GetBackBuffer | Retrieves a back buffer from the device's swap chain.
IDirect3DDevice9::GetClipPlane | Retrieves the coefficients of a user-defined clipping plane for the device.
IDirect3DDevice9::GetClipStatus | Retrieves the clip status.
IDirect3DDevice9::GetCreationParameters | Retrieves the creation parameters of the device.
IDirect3DDevice9::GetCurrentTexturePalette | Retrieves the current texture palette.
IDirect3DDevice9::GetDepthStencilSurface | Gets the depth-stencil surface owned by the Direct3DDevice object.
IDirect3DDevice9::GetDeviceCaps | Retrieves the capabilities of the rendering device.
IDirect3DDevice9::GetDirect3D | Returns an interface to the instance of the Direct3D object that created the device.
IDirect3DDevice9::GetDisplayMode | Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.
IDirect3DDevice9::GetFrontBufferData | Generates a copy of the device's front buffer and places that copy in a system memory buffer provided by the application.
IDirect3DDevice9::GetFVF | Gets the fixed vertex function declaration.
IDirect3DDevice9::GetGammaRamp | Retrieves the gamma correction ramp for the swap chain.
IDirect3DDevice9::GetIndices | Retrieves index data.
IDirect3DDevice9::GetLight | Retrieves a set of lighting properties that this device uses.
IDirect3DDevice9::GetLightEnable | Retrieves the activity status - enabled or disabled - for a set of lighting parameters within a device.
IDirect3DDevice9::GetMaterial | Retrieves the current material properties for the device.
IDirect3DDevice9::GetNPatchMode | Gets the N-patch mode segments.
IDirect3DDevice9::GetNumberOfSwapChains | Gets the number of implicit swap chains.
IDirect3DDevice9::GetPaletteEntries | Retrieves palette entries.
IDirect3DDevice9::GetPixelShader | Retrieves the currently set pixel shader.
IDirect3DDevice9::GetPixelShaderConstantB | Gets a Boolean shader constant.
IDirect3DDevice9::GetPixelShaderConstantF | Gets a floating-point shader constant.
IDirect3DDevice9::GetPixelShaderConstantI | Gets an integer shader constant.
IDirect3DDevice9::GetRasterStatus | Returns information describing the raster of the monitor on which the swap chain is presented.
IDirect3DDevice9::GetRenderState | Retrieves a render-state value for a device.
IDirect3DDevice9::GetRenderTarget | Retrieves a render-target surface.
IDirect3DDevice9::GetRenderTargetData | Copies the render-target data from device memory to system memory.
IDirect3DDevice9::GetSamplerState | Gets the sampler state value.
IDirect3DDevice9::GetScissorRect | Gets the scissor rectangle.
IDirect3DDevice9::GetSoftwareVertexProcessing | Gets the vertex processing (hardware or software) mode.
IDirect3DDevice9::GetStreamSource | Retrieves a vertex buffer bound to the specified data stream.
IDirect3DDevice9::GetStreamSourceFreq | Gets the stream source frequency divider value.
IDirect3DDevice9::GetSwapChain | Gets a pointer to a swap chain.
IDirect3DDevice9::GetTexture | Retrieves a texture assigned to a stage for a device.
IDirect3DDevice9::GetTextureStageState | Retrieves a state value for an assigned texture.
IDirect3DDevice9::GetTransform | Retrieves a matrix describing a transformation state.
IDirect3DDevice9::GetVertexDeclaration | Gets a vertex shader declaration.
IDirect3DDevice9::GetVertexShader | Retrieves the currently set vertex shader.
IDirect3DDevice9::GetVertexShaderConstantB | Gets a Boolean vertex shader constant.
IDirect3DDevice9::GetVertexShaderConstantF | Gets a floating-point vertex shader constant.
IDirect3DDevice9::GetVertexShaderConstantI | Gets an integer vertex shader constant.
IDirect3DDevice9::GetViewport | Retrieves the viewport parameters currently set for the device.
IDirect3DDevice9::LightEnable | Enables or disables a set of lighting parameters within a device.
IDirect3DDevice9::MultiplyTransform | Multiplies a device's world, view, or projection matrices by a specified matrix.
IDirect3DDevice9::Present | Presents the contents of the next buffer in the sequence of back buffers owned by the device.
IDirect3DDevice9::ProcessVertices | Applies the vertex processing defined by the vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer.
IDirect3DDevice9::Reset | Resets the type, size, and format of the swap chain.
IDirect3DDevice9::SetClipPlane | Sets the coefficients of a user-defined clipping plane for the device.
IDirect3DDevice9::SetClipStatus | Sets the clip status.
IDirect3DDevice9::SetCurrentTexturePalette | Sets the current texture palette.
IDirect3DDevice9::SetCursorPosition | Sets the cursor position and update options.
IDirect3DDevice9::SetCursorProperties | Sets properties for the cursor.
IDirect3DDevice9::SetDepthStencilSurface | Sets the depth stencil surface.
IDirect3DDevice9::SetDialogBoxMode | This method allows the use of GDI dialog boxes in full-screen mode applications.
IDirect3DDevice9::SetFVF | Sets the current vertex stream declaration.
IDirect3DDevice9::SetGammaRamp | Sets the gamma correction ramp for the implicit swap chain. This method will affect the entire screen (not just the active window if you are running in windowed mode).
IDirect3DDevice9::SetIndices | Sets index data.
IDirect3DDevice9::SetLight | Assigns a set of lighting properties for this device.
IDirect3DDevice9::SetMaterial | Sets the material properties for the device.
IDirect3DDevice9::SetNPatchMode | Enable or disable N-patches.
IDirect3DDevice9::SetPaletteEntries | Sets palette entries.
IDirect3DDevice9::SetPixelShader | Sets the current pixel shader to a previously created pixel shader.
IDirect3DDevice9::SetPixelShaderConstantB | Sets a Boolean shader constant.
IDirect3DDevice9::SetPixelShaderConstantF | Sets a floating-point shader constant.
IDirect3DDevice9::SetPixelShaderConstantI | Sets an integer shader constant.
IDirect3DDevice9::SetRenderState | Sets a single device render-state parameter.
IDirect3DDevice9::SetRenderTarget | Sets a new color buffer for the device.
IDirect3DDevice9::SetSamplerState | Sets the sampler state value.
IDirect3DDevice9::SetScissorRect | Sets the scissor rectangle.
IDirect3DDevice9::SetSoftwareVertexProcessing | Use this method to switch between software and hardware vertex processing.
IDirect3DDevice9::SetStreamSource | Binds a vertex buffer to a device data stream. For more information, see Setting the Stream Source (Direct3D 9).
IDirect3DDevice9::SetStreamSourceFreq | Sets the stream source frequency divider value. This may be used to draw several instances of geometry.
IDirect3DDevice9::SetTexture | Assigns a texture to a stage for a device.
IDirect3DDevice9::SetTextureStageState | Sets the state value for the currently assigned texture.
IDirect3DDevice9::SetTransform | Sets a single device transformation-related state.
IDirect3DDevice9::SetVertexDeclaration | Sets a Vertex Declaration (Direct3D 9).
IDirect3DDevice9::SetVertexShader | Sets the vertex shader.
IDirect3DDevice9::SetVertexShaderConstantB | Sets a Boolean vertex shader constant.
IDirect3DDevice9::SetVertexShaderConstantF | Sets a floating-point vertex shader constant.
IDirect3DDevice9::SetVertexShaderConstantI | Sets an integer vertex shader constant.
IDirect3DDevice9::SetViewport | Sets the viewport parameters for the device.
IDirect3DDevice9::ShowCursor | Displays or hides the cursor.
IDirect3DDevice9::StretchRect | Copy the contents of the source rectangle to the destination rectangle. The source rectangle can be stretched and filtered by the copy. This function is often used to change the aspect ratio of a video stream.
IDirect3DDevice9::TestCooperativeLevel | Reports the current cooperative-level status of the Direct3D device for a windowed or full-screen application.
IDirect3DDevice9::UpdateSurface | Copies rectangular subsets of pixels from one surface to another.
IDirect3DDevice9::UpdateTexture | Updates the dirty portions of a texture.
IDirect3DDevice9::ValidateDevice | Reports the device's ability to render the current texture-blending operations and arguments in a single pass.

Remarks

The IDirect3DDevice9 interface is obtained by calling the IDirect3D9::CreateDevice method.

This interface, like all COM interfaces, inherits the IUnknown interface methods.

The LPDIRECT3DDEVICE9 and PDIRECT3DDEVICE9 types are defined as pointers to the IDirect3DDevice9 interface.

typedef struct IDirect3DDevice9 *LPDIRECT3DDEVICE9, *PDIRECT3DDEVICE9;

See Also

IDirect3D9::CreateDevice

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DDevice9::BeginScene

Begins a scene.

HRESULT BeginScene();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. The method will fail with D3DERR_INVALIDCALL if IDirect3DDevice9::BeginScene is called while already in a IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene pair. This happens only when IDirect3DDevice9::BeginScene is called twice without first calling IDirect3DDevice9::EndScene.

Remarks

Applications must call IDirect3DDevice9::BeginScene before performing any rendering and must call IDirect3DDevice9::EndScene when rendering is complete and before calling IDirect3DDevice9::BeginScene again.

If IDirect3DDevice9::BeginScene fails, the device was unable to begin the scene, and there is no need to call IDirect3DDevice9::EndScene. In fact, calls to IDirect3DDevice9::EndScene will fail if the previous IDirect3DDevice9::BeginScene failed. This applies to any application that creates multiple swap chains.

There should be at most one IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene pair between any successive calls to present (either IDirect3DDevice9::Present or IDirect3DSwapChain9::Present). IDirect3DDevice9::BeginScene should be called once before any rendering is performed, and IDirect3DDevice9::EndScene should be called once after all rendering for a frame has been submitted to the runtime. To enable maximal parallelism between the CPU and the graphics accelerator, it is advantageous to call IDirect3DDevice9::EndScene as far ahead of calling present as possible.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::BeginStateBlock

Signals Direct3D to begin recording a device-state block.

HRESULT BeginStateBlock();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Applications can ensure that all recorded states are valid by calling the IDirect3DDevice9::ValidateDevice method prior to calling this method.

The following methods can be recorded in a state block, after calling IDirect3DDevice9::BeginStateBlock and before IDirect3DDevice9::EndStateBlock.

  • IDirect3DDevice9::LightEnable
  • IDirect3DDevice9::SetClipPlane
  • IDirect3DDevice9::SetCurrentTexturePalette
  • IDirect3DDevice9::SetFVF
  • IDirect3DDevice9::SetIndices
  • IDirect3DDevice9::SetLight
  • IDirect3DDevice9::SetMaterial
  • IDirect3DDevice9::SetNPatchMode
  • IDirect3DDevice9::SetPixelShader
  • IDirect3DDevice9::SetPixelShaderConstantB
  • IDirect3DDevice9::SetPixelShaderConstantF
  • IDirect3DDevice9::SetPixelShaderConstantI
  • IDirect3DDevice9::SetRenderState
  • IDirect3DDevice9::SetSamplerState
  • IDirect3DDevice9::SetScissorRect
  • IDirect3DDevice9::SetStreamSource
  • IDirect3DDevice9::SetStreamSourceFreq
  • IDirect3DDevice9::SetTexture
  • IDirect3DDevice9::SetTextureStageState
  • IDirect3DDevice9::SetTransform
  • IDirect3DDevice9::SetViewport
  • IDirect3DDevice9::SetVertexDeclaration
  • IDirect3DDevice9::SetVertexShader
  • IDirect3DDevice9::SetVertexShaderConstantB
  • IDirect3DDevice9::SetVertexShaderConstantF
  • IDirect3DDevice9::SetVertexShaderConstantI

The ordering of state changes in a state block is not guaranteed. If the same state is specified multiple times in a state block, only the last value is used.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::EndStateBlock, IDirect3DDevice9::CreateStateBlock


IDirect3DDevice9::Clear

Clears one or more surfaces such as a render target, multiple render targets, a stencil buffer, and a depth buffer.

HRESULT Clear(
  DWORD Count,
  CONST D3DRECT * pRects,
  DWORD Flags,
  D3DCOLOR Color,
  float Z,
  DWORD Stencil
);

Parameters

Count
[in] Number of rectangles in the array at pRects. Must be set to 0 if pRects is NULL. May not be 0 if pRects is a valid pointer.
pRects
[in] Pointer to an array of D3DRECT structures that describe the rectangles to clear. Set a rectangle to the dimensions of the rendering target to clear the entire surface. Each rectangle uses screen coordinates that correspond to points on the render target. Coordinates are clipped to the bounds of the viewport rectangle. To indicate that the entire viewport rectangle is to be cleared, set this parameter to NULL and Count to 0.
Flags
[in] Combination of one or more D3DCLEAR flags that specify the surface(s) that will be cleared.
Color
[in] Clear a render target to this ARGB color.
Z
[in] Clear the depth buffer to this new z value which ranges from 0 to 1. See remarks.
Stencil
[in] Clear the stencil buffer to this new value which ranges from 0 to 2n - 1 (n is the bit depth of the stencil buffer). See remarks.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

Use this method to clear a surface including: a render target, all render targets in an MRT, a stencil buffer, or a depth buffer. Flags determines how many surfaces are cleared. Use pRects to clear a subset of a surface defined by an array of rectangles.

IDirect3DDevice9::Clear will fail if you:

  • Try to clear either the depth buffer or the stencil buffer of a render target that does not have an attached depth buffer.
  • Try to clear the stencil buffer when the depth buffer does not contain stencil data.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::ColorFill

Allows an application to fill a rectangular area of a D3DPOOL_DEFAULT surface with a specified color.

HRESULT ColorFill(
  IDirect3DSurface9 * pSurface,
  CONST RECT * pRect,
  D3DCOLOR color
);

Parameters

pSurface
[in] Pointer to the surface to be filled.
pRect
[in] Pointer to the source rectangle. Using NULL means that the entire surface will be filled.
color
[in] Color used for filling.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method can only be applied to a render target, a render-target texture surface, or an off-screen plain surface with a pool type of D3DPOOL_DEFAULT.

IDirect3DDevice9::ColorFill will work with all formats. However, when using a reference or software device, the only formats supported are D3DFMT_X1R5G5B5, D3DFMT_A1R5G5B5, D3DFMT_R5G6B5, D3DFMT_X8R8G8B8, D3DFMT_A8R8G8B8, D3DFMT_YUY2, D3DFMT_G8R8_G8B8, D3DFMT_UYVY, D3DFMT_R8G8_B8G8, D3DFMT_R16F, D3DFMT_G16R16F, D3DFMT_A16B16G16R16F, D3DFMT_R32F, D3DFMT_G32R32F, and D3DFMT_A32B32G32R32F.

When using a DirectX 7 or DirectX 8.x driver, the only YUV formats supported are D3DFMT_UYVY and D3DFMT_YUY2.

Requirements

Header: Declared in D3D9.h.

See Also

D3DPOOL


IDirect3DDevice9::CreateAdditionalSwapChain

Creates an additional swap chain for rendering multiple views.

HRESULT CreateAdditionalSwapChain(
  D3DPRESENT_PARAMETERS* pPresentationParameters,
  IDirect3DSwapChain9** ppSwapChain
);

Parameters

pPresentationParameters
[in, out] Pointer to a D3DPRESENT_PARAMETERS structure, containing the presentation parameters for the new swap chain. This value cannot be NULL.

Calling this method changes the value of members of the D3DPRESENT_PARAMETERS structure.

  • If BackBufferCount == 0, calling CreateAdditionalSwapChain will increase it to 1.
  • If the application is in windowed mode, and if either the BackBufferWidth or the BackBufferHeight == 0, they will be set to the client area width and height of the hwnd.
ppSwapChain
[out, retval] Address of a pointer to an IDirect3DSwapChain9 interface, representing the additional swap chain.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_NOTAVAILABLE, D3DERR_DEVICELOST, D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

There is always at least one swap chain (the implicit swap chain) for each device because Direct3D 9 has one swap chain as a property of the device.

Note that any given device can support only one full-screen swap chain.

D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9::CreateDevice, IDirect3DDevice9::Reset and CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified.

Requirements

Header: Declared in D3D9.h.

See Also

Presenting Multiple Views in Windowed Mode (Direct3D 9)


IDirect3DDevice9::CreateCubeTexture

Creates a cube texture resource.

HRESULT CreateCubeTexture(
  UINT EdgeLength,
  UINT Levels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  IDirect3DCubeTexture9 ** ppCubeTexture,
  HANDLE* pSharedHandle
);

Parameters

EdgeLength
[in] Size of the edges of all the top-level faces of the cube texture. The pixel dimensions of subsequent levels of each face will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead.
Levels
[in] Number of levels in each face of the cube texture. If this is zero, Direct3D will generate all cube texture sublevels down to 1x1 pixels for each face for hardware that supports mipmapped cube textures. Call IDirect3DBaseTexture9::GetLevelCount to see the number of levels generated.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter in CreateCubeTexture with the behavior flags in IDirect3D9::CreateDevice. For more information, see Remarks.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in all faces of the cube texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
ppCubeTexture
[out, retval] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

A mipmap (texture) is a collection of successively downsampled (mipmapped) surfaces. On the other hand, a cube texture (created by IDirect3DDevice9::CreateCubeTexture) is a collection of six textures (mipmaps), one for each face. All faces must be present in the cube texture. Also, a cube map surface must be the same pixel size in all three dimensions (x, y, and z).

An application can discover support for Automatic Generation of Mipmaps (Direct3D 9) in a particular format by calling IDirect3D9::CheckDeviceFormat with D3DUSAGE_AUTOGENMIPMAP. If IDirect3D9::CheckDeviceFormat returns D3DOK_NOAUTOGEN, IDirect3DDevice9::CreateCubeTexture will succeed but it will return a one-level texture.

Requirements

Header: Declared in D3D9.h.

See Also

D3DXCreateCubeTexture, D3DXCreateCubeTextureFromFile, D3DXCreateCubeTextureFromFileEx, D3DXCreateCubeTextureFromFileInMemory, D3DXCreateCubeTextureFromFileInMemoryEx, D3DXCreateCubeTextureFromResource, D3DXCreateCubeTextureFromResourceEx


IDirect3DDevice9::CreateDepthStencilSurface

Creates a depth-stencil resource.

HRESULT CreateDepthStencilSurface(
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  D3DMULTISAMPLE_TYPE MultiSample,
  DWORD MultisampleQuality,
  BOOL Discard,
  IDirect3DSurface9** ppSurface,
  HANDLE* pSharedHandle
);

Parameters

Width
[in] Width of the depth-stencil surface, in pixels.
Height
[in] Height of the depth-stencil surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the depth-stencil surface. This value must be one of the enumerated depth-stencil formats for this device.
MultiSample
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, describing the multisampling buffer type. This value must be one of the allowed multisample types. When this surface is passed to IDirect3DDevice9::SetDepthStencilSurface, its multisample type must be the same as that of the render target set by IDirect3DDevice9::SetRenderTarget.
MultisampleQuality
[in] Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces, and the MultiSample type must all match.
Discard
[in] Set this flag to TRUE to enable z-buffer discarding, and FALSE otherwise. If this flag is set, the contents of the depth stencil buffer will be invalid after calling either IDirect3DDevice9::Present or IDirect3DDevice9::SetDepthStencilSurface with a different depth surface.

This flag has the same behavior as the constant, D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL, in D3DPRESENTFLAG.

ppSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the created depth-stencil surface resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

The memory class of the depth-stencil buffer is always D3DPOOL_DEFAULT.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::UpdateSurface


IDirect3DDevice9::CreateIndexBuffer

Creates an index buffer.

HRESULT CreateIndexBuffer(
  UINT Length,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  IDirect3DIndexBuffer9** ppIndexBuffer,
  HANDLE* pSharedHandle
);

Parameters

Length
[in] Size of the index buffer, in bytes.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter in CreateIndexBuffer with the behavior flags in IDirect3D9::CreateDevice. For more information, see Remarks.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the index buffer. For more information, see Remarks. The valid settings are the following:
D3DFMT_INDEX16
Indices are 16 bits each.
D3DFMT_INDEX32
Indices are 32 bits each.
Pool
[in] Member of the D3DPOOL enumerated type, describing a valid memory class into which to place the resource.
ppIndexBuffer
[out, retval] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the created index buffer resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

Index buffers are memory resources used to hold indices, they are similar to both surfaces and vertex buffers. The use of index buffers enables Direct3D to avoid unnecessary data copying and to place the buffer in the optimal memory type for the expected usage.

To use index buffers, create an index buffer, lock it, fill it with indices, unlock it, pass it to IDirect3DDevice9::SetIndices, set up the vertices, set up the vertex shader, and call IDirect3DDevice9::DrawIndexedPrimitive for rendering.

The MaxVertexIndex member of the D3DCAPS9 structure indicates the types of index buffers that are valid for rendering.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DIndexBuffer9::GetDesc, Index Buffers (Direct3D 9)


IDirect3DDevice9::CreateOffscreenPlainSurface

Create an off-screen surface.

HRESULT CreateOffscreenPlainSurface(
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  DWORD Pool,
  IDirect3DSurface9** ppSurface,
  HANDLE* pSharedHandle
);

Parameters

Width
[in] Width of the surface.
Height
[in] Height of the surface.
Format
[in] Format of the surface. See D3DFORMAT.
Pool
[in] Surface pool type. See D3DPOOL.
ppSurface
[out, retval] Pointer to the IDirect3DSurface9 interface created.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be the following: D3DERR_INVALIDCALL.

Remarks

D3DPOOL_SCRATCH will return a surface that has identical characteristics to a surface created by the DirectX 8.x method CreateImageSurface.

D3DPOOL_DEFAULT is the appropriate pool for use with the IDirect3DDevice9::StretchRect and IDirect3DDevice9::ColorFill.

D3DPOOL_MANAGED is not allowed when creating an offscreen plain surface. For more information about memory pools, see D3DPOOL.

Off-screen plain surfaces are always lockable, regardless of their pool types.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::CreatePixelShader

Creates a pixel shader.

HRESULT CreatePixelShader(
  CONST DWORD * pFunction,
  IDirect3DPixelShader9** ppShader
);

Parameters

pFunction
[in] Pointer to the pixel shader function token array, specifying the blending operations. This value cannot be NULL.
ppShader
[out, retval] Pointer to the returned pixel shader interface. See IDirect3DPixelShader9.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Requirements

Header: Declared in D3D9.h.

See Also

D3DXAssembleShader, D3DXAssembleShaderFromFile


IDirect3DDevice9::CreateQuery

Creates a status query.

HRESULT CreateQuery(
  D3DQUERYTYPE Type,
  IDirect3DQuery9** ppQuery
);

Parameters

Type
[in] Identifies the query type. For more information, see D3DQUERYTYPE.
ppQuery

Returns a pointer to the query interface that manages the query object. See IDirect3DQuery9.

[out] This parameter can be set to NULL to see if a query is supported. If the query is not supported, the method returns D3DERR_NOTAVAILABLE.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_NOTAVAILABLE or E_OUTOFMEMORY.

Remarks

This method is provided for both synchronous and asynchronous queries. It takes the place of GetInfo, which is no longer supported in Direct3D 9.

Synchronous and asynchronous queries are created with IDirect3DDevice9::CreateQuery with D3DQUERYTYPE. When a query has been created and the API calls have been made that are being queried, use IDirect3DQuery9::Issue to issue a query and IDirect3DQuery9::GetData to get the results of the query.

Requirements

Header: Declared in D3D9.h.

See Also

Asynchronous Notification (Direct3D 9)


IDirect3DDevice9::CreateRenderTarget

Creates a render-target surface.

HRESULT CreateRenderTarget(
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  D3DMULTISAMPLE_TYPE MultiSample,
  DWORD MultisampleQuality,
  BOOL Lockable,
  IDirect3DSurface9** ppSurface,
  HANDLE* pSharedHandle
);

Parameters

Width
[in] Width of the render-target surface, in pixels.
Height
[in] Height of the render-target surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the render target.
MultiSample
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, which describes the multisampling buffer type. This parameter specifies the antialiasing type for this render target. When this surface is passed to IDirect3DDevice9::SetRenderTarget, its multisample type must be the same as that of the depth-stencil set by IDirect3DDevice9::SetDepthStencilSurface.
MultisampleQuality
[in] Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error, D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces, and the multisample type must all match.
Lockable
[in] Render targets are not lockable unless the application specifies TRUE for Lockable.

Note that lockable render targets reduce performance on some graphics hardware. The readback performance (moving data from video memory to system memory) depends on the type of hardware used (AGP vs. PCI Express) and is usually far lower than upload performance (moving data from system to video memory). If you need read access to render targets, use GetRenderTargetData instead of lockable render targets.

ppSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

Render-target surfaces are placed in the D3DPOOL_DEFAULT memory class.

The creation of lockable, multisampled render targets is not supported.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::CreateStateBlock

Creates a new state block that contains the values for all device states, vertex-related states, or pixel-related states.

HRESULT CreateStateBlock(
  D3DSTATEBLOCKTYPE Type,
  IDirect3DStateBlock9** ppSB
);

Parameters

Type
[in] Type of state data that the method should capture. This parameter can be set to a value defined in the D3DSTATEBLOCKTYPE enumerated type.
ppSB
[out, retval] Pointer to a state block interface. See IDirect3DStateBlock9.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

Vertex-related device states typically refer to those states that affect how the system processes vertices. Pixel-related states generally refer to device states that affect how the system processes pixel or depth-buffer data during rasterization. Some states are contained in both groups.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::BeginStateBlock, IDirect3DDevice9::EndStateBlock


IDirect3DDevice9::CreateTexture

Creates a texture resource.

HRESULT CreateTexture(
  UINT Width,
  UINT Height,
  UINT Levels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  IDirect3DTexture9** ppTexture,
  HANDLE* pSharedHandle
);

Parameters

Width
[in] Width of the top-level of the texture, in pixels. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0, 1 will be taken instead.
Height
[in] Height of the top-level of the texture, in pixels. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0, 1 will be taken instead.
Levels
[in] Number of levels in the texture. If this is zero, Direct3D will generate all texture sublevels down to 1 by 1 pixels for hardware that supports mipmapped textures. Call IDirect3DBaseTexture9::GetLevelCount to see the number of levels generated.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter with the behavior flags in IDirect3D9::CreateDevice.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in the texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
ppTexture
[out, retval] Pointer to an IDirect3DTexture9 interface, representing the created texture resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

An application can discover support for Automatic Generation of Mipmaps (Direct3D 9) in a particular format by calling IDirect3D9::CheckDeviceFormat with D3DUSAGE_AUTOGENMIPMAP. If IDirect3D9::CheckDeviceFormat returns D3DOK_NOAUTOGEN, IDirect3DDevice9::CreateTexture will succeed but it will return a one-level texture.

Requirements

Header: Declared in D3D9.h.

See Also

D3DXCreateTexture, D3DXCreateTextureFromFile, D3DXCreateTextureFromFileEx, D3DXCreateTextureFromFileInMemory, D3DXCreateTextureFromFileInMemoryEx, D3DXCreateTextureFromResource, D3DXCreateTextureFromResourceEx


IDirect3DDevice9::CreateVertexBuffer

Creates a vertex buffer.

HRESULT CreateVertexBuffer(
  UINT Length,
  DWORD Usage,
  DWORD FVF,
  D3DPOOL Pool,
  IDirect3DVertexBuffer9** ppVertexBuffer,
  HANDLE* pSharedHandle
);

Parameters

Length
[in] Size of the vertex buffer, in bytes. For FVF vertex buffers, Length must be large enough to contain at least one vertex, but it need not be a multiple of the vertex size. Length is not validated for non-FVF buffers. See Remarks.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter in CreateVertexBuffer with the behavior flags in IDirect3D9::CreateDevice. For more information, see Remarks.
FVF
[in] Combination of D3DFVF, a usage specifier that describes the vertex format of the vertices in this buffer. If this parameter is set to a valid FVF code, the created vertex buffer is an FVF vertex buffer (see Remarks). Otherwise, if this parameter is set to zero, the vertex buffer is a non-FVF vertex buffer.
Pool
[in] Member of the D3DPOOL enumerated type, describing a valid memory class into which to place the resource. Do not set to D3DPOOL_SCRATCH.
ppVertexBuffer
[out, retval] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the created vertex buffer resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

A vertex buffer can be used with either hardware or software vertex processing. This is determined by how the device and the vertex buffer are created.

When a device is created, CreateDevice uses the behavior flag to determine whether to process vertices in hardware or software. There are three possibilities:

  • Process vertices in hardware by setting D3DCREATE_HARDWARE_VERTEXPROCESSING.
  • Process vertices in software by setting D3DCREATE_SOFTWARE_VERTEXPROCESSING.
  • Process vertices in either hardware or software by setting D3DCREATE_MIXED_VERTEXPROCESSING.

Mixed-mode devices might need to switch between software and hardware processing (using IDirect3DDevice9::SetSoftwareVertexProcessing) after the device is created.

When a vertex buffer is created, CreateVertexBuffer uses the usage parameter to decide whether to process vertices in hardware or software.

  • If CreateDevice uses D3DCREATE_HARDWARE_VERTEXPROCESSING, CreateVertexBuffer must use 0.
  • If CreateDevice uses D3DCREATE_SOFTWARE_VERTEXPROCESSING, CreateVertexBuffer must use either 0 or D3DUSAGE_SOFTWAREPROCESSING. For either value, vertices will be processed in software.
  • If CreateDevice uses D3DCREATE_MIXED_VERTEXPROCESSING, CreateVertexBuffer can use either 0 or D3DUSAGE_SOFTWAREPROCESSING.

To use a vertex buffer with a mixed mode device, create a single vertex buffer which can be used for both hardware or software processing. Use IDirect3DDevice9::SetStreamSource to set the current vertex buffer and use IDirect3DDevice9::SetRenderState, if necessary, to change the device behavior to match. It is recommended that the vertex buffer usage matches the device behavior. Note that a vertex buffer created for software processing cannot be located in video memory.

The IDirect3DDevice9 interface supports rendering of primitives using vertex data stored in vertex buffer objects. Vertex buffers are created from the IDirect3DDevice9, and are usable only with the IDirect3DDevice9 object from which they are created.

When set to a nonzero value, which must be a valid FVF code, the FVF parameter indicates that the buffer content is to be characterized by an FVF code. A vertex buffer that is created with an FVF code is referred to as an FVF vertex buffer. For more information, see FVF Vertex Buffers (Direct3D 9).

Non-FVF buffers can be used to interleave data during multipass rendering or multitexture rendering in a single pass. To do this, one buffer contains geometry data and the others contain texture coordinates for each texture to be rendered. When rendering, the buffer containing the geometry data is interleaved with each of the buffers containing the texture coordinates. If FVF buffers were used instead, each of them would need to contain identical geometry data in addition to the texture coordinate data specific to each texture rendered. This would result in either a speed or memory penalty, depending on the strategy used. For more information about texture coordinates, see Texture Coordinates (Direct3D 9).

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVertexBuffer9::GetDesc, IDirect3DDevice9::ProcessVertices, Vertex Buffers (Direct3D 9)


IDirect3DDevice9::CreateVertexDeclaration

Create a vertex shader declaration from the device and the vertex elements.

HRESULT CreateVertexDeclaration(
  CONST D3DVERTEXELEMENT9* pVertexElements,
  IDirect3DVertexDeclaration9** ppDecl
);

Parameters

pVertexElements
[in] An array of D3DVERTEXELEMENT9 vertex elements.
ppDecl
[out, retval] Pointer to an IDirect3DVertexDeclaration9 pointer that returns the created vertex shader declaration.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

See the Vertex Declaration (Direct3D 9) page for a detailed description of how to map vertex declarations between different versions of DirectX.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::CreateVertexShader

Creates a vertex shader.

HRESULT CreateVertexShader(
  CONST DWORD * pFunction,
  IDirect3DVertexShader9** ppShader
);

Parameters

pFunction
[in] Pointer to an array of tokens that represents the vertex shader, including any embedded debug and symbol table information.
  • Use a function such as D3DXCompileShader to create the array from a HLSL shader.
  • Use a function like D3DXAssembleShader to create the token array from an assembly language shader.
  • Use a function like ID3DXEffectCompiler::CompileShader to create the array from an effect.
ppShader
[out, retval] Pointer to the returned vertex shader interface (see IDirect3DVertexShader9).

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

When a device is created, IDirect3D9::CreateDevice uses the behavior flag to determine whether to process vertices in hardware or software. There are three possibilities:

  • Process vertices in hardware by setting D3DCREATE_HARDWARE_VERTEXPROCESSING.
  • Process vertices in software by setting D3DCREATE_SOFTWARE_VERTEXPROCESSING.
  • Process vertices in either hardware or software by setting D3DCREATE_MIXED_VERTEXPROCESSING. To switch a mixed-mode device between software and hardware processing, use IDirect3DDevice9::SetSoftwareVertexProcessing.

For an example using D3DXCompileShader, see HLSLwithoutEffects Sample.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::CreateVolumeTexture

Creates a volume texture resource.

HRESULT CreateVolumeTexture(
  UINT Width,
  UINT Height,
  UINT Depth,
  UINT Levels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  IDirect3DVolumeTexture9** ppVolumeTexture,
  HANDLE* pSharedHandle
);

Parameters

Width
[in] Width of the top-level of the volume texture, in pixels. This value must be a power of two if the D3DPTEXTURECAPS_VOLUMEMAP_POW2 member of D3DCAPS9 is set. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by two results in 0 (zero), 1 will be taken instead. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Height
[in] Height of the top-level of the volume texture, in pixels. This value must be a power of two if the D3DPTEXTURECAPS_VOLUMEMAP_POW2 member of D3DCAPS9 is set. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Depth
[in] Depth of the top-level of the volume texture, in pixels. This value must be a power of two if the D3DPTEXTURECAPS_VOLUMEMAP_POW2 member of D3DCAPS9 is set. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Levels
[in] Number of levels in the texture. If this is zero, Direct3D will generate all texture sublevels down to 1x1 pixels for hardware that supports mipmapped volume textures. Call IDirect3DBaseTexture9::GetLevelCount to see the number of levels generated.
Usage
[in] Usage can be 0, which indicates no usage value. If usage is desired, use D3DUSAGE_DYNAMIC or D3DUSAGE_SOFTWAREPROCESSING. For more information, see D3DUSAGE.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in the volume texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.
ppVolumeTexture
[out, retval] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created volume texture resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Requirements

Header: Declared in D3D9.h.

See Also

D3DXCreateVolumeTexture, D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx


IDirect3DDevice9::DeletePatch

Frees a cached high-order patch.

HRESULT DeletePatch(
  UINT Handle
);

Parameters

Handle
[in] Handle of the cached high-order patch to delete.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::DrawRectPatch, IDirect3DDevice9::DrawTriPatch, Using Higher-Order Primitives (Direct3D 9)


IDirect3DDevice9::DrawIndexedPrimitive

Based on indexing, renders the specified geometric primitive into an array of vertices.

HRESULT DrawIndexedPrimitive(
  D3DPRIMITIVETYPE Type,
  INT BaseVertexIndex,
  UINT MinIndex,
  UINT NumVertices,
  UINT StartIndex,
  UINT PrimitiveCount
);

Parameters

Type
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render. D3DPT_POINTLIST is not supported with this method. See Remarks.
BaseVertexIndex
[in] Offset from the start of the vertex buffer to the first vertex. See Scenario 4.
MinIndex
[in] Minimum vertex index for vertices used during this call. This is a zero based index relative to BaseVertexIndex.
NumVertices
[in] Number of vertices used during this call. The first vertex is located at index: BaseVertexIndex + MinIndex.
StartIndex
[in] Index of the first index to use when accesssing the vertex buffer. Beginning at StartIndex to index vertices from the vertex buffer.
PrimitiveCount
[in] Number of primitives to render. The number of vertices used is a function of the primitive count and the primitive type. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be the following: D3DERR_INVALIDCALL.

Remarks

This method draws indexed primitives from the current set of data input streams. MinIndex and all the indices in the index stream are relative to the BaseVertexIndex.

The MinIndex and NumVertices parameters specify the range of vertex indices used for each IDirect3DDevice9::DrawIndexedPrimitive call. These are used to optimize vertex processing of indexed primitives by processing a sequential range of vertices prior to indexing into these vertices. It is invalid for any indices used during this call to reference any vertices outside of this range.

IDirect3DDevice9::DrawIndexedPrimitive fails if no index array is set.

The D3DPT_POINTLIST member of the D3DPRIMITIVETYPE enumerated type is not supported and is not a valid type for this method.

When converting a legacy application to Direct3D 9, you must add a call to either IDirect3DDevice9::SetFVF to use the fixed function pipeline, or IDirect3DDevice9::SetVertexDeclaration to use a vertex shader before you make any Draw calls.

Requirements

Header: Declared in D3D9.h.

See Also

Rendering from Vertex and Index Buffers (Direct3D 9) , Index Buffers (Direct3D 9) , Vertex Buffers (Direct3D 9) , IDirect3DDevice9::DrawPrimitive


IDirect3DDevice9::DrawIndexedPrimitiveUP

Renders the specified geometric primitive with data specified by a user memory pointer.

HRESULT DrawIndexedPrimitiveUP(
  D3DPRIMITIVETYPE PrimitiveType,
  UINT MinVertexIndex,
  UINT NumVertices,
  UINT PrimitiveCount,
  CONST void * pIndexData,
  D3DFORMAT IndexDataFormat,
  CONST void* pVertexStreamZeroData,
  UINT VertexStreamZeroStride
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
MinVertexIndex
[in] Minimum vertex index. This is a zero-based index.
NumVertices
[in] Number of vertices used during this call. The first vertex is located at index: MinVertexIndex.
PrimitiveCount
[in] Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure (the number of indices is a function of the primitive count and the primitive type).
pIndexData
[in] User memory pointer to the index data.
IndexDataFormat
[in] Member of the D3DFORMAT enumerated type, describing the format of the index data. The valid settings are either:
  • D3DFMT_INDEX16
  • D3DFMT_INDEX32
pVertexStreamZeroData
[in] User memory pointer to the vertex data. The vertex data must be in stream 0.
VertexStreamZeroStride
[in] The number of bytes of data for each vertex. This value may not be 0.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be the following: D3DERR_INVALIDCALL.

Remarks

This method is intended for use in applications that are unable to store their vertex data in vertex buffers. This method supports only a single vertex stream, which must be declared as stream 0.

Following any IDirect3DDevice9::DrawIndexedPrimitiveUP call, the stream 0 settings, referenced by IDirect3DDevice9::GetStreamSource, are set to NULL. Also, the index buffer setting for IDirect3DDevice9::SetIndices is set to NULL.

The vertex data passed to IDirect3DDevice9::DrawIndexedPrimitiveUP does not need to persist after the call. Direct3D completes its access to that data prior to returning from the call.

When converting a legacy application to Direct3D 9, you must add a call to either IDirect3DDevice9::SetFVF to use the fixed function pipeline, or IDirect3DDevice9::SetVertexDeclaration to use a vertex shader before you make any Draw calls.

Requirements

Header: Declared in D3D9.h.

See Also

Rendering from Vertex and Index Buffers (Direct3D 9), IDirect3DDevice9::DrawPrimitive


IDirect3DDevice9::DrawPrimitive

Renders a sequence of nonindexed, geometric primitives of the specified type from the current set of data input streams.

HRESULT DrawPrimitive(
  D3DPRIMITIVETYPE PrimitiveType,
  UINT StartVertex,
  UINT PrimitiveCount
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
StartVertex
[in] Index of the first vertex to load. Beginning at StartVertex the correct number of vertices will be read out of the vertex buffer.
PrimitiveCount
[in] Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure. PrimitiveCount is the number of primitives as determined by the primitive type. If it is a line list, each primitive has two vertices. If it is a triangle list, each primitive has three vertices.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When converting a legacy application to Direct3D 9, you must add a call to either IDirect3DDevice9::SetFVF to use the fixed function pipeline, or IDirect3DDevice9::SetVertexDeclaration to use a vertex shader before you make any Draw calls.

Requirements

Header: Declared in D3D9.h.

See Also

Rendering from Vertex and Index Buffers (Direct3D 9), IDirect3DDevice9::DrawIndexedPrimitive


IDirect3DDevice9::DrawPrimitiveUP

Renders data specified by a user memory pointer as a sequence of geometric primitives of the specified type.

HRESULT DrawPrimitiveUP(
  D3DPRIMITIVETYPE PrimitiveType,
  UINT PrimitiveCount,
  CONST void* pVertexStreamZeroData,
  UINT VertexStreamZeroStride
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
PrimitiveCount
[in] Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure.
pVertexStreamZeroData
[in] User memory pointer to the vertex data.
VertexStreamZeroStride
[in] The number of bytes of data for each vertex. This value may not be 0.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

This method is intended for use in applications that are unable to store their vertex data in vertex buffers. This method supports only a single vertex stream. The effect of this call is to use the provided vertex data pointer and stride for vertex stream 0. It is invalid to have the declaration of the current vertex shader refer to vertex streams other than stream 0.

Following any IDirect3DDevice9::DrawPrimitiveUP call, the stream 0 settings, referenced by IDirect3DDevice9::GetStreamSource, are set to NULL.

The vertex data passed to IDirect3DDevice9::DrawPrimitiveUP does not need to persist after the call. Direct3D completes its access to that data prior to returning from the call.

When converting a legacy application to Direct3D 9, you must add a call to either IDirect3DDevice9::SetFVF to use the fixed function pipeline, or IDirect3DDevice9::SetVertexDeclaration to use a vertex shader before you make any Draw calls.

Requirements

Header: Declared in D3D9.h.

See Also

Rendering from Vertex and Index Buffers (Direct3D 9), IDirect3DDevice9::DrawIndexedPrimitiveUP


IDirect3DDevice9::DrawRectPatch

Draws a rectangular patch using the currently set streams.

HRESULT DrawRectPatch(
  UINT Handle,
  const float* pNumSegs,
  const D3DRECTPATCH_INFO* pRectPatchInfo
);

Parameters

Handle
[in] Handle to the rectangular patch to draw.
pNumSegs
[in] Pointer to an array of four floating-point values that identify the number of segments each edge of the rectangle patch should be divided into when tessellated. See D3DRECTPATCH_INFO.
pRectPatchInfo
[in] Pointer to a D3DRECTPATCH_INFO structure, describing the rectangular patch to draw.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For static patches: Set the vertex shader, set the appropriate streams, supply patch information in the pRectPatchInfo parameter, and specify a handle so that Direct3D can capture and cache information. Call IDirect3DDevice9::DrawRectPatch subsequently with pRectPatchInfo set to NULL to efficiently draw the patch. When drawing a cached patch, the currently set streams are ignored. Override the cached pNumSegs by specifying a new value for pNumSegs. When rendering a cached patch, you must set the same vertex shader that was set when it was captured.

Calling IDirect3DDevice9::DrawRectPatch with a handle invalidates the same handle cached by a previous IDirect3DDevice9::DrawTriPatch call.

For dynamic patches, the patch data changes for every rendering of the patch, so it is not efficient to cache information. The application can convey this to Direct3D by setting Handle to 0. In this case, Direct3D draws the patch using the currently set streams and the pNumSegs values, and does not cache any information. It is not valid to simultaneously set Handle to 0 and pRectPatchInfo to NULL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::DeletePatch, Using Higher-Order Primitives (Direct3D 9)


IDirect3DDevice9::DrawTriPatch

Draws a triangular patch using the currently set streams.

HRESULT DrawTriPatch(
  UINT Handle,
  const float* pNumSegs,
  const D3DTRIPATCH_INFO* pTriPatchInfo
);

Parameters

Handle
[in] Handle to the triangular patch to draw.
pNumSegs
[in] Pointer to an array of three floating-point values that identify the number of segments each edge of the triangle patch should be divided into when tessellated. See D3DTRIPATCH_INFO.
pTriPatchInfo
[in] Pointer to a D3DTRIPATCH_INFO structure, describing the triangular high-order patch to draw.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For static patches: Set the vertex shader, set the appropriate streams, supply patch information in the pTriPatchInfo parameter, and specify a handle so that Direct3D can capture and cache information. To efficiently draw the patch, call IDirect3DDevice9::DrawTriPatch with pTriPatchInfo set to NULL. When drawing a cached patch, the currently set streams are ignored. Override the cached pNumSegs by specifying a new value for pNumSegs. When rendering a cached patch, you must set the same vertex shader that was set when it was captured.

Calling IDirect3DDevice9::DrawTriPatch with a handle invalidates the same handle cached by a previous IDirect3DDevice9::DrawRectPatch call.

For dynamic patches, the patch data changes for every rendering of the patch so it is not efficient to cache information. The application can convey this to Direct3D by setting Handle to 0. In this case, Direct3D draws the patch using the currently set streams and the pNumSegs values, and does not cache any information. It is not valid to simultaneously set Handle to 0 and pTriPatchInfo to NULL.

Requirements

Header: Declared in D3D9.h.

See Also

Using Higher-Order Primitives (Direct3D 9)


IDirect3DDevice9::EndScene

Ends a scene that was begun by calling IDirect3DDevice9::BeginScene.

HRESULT EndScene();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. The method will fail with D3DERR_INVALIDCALL if IDirect3DDevice9::BeginScene is called while already in a IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene pair. This happens only when IDirect3DDevice9::BeginScene is called twice without first calling IDirect3DDevice9::EndScene.

Remarks

When this method succeeds, the scene has been queued up for rendering by the driver. This is not a synchronous method, so the scene is not guaranteed to have completed rendering when this method returns.

Applications must call IDirect3DDevice9::BeginScene before performing any rendering and must call IDirect3DDevice9::EndScene when rendering is complete and before calling IDirect3DDevice9::BeginScene again.

If IDirect3DDevice9::BeginScene fails, the device was unable to begin the scene, and there is no need to call IDirect3DDevice9::EndScene. In fact, calls to IDirect3DDevice9::EndScene will fail if the previous IDirect3DDevice9::BeginScene failed. This applies to any application that creates multiple swap chains.

There should be at most one IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene pair between any successive calls to present (either IDirect3DDevice9::Present or IDirect3DSwapChain9::Present). IDirect3DDevice9::BeginScene should be called once before any rendering is performed, and IDirect3DDevice9::EndScene should be called once after all rendering for a frame has been submitted to the runtime. To enable maximal parallelism between the CPU and the graphics accelerator, it is advantageous to call IDirect3DDevice9::EndScene as far ahead of calling present as possible.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::EndStateBlock

Signals Direct3D to stop recording a device-state block and retrieve a pointer to the state block interface.

HRESULT EndStateBlock(
  IDirect3DStateBlock9 ** ppSB
);

Parameters

ppSB
[in, retval] Pointer to a state block interface. See IDirect3DStateBlock9.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::BeginStateBlock, IDirect3DDevice9::CreateStateBlock


IDirect3DDevice9::EvictManagedResources

Evicts all managed resources, including both Direct3D and driver-managed resources.

HRESULT EvictManagedResources();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_OUTOFVIDEOMEMORY, D3DERR_COMMAND_UNPARSED.

Remarks

This function causes only the D3DPOOL_DEFAULT copy of resources to be evicted. The resource copy in system memory is retained. See D3DPOOL.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetAvailableTextureMem

Returns an estimate of the amount of available texture memory.

UINT GetAvailableTextureMem();

Parameters

None.

Return Values

The function returns an estimate of the available texture memory.

Remarks

The returned value is rounded to the nearest MB. This is done to reflect the fact that video memory estimates are never precise due to alignment and other issues that affect consumption by certain resources. Applications can use this value to make gross estimates of memory availability to make large-scale resource decisions such as how many levels of a mipmap to attempt to allocate, but applications cannot use this value to make small-scale decisions such as if there is enough memory left to allocate another resource.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetBackBuffer

Retrieves a back buffer from the device's swap chain.

HRESULT GetBackBuffer(
  UINT  iSwapChain,
  UINT BackBuffer,
  D3DBACKBUFFER_TYPE Type,
  IDirect3DSurface9 ** ppBackBuffer
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
BackBuffer
[in] Index of the back buffer object to return. Back buffers are numbered from 0 to the total number of back buffers minus one. A value of 0 returns the first back buffer, not the front buffer. The front buffer is not accessible through this method. Use IDirect3DDevice9::GetFrontBufferData to retrieve a copy of the front buffer.
Type
[in] Stereo view is not supported in Direct3D 9, so the only valid value for this parameter is D3DBACKBUFFER_TYPE_MONO.
ppBackBuffer
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned back buffer surface.

Return Values

If the method succeeds, the return value is D3D_OK. If BackBuffer equals or exceeds the total number of back buffers, then the function fails and returns D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetFrontBufferData


IDirect3DDevice9::GetClipPlane

Retrieves the coefficients of a user-defined clipping plane for the device.

HRESULT GetClipPlane(
  DWORD Index,
  float * pPlane
);

Parameters

Index
[in] Index of the clipping plane for which the plane equation coefficients are retrieved.
pPlane
[out] Pointer to a four-element array of values that represent the coefficients of the clipping plane in the form of the general plane equation. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value is D3DERR_INVALIDCALL. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device, or that the array at pPlane is not large enough to contain four floating-point values.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

The coefficients that this method reports take the form of the general plane equation. If the values in the array at pPlane were labeled A, B, C, and D in the order that they appear in the array, they would fit into the general plane equation so that Ax + By + Cz + Dw = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

The plane equation used by this method exists in world space and is set by a previous call to the IDirect3DDevice9::SetClipPlane method.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetClipPlane


IDirect3DDevice9::GetClipStatus

Retrieves the clip status.

HRESULT GetClipStatus(
  D3DCLIPSTATUS9 * pClipStatus
);

Parameters

pClipStatus
[out] Pointer to a D3DCLIPSTATUS9 structure that describes the clip status.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

When clipping is enabled during vertex processing (by IDirect3DDevice9::ProcessVertices, IDirect3DDevice9::DrawPrimitive, or other drawing functions), Direct3D computes a clip code for every vertex. The clip code is a combination of D3DCS_* bits. When a vertex is outside a particular clipping plane, the corresponding bit is set in the clipping code. Direct3D maintains the clip status using D3DCLIPSTATUS9, which has ClipUnion and ClipIntersection members. ClipUnion is a bitwise "OR" of all vertex clip codes and ClipIntersection is a bitwise "AND" of all vertex clip codes. Initial values are zero for ClipUnion and 0xFFFFFFFF for ClipIntersection. When D3DRS_CLIPPING is set to FALSE, ClipUnion and ClipIntersection are set to zero. Direct3D updates the clip status during drawing calls. To compute clip status for a particular object, set ClipUnion and ClipIntersection to their initial value and continue drawing.

Clip status is not updated by IDirect3DDevice9::DrawRectPatch and IDirect3DDevice9::DrawTriPatch because there is no software emulation for them.

Clip status is used during software vertex processing. Therefore, this method is not supported on pure or nonpure hardware processing devices. For more information about pure devices, see D3DCREATE.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetClipStatus


IDirect3DDevice9::GetCreationParameters

Retrieves the creation parameters of the device.

HRESULT GetCreationParameters(
  D3DDEVICE_CREATION_PARAMETERS * pParameters
);

Parameters

pParameters
[out] Pointer to a D3DDEVICE_CREATION_PARAMETERS structure, describing the creation parameters of the device.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

You can query the AdapterOrdinal member of the returned D3DDEVICE_CREATION_PARAMETERS structure to retrieve the ordinal of the adapter represented by this device.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetCurrentTexturePalette

Retrieves the current texture palette.

HRESULT GetCurrentTexturePalette(
  UINT * pPaletteNumber
);

Parameters

pPaletteNumber
[out, retval] Pointer to a returned value that identifies the current texture palette.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetCurrentTexturePalette, Texture Palettes (Direct3D 9)


IDirect3DDevice9::GetDepthStencilSurface

Gets the depth-stencil surface owned by the Direct3DDevice object.

HRESULT GetDepthStencilSurface(
  IDirect3DSurface9 ** ppZStencilSurface
);

Parameters

ppZStencilSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned depth-stencil surface.

Return Values

If the method succeeds, the return value is D3D_OK.If the device doesn't have a depth stencil buffer associated with it, the return value will be D3DERR_NOTFOUND. Otherwise, if the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetDepthStencilSurface


IDirect3DDevice9::GetDeviceCaps

Retrieves the capabilities of the rendering device.

HRESULT GetDeviceCaps(
  D3DCAPS9 * pCaps
);

Parameters

pCaps
[out] Pointer to a D3DCAPS9 structure, describing the returned device.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

IDirect3DDevice9::GetDeviceCaps retrieves the software vertex pipeline capabilities when the device is being used in software vertex processing mode.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetDirect3D

Returns an interface to the instance of the Direct3D object that created the device.

HRESULT GetDirect3D(
  IDirect3D9 ** ppD3D9
);

Parameters

ppD3D9
[out, retval] Address of a pointer to an IDirect3D9 interface, representing the interface of the Direct3D object that created the device.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling IDirect3DDevice9::GetDirect3D will increase the internal reference count on the IDirect3D9 interface. Failure to call IUnknown::Release when finished using this IDirect3D9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetDisplayMode

Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.

HRESULT GetDisplayMode(
  UINT  iSwapChain,
  D3DDISPLAYMODE * pMode
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pMode
[out] Pointer to a D3DDISPLAYMODE structure containing data about the display mode of the adapter. As opposed to the display mode of the device, which may not be active if the device does not own full-screen mode.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetFrontBufferData

Generates a copy of the device's front buffer and places that copy in a system memory buffer provided by the application.

HRESULT GetFrontBufferData(
  UINT  iSwapChain,
  IDirect3DSurface9 * pDestSurface
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pDestSurface

Pointer to an IDirect3DSurface9 interface that will receive a copy of the contents of the front buffer. The data is returned in successive rows with no intervening space, starting from the vertically highest row on the device's output to the lowest.

[in]
For windowed mode, the size of the destination surface should be the size of the desktop. For full-screen mode, the size of the destination surface should be the screen size.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_DRIVERINTERNALERROR, D3DERR_DEVICELOST, D3DERR_INVALIDCALL

Remarks

The buffer pointed to by pDestSurface will be filled with a representation of the front buffer, converted to the standard 32 bits per pixel format D3DFMT_A8R8G8B8.

This method is the only way to capture an antialiased screen shot.

This function is very slow, by design, and should not be used in any performance-critical path.

For more information, see Lost Devices and Retrieved Data.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetFVF

Gets the fixed vertex function declaration.

HRESULT GetFVF(
  DWORD * pFVF
);

Parameters

pFVF
[out] A DWORD pointer to the fixed function vertex type. For more information, see D3DFVF.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The fixed vertex function declaration is a set of FVF flags that determine how vertices processed by the fixed function pipeline will be used.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetFVF


IDirect3DDevice9::GetGammaRamp

Retrieves the gamma correction ramp for the swap chain.

void GetGammaRamp(
  UINT  iSwapChain,
  D3DGAMMARAMP * pRamp
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pRamp
[in, out] Pointer to an application-supplied D3DGAMMARAMP structure to fill with the gamma correction ramp.

Return Values

None.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DSwapChain9, IDirect3DDevice9::SetGammaRamp


IDirect3DDevice9::GetIndices

Retrieves index data.

HRESULT GetIndices(
  IDirect3DIndexBuffer9 ** ppIndexData,
  UINT * pBaseVertexIndex
);

Parameters

ppIndexData
[out] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the returned index data.
pBaseVertexIndex
[out] Pointer to a UINT value, holding the returned base value for vertex indices. This value is added to all indices prior to referencing vertex data, defining a starting position in the vertex streams.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DIndexBuffer9 interface. Failure to call IUnknown::Release when finished using this IDirect3DIndexBuffer9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetIndices , IDirect3DDevice9::DrawIndexedPrimitive, IDirect3DDevice9::DrawIndexedPrimitiveUP, IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawPrimitiveUP, Index Buffers (Direct3D 9)


IDirect3DDevice9::GetLight

Retrieves a set of lighting properties that this device uses.

HRESULT GetLight(
  DWORD Index,
  D3DLight9 * pLight
);

Parameters

Index
[in] Zero-based index of the lighting property set to retrieve. This method will fail if a lighting property has not been set for this index by calling the IDirect3DDevice9::SetLight method.
pLight
[out] Pointer to a D3DLIGHT9 structure that is filled with the retrieved lighting-parameter set.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE.

Retrieve all the properties for an existing light source by calling the IDirect3DDevice9::GetLight method for the device. When calling the IDirect3DDevice9::GetLight method, pass the zero-based index of the light source for which the properties will be retrieved as the first parameter, and supply the address of a D3DLIGHT9 structure as the second parameter. The device fills the D3DLIGHT9 structure to describe the lighting properties it uses for the light source at that index.

// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;
D3DLight9 light;

// Get the property information for the first light.
hr = pd3dDevice->GetLight(0, &light);
if (SUCCEEDED(hr))
    // Handle Success
else
    // Handle failure

If you supply an index outside the range of the light sources assigned in the device, the IDirect3DDevice9::GetLight method fails, returning D3DERR_INVALIDCALL.

When you assign a set of light properties for a light source in a scene, the light source can be activated by calling the IDirect3DDevice9::LightEnable method for the device. New light sources are disabled by default. The IDirect3DDevice9::LightEnable method accepts two parameters. Set the first parameter to the zero-based index of the light source to be affected by the method, and set the second parameter to TRUE to enable the light or FALSE to disable it. The following code example illustrates the use of this method by enabling the first light source in the device's list of light source properties.

// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;

hr = pd3dDevice->LightEnable(0, TRUE);
if (SUCCEEDED(hr))
    // Handle Success
else
    // Handle failure

Check the MaxActiveLights member of the D3DCAPS9 structure when you retrieve device capabilities to determine the maximum number of active lights supported by that device.

If you enable or disable a light that has no properties that are set with IDirect3DDevice9::SetLight, the IDirect3DDevice9::LightEnable method creates a light source with the properties listed in following table and enables or disables it.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetLight, IDirect3DDevice9::GetLightEnable, IDirect3DDevice9::LightEnable


IDirect3DDevice9::GetLightEnable

Retrieves the activity status - enabled or disabled - for a set of lighting parameters within a device.

HRESULT GetLightEnable(
  DWORD Index,
  BOOL * pEnable
);

Parameters

Index
[in] Zero-based index of the set of lighting parameters that are the target of this method.
pEnable
[out, retval] Pointer to a variable to fill with the status of the specified lighting parameters. After the call, a nonzero value at this address indicates that the specified lighting parameters are enabled; a value of 0 indicates that they are disabled.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::LightEnable, IDirect3DDevice9::SetLight


IDirect3DDevice9::GetMaterial

Retrieves the current material properties for the device.

HRESULT GetMaterial(
  D3DMATERIAL9 * pMaterial
);

Parameters

pMaterial
[out] Pointer to a D3DMATERIAL9 structure to fill with the currently set material properties.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL if the pMaterial parameter is invalid.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetMaterial


IDirect3DDevice9::GetNPatchMode

Gets the N-patch mode segments.

FLOAT GetNPatchMode();

Parameters

None.

Return Values

Specifies the number of subdivision segments. If the number of segments is less than 1.0, N-patches are disabled. The default value is 0.0.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetNPatchMode


IDirect3DDevice9::GetNumberOfSwapChains

Gets the number of implicit swap chains.

UINT GetNumberOfSwapChains();

Parameters

None.

Return Values

Number of implicit swap chains. See Remarks.

Remarks

Implicit swap chains are created by the device during IDirect3D9::CreateDevice. This method returns the number of swap chains created by CreateDevice.

An application may create additional swap chains using IDirect3DDevice9::CreateAdditionalSwapChain.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetPaletteEntries

Retrieves palette entries.

HRESULT GetPaletteEntries(
  UINT PaletteNumber,
  PALETTEENTRY * pEntries
);

Parameters

PaletteNumber
[in] An ordinal value identifying the particular palette to retrieve.
pEntries
[in, out] Pointer to a PALETTEENTRY structure, representing the returned palette entries.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For more information about PALETTEENTRY, see the Platform SDK.

Note As of Direct3D 9, the peFlags member of the PALETTEENTRY structure does not work the way it is documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetCurrentTexturePalette, IDirect3DDevice9::SetCurrentTexturePalette, IDirect3DDevice9::SetPaletteEntries, Texture Palettes (Direct3D 9)


IDirect3DDevice9::GetPixelShader

Retrieves the currently set pixel shader.

HRESULT GetPixelShader(
  IDirect3DPixelShader9** ppShader
);

Parameters

ppShader
[out, retval] Pointer to a pixel shader interface.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not work on a device that is created using D3DCREATE_PUREDEVICE.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetPixelShader


IDirect3DDevice9::GetPixelShaderConstantB

Gets a Boolean shader constant.

HRESULT GetPixelShaderConstantB(
  UINT StartRegister,
  BOOL * pConstantData,
  UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
BoolCount
[in] Number of Boolean values in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetPixelShaderConstantB


IDirect3DDevice9::GetPixelShaderConstantF

Gets a floating-point shader constant.

HRESULT GetPixelShaderConstantF(
  UINT StartRegister,
  float * pConstantData,
  UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetPixelShaderConstantF


IDirect3DDevice9::GetPixelShaderConstantI

Gets an integer shader constant.

HRESULT GetPixelShaderConstantI(
  UINT StartRegister,
  int * pConstantData,
  UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetPixelShaderConstantI


IDirect3DDevice9::GetRasterStatus

Returns information describing the raster of the monitor on which the swap chain is presented.

HRESULT GetRasterStatus(
  UINT  iSwapChain,
  D3DRASTER_STATUS * pRasterStatus
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pRasterStatus
[out] Pointer to a D3DRASTER_STATUS structure filled with information about the position or other status of the raster on the monitor driven by this adapter.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if pRasterStatus is invalid or if the device does not support reading the current scan line. To determine if the device supports reading the scan line, check for the D3DCAPS_READ_SCANLINE flag in the Caps member of D3DCAPS9.

Requirements

Header: Declared in D3D9.h.

See Also

D3DRASTER_STATUS


IDirect3DDevice9::GetRenderState

Retrieves a render-state value for a device.

HRESULT GetRenderState(
  D3DRENDERSTATETYPE State,
  DWORD * pValue
);

Parameters

State
[in] Device state variable that is being queried. This parameter can be any member of the D3DRENDERSTATETYPE enumerated type.
pValue
[out, retval] Pointer to a variable that receives the value of the queried render state variable when the method returns.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetRenderState


IDirect3DDevice9::GetRenderTarget

Retrieves a render-target surface.

HRESULT GetRenderTarget(
  DWORD RenderTargetIndex,
  IDirect3DSurface9 ** ppRenderTarget
);

Parameters

RenderTargetIndex
[in] Index of the render target. See Remarks.
ppRenderTarget
[out] Address of a pointer to an IDirect3DSurface9 interface, representing the returned render-target surface for this device.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL if one of the arguments is invalid, or D3DERR_NOTFOUND if there's no render target available for the given index.

Remarks

Typically, methods that return state will not work on a device that is created using D3DCREATE_PUREDEVICE. This method however, will work even on a pure device because it returns an interface.

The device can now support multiple render targets. The number of render targets supported by a device is contained in the NumSimultaneousRTs member of D3DCAPS9. See Multiple Render Targets (Direct3D 9).

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using the IDirect3DSurface9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetRenderTarget


IDirect3DDevice9::GetRenderTargetData

Copies the render-target data from device memory to system memory.

HRESULT GetRenderTargetData(
  IDirect3DSurface9* pRenderTarget,
  IDirect3DSurface9* pDestSurface
);

Parameters

pRenderTarget
[in] Pointer to an IDirect3DSurface9 object, representing a render target.
pDestSurface
[in] Pointer to an IDirect3DSurface9 object, representing a destination surface.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_DRIVERINTERNALERROR, D3DERR_DEVICELOST, D3DERR_INVALIDCALL.

Remarks

The destination surface must be either an off-screen plain surface or a level of a texture (mipmap or cube texture) created with D3DPOOL_SYSTEMMEM.

The source surface must be a regular render target or a level of a render-target texture (mipmap or cube texture) created with POOL_DEFAULT.

This method will fail if:

  • The render target is multisampled.
  • The source render target is a different size than the destination surface.
  • The source render target and destination surface formats do not match.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetSamplerState

Gets the sampler state value.

HRESULT GetSamplerState(
  DWORD Sampler,
  D3DSAMPLERSTATETYPE Type,
  DWORD* pValue
);

Parameters

Sampler
[in] The sampler stage index.
Type
[in] This parameter can be any member of the D3DSAMPLERSTATETYPE enumerated type.
pValue
[out] State value to get. The meaning of this value is determined by the Type parameter.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetSamplerState


IDirect3DDevice9::GetScissorRect

Gets the scissor rectangle.

HRESULT GetScissorRect(
  RECT * pRect
);

Parameters

pRect
[out] Returns a pointer to a RECT structure that defines the rendering area within the render target if scissor test is enabled.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be the following: D3DERR_INVALIDCALL.

Remarks

The scissor rectangle is used as a rectangular clipping region.

See Rectangles (Direct3D 9) for further information on the use of rectangles in DirectX.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetSoftwareVertexProcessing

Gets the vertex processing (hardware or software) mode.

BOOL GetSoftwareVertexProcessing();

Parameters

None.

Return Values

Returns TRUE if software vertex processing is set. Otherwise, it returns FALSE.

Remarks

An application can create a mixed-mode device to use both the software vertex processing and the hardware vertex processing. To switch between the two vertex processing modes in DirectX 8.x, use IDirect3DDevice9::SetRenderState with the render state D3DRS_SOFTWAREVERTEXPROCESSING and the appropriate BOOL argument. The drawback of the render state approach was the difficulty in defining the semantics for state blocks. Applications and the runtime had to do extra work and be careful while recording and playing back state blocks.

In Direct3D 9, use IDirect3DDevice9::SetSoftwareVertexProcessing instead. This new API is not recorded by StateBlocks.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetStreamSource

Retrieves a vertex buffer bound to the specified data stream.

HRESULT GetStreamSource(
  UINT StreamNumber,
  IDirect3DVertexBuffer9 ** ppStreamData,
  UINT * pOffsetInBytes,
  UINT * pStride
);

Parameters

StreamNumber
[in] Specifies the data stream, in the range from 0 to the maximum number of streams minus one.
ppStreamData
[in, out] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the returned vertex buffer bound to the specified data stream.
pOffsetInBytes
[out] Pointer containing the offset from the beginning of the stream to the beginning of the vertex data. The offset is measured in bytes. See Remarks.
pStride
[out] Pointer to a returned stride of the component, in bytes. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A stream is defined as a uniform array of component data, where each component consists of one or more elements representing a single entity such as position, normal, color, and so on.

When a FVF vertex shader is used, the stride of the vertex stream must match the vertex size, computed from the FVF. When a declaration is used, the stride should be greater than or equal to the stream size computed from the declaration.

Calling this method will increase the internal reference count on the IDirect3DVertexBuffer9 interface. Failure to call IUnknown::Release when finished using this IDirect3DVertexBuffer9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetStreamSource, IDirect3DDevice9::DrawIndexedPrimitive, IDirect3DDevice9::DrawIndexedPrimitiveUP, IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawPrimitiveUP, Vertex Buffers (Direct3D 9)


IDirect3DDevice9::GetStreamSourceFreq

Gets the stream source frequency divider value.

HRESULT GetStreamSourceFreq(
  UINT StreamNumber,
  UINT* pDivider
);

Parameters

StreamNumber
[in] Stream source number.
pDivider
[out] Returns the frequency divider value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Vertex shaders can now be invoked more than once per vertex. See Drawing Non-Indexed Geometry.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetStreamSourceFreq


IDirect3DDevice9::GetSwapChain

Gets a pointer to a swap chain.

HRESULT GetSwapChain(
  UINT  iSwapChain,
  IDirect3DSwapChain9 ** ppSwapChain
);

Parameters

iSwapChain
[in] The swap chain ordinal value. For more information, see NumberOfAdaptersInGroup in D3DCAPS9.
ppSwapChain
[in] Pointer to an IDirect3DSwapChain9 interface that will receive a copy of swap chain.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetTexture

Retrieves a texture assigned to a stage for a device.

HRESULT GetTexture(
  DWORD Stage,
  IDirect3DBaseTexture9 ** ppTexture
);

Parameters

Stage
[in] Stage identifier of the texture to retrieve. Stage identifiers are zero-based.
ppTexture
[out, retval] Address of a pointer to an IDirect3DBaseTexture9 interface, representing the returned texture.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Typically, methods that return state will not work on a device that is created using D3DCREATE_PUREDEVICE. This method however, will work even on a pure device because it returns an interface.

Calling this method will increase the internal reference count on the IDirect3DTexture9 interface. Failure to call IUnknown::Release when finished using this IDirect3DTexture9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetTexture, IDirect3DDevice9::GetTextureStageState IDirect3DDevice9::SetTextureStageState


IDirect3DDevice9::GetTextureStageState

Retrieves a state value for an assigned texture.

HRESULT GetTextureStageState(
  DWORD Stage,
  D3DTEXTURESTAGESTATETYPE Type,
  DWORD * pValue
);

Parameters

Stage
[in] Stage identifier of the texture for which the state is retrieved. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
Type
[in] Texture state to retrieve. This parameter can be any member of the D3DTEXTURESTAGESTATETYPE enumerated type.
pValue
[out, retval] Pointer a variable to fill with the retrieved state value. The meaning of the retrieved value is determined by the Type parameter.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other flag values in D3DCREATE."

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetTextureStageState, IDirect3DDevice9::GetTexture, IDirect3DDevice9::SetTexture


IDirect3DDevice9::GetTransform

Retrieves a matrix describing a transformation state.

HRESULT GetTransform(
  D3DTRANSFORMSTATETYPE State,
  D3DMATRIX * pMatrix
);

Parameters

State
[in] Device state variable that is being modified. This parameter can be any member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro.
pMatrix
[out] Pointer to a D3DMATRIX structure, describing the returned transformation state.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other flag values in D3DCREATE.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetTransform


IDirect3DDevice9::GetVertexDeclaration

Gets a vertex shader declaration.

HRESULT GetVertexDeclaration(
  IDirect3DVertexDeclaration9** ppDecl
);

Parameters

ppDecl
[out] Pointer to an IDirect3DVertexDeclaration9 object that is returned.

Return Values

If the method succeeds, the return value is D3D_OK. The return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetVertexDeclaration


IDirect3DDevice9::GetVertexShader

Retrieves the currently set vertex shader.

HRESULT GetVertexShader(
  IDirect3DVertexShader9** ppShader
);

Parameters

ppShader
[out, retval] Pointer to a vertex shader interface.

Return Values

If the method succeeds, the return value is D3D_OK. If ppShader is invalid, D3DERR_INVALIDCALL is returned.

Remarks

Typically, methods that return state will not work on a device that is created using D3DCREATE_PUREDEVICE. This method however, will work even on a pure device because it returns an interface.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetVertexShader


IDirect3DDevice9::GetVertexShaderConstantB

Gets a Boolean vertex shader constant.

HRESULT GetVertexShaderConstantB(
  UINT StartRegister,
  BOOL * pConstantData,
  UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
BoolCount
[in] Number of Boolean values in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetVertexShaderConstantF

Gets a floating-point vertex shader constant.

HRESULT GetVertexShaderConstantF(
  UINT StartRegister,
  float * pConstantData,
  UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetVertexShaderConstantI

Gets an integer vertex shader constant.

HRESULT GetVertexShaderConstantI(
  UINT StartRegister,
  int * pConstantData,
  UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::GetViewport

Retrieves the viewport parameters currently set for the device.

HRESULT GetViewport(
  D3DVIEWPORT9 * pViewport
);

Parameters

pViewport
[out] Pointer to a D3DVIEWPORT9 structure, representing the returned viewport parameters.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if the pViewport parameter is invalid.

Remarks

Typically, methods that return state will not work on a device that is created using D3DCREATE_PUREDEVICE. This method however, will work even on a pure device.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetViewport


IDirect3DDevice9::LightEnable

Enables or disables a set of lighting parameters within a device.

HRESULT LightEnable(
  DWORD LightIndex,
  BOOL bEnable
);

Parameters

LightIndex
[in] Zero-based index of the set of lighting parameters that are the target of this method.
bEnable
[in] Value that indicates if the set of lighting parameters are being enabled or disabled. Set this parameter to TRUE to enable lighting with the parameters at the specified index, or FALSE to disable it.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If a value for LightIndex is outside the range of the light property sets assigned within the device, the IDirect3DDevice9::LightEnable method creates a light source represented by a D3DLIGHT9 structure with the following properties and sets its enabled state to the value specified in bEnable.

Member | Default
Type | D3DLIGHT_DIRECTIONAL
Diffuse | (R:1, G:1, B:1, A:0)
Specular | (R:0, G:0, B:0, A:0)
Ambient | (R:0, G:0, B:0, A:0)
Position | (0, 0, 0)
Direction | (0, 0, 1)
Range | 0
Falloff | 0
Attenuation0 | 0
Attenuation1 | 0
Attenuation2 | 0
Theta | 0
Phi | 0

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::GetLightEnable, IDirect3DDevice9::SetLight


IDirect3DDevice9::MultiplyTransform

Multiplies a device's world, view, or projection matrices by a specified matrix.

HRESULT MultiplyTransform(
  D3DTRANSFORMSTATETYPE State,
  CONST D3DMATRIX * pMatrix
);

Parameters

State
[in] Member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro that identifies which device matrix is to be modified. The most common setting, D3DTS_WORLDMATRIX(0), modifies the world matrix, but you can specify that the method modify the view or projection matrices, if needed.
pMatrix
[in] Pointer to a D3DMATRIX structure that modifies the current transformation.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

The multiplication order is pMatrix times State.

An application might use the IDirect3DDevice9::MultiplyTransform method to work with hierarchies of transformations. For example, the geometry and transformations describing an arm might be arranged in the following hierarchy.

    shoulder_transformation

    upper_arm geometry

    elbow transformation

    lower_arm geometry

    wrist transformation

    hand geometry

An application might use the following series of calls to render this hierarchy. Not all the parameters are shown in this pseudocode.

IDirect3DDevice9::SetTransform(D3DTS_WORLDMATRIX(0),
                               shoulder_transform)
IDirect3DDevice9::DrawPrimitive(upper_arm)
IDirect3DDevice9::MultiplyTransform(D3DTS_WORLDMATRIX(0),
                                    elbow_transform)
IDirect3DDevice9::DrawPrimitive(lower_arm)
IDirect3DDevice9::MultiplyTransform(D3DTS_WORLDMATRIX(0),
                                    wrist_transform)
IDirect3DDevice9::DrawPrimitive(hand)

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::SetTransform, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX


IDirect3DDevice9::Present

Presents the contents of the next buffer in the sequence of back buffers owned by the device.

HRESULT Present(
  CONST RECT * pSourceRect,
  CONST RECT * pDestRect,
  HWND hDestWindowOverride,
  CONST RGNDATA * pDirtyRegion
);

Parameters

pSourceRect
[in] Pointer to a value that must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. pSourceRect is a pointer to a RECT structure containing the source rectangle. If NULL, the entire source surface is presented. If the rectangle exceeds the source surface, the rectangle is clipped to the source surface.
pDestRect
[in] Pointer to a value that must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. pDestRect is a pointer to a RECT structure containing the destination rectangle, in window client coordinates. If NULL, the entire client area is filled. If the rectangle exceeds the destination client area, the rectangle is clipped to the destination client area.
hDestWindowOverride
[in] Pointer to a destination window whose client area is taken as the target for this presentation. If this value is NULL, then the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is taken.
pDirtyRegion
[in] Value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. For more information about swap chains, see Flipping Surfaces (Direct3D 9) and D3DSWAPEFFECT. If this value is non-NULL, the contained region is expressed in back buffer coordinates. The rectangles within the region are the minimal set of pixels that need to be updated. This method takes these rectangles into account when optimizing the presentation by copying only the pixels within the region, or some suitably expanded set of rectangles. This is an aid to optimization only, and the application should not rely on the region being copied exactly. The implementation can choose to copy the whole source rectangle.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_DEVICELOST, D3DERR_DRIVERINTERNALERROR, D3DERR_INVALIDCALL.

Remarks

If necessary, a stretch operation is applied to transfer the pixels within the source rectangle to the destination rectangle in the client area of the target window.

IDirect3DDevice9::Present will fail, returning D3DERR_INVALIDCALL, if called between BeginScene and EndScene pairs unless the render target is not the current render target (such as the back buffer you get from creating an additional swap chain). This is a new behavior for Direct3D 9.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::Reset, Multihead (Direct3D 9)


IDirect3DDevice9::ProcessVertices

Applies the vertex processing defined by the vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer.

HRESULT ProcessVertices(
  UINT SrcStartIndex,
  UINT DestIndex,
  UINT VertexCount,
  IDirect3DVertexBuffer9 * pDestBuffer,
  IDirect3DVertexDeclaration9* pVertexDecl,
  DWORD Flags
);

Parameters

SrcStartIndex
[in] Index of first vertex to load.
DestIndex
[in] Index of first vertex in the destination vertex buffer into which the results are placed.
VertexCount
[in] Number of vertices to process.
pDestBuffer
[in] Pointer to an IDirect3DVertexBuffer9 interface, the destination vertex buffer representing the stream of interleaved vertex data.
pVertexDecl
[in] Pointer to an IDirect3DVertexDeclaration9 interface that represents the output vertex data declaration. When vertex shader 3.0 or above is set as the current vertex shader, the output vertex declaration must be present.
Flags
[in] Processing options. Set this parameter to 0 for default processing. Set to D3DPV_DONOTCOPYDATA to prevent the system from copying vertex data not affected by the vertex operation into the destination buffer. The D3DPV_DONOTCOPYDATA value may be combined with one or more D3DLOCK values appropriate for the destination buffer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The order of operations for this method is as follows:

  • Transform vertices to projection space using the world + view + projection matrix.
  • Compute screen coordinates using viewport settings.
  • If clipping is enabled, compute clipping codes and store them in an internal buffer, associated with the destination vertex buffer. If a vertex is inside the viewing frustum, its screen coordinates are computed. If the vertex is outside the viewing frustum, the vertex is stored in the destination vertex buffer in projection space coordinates.
  • Other notes: The user does not have access to the internal clip code buffer. No clipping is done on triangles or any other primitives.

The destination vertex buffer, pDestBuffer, must be created with a nonzero FVF parameter in IDirect3DDevice9::CreateVertexBuffer. The FVF code specified during the call to the IDirect3DDevice9::CreateVertexBuffer method specifies the vertex elements present in the destination vertex buffer.

When Direct3D generates texture coordinates, or copies or transforms input texture coordinates, and the output texture coordinate format defines more texture coordinate components than Direct3D generates, Direct3D does not change these extra components.

Requirements

Header: Declared in D3D9.h.

See Also

Device Types and Vertex Processing Requirements (Direct3D 9), Fixed Function Vertex Processing (Direct3D 9)


IDirect3DDevice9::Reset

Resets the type, size, and format of the swap chain.

HRESULT Reset(
  D3DPRESENT_PARAMETERS* pPresentationParameters
);

Parameters

pPresentationParameters

Pointer to a D3DPRESENT_PARAMETERS structure, describing the new presentation parameters. This value cannot be NULL.

[in, out] When switching to full-screen mode, Direct3D will try to find a desktop format that matches the back buffer format, so that back buffer and front buffer formats will be identical (to eliminate the need for color conversion).

When this method returns:

  • BackBufferCount, BackBufferWidth, and BackBufferHeight are set to zero.
  • BackBufferFormat is set to D3DFMT_UNKNOWN for windowed mode only; a full-screen mode must specify a format.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_DEVICELOST, D3DERR_DRIVERINTERNALERROR, D3DERR_OUTOFVIDEOMEMORY.

Remarks

If a call to IDirect3DDevice9::Reset fails, the device will be placed in the "lost" state (as indicated by a return value of D3DERR_DEVICELOST from a call to IDirect3DDevice9::TestCooperativeLevel) unless it is already in the "not reset" state (as indicated by a return value of D3DERR_DEVICENOTRESET from a call to IDirect3DDevice9::TestCooperativeLevel). Refer to IDirect3DDevice9::TestCooperativeLevel and Lost Devices (Direct3D 9) for further information concerning the use of IDirect3DDevice9::Reset in the context of lost devices.

Calling IDirect3DDevice9::Reset causes all texture memory surfaces to be lost, managed textures to be flushed from video memory, and all state information to be lost. Before calling the IDirect3DDevice9::Reset method for a device, an application should release any explicit render targets, depth stencil surfaces, additional swap chains, state blocks, and D3DPOOL_DEFAULT resources associated with the device.

There are two different types of swap chains: full-screen or windowed. If the new swap chain is full-screen, the adapter will be placed in the display mode that matches the new size.

Direct3D 9 applications can expect messages to be sent to them during this call (for example, before this call is returned); applications should take precautions not to call into Direct3D at this time. In addition, when IDirect3DDevice9::Reset fails, the only valid methods that can be called are IDirect3DDevice9::Reset, IDirect3DDevice9::TestCooperativeLevel, and the various Release member functions. Calling any other method can result in an exception.

A call to IDirect3DDevice9::Reset will fail if called on a different thread than that used to create the device being reset.

Pixel shaders and vertex shaders survive IDirect3DDevice9::Reset calls for Direct3D 9. They do not need to be re-created explicitly by the application.

D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9::CreateDevice, IDirect3DDevice9::Reset, and IDirect3DDevice9::CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling IDirect3D9::CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified. Setting BackBufferCount equal to zero (BackBufferCount = 0) results in one back buffer.

When trying to reset more than one display adapter in a group, set pPresentationParameters to point to an array of D3DPRESENT_PARAMETERS structures, one for each display in the adapter group.

If a multihead device was created with D3DCREATE_ADAPTERGROUP_DEVICE, IDirect3DDevice9::Reset requires an array of D3DPRESENT_PARAMETERS structures wherein each structure must specify a full-screen display. To switch back to windowed mode, the application must destroy the device and re-create a non-multihead device in windowed mode.

Requirements

Header: Declared in D3D9.h.

See Also

D3DSWAPEFFECT, D3DPRESENT_PARAMETERS, IDirect3DDevice9::Present, Multihead (Direct3D 9)


IDirect3DDevice9::SetClipPlane

Sets the coefficients of a user-defined clipping plane for the device.

HRESULT SetClipPlane(
  DWORD Index,
  CONST float * pPlane
);

Parameters

Index
[in] Index of the clipping plane for which the plane equation coefficients are to be set.
pPlane
[in] Pointer to an address of a four-element array of values that represent the clipping plane coefficients to be set, in the form of the general plane equation. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value is D3DERR_INVALIDCALL. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device or that the array at pPlane is not large enough to contain four floating-point values.

Remarks

The coefficients that this method sets take the form of the general plane equation. If the values in the array at pPlane were labeled A, B, C, and D in the order that they appear in the array, they would fit into the general plane equation so that Ax + By + Cz + Dw = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist behind the clipping plane are clipped from the scene.

When the fixed function pipeline is used the plane equations are assumed to be in world space. When the programmable pipeline is used the plane equations are assumed to be in the clipping space (the same space as output vertices).

This method does not enable the clipping plane equation being set. To enable a clipping plane, set the corresponding bit in the DWORD value applied to the D3DRS_CLIPPLANEENABLE render state.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetClipPlane


IDirect3DDevice9::SetClipStatus

Sets the clip status.

HRESULT SetClipStatus(
  CONST D3DCLIPSTATUS9 * pClipStatus
);

Parameters

pClipStatus
[in] Pointer to a D3DCLIPSTATUS9 structure, describing the clip status settings to be set.

Return Values

If the method succeeds, the return value is D3D_OK. If one of the arguments is invalid, the return value is D3DERR_INVALIDCALL.

Remarks

Clip status is used during software vertex processing. Therefore, this method is not supported on pure or nonpure hardware processing devices. For more information about pure devices, see D3DCREATE.

When clipping is enabled during vertex processing (by IDirect3DDevice9::ProcessVertices, IDirect3DDevice9::DrawPrimitive, or other drawing functions), Direct3D computes a clip code for every vertex. The clip code is a combination of D3DCS_* bits. When a vertex is outside a particular clipping plane, the corresponding bit is set in the clipping code. Direct3D maintains the clip status using D3DCLIPSTATUS9, which has ClipUnion and ClipIntersection members. ClipUnion is a bitwise "OR" of all vertex clip codes and ClipIntersection is a bitwise "AND" of all vertex clip codes. Initial values are zero for ClipUnion and 0xFFFFFFFF for ClipIntersection. When D3DRS_CLIPPING is set to FALSE, ClipUnion and ClipIntersection are set to zero. Direct3D updates the clip status during drawing calls. To compute clip status for a particular object, set ClipUnion and ClipIntersection to their initial value and continue drawing.

Clip status is not updated by IDirect3DDevice9::DrawRectPatch and IDirect3DDevice9::DrawTriPatch because there is no software emulation for them.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetClipStatus


IDirect3DDevice9::SetCurrentTexturePalette

Sets the current texture palette.

HRESULT SetCurrentTexturePalette(
  UINT PaletteNumber
);

Parameters

PaletteNumber
[in] Value that specifies the texture palette to set as the current texture palette.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A single logical palette is associated with the device, and is shared by all texture stages.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetCurrentTexturePalette, Texture Palettes (Direct3D 9)


IDirect3DDevice9::SetCursorPosition

Sets the cursor position and update options.

void SetCursorPosition(
  INT X,
  INT Y,
  DWORD Flags
);

Parameters

X
[in] The new X-position of the cursor in virtual desktop coordinates. See Remarks.
Y
[in] The new Y-position of the cursor in virtual desktop coordinates. See Remarks.
Flags
[in] Specifies the update options for the cursor. Currently, only one flag is defined.
D3DCURSOR_IMMEDIATE_UPDATE

Update cursor at the refresh rate.

If this flag is specified, the system guarantees that the cursor will be updated at a minimum of half the display refresh rate, but never more frequently than the display refresh rate. Otherwise, the method delays cursor updates until the next IDirect3DDevice9::Present call. Not setting this flag usually results in better performance than if the flag is set. However, applications should set this flag if the rate of calls to Present is low enough that users would notice a significant delay in cursor motion. This flag has no effect in a windowed-mode application. Some video cards implement hardware color cursors. This flag does not have an effect on these cards.

Return Values

None.

Remarks

When running in full-screen mode, screen space coordinates are the back buffer coordinates appropriately scaled to the current display mode. When running in windowed mode, screen space coordinates are the desktop coordinates. The cursor image is drawn at the specified position minus the hotspot-offset specified by the IDirect3DDevice9::SetCursorProperties method.

If the cursor has been hidden by IDirect3DDevice9::ShowCursor, the cursor is not drawn.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetCursorProperties, IDirect3DDevice9::ShowCursor


IDirect3DDevice9::SetCursorProperties

Sets properties for the cursor.

HRESULT SetCursorProperties(
  UINT XHotSpot,
  UINT YHotSpot,
  IDirect3DSurface9 * pCursorBitmap
);

Parameters

XHotSpot
[in] X-coordinate offset (in pixels) that marks the center of the cursor. The offset is relative to the upper-left corner of the cursor. When the cursor is given a new position, the image is drawn at an offset from this new position determined by subtracting the hot spot coordinates from the position.
YHotSpot
[in] Y-coordinate offset (in pixels) that marks the center of the cursor. The offset is relative to the upper-left corner of the cursor. When the cursor is given a new position, the image is drawn at an offset from this new position determined by subtracting the hot spot coordinates from the position.
pCursorBitmap
[in] Pointer to an IDirect3DSurface9 interface. This parameter must point to an 8888 ARGB surface (format D3DFMT_A8R8G8B8). The contents of this surface will be copied and potentially format-converted into an internal buffer from which the cursor is displayed. The dimensions of this surface must be less than the dimensions of the display mode, and must be a power of two in each direction, although not necessarily the same power of two. The alpha channel must be either 0.0 or 1.0.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An operating system cursor is created and used under either of these conditions:

  • The hardware has set D3DCURSORCAPS_COLOR (see D3DCURSORCAPS), and the cursor size is 32x32 (which is the cursor size in the operating system).
  • The application is running in windowed mode.

Otherwise, DirectX uses an emulated cursor. An application uses IDirect3DDevice9::SetCursorPosition to move an emulated cursor to follow mouse movement.

It is recommended for applications to always trap WM_MOUSEMOVE events and call DXSetCursorPosition.

Direct3D cursor functions use either GDI cursor or software emulation, depending on the hardware. Users typically want to respond to a WM_SETCURSOR message. For example, they might want to write the message handler as follows:

case WM_SETCURSOR:
// Turn off window cursor.
SetCursor( NULL );
m_pd3dDevice->ShowCursor( TRUE );
return TRUE; // Prevent Windows from setting cursor to window class cursor.
break;

Or, users might want to call the IDirect3DDevice9::SetCursorProperties method if they want to change the cursor.

The application can determine what hardware support is available for cursors by examining appropriate members of the D3DCAPS9 structure. Typically, hardware supports only 32x32 cursors and, when windowed, the system might support only 32x32 cursors. In this case, IDirect3DDevice9::SetCursorProperties still succeeds but the cursor might be reduced to that size. The hot spot is scaled appropriately.

The cursor does not survive when the device is lost. This method must be called after the device is reset.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::ShowCursor, D3DCAPS9


IDirect3DDevice9::SetDepthStencilSurface

Sets the depth stencil surface.

HRESULT SetDepthStencilSurface(
  IDirect3DSurface9 * pNewZStencil
);

Parameters

pNewZStencil
[in] Address of a pointer to an IDirect3DSurface9 interface representing the depth stencil surface. Setting this to NULL disables the depth stencil operation.

Return Values

If the method succeeds, the return value is D3D_OK. If pZStencilSurface is other than NULL, the return value is D3DERR_INVALIDCALL when the stencil surface is invalid.

Remarks

Restrictions for using this method include the following:

  • The multisample type must be the same for the render target and the depth stencil surface.
  • The formats must be compatible for the render target and the depth stencil surface. See IDirect3D9::CheckDepthStencilMatch.
  • The size of the depth stencil surface must be greater than or equal to the size of the render target.

These restrictions are validated only when using the debug runtime when any of the IDirect3DDevice9 Draw methods are called.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetDepthStencilSurface with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetDepthStencilSurface.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetDepthStencilSurface


IDirect3DDevice9::SetDialogBoxMode

This method allows the use of GDI dialog boxes in full-screen mode applications.

HRESULT SetDialogBoxMode(
  BOOL bEnableDialogs
);

Parameters

bEnableDialogs
[in] TRUE to enable GDI dialog boxes, and FALSE to disable them.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL unless all of the following are true.

  • The application specified a back buffer format compatible with GDI, in other words, one of D3DFMT_X1R5G5B5, D3DFMT_R5G6B5, or D3DFMT_X8R8G8B8.
  • The application specified no multisampling.
  • The application specified D3DSWAPEFFECT_DISCARD.
  • The application specified D3DPRESENTFLAG_LOCKABLE_BACKBUFFER.
  • The application did not specify D3DCREATE_ADAPTERGROUP_DEVICE.
  • The application is not between BeginScene and EndScene.

Remarks

The GDI dialog boxes must be created as child to the device window. They should also be created within the same thread that created the device because this enables the parent window to manage redrawing the child window.

The method has no effect for windowed mode applications, but this setting will be respected if the application resets the device into full-screen mode. If SetDialogBoxMode succeeds in a windowed mode application, any subsequent reset to full-screen mode will be checked against the restrictions listed above. Also, SetDialogBoxMode causes all back buffers on the swap chain to be discarded, so an application is expected to refresh its content for all back buffers after this call.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::SetFVF

Sets the current vertex stream declaration.

HRESULT SetFVF(
  DWORD FVF
);

Parameters

FVF
[in] DWORD containing the fixed function vertex type. For more information, see D3DFVF.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

Here are the steps necessary to initialize and use vertices that have a position, diffuse and specular color, and texture coordinates:

  1. Define the custom vertex type and FVF code.
    struct LVertex
{
    FLOAT    x, y, z;
    D3DCOLOR specular, diffuse;
    FLOAT    tu, tv;
};

const DWORD VertexFVF = (D3DFVF_XYZ | D3DFVF_DIFFUSE |
                         D3DFVF_SPECULAR | D3DFVF_TEX1 );
  2. Create a vertex buffer with enough room for four vertices using IDirect3DDevice9::CreateVertexBuffer.
    g_d3dDevice->CreateVertexBuffer( 4*sizeof(LVertex),
    D3DUSAGE_WRITEONLY, VertexFVF, D3DPOOL_DEFAULT, &pBigSquareVB, NULL );
  3. Set the values for each vertex.
    LVertex * v;
pBigSquareVB->Lock( 0, 0, (BYTE**)&v, 0 );

v[0].x  = 0.0f;  v[0].y  = 10.0;  v[0].z  = 10.0f;
v[0].diffuse  = 0xffff0000;
v[0].specular = 0xff00ff00;
v[0].tu = 0.0f;  v[0].tv = 0.0f;

v[1].x  = 0.0f;  v[1].y  = 0.0f;  v[1].z  = 10.0f;
v[1].diffuse  = 0xff00ff00;
v[1].specular = 0xff00ffff;
v[1].tu = 0.0f;  v[1].tv = 0.0f;

v[2].x  = 10.0f; v[2].y  = 10.0f; v[2].z  = 10.0f;
v[2].diffuse  = 0xffff00ff;
v[2].specular = 0xff000000;
v[2].tu = 0.0f;  v[2].tv = 0.0f;

v[3].x  = 0.0f; v[3].y  = 10.0f;  v[3].z = 10.0f;
v[3].diffuse  = 0xffffff00;
v[3].specular = 0xffff0000;
v[3].tu = 0.0f; v[3].tv = 0.0f;

pBigSquareVB->Unlock();
  4. The vertex buffer has been initialized and is ready to render. The following code example shows how to use the legacy FVF to draw a square.
    g_d3dDevice->SetFVF(VertexFVF);
g_d3dDevice->SetStreamSource(0, pBigSquareVB, 0, sizeof(LVertex));
g_d3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0 ,2);

Here are the steps necessary to initialize and use vertices that have a position, a normal, and texture coordinates:

  1. Define the custom vertex type and FVF code.
    struct Vertex
{
    FLOAT x, y, z;
    FLOAT nx, ny, nz;
    FLOAT tu, tv;
};

const DWORD VertexFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 );
  2. Create a vertex buffer with enough room for four vertices using IDirect3DDevice9::CreateVertexBuffer (similar to the example above).
  3. Set the values for each vertex.
    Vertex * v;
pBigSquareVB->Lock(0, 0, (BYTE**)&v, 0);

v[0].x  = 0.0f;  v[0].y  = 10.0;  v[0].z  = 10.0f;
v[0].nx = 0.0f;  v[0].ny = 1.0f;  v[0].nz = 0.0f;
v[0].tu = 0.0f;  v[0].tv = 0.0f;

v[1].x  = 0.0f;  v[1].y  = 0.0f;  v[1].z  = 10.0f;
v[1].nx = 0.0f;  v[1].ny = 1.0f;  v[1].nz = 0.0f;
v[1].tu = 0.0f;  v[1].tv = 0.0f;

v[2].x  = 10.0f; v[2].y  = 10.0f; v[2].z  = 10.0f;
v[2].nx = 0.0f;  v[2].ny = 1.0f;  v[2].nz = 0.0f;
v[2].tu = 0.0f;  v[2].tv = 0.0f;

v[3].x  = 0.0f; v[3].y  = 10.0f;  v[3].z = 10.0f;
v[3].nx = 0.0f; v[3].ny = 1.0f;   v[3].nz = 0.0f;
v[3].tu = 0.0f; v[3].tv = 0.0f;

pBigSquareVB->Unlock();
  4. Draw the object (similar to the example above).

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetFVF


IDirect3DDevice9::SetGammaRamp

Sets the gamma correction ramp for the implicit swap chain. This method will affect the entire screen (not just the active window if you are running in windowed mode).

void SetGammaRamp(
  UINT  iSwapChain,
  DWORD Flags,
  CONST D3DGAMMARAMP * pRamp
);

Parameters

iSwapChain
[in] Unsigned integer specifying the swap chain.
Flags
[in] Indicates whether correction should be applied. Gamma correction results in a more consistent display, but can incur processing overhead and should not be used frequently. Short-duration effects, such as flashing the whole screen red, should not be calibrated, but long-duration gamma changes should be calibrated. One of the following values can be set:
D3DSGR_CALIBRATE
If a gamma calibrator is installed, the ramp will be modified before being sent to the device to account for the system and monitor response curves. If a calibrator is not installed, the ramp will be passed directly to the device.
D3DSGR_NO_CALIBRATION
No gamma correction is applied. The supplied gamma table is transferred directly to the device.
pRamp
[in] Pointer to a D3DGAMMARAMP structure, representing the gamma correction ramp to be set for the implicit swap chain.

Return Values

No return value.

Remarks

There is always at least one swap chain (the implicit swap chain) for each device, because Direct3D 9 has one swap chain as a property of the device. The gamma ramp takes effect immediately; there is no wait for a vertical sync.

If the device does not support gamma ramps in the swap chain's current presentation mode (full-screen or windowed), no error return is given. Applications can check the D3DCAPS2_FULLSCREENGAMMA and D3DCAPS2_CANCALIBRATEGAMMA capability bits in the Caps2 member of the D3DCAPS9 structure to determine the capabilities of the device and whether a calibrator is installed.

For windowed gamma correction presentation, use IDirect3DSwapChain9::Present if the hardware supports the feature. In DirectX 8, SetGammaRamp will set the gamma ramp only on a full-screen mode application. For more information about gamma correction, see Gamma (Direct3D 9).

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DSwapChain9, IDirect3DDevice9::GetGammaRamp


IDirect3DDevice9::SetIndices

Sets index data.

HRESULT SetIndices(
  IDirect3DIndexBuffer9 * pIndexData
);

Parameters

pIndexData
[in] Pointer to an IDirect3DIndexBuffer9 interface, representing the index data to be set.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

When an application no longer holds a references to this interface, the interface will automatically be freed.

The IDirect3DDevice9::SetIndices method sets the current index array to an index buffer. The single set of indices is used to index all streams.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetIndices , IDirect3DDevice9::DrawIndexedPrimitive, IDirect3DDevice9::DrawIndexedPrimitiveUP, IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawPrimitiveUP , Index Buffers (Direct3D 9)


IDirect3DDevice9::SetLight

Assigns a set of lighting properties for this device.

HRESULT SetLight(
  DWORD Index,
  CONST D3DLight9 * pLight
);

Parameters

Index
[in] Zero-based index of the set of lighting properties to set. If a set of lighting properties exists at this index, it is overwritten by the new properties specified in pLight.
pLight
[in] Pointer to a D3DLIGHT9 structure, containing the lighting parameters to set.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Set light properties by preparing a D3DLIGHT9 structure and then calling the IDirect3DDevice9::SetLight method. The IDirect3DDevice9::SetLight method accepts the index at which the device should place the set of light properties to its internal list of light properties, and the address of a prepared D3DLIGHT9 structure that defines those properties. You can call IDirect3DDevice9::SetLight with new information as needed to update the light's illumination properties.

The system allocates memory to accommodate a set of lighting properties each time you call the IDirect3DDevice9::SetLight method with an index that has never been assigned properties. Applications can set a number of lights, with only a subset of the assigned lights enabled at a time. Check the MaxActiveLights member of the D3DCAPS9 structure when you retrieve device capabilities to determine the maximum number of active lights supported by that device. If you no longer need a light, you can disable it or overwrite it with a new set of light properties.

The following example prepares and sets properties for a white point-light whose emitted light will not attenuate over distance.

// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface.
D3DLight9 d3dLight;
HRESULT   hr;

// Initialize the structure.
ZeroMemory(&D3dLight, sizeof(d3dLight));

// Set up a white point light.
d3dLight.Type = D3DLIGHT_POINT;
d3dLight.Diffuse.r  = 1.0f;
d3dLight.Diffuse.g  = 1.0f;
d3dLight.Diffuse.b  = 1.0f;
d3dLight.Ambient.r  = 1.0f;
d3dLight.Ambient.g  = 1.0f;
d3dLight.Ambient.b  = 1.0f;
d3dLight.Specular.r = 1.0f;
d3dLight.Specular.g = 1.0f;
d3dLight.Specular.b = 1.0f;

// Position it high in the scene and behind the user.
// Remember, these coordinates are in world space, so
// the user could be anywhere in world space, too.
// For the purposes of this example, assume the user
// is at the origin of world space.
d3dLight.Position.x = 0.0f;
d3dLight.Position.y = 1000.0f;
d3dLight.Position.z = -100.0f;

// Don't attenuate.
d3dLight.Attenuation0 = 1.0f;
d3dLight.Range        = 1000.0f;

// Set the property information for the first light.
hr = d3dDevice->SetLight(0, &d3dLight);
if (SUCCEEDED(hr))
    // Handle Success
else
    // Handle failure

Enable a light source by calling the IDirect3DDevice9::LightEnable method for the device.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::GetLightEnable, IDirect3DDevice9::LightEnable


IDirect3DDevice9::SetMaterial

Sets the material properties for the device.

HRESULT SetMaterial(
  CONST D3DMATERIAL9 * pMaterial
);

Parameters

pMaterial
[in] Pointer to a D3DMATERIAL9 structure, describing the material properties to set.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL if the pMaterial parameter is invalid.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetMaterial


IDirect3DDevice9::SetNPatchMode

Enable or disable N-patches.

HRESULT SetNPatchMode(
  float nSegments
);

Parameters

nSegments
[in] Specifies the number of subdivision segments. If the number of segments is less than 1.0, N-patches are disabled. The default value is 0.0.

Return Values

If the method succeeds, the return value is D3D_OK.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetNPatchMode


IDirect3DDevice9::SetPaletteEntries

Sets palette entries.

HRESULT SetPaletteEntries(
  UINT PaletteNumber,
  CONST PALETTEENTRY * pEntries
);

Parameters

PaletteNumber
[in] An ordinal value identifying the particular palette upon which the operation is to be performed.
pEntries
[in] Pointer to a PALETTEENTRY structure, representing the palette entries to set. The number of PALETTEENTRY structures pointed to by pEntries is assumed to be 256. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For Direct3D 9 applications, any palette sent to this method must conform to the D3DPTEXTURECAPS_ALPHAPALETTE capability bit of the D3DCAPS9 structure. If D3DPTEXTURECAPS_ALPHAPALETTE is not set, every entry in the palette must have alpha set to 1.0 or this method will fail with D3DERR_INVALIDCALL. If D3DPTEXTURECAPS_ALPHAPALETTE is set, then any set of alpha values are allowed. Note that the debug runtime will print a warning message if all palette entries have alpha set to 0.

A single logical palette is associated with the device, and is shared by all texture stages.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetCurrentTexturePalette, IDirect3DDevice9::GetPaletteEntries, IDirect3DDevice9::SetCurrentTexturePalette, Texture Palettes (Direct3D 9)


IDirect3DDevice9::SetPixelShader

Sets the current pixel shader to a previously created pixel shader.

HRESULT SetPixelShader(
  IDirect3DPixelShader9* pShader
);

Parameters

pShader
[in] Pixel shader interface.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetPixelShader


IDirect3DDevice9::SetPixelShaderConstantB

Sets a Boolean shader constant.

HRESULT SetPixelShaderConstantB(
  UINT StartRegister,
  CONST BOOL * pConstantData,
  UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
BoolCount
[in] Number of boolean values in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetPixelShaderConstantB


IDirect3DDevice9::SetPixelShaderConstantF

Sets a floating-point shader constant.

HRESULT SetPixelShaderConstantF(
  UINT StartRegister,
  CONST float * pConstantData,
  UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetPixelShaderConstantF


IDirect3DDevice9::SetPixelShaderConstantI

Sets an integer shader constant.

HRESULT SetPixelShaderConstantI(
  UINT StartRegister,
  CONST int * pConstantData,
  UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetPixelShaderConstantI


IDirect3DDevice9::SetRenderState

Sets a single device render-state parameter.

HRESULT SetRenderState(
  D3DRENDERSTATETYPE State,
  DWORD Value
);

Parameters

State
[in] Device state variable that is being modified. This parameter can be any member of the D3DRENDERSTATETYPE enumerated type.
Value
[in] New value for the device render state to be set. The meaning of this parameter is dependent on the value specified for State. For example, if State were D3DRS_SHADEMODE, the second parameter would be one member of the D3DSHADEMODE enumerated type.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetRenderState, IDirect3DDevice9::SetTransform


IDirect3DDevice9::SetRenderTarget

Sets a new color buffer for the device.

HRESULT SetRenderTarget(
  DWORD RenderTargetIndex,
  IDirect3DSurface9 * pRenderTarget
);

Parameters

RenderTargetIndex
[in] Index of the render target. See Remarks.
pRenderTarget
[in] Pointer to a new color buffer. If NULL, the color buffer for the corresponding RenderTargetIndex is disabled. Devices always must be associated with a color buffer. The new render-target surface must have at least D3DUSAGE_RENDERTARGET specified.

Return Values

If the method succeeds, the return value is D3D_OK. This method will return D3DERR_INVALIDCALL if either:

  • pRenderTarget = NULL and RenderTargetIndex = 0
  • pRenderTarget is != NULL and the render target is invalid.

Remarks

The device can support multiple render targets. The number of render targets supported by a device is contained in the NumSimultaneousRTs member of D3DCAPS9. See Multiple Render Targets (Direct3D 9).

Setting a new render target will cause the viewport (see Viewports and Clipping (Direct3D 9)) to be set to the full size of the new render target.

Some hardware tests the compatibility of the depth stencil buffer with the color buffer. If this is done, it is only done in a debug build.

Restrictions for using this method include the following:

  • The multisample type must be the same for the render target and the depth stencil surface.
  • The formats must be compatible for the render target and the depth stencil surface. See IDirect3D9::CheckDepthStencilMatch.
  • The size of the depth stencil surface must be greater than or equal to the size of the render target.

These restrictions are validated only when using the debug runtime when any of the IDirect3DDevice9 Draw methods are called.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::SetSamplerState

Sets the sampler state value.

HRESULT SetSamplerState(
  DWORD Sampler,
  D3DSAMPLERSTATETYPE Type,
  DWORD Value
);

Parameters

Sampler
[in] The sampler stage index.
Type
[in] This parameter can be any member of the D3DSAMPLERSTATETYPE enumerated type.
Value
[in] State value to set. The meaning of this value is determined by the Type parameter.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetSamplerState


IDirect3DDevice9::SetScissorRect

Sets the scissor rectangle.

HRESULT SetScissorRect(
  CONST RECT * pRect
);

Parameters

pRect
[in] Pointer to a RECT structure that defines the rendering area within the render target if scissor test is enabled. This parameter may not be NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The scissor rectangle is used as a rectangular clipping region.

See Rectangles (Direct3D 9) for further information on the use of rectangles in DirectX.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::SetSoftwareVertexProcessing

Use this method to switch between software and hardware vertex processing.

HRESULT SetSoftwareVertexProcessing(
  BOOL bSoftware
);

Parameters

bSoftware
[in] TRUE to specify software vertex processing; FALSE to specify hardware vertex processing.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The restrictions for changing modes are as follows:

  • If a device is created with D3DCREATE_SOFTWARE_VERTEXPROCESSING, the vertex processing will be done in software and cannot be changed.
  • If a device is created with D3DCREATE_HARDWARE_VERTEXPROCESSING, the vertex processing will be done in hardware and cannot be changed.
  • If a device is created with D3DCREATE_MIXED_VERTEXPROCESSING, the vertex processing will be done in hardware by default. The processing can be switched to software (or back to hardware) using IDirect3DDevice9::SetSoftwareVertexProcessing.

An application can create a mixed-mode device to use both the software vertex processing and the hardware vertex processing. To switch between the two vertex processing modes in DirectX 8.x, use IDirect3DDevice8::SetRenderState with the render state D3DRS_SOFTWAREVERTEXPROCESSING and the appropriate DWORD argument. The drawback of the render state approach was the difficulty in defining the semantics for state blocks. Applications and the runtime had to do extra work and be careful while recording and playing back state blocks.

In Direct3D 9, use SetSoftwareVertexProcessing instead. This new API is not recorded by StateBlocks.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetSoftwareVertexProcessing


IDirect3DDevice9::SetStreamSource

Binds a vertex buffer to a device data stream. For more information, see Setting the Stream Source (Direct3D 9).

HRESULT SetStreamSource(
  UINT StreamNumber,
  IDirect3DVertexBuffer9 * pStreamData,
  UINT OffsetInBytes,
  UINT Stride
);

Parameters

StreamNumber
[in] Specifies the data stream, in the range from 0 to the maximum number of streams -1.
pStreamData
[in] Pointer to an IDirect3DVertexBuffer9 interface, representing the vertex buffer to bind to the specified data stream.
OffsetInBytes
[in] Offset from the beginning of the stream to the beginning of the vertex data, in bytes. To find out if the device supports stream offsets, see the D3DDEVCAPS2_STREAMOFFSET constant in D3DDEVCAPS2.
Stride
[in] Stride of the component, in bytes. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When a FVF vertex shader is used, the stride of the vertex stream must match the vertex size, computed from the FVF. When a declaration is used, the stride should be greater than or equal to the stream size computed from the declaration.

When calling SetStreamSource, the stride is normally required to be equal to the vertex size. However, there are times when you may want to draw multiple instances of the same or similar geometry (such as when using instancing to draw). For this case, use a zero stride to tell the runtime not to increment the vertex buffer offset (ie: use the same vertex data for all instances). For more information about instancing, see Efficiently Drawing Multiple Instances of Geometry (Direct3D 9).

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetStreamSource, IDirect3DDevice9::DrawIndexedPrimitive, IDirect3DDevice9::DrawIndexedPrimitiveUP, IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawPrimitiveUP, Vertex Buffers (Direct3D 9)


IDirect3DDevice9::SetStreamSourceFreq

Sets the stream source frequency divider value. This may be used to draw several instances of geometry.

HRESULT SetStreamSourceFreq(
  UINT StreamNumber,
  UINT FrequencyParameter
);

Parameters

StreamNumber
[in] Stream source number.
FrequencyParameter
[in] This parameter may have two different values. See remarks.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

There are two constants defined in d3d9types.h that are designed to use with SetStreamSourceFreq: D3DSTREAMSOURCE_INDEXEDDATA and D3DSTREAMSOURCE_INSTANCEDATA. To see how to use the constants, see Efficiently Drawing Multiple Instances of Geometry (Direct3D 9).

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetStreamSourceFreq


IDirect3DDevice9::SetTexture

Assigns a texture to a stage for a device.

HRESULT SetTexture(
  DWORD Sampler,
  IDirect3DBaseTexture9 * pTexture
);

Parameters

Sampler

Zero based sampler number. Textures are bound to samplers; samplers define sampling state such as the filtering mode and the address wrapping mode. Textures are referenced differently by the programmable and the fixed function pipeline:

  • Programmable shaders reference textures using the sampler number. The number of samplers available to a programmable shader is dependent on the shader version. For vertex shaders, see Sampler. For pixel shaders see Sampler.
  • The fixed function pipeline on the other hand, references textures by texture stage number. The maximum number of samplers is determined from two caps: MaxSimultaneousTextures and MaxTextureBlendStages of the D3DCAPS9 structure.
[in] There are two other special cases for stage/sampler numbers.
  • A special number called D3DDMAPSAMPLER is used for Displacement Mapping (Direct3D 9).
  • A programmable vertex shader uses a special number defined by a D3DVERTEXTEXTURESAMPLER when accessing Vertex Textures in vs_3_0 (Direct3D 9).

pTexture
[in] Pointer to an IDirect3DBaseTexture9 interface, representing the texture being set.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

IDirect3DDevice9::SetTexture is not allowed if the texture is created with a pool type of D3DPOOL_SCRATCH. IDirect3DDevice9::SetTexture is not allowed with a pool type of D3DPOOL_SYSTEMMEM texture unless DevCaps is set with D3DDEVCAPS_TEXTURESYSTEMMEMORY.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetTexture, IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState


IDirect3DDevice9::SetTextureStageState

Sets the state value for the currently assigned texture.

HRESULT SetTextureStageState(
  DWORD Stage,
  D3DTEXTURESTAGESTATETYPE Type,
  DWORD Value
);

Parameters

Stage
[in] Stage identifier of the texture for which the state value is set. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
Type
[in] Texture state to set. This parameter can be any member of the D3DTEXTURESTAGESTATETYPE enumerated type.
Value
[in] State value to set. The meaning of this value is determined by the Type parameter.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::GetTexture, IDirect3DDevice9::SetTexture


IDirect3DDevice9::SetTransform

Sets a single device transformation-related state.

HRESULT SetTransform(
  D3DTRANSFORMSTATETYPE State,
  CONST D3DMATRIX * pMatrix
);

Parameters

State
[in] Device-state variable that is being modified. This parameter can be any member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro.
pMatrix
[in] Pointer to a D3DMATRIX structure that modifies the current transformation.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetTransform, IDirect3DDevice9::SetRenderState, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX


IDirect3DDevice9::SetVertexDeclaration

Sets a Vertex Declaration (Direct3D 9).

HRESULT SetVertexDeclaration(
  IDirect3DVertexDeclaration9 * pDecl
);

Parameters

pDecl
[in] Pointer to an IDirect3DVertexDeclaration9 object, which contains the vertex declaration.

Return Values

If the method succeeds, the return value is D3D_OK. The return value can be D3DERR_INVALIDCALL.

Remarks

A vertex declaration is an IDirect3DVertexDeclaration9 object that defines the data members of a vertex (i.e. texture coordinates, colors, normals, etc.). This data can be useful for implementing vertex shaders and pixel shaders.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetVertexDeclaration


IDirect3DDevice9::SetVertexShader

Sets the vertex shader.

HRESULT SetVertexShader(
  IDirect3DVertexShader9* pShader
);

Parameters

pShader
[in] Vertex shader interface. For more information, see IDirect3DVertexShader9.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

To set a fixed-function vertex shader (after having set a programmable vertex shader), call IDirect3DDevice9::SetVertexShader(NULL) to release the programmable shader, and then call IDirect3DDevice9::SetFVF with the fixed-function vertex format.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetVertexShader


IDirect3DDevice9::SetVertexShaderConstantB

Sets a Boolean vertex shader constant.

HRESULT SetVertexShaderConstantB(
  UINT StartRegister,
  CONST BOOL * pConstantData,
  UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
BoolCount
[in] Number of boolean values in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::SetVertexShaderConstantF

Sets a floating-point vertex shader constant.

HRESULT SetVertexShaderConstantF(
  UINT StartRegister,
  CONST float * pConstantData,
  UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::SetVertexShaderConstantI

Sets an integer vertex shader constant.

HRESULT SetVertexShaderConstantI(
  UINT StartRegister,
  CONST int * pConstantData,
  UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::SetViewport

Sets the viewport parameters for the device.

HRESULT SetViewport(
  CONST D3DVIEWPORT9 * pViewport
);

Parameters

pViewport
[in] Pointer to a D3DVIEWPORT9 structure, specifying the viewport parameters to set.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, it will return D3DERR_INVALIDCALL. This will happen if pViewport is invalid, or if pViewport describes a region that cannot exist within the render target surface.

Remarks

Direct3D sets the following default values for the viewport.

D3DVIEWPORT9 vp;
vp.X      = 0;
vp.Y      = 0;
vp.Width  = RenderTarget.Width;
vp.Height = RenderTarget.Height;
vp.MinZ   = 0.0f;
vp.MaxZ   = 1.0f;

IDirect3DDevice9::SetViewport can be used to draw on part of the screen. Make sure to call it before any geometry is drawn so the viewport settings will take effect.

To draw multiple views within a scene, repeat the IDirect3DDevice9::SetViewport and draw geometry sequence for each view.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetViewport


IDirect3DDevice9::ShowCursor

Displays or hides the cursor.

BOOL ShowCursor(
  BOOL bShow
);

Parameters

bShow
[in] If bShow is TRUE, the cursor is shown. If bShow is FALSE, the cursor is hidden.

Return Values

Value indicating whether the cursor was previously visible. TRUE if the cursor was previously visible, or FALSE if the cursor was not previously visible.

Remarks

Direct3D cursor functions use either GDI cursor or software emulation, depending on the hardware. Users usually want to respond to a WM_SETCURSOR message. For example, the users might want to write the message handler like this:

case WM_SETCURSOR:

// Turn off window cursor

SetCursor( NULL );

m_pd3dDevice->ShowCursor( TRUE );

return TRUE; // prevent Windows from setting cursor to window class cursor

break;

Or users might want to call the IDirect3DDevice9::SetCursorProperties method if they want to change the cursor. See the code in the DirectX Graphics C/C++ Samples for more detail.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::SetCursorPosition, IDirect3DDevice9::SetCursorProperties


IDirect3DDevice9::StretchRect

Copy the contents of the source rectangle to the destination rectangle. The source rectangle can be stretched and filtered by the copy. This function is often used to change the aspect ratio of a video stream.

HRESULT StretchRect(
  IDirect3DSurface9 * pSourceSurface,
  CONST RECT * pSourceRect,
  IDirect3DSurface9 * pDestSurface,
  CONST RECT * pDestRect,
  D3DTEXTUREFILTERTYPE Filter
);

Parameters

pSourceSurface
[in] Pointer to the source surface. See IDirect3DSurface9.
pSourceRect
[in] Pointer to the source rectangle. A NULL for this parameter causes the entire source surface to be used.
pDestSurface
[in] Pointer to the destination surface. See IDirect3DSurface9.
pDestRect
[in] Pointer to the destination rectangle. A NULL for this parameter causes the entire destination surface to be used.
Filter
[in] Filter type. Allowable values are D3DTEXF_NONE, D3DTEXF_POINT, or D3DTEXF_LINEAR. For more information, see D3DTEXTUREFILTERTYPE.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

StretchRect Restrictions

  • Driver support varies. See the section on driver support (below) to see which drivers support which source and destination formats.
  • The source and destination surfaces must be created in the default memory pool.
  • If filtering is specified, you must set the appropriate filter caps (see StretchRectFilterCaps in D3DCAPS9).
  • Stretching is not supported between source and destination rectangles on the same surface.
  • Stretching is not supported if the destination surface is an off-screen plain surface but the source is not.
  • You many not stretch between source and destination rectangles if either surface is in a compressed format (see Using Compressed Textures (Direct3D 9)).
  • Stretching supports color-space conversion from YUV to high-precision RGBA only. Since color conversion support is not supported by software emulation, use IDirect3D9::CheckDeviceFormatConversion to test the hardware for color conversion support.
  • If the source or destination surface is a texture surface (or a cube texture surface), you must use a Direct3D 9 driver that supports D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES (see D3DDEVCAPS2).

Additional Restrictions for Depth and Stencil Surfaces

  • The source and destination surfaces must be plain depth stencil surfaces (not textures) (see IDirect3DDevice9::CreateDepthStencilSurface).
  • Neither of the surfaces can be discardable.
  • The entire surface must be copied (that is: sub-rectangle copies are not allowed).
  • Format conversion, stretching, and shrinking are not supported.
  • StretchRect cannot be called inside of a BeginScene/EndScene pair.

Using StretchRect to downsample a Multisample Rendertarget

You can use StretchRect to copy from one rendertarget to another. If the source rendertarget is multisampled, this results in downsampling the source rendertarget. For instance you could:

  • Create a multisampled rendertarget.
  • Create a second rendertarget of the same size, that is not multisampled.
  • Copy (using StretchRect the multisample rendertarget to the second rendertarget.

Driver Support

There are many restrictions as to which surface combinations are valid for StretchRect. Factors include whether the driver is a Direct3D 9 driver or older, and whether the operation will result in stretching/shrinking. Since applications are not expected to recognize if the driver is a Direct3D 9 driver or not, the runtime will automatically set a new cap, D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES cap (see D3DDEVCAPS2), for Direct3D 9-level drivers and above.

DirectX 8 Driver (no stretching) |  |  |  |  |
 |  | Dest formats |  |  |
 |  | Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | No | No | No
 | RT texture | No | Yes | Yes | No
 | RT | No | Yes | Yes | No
 | Off-screen plain | Yes | Yes | Yes | Yes
DirectX 8 Driver (stretching) |  |  |  |  |
 |  | Dest formats |  |  |
 |  | Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | No | No | No
 | RT texture | No | No | No | No
 | RT | No | Yes | Yes | No
 | Off-screen plain | No | Yes | Yes | No
Direct3D 9 Driver (no stretching) |  |  |  |  |
 |  | Dest formats |  |  |
 |  | Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | Yes | Yes | No
 | RT texture | No | Yes | Yes | No
 | RT | No | Yes | Yes | No
 | Off-screen plain | No | Yes | Yes | Yes
Direct3D 9 Driver (stretching) |  |  |  |  |
 |  | Dest formats |  |  |
 |  | Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | Yes | Yes | No
 | RT texture | No | Yes | Yes | No
 | RT | No | Yes | Yes | No
 | Off-screen plain | No | Yes | Yes | No

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::BeginScene, IDirect3DDevice9::EndScene


IDirect3DDevice9::TestCooperativeLevel

Reports the current cooperative-level status of the Direct3D device for a windowed or full-screen application.

HRESULT TestCooperativeLevel();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK, indicating that the device is operational and the calling application can continue. If the method fails, the return value can be one of the following values: D3DERR_DEVICELOST, D3DERR_DEVICENOTRESET, D3DERR_DRIVERINTERNALERROR.

Remarks

If the device is lost but cannot be restored at the current time, IDirect3DDevice9::TestCooperativeLevel returns the D3DERR_DEVICELOST return code. This would be the case, for example, when a full-screen device has lost focus. If an application detects a lost device, it should pause and periodically call IDirect3DDevice9::TestCooperativeLevel until it receives a return value of D3DERR_DEVICENOTRESET. The application may then attempt to reset the device by calling IDirect3DDevice9::Reset and, if this succeeds, restore the necessary resources and resume normal operation. Note that IDirect3DDevice9::Present will return D3DERR_DEVICELOST if the device is either "lost" or "not reset".

A call to IDirect3DDevice9::TestCooperativeLevel will fail if called on a different thread than that used to create the device being reset.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::UpdateSurface

Copies rectangular subsets of pixels from one surface to another.

HRESULT UpdateSurface(
  IDirect3DSurface9* pSourceSurface,
  CONST RECT* pSourceRect,
  IDirect3DSurface9* pDestinationSurface,
  CONST POINT* pDestinationPoint
);

Parameters

pSourceSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the source surface. This parameter must point to a different surface than pDestinationSurface.
pSourceRect
[in] Pointer to a rectangle on the source surface. Specifying NULL for this parameter causes the entire surface to be copied.
pDestinationSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the destination surface.
pDestinationPoint
[in] Pointer to the upper left corner of the destination rectangle. Specifying NULL for this parameter causes the entire surface to be copied.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL.

Remarks

This method is similar to CopyRects in DirectX 8.

This function has the following restrictions.

  • The source surface must have been created with D3DPOOL_SYSTEMMEM.
  • The destination surface must have been created with D3DPOOL_DEFAULT.
  • Neither surface can be locked or holding an outstanding device context.
  • Neither surface can be created with multisampling. The only valid flag for both surfaces is D3DMULTISAMPLE_NONE.
  • The surface format cannot be a depth stencil format.
  • The source and dest rects must fit within the surface.
  • No stretching or shrinking is allowed (the rects must be the same size).
  • The source format must match the dest format.

The following table shows the supported combinations.

 |  | Dest formats |  |  |
 |  | Texture | RT texture | RT | Off-screen plain
Src formats | Texture | Yes | Yes | Yes* | Yes
 | RT texture | No | No | No | No
 | RT | No | No | No | No
 | Off-screen plain | Yes | Yes | Yes | Yes

* If the driver does not support the requested copy, it will be emulated using lock and copy.

If the application needs to copy data from a D3DPOOL_DEFAULT render target to a D3DPOOL_SYSTEMMEM surface, it can use IDirect3DDevice9::GetRenderTargetData.

Requirements

Header: Declared in D3D9.h.


IDirect3DDevice9::UpdateTexture

Updates the dirty portions of a texture.

HRESULT UpdateTexture(
  IDirect3DBaseTexture9 * pSourceTexture,
  IDirect3DBaseTexture9 * pDestinationTexture
);

Parameters

pSourceTexture
[in] Pointer to an IDirect3DBaseTexture9 interface, representing the source texture. The source texture must be in system memory (D3DPOOL_SYSTEMMEM).
pDestinationTexture
[in] Pointer to an IDirect3DBaseTexture9 interface, representing the destination texture. The destination texture must be in the D3DPOOL_DEFAULT memory pool.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

You can dirty a portion of a texture by locking it, or by calling one of the following methods.

  • IDirect3DCubeTexture9::AddDirtyRect
  • IDirect3DTexture9::AddDirtyRect
  • IDirect3DVolumeTexture9::AddDirtyBox
  • IDirect3DDevice9::UpdateSurface

IDirect3DDevice9::UpdateTexture retrieves the dirty portions of the texture by calculating what has been accumulated since the last update operation.

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when LockRect or IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of IDirect3DDevice9::UpdateSurface is marked dirty.

This method fails if the textures are of different types, if their bottom-level buffers are of different sizes, or if their matching levels do not match. For example, consider a six-level source texture with the following dimensions.

32x16, 16x8, 8x4, 4x2, 2x1, 1x1

This six-level source texture could be the source for the following one-level destination.

1x1

For the following two-level destination.

2x1, 1x1

Or, for the following three-level destination.

4x2, 2x1, 1x1

In addition, this method will fail if the textures are of different formats. If the destination texture has fewer levels than the source, only the matching levels are copied. If the source texture has fewer levels than the destination, the method will fail.

If the source texture has dirty regions, the copy can be optimized by restricting the copy to only those regions. It is not guaranteed that only those bytes marked dirty will be copied.

Here are the possibilities for source and destination surface combinations:

  • If pSourceTexture is a non-autogenerated mipmap and pDestinationTexture is an autogenerated mipmap, only the topmost matching level is updated, and the destination sublevels are regenerated. All other source sublevels are ignored.
  • If both pSourceTexture and pDestinationTexture are autogenerated mipmaps, only the topmost matching level is updated. The sublevels from the source are ignored and the destination sublevels are regenerated.
  • If pSourceTexture is an autogenerated mipmap and pDestinationTexture a non-autogenerated mipmap, UpdateTexture will fail.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3D9::CreateDevice


IDirect3DDevice9::ValidateDevice

Reports the device's ability to render the current texture-blending operations and arguments in a single pass.

HRESULT ValidateDevice(
  DWORD * pNumPasses
);

Parameters

pNumPasses
[out, retval] Pointer to a DWORD value to fill with the number of rendering passes needed to complete the desired effect through multipass rendering.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_CONFLICTINGRENDERSTATE, D3DERR_CONFLICTINGTEXTUREFILTER, D3DERR_DEVICELOST, D3DERR_DRIVERINTERNALERROR, D3DERR_TOOMANYOPERATIONS, D3DERR_UNSUPPORTEDALPHAARG, D3DERR_UNSUPPORTEDALPHAOPERATION, D3DERR_UNSUPPORTEDCOLORARG, D3DERR_UNSUPPORTEDCOLOROPERATION, D3DERR_UNSUPPORTEDFACTORVALUE, D3DERR_UNSUPPORTEDTEXTUREFILTER, D3DERR_WRONGTEXTUREFORMAT,.

Remarks

The IDirect3DDevice9::ValidateDevice method should be used to validate scenarios only when other capabilities are deficient. For example, in a multistage texturing scenario, you could query the MaxTextureBlendStages and MaxSimultaneousTextures members of a D3DCAPS9 structure to determine if multistage texturing is possible on the device.

Current hardware does not necessarily implement all possible combinations of operations and arguments. You can determine whether a particular blending operation can be performed with given arguments by setting the desired blending operation, and then calling the IDirect3DDevice9::ValidateDevice method.

The IDirect3DDevice9::ValidateDevice method uses the current render states, textures, and texture-stage states to perform validation at the time of the call. Changes to these factors after the call invalidate the previous result, and the method must be called again before rendering a scene.

For best performance, call IDirect3DDevice9::ValidateDevice at initialization time; do not use it within a render loop.

Using diffuse iterated values, either as an argument or as an operation (D3DTA_DIFFUSED3DTOP_BLENDDIFFUSEALPHA) is rarely supported on current hardware. Most hardware can introduce iterated color data only at the last texture operation stage.

Try to specify the texture (D3DTA_TEXTURE) for each stage as the first argument, rather than the second argument.

Many cards do not support use of diffuse or scalar values at arbitrary texture stages. Often, these are available only at the first or last texture-blending stage.

Many cards do not have a blending unit associated with the first texture that is capable of more than replicating alpha to color channels or inverting the input. Therefore, your application might need to use only the second texture stage, if possible. On such hardware, the first unit is presumed to be in its default state, which has the first color argument set to D3DTA_TEXTURE with the D3DTOP_SELECTARG1 operation.

Operations on the output alpha that are more intricate than or substantially different from the color operations are less likely to be supported.

Some hardware does not support simultaneous use of D3DTA_TFACTOR and D3DTA_DIFFUSE.

Many cards do not support simultaneous use of multiple textures and mipmapped trilinear filtering. If trilinear filtering has been requested for a texture involved in multitexture blending operations and validation fails, turn off trilinear filtering and revalidate. In this case, you might want to perform multipass rendering instead.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState


IDirect3DDevice9Ex

Applications use the methods of the IDirect3DDevice9Ex interface to render primitives, create resources, work with system-level variables, adjust gamma ramp levels, work with palettes, and create shaders. The IDirect3DDevice9Ex interface derives from the IDirect3DDevice9 interface.

IUnknown
IDirect3DDevice9
IDirect3DDevice9Ex
IDirect3DDevice9Ex::CheckDeviceState | Reports the current cooperative-level status of the Direct3D device for a windowed or full-screen application.
IDirect3DDevice9Ex::CheckResourceResidency | Checks an array of resources to determine if it is likely that they will cause a large stall at Draw time because the system must make the resources GPU-accessible.
IDirect3DDevice9Ex::CreateDepthStencilSurfaceEx | Creates a depth-stencil surface.
IDirect3DDevice9Ex::CreateOffscreenPlainSurfaceEx | Create an off-screen surface.
IDirect3DDevice9Ex::CreateRenderTargetEx | Creates a render-target surface.
IDirect3DDevice9Ex::ComposeRect | Sets the filter that the Device object uses to perform monochrome convolution filtering.
IDirect3DDevice9Ex::GetDisplayModeEx | Retrieves the display mode's spatial resolution, color resolution, refresh frequency, and rotation settings.
IDirect3DDevice9Ex::GetGPUThreadPriority | Gets the current priority stored with the Direct3D device.
IDirect3DDevice9Ex::GetMaximumFrameLatency | Retrieves the number of frames of data that the drivers are allowed to queue.
IDirect3DDevice9Ex::PresentEx | Presents the contents of the next buffer in the sequence of back buffers owned by the device.
IDirect3DDevice9Ex::ResetEx | Resets the type, size, and format of the swap chain.
IDirect3DDevice9Ex::SetConvolutionMonoKernel | Sets the filter that the Device object uses to perform monochrome convolution filtering.
IDirect3DDevice9Ex::SetGPUThreadPriority | Connects to a new kernel-mode entry point with the specified thread priority.
IDirect3DDevice9Ex::SetMaximumFrameLatency | Sets the number of frames of data that the drivers are allowed to queue.
IDirect3DDevice9Ex::TestCooperativeLevel | Reports the current cooperative-level status of the Direct3D device for a windowed or full-screen application. Deprecated
IDirect3DDevice9Ex::WaitForVBlank | Enables applications to efficiently throttle their frame rate to that of the monitor associated with the device.

The IDirect3DDevice9Ex interface is obtained by calling IDirect3D9Ex::CreateDeviceEx.

The LPDIRECT3DDEVICE9EX and PDIRECT3DDEVICE9EX types are defined as pointers to the IDirect3DDevice9Ex interface:

typedef struct IDirect3DDevice9Ex *LPDIRECT3DDEVICE9EX, *PDIRECT3DDEVICE9EX;

Creating a Device

Follow these two steps to initialize a Direct3D device:

  1. Call Direct3DCreate9Ex to create the Direct3D object.
  2. Call CreateDeviceEx to create the Direct3D device.

Here is an example:

IDirect3D9Ex *pDirect3DEx;
LPDIRECT3DDEVICE9EX pDeviceEx;
DWORD behaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING;

Direct3DCreate9Ex(D3D_SDK_VERSION, &pDirect3DEx);
pDirect3DEx->CreateDeviceEx(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, behaviorFlags, &d3dpp, NULL, &pDeviceEx);


IDirect3DDevice9Ex::CheckDeviceState

Reports the current cooperative-level status of the Direct3D device for a windowed or full-screen application.

HRESULT CheckDeviceState(
  HWND hWindow
);

Parameters

hWindow
[in] The destination window handle to check for occlusion. When this parameter is NULL, S_PRESENT_OCCLUDED is returned when another device has fullscreen ownership. When the window handle is not NULL, window's client area is checked for occlusion. A window is occluded if any part of it is obscured by another application.

Return Values

S_OK the device is ok for rendering.

S_PRESENT_MODE_CHANGED the display mode has changed.

S_PRESENT_OCCLUDED the window is occluded.

D3DERR_DEVICELOST the device has been lost.

D3DERR_DEVICEHUNG if the device is hung.

D3DERR_DEVICEREMOVED if the device has been removed.

Remarks

This method replaces IDirect3DDevice9::TestCooperativeLevel, which always returns S_OK in Direct3D 9Ex applications.

See Lost Device Behavior Changes for more information about lost, hung, and removed devices.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::CheckResourceResidency

Checks an array of resources to determine if it is likely that they will cause a large stall at Draw time because the system must make the resources GPU-accessible.

HRESULT CheckResourceResidency(
  IDirect3DResource9 * pResourceArray,
  UINT32 NumResources
);

Parameters

pResourceArray
[in] An array of IDirect3DResource9 pointers that indicate the resources to check (for a description of IDirect3DResource9, see the DirectX SDK documentation).
NumResources
[in] A value indicating the number of resources passed into the pResourceArray parameter up to a maximum of 65535.

Return Values

If all the resources are in GPU-accessible memory, the method will return S_OK. The system may need to perform a remapping operation to promote the resources, but will not have to copy data.

If no allocation that comprises the resources is on disk, but at least one allocation is not in GPU-accessible memory, the method will return S_RESIDENT_IN_SHARED_MEMORY. The system may need to perform a copy to promote the resource.

If at least one allocation that comprises the resources is on disk, this method will return S_NOT_RESIDENT. The system may need to perform a copy to promote the resource.

Remarks

This API is no more than a reasonable guess at residency, since resources may have been demoted by the time the application uses them.

The expected usage pattern is as follows. If the application determines that a set of resources are not resident, then the application will substitute a lower-LOD version of the resource and continue with rendering. The video memory manager API, offers a feature to allow the application to express that it would like these lower-LOD resources to be made more likely to stay resident in GPU-accessible memory. It is the app's responsibility to create, fill and destroy these lower-LOD versions, if it so chooses.

The application also needs to begin promotion of the higher-LOD versions when the residency check indicates that the resource is not resident in GPU-accessible memory. Since a per-process lock exists in kernel mode, a performant implementation will spawn a separate process whose sole job is to promote resources. The application communicates resource identity between the two process by means of the Sharing Resources shared surfaces API and promotes them by means of the IDirect3DResource9::SetPriority.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::ComposeRect

Copy a text string to one surface using an alphabet of glyphs on another surface. Composition is done by the GPU using bitwise operations.

HRESULT ComposeRect(
  IDirect3DSurface9 *pSource,
  IDirect3DSurface9 *pDestination,
  IDirect3DVertexBuffer9 *pSrcRectDescriptors,
  UINT NumRects,
  IDirect3DVertexBuffer9 *pDstRectDescriptors,
  D3DCOMPOSEOP Operation,
  INT XOffset,
  INT YOffset
);

Parameters

pSource
[in] A pointer to a IDirect3DSurface9 that contains the source alphabet glyphs. This surface must be created with the D3DUSAGE_TEXTAPI flag.
pDestination
[in] A pointer to the destination IDirect3DSurface9 surface that contains the source glyph data. The surface must be part of a texture.
pSrcRectDescriptors
[in] A pointer to a vertex buffer (see IDirect3DVertexBuffer9) containing rectangles (see D3DCOMPOSERECTDESC (DirectX 9Ex only)) that enclose the desired glyphs in the source surface.
NumRects
[in] The number of rectangles or glyphs used in the operation. The number applies to both the source and destination surfaces. The range is 0 to D3DCOMPOSERECTS_MAXNUMRECTS.
pDstRectDescriptors
[in] A pointer to a vertex buffer (see IDirect3DVertexBuffer9) containing rectangles (see D3DCOMPOSERECTDESTINATION (DirectX 9Ex only)) that describe where the indicated glyph from the source surface will be copied to.
Operation
[in] Specifies how the combine the source and destination surfaces. See D3DCOMPOSERECTSOP (DirectX 9Ex only).
XOffset
[in] A value added to the X coordinates of all destination rectangles. This value can be negative which may cause the glyph to be rejected or clipped if the result is beyond the bounds of the surface.
YOffset
[in] A value added to the Y coordinates of all destination rectangles. This value can be negative which may cause the glyph to be rejected or clipped if the result is beyond the bounds of the surface.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

Glyphs from a one-bit source surface are put together into another one-bit texture surface with this method. The destination surface can then be used as the source for a normal texturing operation that will filter and scale the strings of text onto some other non-monochrome surface.

This method has several constraints (which are similar to IDirect3DDevice9::StretchRect):

  • Surfaces cannot be locked.
  • The source and destination surfaces cannot be the same surface.
  • The source and destination surfaces must be created with the D3DFMT_A1 format.
  • The source surface and both vertex buffers must be created with the D3DPOOL_DEFAULT flag.
  • The destination surface must be created with either the D3DPOOL_DEFAULT or D3DPOOL_SYSTEMMEM flags.
  • The source rectangles must be within the source surface.

The method is not recorded in state blocks.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::CreateDepthStencilSurfaceEx

Creates a depth-stencil surface.

HRESULT CreateDepthStencilSurfaceEx(
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  D3DMULTISAMPLE_TYPE MultiSample,
  DWORD MultisampleQuality,
  BOOL Discard,
  IDirect3DSurface9 **ppSurface,
  HANDLE *pSharedHandle,
  DWORD Usage
);

Parameters

Width
[in] Width of the depth-stencil surface, in pixels.
Height
[in] Height of the depth-stencil surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the depth-stencil surface. This value must be one of the enumerated depth-stencil formats for this device.
MultiSample
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, describing the multisampling buffer type. This value must be one of the allowed multisample types. When this surface is passed to IDirect3DDevice9::SetDepthStencilSurface, its multisample type must be the same as that of the render target set by IDirect3DDevice9::SetRenderTarget.
MultisampleQuality
[in] Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces, and the MultiSample type must all match.
Discard
[in] Set this flag to TRUE to enable z-buffer discarding, and FALSE otherwise. If this flag is set, the contents of the depth stencil buffer will be invalid after calling either IDirect3DDevice9::Present or IDirect3DDevice9::SetDepthStencilSurface with a different depth surface.

This flag has the same behavior as the constant, D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL, in D3DPRESENTFLAG.

ppSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the created depth-stencil surface resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.
Usage
[in] Combination of one or more D3DUSAGE constants which can be OR'd together. Value of 0 indicates no usage.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

The memory class of the depth-stencil buffer is always D3DPOOL_DEFAULT.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::CreateOffscreenPlainSurfaceEx

Create an off-screen surface.

HRESULT CreateOffscreenPlainSurfaceEx(
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  DWORD Pool,
  IDirect3DSurface9 **ppSurface,
  HANDLE *pSharedHandle,
  DWORD Usage
);

Parameters

Width
[in] Width of the surface.
Height
[in] Height of the surface.
Format
[in] Format of the surface. See D3DFORMAT.
Pool
[in] Surface pool type. See D3DPOOL.
ppSurface
[out, retval] Pointer to the IDirect3DSurface9 interface created.
pSharedHandle
[in] Reserved. Set this parameter to NULL.
Usage
[in] Combination of one or more D3DUSAGE constants which can be OR'd together. Value of 0 indicates no usage.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be the following: D3DERR_INVALIDCALL.

Remarks

D3DPOOL_SCRATCH will return a surface that has identical characteristics to a surface created by the DirectX 8.x method CreateImageSurface.

D3DPOOL_DEFAULT is the appropriate pool for use with the IDirect3DDevice9::StretchRect and IDirect3DDevice9::ColorFill.

D3DPOOL_MANAGED is not allowed when creating an offscreen plain surface. For more information about memory pools, see D3DPOOL.

Off-screen plain surfaces are always lockable, regardless of their pool types.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::CreateRenderTargetEx

Creates a render-target surface.

HRESULT CreateRenderTargetEx(
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  D3DMULTISAMPLE_TYPE MultiSample,
  DWORD MultisampleQuality,
  BOOL Lockable,
  IDirect3DSurface9 **ppSurface,
  HANDLE *pSharedHandle,
  DWORD Usage
);

Parameters

Width
[in] Width of the render-target surface, in pixels.
Height
[in] Height of the render-target surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the render target.
MultiSample
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, which describes the multisampling buffer type. This parameter specifies the antialiasing type for this render target. When this surface is passed to IDirect3DDevice9::SetRenderTarget, its multisample type must be the same as that of the depth-stencil set by IDirect3DDevice9::SetDepthStencilSurface.
MultisampleQuality
[in] Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error, D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces, and the multisample type must all match.
Lockable
[in] Render targets are not lockable unless the application specifies TRUE for Lockable.

Note that lockable render targets reduce performance on some graphics hardware. The readback performance (moving data from video memory to system memory) depends on the type of hardware used (AGP vs. PCI Express) and is usually far lower than upload performance (moving data from system to video memory). If you need read access to render targets, use GetRenderTargetData instead of lockable render targets.

ppSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface.
pSharedHandle
[in] Reserved. Set this parameter to NULL.
Usage
[in] Combination of one or more D3DUSAGE constants which can be OR'd together. Value of 0 indicates no usage.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

Render-target surfaces are placed in the D3DPOOL_DEFAULT memory class.

The creation of lockable, multisampled render targets is not supported.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::GetDisplayModeEx

Retrieves the display mode's spatial resolution, color resolution, refresh frequency, and rotation settings.

HRESULT GetDisplayModeEx(
  UINT  iSwapChain,
  D3DDISPLAYMODEEX *pMode,
  D3DDISPLAYROTATION *pRotation
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pMode
[out] Pointer to a D3DDISPLAYMODEEX (DirectX 9Ex only) structure containing data about the display mode of the adapter. As opposed to the display mode of the device, which may not be active if the device does not own full-screen mode. Can be set to NULL.
pRotation
[out] Pointer to a D3DDISPLAYROTATION (DirectX 9Ex only) indicating the type of screen rotation the application will do. The value returned through this pointer is important when the D3DPRESENTFLAG_NOAUTOROTATE flag is used; otherwise, it can be set to NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::GetGPUThreadPriority

Get the priority of the GPU thread.

HRESULT GetGPUThreadPriority(
  INT *pPriority
);

Parameters

pPriority
Current GPU priority. Valid values range from -7 to 7.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

Use IDirect3DDevice9Ex::SetGPUThreadPriority to set the priority of a thread.

This method will retrieve the priority of the thread stored with the Direct3D device even if it was created with the D3DCREATE_PUREDEVICE flag.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::GetMaximumFrameLatency

Retrieves the number of frames of data that the system is allowed to queue.

GetMaximumFrameLatency(
  UINT *pMaxLatency
);

Parameters

pMaxLatency
[out] Returns the number of frames that can be queued for render. The value is typically 3, but can range from 1 to 20.

Remarks

Frame latency is the number of frames that are allowed to be stored in a queue, before submission for rendering. Latency is often used to control how the CPU chooses between responding to user input and frames that are in the render queue.

It is often beneficial for applications that have no user input (for example, video playback) to queue more than 3 frames of data.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::PresentEx

Swap the swapchain's next buffer with the front buffer.

HRESULT PresentEx(
  CONST RECT *pSourceRect,
  CONST RECT *pDestRect,
  HWND hDestWindowOverride,
  CONST RGNDATA *pDirtyRegion,
  DWORD dwFlags
);

Parameters

pSourceRect
[in] Pointer to a RECT structure indicating region on the source surface to copy in window client coordinates. Only applies when the swapchain was created with D3DSWAPEFFECT_COPY flag. If NULL, the entire source surface is presented. If the rectangle exceeds the source surface, it is clipped to the source surface.
pDestRect
[in] Pointer to RECT structure indicating the target region on the destination surface in window client coordinates. Only applies when the swapchain was created with the D3DSWAPEFFECT_COPY flag. If NULL, the entire client area is filled. If the rectangle exceeds the destination client area, it is clipped to the destination client area.
hDestWindowOverride
[in] Pointer to a destination window handle whose client area is taken as the target for this presentation. If this value is NULL, then the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is taken.
pDirtyRegion
[in] Pointer to a RGNDATA structure indicating the smallest set of pixels that need to be transferred. This value must be NULL unless the swapchain was created with the D3DSWAPEFFECT_COPY flag. For more information about swapchains, see Flipping Surfaces (Direct3D 9).

If this value is non-NULL, the contained region is expressed in back buffer coordinates. The method takes these rectangles into account when optimizing the presentation by copying only the pixels within the region, or some suitably expanded set of rectangles. This is an aid to optimization only, and the application should not rely on the region being copied exactly. The implementation can choose to copy the whole source rectangle.

dwFlags
[in] Allows the application to request that the method return immediately when the driver reports that it cannot schedule a presentation. Valid values are 0, or any combination of D3DPRESENT_DONOTWAIT, D3DPRESENT_LINEAR_CONTENT or D3DPRESENT_DONOTFLIP.
  • If dwFlags = 0, this method behaves as it did prior to Direct3D 9. Present will spin until the hardware is free, without returning an error.
  • If dwFlags = D3DPRESENT_DONOTWAIT, and the hardware is busy processing or waiting for a vertical sync interval, the method will return D3DERR_WASSTILLDRAWING.
  • If dwFlags = D3DPRESENT_LINEAR_CONTENT, gamma correction is performed from linear space to sRGB for windowed swap chains. This flag will take effect only when the driver exposes D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION (see Gamma (Direct3D 9)).
  • If dwFlags = D3DPRESENT_DONOTFLIP the display driver is called with the front buffer as both the source and target surface. The driver responds by scheduling a frame synch, but not changing the displayed surface. This flag is only available in fullscreen mode.

Return Values

S_OK the device is ok for rendering.

S_PRESENT_MODE_CHANGED the display mode has changed.

S_PRESENT_OCCLUDED the window is occluded.

D3DERR_DEVICELOST the device has been lost.

D3DERR_DEVICEHUNG if the device is hung.

D3DERR_DEVICEREMOVED if the device has been removed.

See Device State Return Codes for more information about these Return codes. See Lost Device Behavior Changes for more information about lost, hung, and removed devices.

Remarks

Similar to the IDirect3DDevice9::Present Method, PresentEx adds a dwflags parameter.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::ResetEx

Resets the type, size, and format of the swap chain with all other surfaces persistent.

HRESULT ResetEx(
  D3DPRESENT_PARAMETERS* pPresentationParameters,
  D3DDISPLAYMODEEX* pFullscreenDisplayMode
);

Parameters

pPresentationParameters

Pointer to a D3DPRESENT_PARAMETERS structure, describing the new presentation parameters. This value cannot be NULL.

[in, out] When switching to full-screen mode, Direct3D will try to find a desktop format that matches the back buffer format, so that back buffer and front buffer formats will be identical (to eliminate the need for color conversion).

When this method returns:

  • BackBufferCount, BackBufferWidth, and BackBufferHeight are set to zero.
  • BackBufferFormat is set to D3DFORMAT for windowed mode only; a full-screen mode must specify a format.

pFullscreenDisplayMode
[in, out] Pointer to a D3DDISPLAYMODEEX (DirectX 9Ex only) structure that describes the properties of the desired display mode. This value must be provided for fullscreen applications, but can be NULL for windowed applications.

Return Values

If the method succeeds, the return value is D3D_OK.

If this method returns D3DERR_DEVICELOST or D3DERR_DEVICEHUNG then the application can only call IDirect3DDevice9Ex::ResetEx, IDirect3DDevice9Ex::CheckDeviceState or Release. Any other API call will result in an exception.

If ResetEx fails with any other error code, destroy the device and quit the application.

Remarks

If a call to IDirect3DDevice9Ex::ResetEx fails, the device will be placed in the lost state (as indicated by a return value of D3DERR_DEVICELOST from a call to IDirect3DDevice9Ex::CheckDeviceState). Refer to IDirect3DDevice9Ex::CheckDeviceState and Lost Device Behavior Changes for further information concerning the use of IDirect3DDevice9Ex::ResetEx in the context of lost devices.

Unlike previous versions of DirectX, calling IDirect3DDevice9Ex::ResetEx does not cause surfaces, textures or state information to be lost.

Pixel shaders and vertex shaders survive IDirect3DDevice9Ex::ResetEx calls for Direct3D 9. They do not need to be re-created explicitly by the application.

There are two different types of swap chains: full-screen or windowed. If the new swap chain is full-screen, the adapter will be placed in the display mode that matches the new size.

Applications can expect messages to be sent to them during this call (for example, before this call is returned); applications should take precautions not to call into Direct3D at this time.

A call to IDirect3DDevice9Ex::ResetEx will fail if called on a different thread than that used to create the device being reset.

D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9Ex::CreateDeviceEx, IDirect3DDevice9Ex::ResetEx, and IDirect3DDevice9::CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling IDirect3D9Ex::CreateDeviceEx for windowed mode. For full-screen mode, the back buffer format must be specified. Setting BackBufferCount equal to zero (BackBufferCount = 0) results in one back buffer.

When trying to reset more than one display adapter in a group, set pPresentationParameters to point to an array of D3DPRESENT_PARAMETERS structures, one for each display in the adapter group.

If a multihead device was created with D3DCREATE_ADAPTERGROUP_DEVICE, IDirect3DDevice9Ex::ResetEx requires an array of D3DPRESENT_PARAMETERS structures wherein each structure must specify a full-screen display. To switch back to windowed mode, the application must destroy the device and re-create a non-multihead device in windowed mode.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::SetConvolutionMonoKernel

Prepare the texture sampler for monochrome convolution filtering on a single-color texture.

HRESULT SetConvolutionMonoKernel(
  UINT Width,
  UINT Height,
  float *RowWeights,
  float *ColumnWeights
);

Parameters

Width
[in] The width of the filter kernel; ranging from 1 - D3DCONVOLUTIONMONO_MAXWIDTH. The default value is 1.
Height
[in] The height of the filter kernel; ranging from 1 - D3DCONVOLUTIONMONO_MAXHEIGHT. The default value is 1.
RowWeights
[in] An array of weights, one weight for each kernel sub-element in the width. This parameter must be NULL, which will set the weights equal to the default value.
ColumnWeights
[in] An array of weights, one weight for each kernel sub-element in the height. This parameter must be NULL, which will set the weights equal to the default value.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method is designed to filter a single color texture. A monochrome convolution filter is a 2D box filter with all of the weights set to 1.0; the filter kernel resolution ranges from 1 x 1 to 7 x 7. When monochrome texture filtering is set to a texture sampler and texture sampling is performed at location, then D3D performs convolution.

Restrictions include:

  • The filter specified by this method is recorded in state blocks as a part of D3DSBT_PIXELSTATE.
  • The only texture address mode supported is: D3DPTADDRESSCAPS_BORDER; the border color is always 0.
  • This method is not supported for mipmaps.
  • Using a non-monochrome texture with convolution filtering will generate a driver error.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::SetGPUThreadPriority

Set the priority on the GPU thread.

HRESULT SetGPUThreadPriority(
  INT pPriority
);

Parameters

pPriority
[in] The thread priority, ranging from -7 to 7.

Return Values

If the method succeeds, the return value is D3D_OK.

Non-LDDM drivers will return D3DERR_INVALIDCALL.

Remarks

The effects of calls to this method are not recorded in state blocks.

GPU thread priority is not reset when the Device is lost.

Use IDirect3DDevice9Ex::GetGPUThreadPriority to get the priority of a thread.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::SetMaximumFrameLatency

Set the number of frames that the system is allowed to queue for rendering.

HRESULT SetMaximumFrameLatency(
  UINT pMaxLatency
);

Parameters

pMaxLatency
[in] The maximum number of back buffer frames that a driver can queue. The value is typically 3, but can range from 1 to 20. A value of 0 will reset latency to the default. For multi-head devices, MaxLatency is specified per-head.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

Frame latency is the number of frames that are allowed to be stored in a queue, before submission for rendering. Latency is often used to control how the CPU chooses between responding to user input and frames that are in the render queue.

It is often beneficial for applications that have no user input (for example, video playback) to queue more than 3 frames of data.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::TestCooperativeLevel

Deprecated. Reports the current cooperative-level status of the Direct3D device for a windowed or full-screen application.

HRESULT TestCooperativeLevel();

Parameters

None.

Return Values

Always returns D3D_OK.

Remarks

This method is now deprecated. Use the IDirect3DDevice9Ex::CheckDeviceState method to check for lost devices, devices that have not been reset, or internal driver errors.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DDevice9Ex::WaitForVBlank

Suspend execution of the calling thread until the next vertical blank signal.

HRESULT WaitForVBlank(
  UINT SwapChainIndex
);

Parameters

SwapChainIndex
[in] Swap chain index. This is an optional, zero-based index used to specify a swap chain on a multihead card.

Return Values

This method will always return D3D_OK.

Remarks

This method allows applications to efficiently throttle their frame rate to that of the monitor associated with the device. Following a vertical blank, the amount of time it takes for the thread to wake up is typically very short.

In some scenarios the hardware may stop generating vertical blank signals when nothing is being displayed on the monitor. In this case, the method will wait approximately 100ms and return with D3D_OK.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DDevice9Ex


IDirect3DIndexBuffer9

Applications use the methods of the IDirect3DIndexBuffer9 interface to manipulate an index buffer resource.

IDirect3DResource9
IDirect3DIndexBuffer9

IDirect3DIndexBuffer9 Members

Method | Description
IDirect3DIndexBuffer9::GetDesc | Retrieves a description of the index buffer resource.
IDirect3DIndexBuffer9::Lock | Locks a range of index data and obtains a pointer to the index buffer memory.
IDirect3DIndexBuffer9::Unlock | Unlocks index data.

Remarks

The IDirect3DIndexBuffer9 interface is obtained by calling the IDirect3DDevice9::CreateIndexBuffer method.

This interface inherits additional functionality from the IDirect3DResource9 interface.

This interface, like all COM interfaces, inherits from the IUnknown interface.

The LPDIRECT3DINDEXBUFFER9 and PDIRECT3DINDEXBUFFER9 types are defined as pointers to the IDirect3DIndexBuffer9 interface.

typedef struct IDirect3DIndexBuffer9 *LPDIRECT3DINDEXBUFFER9, *PDIRECT3DINDEXBUFFER9;

See Also

IDirect3DDevice9::CreateIndexBuffer, Index Buffers (Direct3D 9)

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DIndexBuffer9::GetDesc

Retrieves a description of the index buffer resource.

HRESULT GetDesc(
  D3DINDEXBUFFER_DESC * pDesc
);

Parameters

pDesc
[out] Pointer to a D3DINDEXBUFFER_DESC structure, describing the returned index buffer.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if the argument is invalid.

Requirements

Header: Declared in D3D9.h.

See Also

Index Buffers (Direct3D 9)


IDirect3DIndexBuffer9::Lock

Locks a range of index data and obtains a pointer to the index buffer memory.

HRESULT Lock(
  UINT OffsetToLock,
  UINT SizeToLock,
  VOID ** ppbData,
  DWORD Flags
);

Parameters

OffsetToLock
[in] Offset into the index data to lock, in bytes. Lock the entire index buffer by specifying 0 for both parameters, SizeToLock and OffsetToLock.
SizeToLock
[in] Size of the index data to lock, in bytes. Lock the entire index buffer by specifying 0 for both parameters, SizeToLock and OffsetToLock.
ppbData
[out] VOID* pointer to a memory buffer containing the returned index data.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE
For a description of the flags, see D3DLOCK.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. IDirect3DDevice9::DrawIndexedPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

The D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE flags are valid only on buffers created with D3DUSAGE_DYNAMIC.

See Programming Tips (Direct3D 9) for information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DIndexBuffer9::Unlock, Index Buffers (Direct3D 9)


IDirect3DIndexBuffer9::Unlock

Unlocks index data.

HRESULT Unlock();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DIndexBuffer9::Lock, Index Buffers (Direct3D 9)


IDirect3DPixelShader9

Applications use the methods of the IDirect3DPixelShader9 interface to encapsulate the functionality of a pixel shader.

IDirect3DPixelShader9 Members

Method | Description
IDirect3DPixelShader9::GetDevice | Gets the device.
IDirect3DPixelShader9::GetFunction | Gets a pointer to the shader data.

Remarks

The LPDIRECT3DPIXELSHADER9 and PDIRECT3DPIXELSHADER9 types are defined as pointers to the IDirect3DPixelShader9 interface.

typedef struct IDirect3DPixelShader9 *LPDIRECT3DPIXELSHADER9, *PDIRECT3DPIXELSHADER9;

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DPixelShader9::GetDevice

Gets the device.

HRESULT GetDevice(
  IDirect3DDevice9 ** ppDevice
);

Parameters

ppDevice
[out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DPixelShader9::GetFunction

Gets a pointer to the shader data.

HRESULT GetFunction(
  void* pData,
  UINT* pSizeOfData
);

Parameters

pData
[in, out] Pointer to a buffer that contains the shader data. The application needs to allocate enough room for this.
pSizeOfData
[in, out] Size of the data, in bytes. To get the buffer size that is needed to retrieve the data, set pData = NULL when calling GetFunction. Then call GetFunction with the returned size, to get the buffer data.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DQuery9

Applications use the methods of the IDirect3DQuery9 interface to perform asynchronous queries on a driver.

IDirect3DQuery9 Members

Method | Description
IDirect3DQuery9::GetData | Polls a queried resource to get the query state or a query result. For more information about queries, see Queries (Direct3D 9).
IDirect3DQuery9::GetDataSize | Gets the number of bytes in the query data.
IDirect3DQuery9::GetDevice | Gets the device that is being queried.
IDirect3DQuery9::GetType | Gets the query type.
IDirect3DQuery9::Issue | Issue a query.

Remarks

The LPDIRECT3DQUERY9 and PDIRECT3DQUERY9 types are defined as pointers to the IDirect3DQuery9 interface.

typedef struct IDirect3DQuery9 *LPDIRECT3DQUERY9, *PDIRECT3DQUERY9;

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DQuery9::GetData

Polls a queried resource to get the query state or a query result. For more information about queries, see Queries (Direct3D 9).

HRESULT GetData(
  void* pData,
  DWORD dwSize,
  DWORD dwGetDataFlags
);

Parameters

pData
[in, out] Pointer to a buffer containing the query data. The user is responsible for allocating this. pData may be NULL only if dwSize is 0.
dwSize
[in] Number of bytes of data in pData. If you set dwSize to zero, you can use this method to poll the resource for the query status. See remarks.
dwGetDataFlags
[in] Data flags specifying the query type. Valid values are either 0 or D3DGETDATA_FLUSH. Use 0 to avoid flushing batched queries to the driver and use D3DGETDATA_FLUSH to go ahead and flush them. For applications writing their own version of waiting, a query result is not realized until the driver receives a flush.

Return Values

The return type identifies the query state (see Queries (Direct3D 9)). The method returns S_OK if the query data is available and S_FALSE if it is not. These are considered successful return values. If the method fails when D3DGETDATA_FLUSH is used, the return value can be D3DERR_DEVICELOST.

Remarks

It is possible to lose the device while polling for query status. When D3DGETDATA_FLUSH is specified, this method will return D3DERR_DEVICELOST in response to a lost device. This allows an application to prevent threads from endlessly polling due to a lost device (which cannot respond to the query).

An application must never write code that only invokes GetData ( ... , 0 ), expecting that GetData will eventually return S_OK by itself over time. This is true, even if the application has used the FLUSH flag with GetData in the past. For example:

// Enables an infinite loop:
while( pQuery->GetData( ... , 0 ) == S_FALSE ) ;

// Still enables an infinite loop:
pQuery->GetData( ... , D3DGETDATA_FLUSH );
while( pQuery->GetData( ... , 0 ) == S_FALSE ) ;

// Does not enable an infinite loop because eventually the command
// buffer will fill up and that will cause a flush to occur.
while( pQuery->GetData( ..., 0 ) == S_FALSE ) {
    pDevice->SetTexture(...);
    pDevice->Draw(...);
}

Requirements

Header: Declared in D3D9.h.


IDirect3DQuery9::GetDataSize

Gets the number of bytes in the query data.

DWORD GetDataSize();

Parameters

None.

Return Values

Returns the number of bytes of query data.

Requirements

Header: Declared in D3D9.h.


IDirect3DQuery9::GetDevice

Gets the device that is being queried.

HRESULT GetDevice(
  IDirect3DDevice9 ** pDevice
);

Parameters

pDevice
[out] Pointer to the device being queried. See IDirect3DDevice9.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DQuery9::GetType

Gets the query type.

D3DQUERYTYPE GetType();

Parameters

None.

Return Values

Returns the query type. See D3DQUERYTYPE.

Requirements

Header: Declared in D3D9.h.


IDirect3DQuery9::Issue

Issue a query.

HRESULT Issue(
  DWORD dwIssueFlags
);

Parameters

dwIssueFlags
[in] Query flags specify the type of state change for the query. See D3DISSUE_BEGIN and D3DISSUE_END.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A signaled query means the query has completed, the data is available, and IDirect3DQuery9::GetData will return S_OK.

Requirements

Header: Declared in D3D9.h.


IDirect3DResource9

Applications use the methods of the IDirect3DResource9 interface to query and prepare resources.

IDirect3DResource9
IDirect3DBaseTexture9
IDirect3DCubeTexture9
IDirect3DTexture9
IDirect3DVolumeTexture9
IDirect3DIndexBuffer9
IDirect3DSurface9
IDirect3DVertexBuffer9
IDirect3DVolume9

IDirect3DResource9 Members

Method | Description
IDirect3DResource9::FreePrivateData | Frees the specified private data associated with this resource.
IDirect3DResource9::GetDevice | Retrieves the device associated with a resource.
IDirect3DResource9::GetPriority | Retrieves the priority for this resource.
IDirect3DResource9::GetPrivateData | Copies the private data associated with the resource to a provided buffer.
IDirect3DResource9::GetType | Returns the type of the resource.
IDirect3DResource9::PreLoad | Preloads a managed resource.
IDirect3DResource9::SetPriority | Assigns the resource-management priority for this resource.
IDirect3DResource9::SetPrivateData | Associates data with the resource that is intended for use by the application, not by Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Remarks

To create a texture resource, you can call one of the following methods.

  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVolumeTexture

To create a geometry-oriented resource, you can call one of the following methods.

  • IDirect3DDevice9::CreateIndexBuffer
  • IDirect3DDevice9::CreateVertexBuffer

This interface, like all COM interfaces, inherits from the IUnknown interface.

The LPDIRECT3DRESOURCE9 and PDIRECT3DRESOURCE9 types are defined as pointers to the IDirect3DResource9 interface.

    typedef struct IDirect3DResource9 *LPDIRECT3DRESOURCE9, *PDIRECT3DRESOURCE9;

See Also

Direct3D Resources (Direct3D 9)

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DResource9::FreePrivateData

Frees the specified private data associated with this resource.

HRESULT FreePrivateData(
  REFGUID refguid
);

Parameters

refguid
[in] Reference to the globally unique identifier that identifies the private data to free.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_NOTFOUND.

Remarks

Direct3D calls this method automatically when a resource is released.

Requirements

Header: Declared in D3D9.h.


IDirect3DResource9::GetDevice

Retrieves the device associated with a resource.

HRESULT GetDevice(
  IDirect3DDevice9 ** ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.


IDirect3DResource9::GetPriority

Retrieves the priority for this resource.

DWORD GetPriority();

Parameters

None.

Return Values

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DResource9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

Requirements

Header: Declared in D3D9.h.


IDirect3DResource9::GetPrivateData

Copies the private data associated with the resource to a provided buffer.

HRESULT GetPrivateData(
  REFGUID refguid,
  void * pData,
  DWORD * pSizeOfData
);

Parameters

refguid
[in] The globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_MOREDATA, D3DERR_NOTFOUND.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.

Requirements

Header: Declared in D3D9.h.


IDirect3DResource9::GetType

Returns the type of the resource.

D3DRESOURCETYPE GetType();

Parameters

None.

Return Values

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.

Requirements

Header: Declared in D3D9.h.


IDirect3DResource9::PreLoad

Preloads a managed resource.

PreLoad();

Parameters

None.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DResource9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DResource9::PreLoad silently does nothing.

Requirements

Header: Declared in D3d9.h.


IDirect3DResource9::SetPriority

Assigns the priority of a resource for scheduling purposes.

DWORD SetPriority(
  DWORD PriorityNew
);

Parameters

PriorityNew
[in] Priority to assign to a resource.

Differences between Direct3D 9 and Direct3D 9 for Windows Vista

The priority can be any DWORD value; Direct3D 9 for Windows Vista also supports any of these pre-defined values D3D9_RESOURCE_PRIORITY (DirectX 9Ex only).

Return Values

Returns the previous priority value for the resource.

Remarks

This method is used to change the priority of managed resources (resources created with the D3DPOOL_MANAGED flag). This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

Windows Vista only - When this method is called using an IDirect3D9Ex interface, only resources created with the D3DPOOL_DEFAULT flag will be affected.

Requirements

Header: Declared in D3D9.h.


IDirect3DResource9::SetPrivateData

Associates data with the resource that is intended for use by the application, not by Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

HRESULT SetPrivateData(
  REFGUID refguid,
  CONST void * pData,
  DWORD SizeOfData,
  DWORD Flags
);

Parameters

refguid
[in] Reference to the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to IUnknown, that is, sizeof(IUnknown*). Direct3D automatically callsIUnknown through pData when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DResource9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

Requirements

Header: Declared in D3D9.h.


IDirect3DStateBlock9

Applications use the methods of the IDirect3DStateBlock9 interface to encapsulate render states.

IDirect3DStateBlock9 Members

Method | Description
IDirect3DStateBlock9::Apply | Apply the state block to the current device state.
IDirect3DStateBlock9::Capture | Capture the current value of states that are included in a stateblock.
IDirect3DStateBlock9::GetDevice | Gets the device.

Remarks

This interface can be used to save and restore pipeline state. It can also be used to capture the current state.

The LPDIRECT3DSTATEBLOCK9 and PDIRECT3DSTATEBLOCK9 types are defined as pointers to the IDirect3DStateBlock9 interface.

typedef struct IDirect3DStateBlock9 *LPDIRECT3DSTATEBLOCK9, *PDIRECT3DSTATEBLOCK9;

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DStateBlock9::Apply

Apply the state block to the current device state.

HRESULT Apply();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails while in record mode, the return value is D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DStateBlock9::Capture

Capture the current value of states that are included in a stateblock.

HRESULT Capture();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails because capture cannot be done while in record mode, the return value is D3DERR_INVALIDCALL.

Remarks

Capture captures current values for states within an existing state block. It does not capture the entire state of the device. For example:

HRESULT hr;
IDirect3DStateBlock9* pStateBlock = NULL;
if(SUCCEEDED(pd3dDevice->CreateStateBlock(D3DSBT_PIXELSTATE, &pStateBlock)))
{
    pd3dDevice->BeginStateBlock();
    // Add the ZENABLE state to the stateblock
    pd3dDevice->SetRenderState ( D3DRS_ZENABLE, true );
    pd3dDevice->EndStateBlock ( &pStateBlock );

    // Change the current value
    pd3dDevice->SetRenderState ( D3DRS_ZENABLE, false );
    hr = pStateBlock->Capture();
    pStateBlock->Release();
}

Creating an empty stateblock and calling Capture does nothing if no states have been set.

Capture will not capture information for lights that are explicitly or implicitly created after the stateblock is created.

Requirements

Header: Declared in D3D9.h.


IDirect3DStateBlock9::GetDevice

Gets the device.

HRESULT GetDevice(
  IDirect3DDevice9 ** ppDevice
);

Parameters

ppDevice
[in, out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DSurface9

Applications use the methods of the IDirect3DSurface9 interface to query and prepare surfaces.

IDirect3DSurface9 Members

Method | Description
IDirect3DSurface9::GetContainer | Provides access to the parent cube texture or texture (mipmap) object, if this surface is a child level of a cube texture or a mipmap. This method can also provide access to the parent swap chain if the surface is a back-buffer child.
IDirect3DSurface9::GetDC | Retrieves a device context.
IDirect3DSurface9::GetDesc | Pointer to a D3DSURFACE_DESC structure, describing the surface.
IDirect3DSurface9::LockRect | Pointer to a D3DLOCKED_RECT structure that describes the locked region.
IDirect3DSurface9::ReleaseDC | Release a device context handle.
IDirect3DSurface9::UnlockRect | Unlocks a rectangle on a surface.

Remarks

This interface, like all COM interfaces, inherits from the IUnknown interface.

The LPDIRECT3DSURFACE9 and PDIRECT3DSURFACE9 types are defined as pointers to the IDirect3DSurface9 interface.

typedef struct IDirect3DSurface9 *LPDIRECT3DSURFACE9, *PDIRECT3DSURFACE9;

See Also

D3D Interfaces

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DSurface9::GetContainer

Provides access to the parent cube texture or texture (mipmap) object, if this surface is a child level of a cube texture or a mipmap. This method can also provide access to the parent swap chain if the surface is a back-buffer child.

HRESULT GetContainer(
  REFIID riid,
  void ** ppContainer
);

Parameters

riid
[in] Reference identifier of the container being requested.
ppContainer
[out] Address of a pointer to fill with the container pointer if the query succeeds. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the surface is created using IDirect3DDevice9::CreateRenderTarget or IDirect3DDevice9::CreateOffscreenPlainSurface or IDirect3DDevice9::CreateDepthStencilSurface, the surface is considered stand alone. In this case, IDirect3DSurface9::GetContainer will return the Direct3D device used to create the surface.

If the call succeeds, the reference count of the container is increased by one.

Here's an example getting the parent texture of a mip surface.

// Assumes pSurface is a valid IDirect3DSurface9 pointer
void *pContainer = NULL;
IDirect3DTexture9 *pTexture = NULL;
HRESULT hr = pSurface->GetContainer(IID_IDirect3DTexture9, &pContainer);
if (SUCCEEDED(hr) && pContainer)
{
    pTexture = (IDirect3DTexture9 *)pContainer;
}

Requirements

Header: Declared in D3D9.h.


IDirect3DSurface9::GetDC

Retrieves a device context.

HRESULT GetDC(
  HDC* phdc
);

Parameters

phdc
[out] Pointer to the device context for the surface.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

The following restrictions apply.

  • IDirect3DSurface9::GetDC is valid on the following formats only: D3DFMT_R5G6B5, D3DFMT_X1R5G5B5, D3DFMT_R8G8B8, and D3DFMT_X8R8G8B8. Formats that contain Alpha are not supported because the GDI implementations don't have a well-defined behavior on the alpha channel. For more information about formats, see D3DFORMAT.
  • Only one device context per surface can be returned at a time.
  • IDirect3DSurface9::GetDC will fail if the surface is already locked. If the surface is a member of a mipmap or cubemap, IDirect3DSurface9::GetDC fails if any other mipmap or cubemap member is locked.
  • IDirect3DSurface9::GetDC fails on render targets unless they were created lockable (or, in the case of back buffers, with the D3DPRESENTFLAG_LOCKABLE_BACKBUFFER flag).
  • For surfaces not created with IDirect3DDevice9::CreateOffscreenPlainSurface, IDirect3DSurface9::GetDC will fail on default pool (D3DPOOL_DEFAULT) surfaces unless they are dynamic (D3DUSAGE_DYNAMIC) or are lockable render targets.
  • IDirect3DSurface9::GetDC will fail on D3DPOOL_SCRATCH surfaces.

When a device context is outstanding on a surface, the application may not call these methods:

IDirect3DCubeTexture9 | IDirect3DCubeTexture9::LockRect
IDirect3DDevice9 | IDirect3DDevice9::ColorFill
 | IDirect3DDevice9::StretchRect
 | IDirect3DDevice9::UpdateSurface
 | IDirect3DDevice9::UpdateTexture
IDirect3DSurface9 | IDirect3DSurface9::LockRect
IDirect3DSwapChain9 | IDirect3DSwapChain9::Present *
IDirect3DTexture9 | IDirect3DTexture9::LockRect

* (on a swap chain that contains the surface)

IDirect3DSurface9::GetDC causes an implicit lock; do not retain the device context for later use. Call IDirect3DSurface9::ReleaseDC to release it.

It is valid to call IDirect3DSurface9::GetDC/IDirect3DSurface9::ReleaseDC on levels of a mipmap or cubemap, however, these calls will be slow to all miplevels except the topmost level, and GDI operations to these miplevels will not be accelerated.

The hdc provides access to Win32 and GDI functionality.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DSurface9::ReleaseDC, D3DUSAGE, D3DPOOL, D3DPRESENT_PARAMETERS


IDirect3DSurface9::GetDesc

Retrieves a description of the surface.

HRESULT GetDesc(
  D3DSURFACE_DESC * pDesc
);

Parameters

pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing the surface.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Requirements

Header: Declared in D3D9.h.


IDirect3DSurface9::LockRect

Locks a rectangle on a surface.

HRESULT LockRect(
  D3DLOCKED_RECT * pLockedRect,
  CONST RECT * pRect,
  DWORD Flags
);

Parameters

pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure that describes the locked region.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT structure. Specifying NULL for this parameter expands the dirty region to cover the entire surface.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_DONOTWAIT
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
You may not specify a subrect when using D3DLOCK_DISCARD. For a description of the flags, see D3DLOCK.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL or D3DERR_WASSTILLDRAWING.

Remarks

If the D3DLOCK_DONOTWAIT flag is specified and the driver cannot lock the surface immediately, IDirect3DSurface9::LockRect will return D3DERR_WASSTILLDRAWING so that an application can use the CPU cycles while waiting for the driver to lock the surface.

The only lockable format for a depth-stencil surface is D3DFMT_D16_LOCKABLE. See D3DFORMAT.

For performance reasons, dirty regions are recorded only for level zero of a texture. Dirty regions are automatically recorded when IDirect3DSurface9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

A multisample back buffer cannot be locked.

This method cannot retrieve data from a surface that is is contained by a texture resource created with D3DUSAGE_RENDERTARGET because such a texture must be assigned to D3DPOOL_DEFAULT memory and is therefore not lockable. In this case, use instead IDirect3DDevice9::GetRenderTargetData to copy texture data from device memory to system memory.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DSurface9::UnlockRect


IDirect3DSurface9::ReleaseDC

Release a device context handle.

HRESULT ReleaseDC(
  HDC hdc
);

Parameters

hdc
[in] Handle to a device context.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

An hdc is a Windows resource. It must be released after use so Windows can return it to the pool of available resources.

This method will release only the device context returned by IDirect3DSurface9::GetDC. Otherwise, this method will fail.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DSurface9::GetDC


IDirect3DSurface9::UnlockRect

Unlocks a rectangle on a surface.

HRESULT UnlockRect();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DSurface9::LockRect


IDirect3DSwapChain9

Applications use the methods of the IDirect3DSwapChain9 interface to manipulate a swap chain.

IDirect3DSwapChain9 Members

Method | Description
IDirect3DSwapChain9::GetBackBuffer | Retrieves a back buffer from the swap chain of the device.
IDirect3DSwapChain9::GetDevice | Retrieves the device associated with the swap chain.
IDirect3DSwapChain9::GetDisplayMode | Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.
IDirect3DSwapChain9::GetFrontBufferData | Generates a copy of the swapchain's front buffer and places that copy in a system memory buffer provided by the application.
IDirect3DSwapChain9::GetPresentParameters | Retrieves the presentation parameters associated with a swap chain.
IDirect3DSwapChain9::GetRasterStatus | Returns information describing the raster of the monitor on which the swap chain is presented.
IDirect3DSwapChain9::Present | Presents the contents of the next buffer in the sequence of back buffers owned by the swap chain.

Remarks

There is always at least one swap chain for each device, known as the implicit swap chain. However, an additional swap chain for rendering multiple views from the same device can be created by calling the IDirect3DDevice9::CreateAdditionalSwapChain method.

This interface, like all COM interfaces, inherits from the IUnknown interface.

The LPDIRECT3DSWAPCHAIN9 and PDIRECT3DSWAPCHAIN9 types are defined as pointers to the IDirect3DSwapChain9 interface.

typedef struct IDirect3DSwapChain9 *LPDIRECT3DSWAPCHAIN9, *PDIRECT3DSWAPCHAIN9;

See Also

IDirect3DDevice9::CreateAdditionalSwapChain

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DSwapChain9::GetBackBuffer

Retrieves a back buffer from the swap chain of the device.

HRESULT GetBackBuffer(
  UINT BackBuffer,
  D3DBACKBUFFER_TYPE Type,
  IDirect3DSurface9 ** ppBackBuffer
);

Parameters

BackBuffer
[in] Index of the back buffer object to return. Back buffers are numbered from 0 to the total number of back buffers - 1. A value of 0 returns the first back buffer, not the front buffer. The front buffer is not accessible through this method. Use IDirect3DSwapChain9::GetFrontBufferData to retrieve a copy of the front buffer.
Type
[in] Stereo view is not supported in Direct3D 9, so the only valid value for this parameter is D3DBACKBUFFER_TYPE_MONO.
ppBackBuffer
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned back buffer surface.

Return Values

If the method succeeds, the return value is D3D_OK. If BackBuffer exceeds or equals the total number of back buffers, then the function fails and returns D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DSwapChain9::GetFrontBufferData


IDirect3DSwapChain9::GetDevice

Retrieves the device associated with the swap chain.

HRESULT GetDevice(
  IDirect3DDevice9 ** ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.


IDirect3DSwapChain9::GetDisplayMode

Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.

HRESULT GetDisplayMode(
  D3DDISPLAYMODE * pMode
);

Parameters

pMode
[out] Pointer to a D3DDISPLAYMODE structure containing data about the display mode of the adapter. As opposed to the display mode of the device, which may not be active if the device does not own full-screen mode.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DSwapChain9::GetFrontBufferData

Generates a copy of the swapchain's front buffer and places that copy in a system memory buffer provided by the application.

HRESULT GetFrontBufferData(
  IDirect3DSurface9 * pDestSurface
);

Parameters

pDestSurface
[in, out] Pointer to an IDirect3DSurface9 interface that will receive a copy of the swapchain's front buffer. The data is returned in successive rows with no intervening space, starting from the vertically highest row to the lowest. For windowed mode, the size of the destination surface should be the size of the desktop. For full screen mode, the size of the destination surface should be the screen size.

Return Values

If the method succeeds, the return value is D3D_OK. If BackBuffer exceeds or equals the total number of back buffers, the function fails and returns D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.


IDirect3DSwapChain9::GetPresentParameters

Retrieves the presentation parameters associated with a swap chain.

HRESULT GetPresentParameters(
  D3DPRESENT_PARAMETERS* pPresentationParameters
);

Parameters

pPresentationParameters
[out, retval] Pointer to the presentation parameters. See D3DPRESENT_PARAMETERS.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method can be used to see the presentation parameters of the parent swap chain of a surface (a back buffer, for instance). The parent swap chain can be retrieved with IDirect3DSurface9::GetContainer.

Requirements

Header: Declared in D3D9.h.


IDirect3DSwapChain9::GetRasterStatus

Returns information describing the raster of the monitor on which the swap chain is presented.

HRESULT GetRasterStatus(
  D3DRASTER_STATUS * pRasterStatus
);

Parameters

pRasterStatus
[out] Pointer to a D3DRASTER_STATUS structure filled with information about the position or other status of the raster on the monitor driven by this adapter.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if pRasterStatus is invalid or if the device does not support reading the current scan line. To determine if the device supports reading the scan line, check for the D3DCAPS_READ_SCANLINE flag in the Caps member of D3DCAPS9.

Requirements

Header: Declared in D3D9.h.

See Also

D3DRASTER_STATUS


IDirect3DSwapChain9::Present

Presents the contents of the next buffer in the sequence of back buffers owned by the swap chain.

HRESULT Present(
  CONST RECT * pSourceRect,
  CONST RECT * pDestRect,
  HWND hDestWindowOverride,
  CONST RGNDATA * pDirtyRegion,
  DWORD dwFlags
);

Parameters

pSourceRect
[in] Pointer to the source rectangle (see RECT). Use NULL to present the entire surface. This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. If the rectangle exceeds the source surface, the rectangle is clipped to the source surface.
pDestRect
[in] Pointer to the destination rectangle in client coordinates (see RECT). This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. Use NULL to fill the entire client area. If the rectangle exceeds the destination client area, the rectangle is clipped to the destination client area.
hDestWindowOverride
[in] Destination window whose client area is taken as the target for this presentation. If this value is NULL, the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is taken.
pDirtyRegion
[in] This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. See Flipping Surfaces (Direct3D 9). If this value is non-NULL, the contained region is expressed in back buffer coordinates. The rectangles within the region are the minimal set of pixels that need to be updated. This method takes these rectangles into account when optimizing the presentation by copying only the pixels within the region, or some suitably expanded set of rectangles. This is an aid to optimization only, and the application should not rely on the region being copied exactly. The implementation may choose to copy the whole source rectangle.
dwFlags
[in] Allows the application to request that the method return immediately when the driver reports that it cannot schedule a presentation. Valid values are 0, or any combination of D3DPRESENT_DONOTWAIT or D3DPRESENT_LINEAR_CONTENT (see D3DPRESENT).
  • If dwFlags = 0, this method behaves as it did prior to Direct3D 9. Present will spin until the hardware is free, without returning an error.
  • If dwFlags = D3DPRESENT_DONOTWAIT, and the hardware is busy processing or waiting for a vertical sync interval, the method will return D3DERR_WASSTILLDRAWING.
  • If dwFlags = D3DPRESENT_LINEAR_CONTENT, gamma correction is performed from linear space to sRGB for windowed swap chains. This flag will take effect only when the driver exposes D3DCAPS3_LINEAR_TO_SRGB_PresentATION (see Gamma (Direct3D 9)).

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_DEVICELOST, D3DERR_DRIVERINTERNALERROR, D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

The IDirect3DDevice9::Present method is a shortcut to Present. Present has been updated to take a flag allowing the application to request that the method return immediately when the driver reports that it cannot schedule a presentation.

If necessary, a stretch operation is applied to transfer the pixels within the source rectangle to the destination rectangle in the client area of the target window.

Present will fail if called between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene pairs unless the render target is not the current render target (such as the back buffer you get from creating an additional swap chain). This is a new behavior for Direct3D 9.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DDevice9::Reset


IDirect3DSwapChain9Ex

Applications use the methods of the IDirect3DSwapChain9Ex interface to manipulate a swap chain.

IUnknown
IDirect3DSwapChain9
IDirect3DSwapChain9Ex
GetDisplayModeEx | Retrieves the display mode's spatial resolution, color resolution, refresh frequency, and rotation settings.
GetLastPresentCount | Retrieves the number of times the IDirect3DDevice9Ex::PresentEx method has been called.
GetPresentStatistics | Retrieves a structure that contains presentation statistics.

There is always at least one swap chain for each device, known as the implicit swap chain. However, an additional swap chain for rendering multiple views from the same device can be created by calling the IDirect3DDevice9::CreateAdditionalSwapChain method.

This interface, like all COM interfaces, inherits from the IUnknown interface.

The LPDIRECT3DSWAPCHAIN9 and PDIRECT3DSWAPCHAIN9 types are defined as pointers to the IDirect3DSwapChain9 interface.

typedef struct IDirect3DSwapChain9 *LPDIRECT3DSWAPCHAIN9, *PDIRECT3DSWAPCHAIN9;

See Also

Direct3D 9Ex Interfaces

Requirements

Header: Declared in D3d9.h.


IDirect3DSwapChain9Ex::GetDisplayModeEx

Retrieves the display mode's spatial resolution, color resolution, refresh frequency, and rotation settings.

HRESULT GetDisplayModeEx(
  D3DDISPLAYMODEEX *pMode,
  D3DDISPLAYROTATION *pRotation
);

Parameters

pMode
[out] Pointer to a D3DDISPLAYMODEEX (DirectX 9Ex only) structure containing data about the display mode of the adapter. As opposed to the display mode of the device, which may not be active if the device does not own full-screen mode.
pRotation
[out] Pointer to a D3DDISPLAYROTATION (DirectX 9Ex only) indicating the type of screen rotation the application will do. The value returned through this pointer is important when the D3DPRESENTFLAG_NOAUTOROTATE flag is used; otherwise, it can be set to NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DSwapChain9Ex


IDirect3DSwapChain9Ex::GetLastPresentCount

Returns the number of times the swapchain has been processed.

HRESULT GetLastPresentCount(
  UINT * pLastPresentCount
);

Parameters

pLastPresentCount
[out] Pointer to a UINT to be filled with the number of times the IDirect3DDevice9Ex::PresentEx method has been called. The count will also be incremented by calling some other APIs such as IDirect3DDevice9::SetDialogBoxMode.

Return Values

S_OK the method was successful.

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DSwapChain9Ex


IDirect3DSwapChain9Ex::GetPresentStatistics

Retrieves a structure that contains presentation statistics allowing an application to identify frames that do not have a Present method call.

HRESULT GetPresentStatistics(
  D3DPRESENTSTATS * pPresentationStatistics
);

Parameters

pPresentationStatistics
[out] Returns a D3DPRESENTSTATS (DirectX 9Ex only) structure that contains statistics about IDirect3DDevice9Ex::PresentEx calls.

Return Values

S_OK the method was successful.

Remarks

The device must be created with the D3DCREATE_ENABLE_PRESENTSTATS flag, otherwise, the data returned by the method is undefined.

The structure that returns from this method can be used to determine if a frame was skipped. A frame in this context is a period of time separated by 2 vertical retraces. For instance, if a monitor is set to refresh at 60hz, then you are running at 60 frames per second.

In case of windowed mode, all structure values will be zeroes.

This me

Requirements

Header: Declared in D3d9.h.

See Also

IDirect3DSwapChain9Ex


IDirect3DTexture9

Applications use the methods of the IDirect3DTexture9 interface to manipulate a texture resource.

IDirect3DResource9
IDirect3DBaseTexture9
IDirect3DTexture9

IDirect3DTexture9 Members

Method | Description
IDirect3DTexture9::AddDirtyRect | Adds a dirty region to a texture resource.
IDirect3DTexture9::GetLevelDesc | Retrieves a level description of a texture resource.
IDirect3DTexture9::GetSurfaceLevel | Retrieves the specified texture surface level.
IDirect3DTexture9::LockRect | Locks a rectangle on a texture resource.
IDirect3DTexture9::UnlockRect | Unlocks a rectangle on a texture resource.

Remarks

The IDirect3DTexture9 interface can be obtained by calling the IDirect3DDevice9::CreateTexture method or one of the D3DXCreateTexturexxx functions.

This interface inherits additional functionality from the IDirect3DBaseTexture9 interface.

This interface, like all COM interfaces, inherits from the IUnknown interface.

The LPDIRECT3DTEXTURE9 and PDIRECT3DTEXTURE9 types are defined as pointers to the IDirect3DTexture9 interface.

typedef struct IDirect3DTexture9 *LPDIRECT3DTEXTURE9, *PDIRECT3DTEXTURE9;

See Also

IDirect3DDevice9::CreateTexture, D3DXCreateTexture, D3DXCreateTextureFromFile, D3DXCreateTextureFromFileEx, D3DXCreateTextureFromFileInMemory, D3DXCreateTextureFromFileInMemoryEx, D3DXCreateTextureFromResource, D3DXCreateTextureFromResourceEx

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DTexture9::AddDirtyRect

Adds a dirty region to a texture resource.

HRESULT AddDirtyRect(
  CONST RECT * pDirtyRect
);

Parameters

pDirtyRect
[in] Pointer to a RECT structure, specifying the dirty region to add. Specifying NULL expands the dirty region to cover the entire texture.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when IDirect3DTexture9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. The destination surface of IDirect3DDevice9::UpdateSurface is also marked dirty automatically.

Using D3DLOCK_NO_DIRTY_UPDATE and explicitly specifying dirty regions can be used to increase the efficiency of IDirect3DDevice9::UpdateTexture. Using this method, applications can optimize what subset of a resource is copied by specifying dirty regions on the resource. However, the dirty regions may be expanded to optimize alignment.

Requirements

Header: Declared in D3D9.h.


IDirect3DTexture9::GetLevelDesc

Retrieves a level description of a texture resource.

HRESULT GetLevelDesc(
  UINT Level,
  D3DSURFACE_DESC * pDesc
);

Parameters

Level
[in] Identifies a level of the texture resource. This method returns a surface description for the level specified by this parameter.
pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing the returned level.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

Requirements

Header: Declared in D3D9.h.


IDirect3DTexture9::GetSurfaceLevel

Retrieves the specified texture surface level.

HRESULT GetSurfaceLevel(
  UINT Level,
  IDirect3DSurface9 ** ppSurfaceLevel
);

Parameters

Level
[in] Identifies a level of the texture resource. This method returns a surface for the level specified by this parameter. The top-level surface is denoted by 0.
ppSurfaceLevel
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned surface.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.


IDirect3DTexture9::LockRect

Locks a rectangle on a texture resource.

HRESULT LockRect(
  UINT Level,
  D3DLOCKED_RECT * pLockedRect,
  CONST RECT * pRect,
  DWORD Flags
);

Parameters

Level
[in] Specifies the level of the texture resource to lock.
pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure, describing the locked region.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT structure. Specifying NULL for this parameter expands the dirty region to cover the entire texture.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
You may not specify a subrect when using D3DLOCK_DISCARD. For a description of the flags, see D3DLOCK.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Textures created with D3DPOOL_DEFAULT are not lockable. Textures created in video memory are lockable when created with USAGE_DYNAMIC.

For performance reasons, dirty regions are recorded only for level zero of a texture. Dirty regions are automatically recorded when IDirect3DTexture9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

The only lockable format for a depth-stencil texture is D3DLOCK_D16_LOCKABLE.

Video memory textures cannot be locked, but must be modified by calling IDirect3DDevice9::UpdateSurface or IDirect3DDevice9::UpdateTexture. There are exceptions for some proprietary driver pixel formats that Direct3D 9 does not recognize. These can be locked.

This method cannot retrieve data from a texture resource created with D3DUSAGE_RENDERTARGET because such a texture must be assigned to D3DPOOL_DEFAULT memory and is therefore not lockable. In this case, use instead IDirect3DDevice9::GetRenderTargetData to copy texture data from device memory to system memory.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DTexture9::UnlockRect, IDirect3DDevice9::UpdateTexture, IDirect3DDevice9::GetRenderTargetData


IDirect3DTexture9::UnlockRect

Unlocks a rectangle on a texture resource.

HRESULT UnlockRect(
  UINT Level
);

Parameters

Level
[in] Specifies the level of the texture resource to unlock.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DTexture9::LockRect


IDirect3DVertexBuffer9

Applications use the methods of the IDirect3DVertexBuffer9 interface to manipulate vertex buffer resources.

IDirect3DResource9
IDirect3DVertexBuffer9

IDirect3DVertexBuffer9 Members

Method | Description
IDirect3DVertexBuffer9::GetDesc | Retrieves a description of the vertex buffer resource.
IDirect3DVertexBuffer9::Lock | Locks a range of vertex data and obtains a pointer to the vertex buffer memory.
IDirect3DVertexBuffer9::Unlock | Unlocks vertex data.

Remarks

The IDirect3DVertexBuffer9 interface is obtained by calling the IDirect3DDevice9::CreateVertexBuffer method.

This interface inherits additional functionality from the IDirect3DResource9 interface.

This interface, like all COM interfaces, inherits from the IUnknown interface.

The LPDIRECT3DVERTEXBUFFER9 and PDIRECT3DVERTEXBUFFER9 types are defined as pointers to the IDirect3DVertexBuffer9 interface.

typedef struct IDirect3DVertexBuffer9 *LPDIRECT3DVERTEXBUFFER9, *PDIRECT3DVERTEXBUFFER9;

See Also

IDirect3DDevice9::CreateVertexBuffer, Vertex Buffers (Direct3D 9)

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DVertexBuffer9::GetDesc

Retrieves a description of the vertex buffer resource.

HRESULT GetDesc(
  D3DVERTEXBUFFER_DESC * pDesc
);

Parameters

pDesc
[out] Pointer to a D3DVERTEXBUFFER_DESC structure, describing the returned vertex buffer.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if the argument is invalid.

Requirements

Header: Declared in D3D9.h.

See Also

Vertex Buffers (Direct3D 9)


IDirect3DVertexBuffer9::Lock

Locks a range of vertex data and obtains a pointer to the vertex buffer memory.

HRESULT Lock(
  UINT OffsetToLock,
  UINT SizeToLock,
  VOID ** ppbData,
  DWORD Flags
);

Parameters

OffsetToLock
[in] Offset into the vertex data to lock, in bytes. To lock the entire vertex buffer, specify 0 for both parameters, SizeToLock and OffsetToLock.
SizeToLock
[in] Size of the vertex data to lock, in bytes. To lock the entire vertex buffer, specify 0 for both parameters, SizeToLock and OffsetToLock.
ppbData
[out] VOID* pointer to a memory buffer containing the returned vertex data.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE
For a description of the flags, see D3DLOCK.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

The D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE flags are valid only on buffers created with D3DUSAGE_DYNAMIC.

For information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE with IDirect3DVertexBuffer9::Lock, see Using Dynamic Vertex and Index Buffers.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVertexBuffer9::Unlock, Vertex Buffers (Direct3D 9)


IDirect3DVertexBuffer9::Unlock

Unlocks vertex data.

HRESULT Unlock();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVertexBuffer9::Lock, Vertex Buffers (Direct3D 9)


IDirect3DVertexDeclaration9

Applications use the methods of the IDirect3DVertexDeclaration9 interface to encapsulate the vertex shader declaration.

IDirect3DVertexDeclaration9 Members

Method | Description
IDirect3DVertexDeclaration9::GetDeclaration | Gets the vertex shader declaration.
IDirect3DVertexDeclaration9::GetDevice | Gets the current device.

Remarks

A vertex shader declaration is made up of an array of vertex elements.

The LPDIRECT3DVERTEXDECLARATION9 and PDIRECT3DVERTEXDECLARATION9 types are defined as pointers to the IDirect3DVertexDeclaration9 interface.

typedef struct IDirect3DVertexDeclaration9 *LPDIRECT3DVERTEXDECLARATION9, *PDIRECT3DVERTEXDECLARATION9;

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DVertexDeclaration9::GetDeclaration

Gets the vertex shader declaration.

HRESULT GetDeclaration(
  D3DVERTEXELEMENT9* pDecl,
  UINT* pNumElements
);

Parameters

pDecl
[in, out] Array of vertex elements (see D3DVERTEXELEMENT9) that make up a vertex shader declaration. The application needs to allocate enough room for this. The vertex element array ends with the D3DDECL_END macro.
pNumElements
[out] Number of elements in the array. The application needs to allocate enough room for this.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

The number of elements, pNumElements, includes the D3DDECL_END macro, which ends the declaration. So the element count is actually one higher than the number of valid vertex elements.

Here's an example that will return the vertex declaration array of up to 256 elements:

D3DVERTEXELEMENT9 decl[MAXD3DDECLLENGTH];
UINT numElements;
HRESULT hr = m_pVertexDeclaration->GetDeclaration( decl, &numElements);

Specify NULL for pDeclto get the number of elements in the declaration.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVertexDeclaration9


IDirect3DVertexDeclaration9::GetDevice

Gets the current device.

HRESULT GetDevice(
  IDirect3DDevice9 ** ppDevice
);

Parameters

ppDevice
[out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVertexDeclaration9


IDirect3DVertexShader9

Applications use the methods of the IDirect3DVertexShader9 interface to encapsulate the functionality of a vertex shader.

IDirect3DVertexShader9 Members

Method | Description
IDirect3DVertexShader9::GetDevice | Gets the device.
IDirect3DVertexShader9::GetFunction | Gets a pointer to the shader data.

Remarks

The LPDIRECT3DVERTEXSHADER9 and PDIRECT3DVERTEXSHADER9 types are defined as pointers to the IDirect3DVertexShader9 interface.

typedef struct IDirect3DVertexShader9 *LPDIRECT3DVERTEXSHADER9, *PDIRECT3DVERTEXSHADER9;

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DVertexShader9::GetDevice

Gets the device.

HRESULT GetDevice(
  IDirect3DDevice9 ** ppDevice
);

Parameters

ppDevice
[out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DVertexShader9::GetFunction

Gets a pointer to the shader data.

HRESULT GetFunction(
  void* pData,
  UINT* pSizeOfData
);

Parameters

pData
[in, out] Pointer to a buffer that contains the shader data. The application needs to allocate enough room for this.
pSizeOfData
[in, out] Size of the data, in bytes. To get the buffer size that is needed to retrieve the data, set pData = NULL when calling GetFunction. Then call GetFunction with the returned size, to get the buffer data.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.


IDirect3DVolume9

Applications use the methods of the IDirect3DVolume9 interface to manipulate volume resources.

IDirect3DResource9
IDirect3DVolume9

IDirect3DVolume9 Members

Method | Description
IDirect3DVolume9::FreePrivateData | Frees the specified private data associated with this volume.
IDirect3DVolume9::GetContainer | Provides access to the parent volume texture object, if this surface is a child level of a volume texture.
IDirect3DVolume9::GetDesc | Retrieves a description of the volume.
IDirect3DVolume9::GetDevice | Retrieves the device associated with a volume.
IDirect3DVolume9::GetPrivateData | Copies the private data associated with the volume to a provided buffer.
IDirect3DVolume9::LockBox | Locks a box on a volume resource.
IDirect3DVolume9::SetPrivateData | Associates data with the volume that is intended for use by the application, not by Direct3D.
IDirect3DVolume9::UnlockBox | Unlocks a box on a volume resource.

Remarks

The IDirect3DVolume9 interface is obtained by calling the IDirect3DVolumeTexture9::GetVolumeLevel method.

This interface, like all COM interfaces, inherits from the IUnknown interface.

The LPDIRECT3DVOLUME9 and PDIRECT3DVOLUME9 types are defined as pointers to the IDirect3DVolume9 interface.

typedef struct IDirect3DVolume9 *LPDIRECT3DVOLUME9, *PDIRECT3DVOLUME9;

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DVolume9::FreePrivateData

Frees the specified private data associated with this volume.

HRESULT FreePrivateData(
  REFGUID refguid
);

Parameters

refguid
[in] Reference to the globally unique identifier that identifies the private data to free.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_NOTFOUND.

Remarks

Direct3D calls this method automatically when a volume is released.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVolume9::GetPrivateData, IDirect3DVolume9::SetPrivateData


IDirect3DVolume9::GetContainer

Provides access to the parent volume texture object, if this surface is a child level of a volume texture.

HRESULT GetContainer(
  REFIID riid,
  void ** ppContainer
);

Parameters

riid
[in] Reference identifier of the volume being requested.
ppContainer
[out, retval] Address of a pointer to fill with the container pointer, if the query succeeds.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the call succeeds, the reference count of the container is increased by one.

Here's an example getting the parent volume texture of a volume texture.

// Assumes pSurface is a valid IDirect3DVolume9 pointer
void *pContainer = NULL;
IDirect3DVolumeTexture9 *pVolumeTexture = NULL;
HRESULT hr = pVolume->GetContainer(IID_IDirect3DVolumeTexture9, &pContainer);
if (SUCCEEDED(hr) && pContainer)
{
    pVolumeTexture = (IDirect3DVolumeTexture9 *)pContainer;

Requirements

Header: Declared in D3D9.h.


IDirect3DVolume9::GetDesc

Retrieves a description of the volume.

HRESULT GetDesc(
  D3DVOLUME_DESC * pDesc
);

Parameters

pDesc
[out] Pointer to a D3DVOLUME_DESC structure, describing the volume.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if the argument is invalid.

Requirements

Header: Declared in D3D9.h.


IDirect3DVolume9::GetDevice

Retrieves the device associated with a volume.

HRESULT GetDevice(
  IDirect3DDevice9 ** ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.


IDirect3DVolume9::GetPrivateData

Copies the private data associated with the volume to a provided buffer.

HRESULT GetPrivateData(
  REFGUID refguid,
  void * pData,
  DWORD * pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data, such as 0, the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_MOREDATA, D3DERR_NOTFOUND.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVolume9::FreePrivateData, IDirect3DVolume9::SetPrivateData


IDirect3DVolume9::LockBox

Locks a box on a volume resource.

HRESULT LockBox(
  D3DLOCKED_BOX * pLockedVolume,
  CONST D3DBOX * pBox,
  DWORD Flags
);

Parameters

pLockedVolume
[out] Pointer to a D3DLOCKED_BOX structure, describing the locked region.
pBox
[in] Pointer to a box to lock. Specified by a pointer to a D3DBOX structure. Specifying NULL for this parameter locks the entire volume.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
For a description of the flags, see D3DLOCK.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when IDirect3DVolume9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVolume9::UnlockBox


IDirect3DVolume9::SetPrivateData

Associates data with the volume that is intended for use by the application, not by Direct3D.

HRESULT SetPrivateData(
  REFGUID refguid,
  CONST void * pData,
  DWORD SizeOfData,
  DWORD Flags
);

Parameters

refguid
[in] Reference to the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to associate with the volume.
SizeOfData
[in] Size of the buffer at pData in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown through pData and IUnknown when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DVolume9::SetPrivateData with the same GUID, a subsequent call to IDirect3DVolume9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

Data is passed by value, and multiple sets of data can be associated with a single volume.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVolume9::FreePrivateData, IDirect3DVolume9::GetPrivateData


IDirect3DVolume9::UnlockBox

Unlocks a box on a volume resource.

HRESULT UnlockBox();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVolume9::LockBox


IDirect3DVolumeTexture9

Applications use the methods of the IDirect3DVolumeTexture9 interface to manipulate a volume texture resource.

IDirect3DResource9
IDirect3DBaseTexture9
IDirect3DVolumeTexture9

IDirect3DVolumeTexture9 Members

Method | Description
IDirect3DVolumeTexture9::AddDirtyBox | Adds a dirty region to a volume texture resource.
IDirect3DVolumeTexture9::GetLevelDesc | Retrieves a level description of a volume texture resource.
IDirect3DVolumeTexture9::GetVolumeLevel | Retrieves the specified volume texture level.
IDirect3DVolumeTexture9::LockBox | Locks a box on a volume texture resource.
IDirect3DVolumeTexture9::UnlockBox | Unlocks a box on a volume texture resource.

Remarks

The IDirect3DVolumeTexture9 interface can be obtained by calling the IDirect3DDevice9::CreateVolumeTexture method or one of the D3DXCreateVolumeTexturexxx functions.

This interface inherits additional functionality from the IDirect3DBaseTexture9 interface.

This interface, like all COM interfaces, inherits from the IUnknown interface.

The LPDIRECT3DVOLUMETEXTURE9 and PDIRECT3DVOLUMETEXTURE9 types are defined as pointers to the IDirect3DVolumeTexture9 interface.

typedef struct IDirect3DVolumeTexture9 *LPDIRECT3DVOLUMETEXTURE9, *PDIRECT3DVOLUMETEXTURE9;

See Also

IDirect3DDevice9::CreateVolumeTexture, D3DXCreateVolumeTexture, D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx

Requirements

Header: Declared in D3D9.h.

Library: Use D3d9.lib.


IDirect3DVolumeTexture9::AddDirtyBox

Adds a dirty region to a volume texture resource.

HRESULT AddDirtyBox(
  CONST D3DBOX * pDirtyBox
);

Parameters

pDirtyBox
[in] Pointer to a D3DBOX structure, specifying the dirty region to add. Specifying NULL expands the dirty region to cover the entire volume texture.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) box is also dirty. Dirty regions are automatically recorded when IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY.

Using D3DLOCK_NO_DIRTY_UPDATE and explicitly specifying dirty regions can be used to increase the efficiency of IDirect3DDevice9::UpdateTexture. Using this method, applications can optimize what subset of a resource is copied by specifying dirty boxes on the resource. However, the dirty regions may be expanded to optimize alignment.

Requirements

Header: Declared in D3D9.h.


IDirect3DVolumeTexture9::GetLevelDesc

Retrieves a level description of a volume texture resource.

HRESULT GetLevelDesc(
  UINT Level,
  D3DVOLUME_DESC * pDesc
);

Parameters

Level
[in] Identifies a level of the volume texture resource. This method returns a volume description for the level specified by this parameter.
pDesc
[out] Pointer to a D3DVOLUME_DESC structure, describing the returned volume texture level.

Return Values

If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL is returned if one or more of the arguments are invalid.

Requirements

Header: Declared in D3D9.h.


IDirect3DVolumeTexture9::GetVolumeLevel

Retrieves the specified volume texture level.

HRESULT GetVolumeLevel(
  UINT Level,
  IDirect3DVolume9 ** ppVolumeLevel
);

Parameters

Level
[in] Identifies a level of the volume texture resource. This method returns a volume for the level specified by this parameter.
ppVolumeLevel
[out, retval] Address of a pointer to an IDirect3DVolume9 interface, representing the returned volume level.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DVolume9 interface. Failure to call IUnknown::Release when finished using this IDirect3DVolume9 interface results in a memory leak.

Requirements

Header: Declared in D3D9.h.


IDirect3DVolumeTexture9::LockBox

Locks a box on a volume texture resource.

HRESULT LockBox(
  UINT Level,
  D3DLOCKED_BOX * pLockedVolume,
  CONST D3DBOX * pBox,
  DWORD Flags
);

Parameters

Level
[in] Specifies the level of the volume texture resource to lock.
pLockedVolume
[out] Pointer to a D3DLOCKED_BOX structure, describing the locked region.
pBox
[in] Pointer to the volume to lock. This parameter is specified by a pointer to a D3DBOX structure. Specifying NULL for this parameter locks the entire volume level.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
For a description of the flags, see D3DLOCK.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. For more information, see IDirect3DDevice9::UpdateTexture.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVolumeTexture9::UnlockBox


IDirect3DVolumeTexture9::UnlockBox

Unlocks a box on a volume texture resource.

HRESULT UnlockBox(
  UINT Level
);

Parameters

Level
[in] Specifies the level of the volume texture resource to unlock.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3D9.h.

See Also

IDirect3DVolumeTexture9::LockBox


D3D Functions

This section contains reference information for the functions that you need to use when you work with Direct3D. The following functions are implemented:

  • DebugSetMute
  • Direct3DCreate9
  • Direct3DCreate9Ex
  • Direct3DShaderValidatorCreate9


DebugSetMute

Note This function is internal and not intended to be used by software developers.

DebugSetMute();

Parameters

None.


Direct3DCreate9

Create an IDirect3D9 object and return an interace to it.

IDirect3D9 * Direct3DCreate9(
  UINT SDKVersion
);

Parameters

SDKVersion
The value of this parameter should be D3D_SDK_VERSION. See Remarks.

Return Values

If successful, this function returns a pointer to an IDirect3D9 interface; otherwise, a NULL pointer is returned.

Remarks

The Direct3D object is the first object that your application creates and the last object that your application releases. Functions for enumerating and retrieving capabilities of a device are accessible through the Direct3D object. This enables applications to select devices without creating them.

Create an IDirect3D9 object as shown here:

LPDIRECT3D9 g_pD3D = NULL;

if( NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
    return E_FAIL;

The IDirect3D9 interface supports enumeration of active display adapters and allows the creation of IDirect3DDevice9 objects. If the user dynamically adds adapters (either by adding devices to the desktop, or by hot-docking a laptop), those devices will not be included in the enumeration. Creating a new IDirect3D9 interface will expose the new devices.

D3D_SDK_VERSION is passed to this function to ensure that the header files against which an application is compiled match the version of the runtime DLL's that are installed on the machine. D3D_SDK_VERSION is only changed in the runtime when a header change (or other code change) would require an application to be rebuilt. If this function fails, it indicates that the header file version does not match the runtime DLL version. See GetDXVer Sample for help checking the version of the runtime that is installed on your machine.

Requirements

Header: Declared in D3D9.h.

See Also

D3D Functions


Direct3DCreate9Ex

Create an IDirect3D9Ex object and return an interface to it.

HRESULT Direct3DCreate9Ex(
  UINT SDKVersion,
  IDirect3D9EX **ppD3D
);

Parameters

SDKVersion
[in] The value of this parameter should be D3D_SDK_VERSION. See Remarks.
ppD3D
[out] Address of a pointer to an IDirect3D9Ex interface, representing the created Direct3D9Ex object. If the function fails, NULL will be placed here.

Return Values

  • D3DERR_NOTAVAILABLE when D3D9L features are not supported (no WDDM driver installed) or when the SDKVersion does not match the version of the DLL.
  • D3DERR_OUTOFMEMORY when out of memory conditions are detected when creating the enumerator object.
  • S_OK when the creation of the enumerator object was successful.

Remarks

The IDirect3D9Ex object is the first object that your application creates and the last object that your application releases. Functions for enumerating and retrieving capabilities of a device are accessible through the Direct3DEx object. This enables applications to select devices without creating them.

IDirect3D9Ex *g_pD3D = NULL;

if( FAILED(Direct3DCreate9Ex(D3D_SDK_VERSION, &g_pD3D)))
    return E_FAIL;

The IDirect3D9Ex interface supports enumeration of active display adapters and allows the creation of IDirect3DDevice9Ex objects. If the user dynamically adds adapters (either by adding devices to the desktop, or by hot-docking a laptop), those devices will not be included in the enumeration. Creating a new IDirect3D9Ex interface will expose the new devices.

D3D_SDK_VERSION is passed to this function to ensure that the header files against which an application is compiled match the version of the runtime DLL's that are installed on the machine. D3D_SDK_VERSION is only changed in the runtime when a header change (or other code change) would require an application to be rebuilt. If this function fails, it indicates that the header file version does not match the runtime DLL version. See GetDXVer Sample for help checking the version of the runtime that is installed on your machine.

Requirements

Header: Declared in D3d9.h.

See Also

D3D Functions


Direct3DShaderValidatorCreate9

Note This function is internal and not intended to be used by software developers.

Direct3DShaderValidatorCreate9();

Parameters

None.


Macros

This section contains reference information for the macros provided by Direct3D.

  • D3DCLIPPLANEn
  • D3DCOLOR_ARGB
  • D3DCOLOR_AYUV
  • D3DCOLOR_COLORVALUE
  • D3DCOLOR_RGBA
  • D3DCOLOR_XRGB
  • D3DCOLOR_XYUV
  • D3DDECL_END
  • D3DFVF_TEXCOORDSIZEN
  • D3DGETDATA_FLUSH
  • D3DISSUE_BEGIN
  • D3DISSUE_END
  • D3DPS_VERSION
  • D3DTS_WORLD
  • D3DTS_WORLDMATRIX
  • D3DTS_WORLDn
  • D3DVS_VERSION

All D3D Macros have the following requirements:

Requirements

Header: Declared in D3d9types.h.


D3DCLIPPLANEn

Defines bit patterns that enable user-defined clipping planes. These macros are defined as a convenience when setting values for the D3DRS_CLIPPLANEENABLE render state.

D3DCLIPPLANEn();

Parameters

None.

Remarks

User-defined clipping planes are enabled when the value set in the D3DRS_CLIPPLANEENABLE render state contains one or more set bits (that is, is not 0). The value of the render-state is not important; the system does not interpret the value as a number. Rather, the value enables the clipping plane whose corresponding bit is set. Bit 0 controls the state of the first clipping plane (at index 0), bit 1 the second plane, and so on.

The bit patterns that these macros create can be combined by using a logical OR operation to simultaneously enable multiple clipping planes. Omitting one of these macros from the combination effectively disables the clipping plane at that index.


D3DCOLOR_ARGB

Initializes a color with the supplied alpha, red, green, and blue values.

#define D3DCOLOR_ARGB(a,r,g,b) ((D3DCOLOR)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))

Parameters

a
Alpha component of the color. This value must be in the range 0 through 255.
r
Red component of the color. This value must be in the range 0 through 255.
g
Green component of the color. This value must be in the range 0 through 255.
b
Blue component of the color. This value must be in the range 0 through 255.

Return Values

Returns the D3DCOLOR value that corresponds to the supplied ARGB values.

See Also

D3DCOLOR_RGBA, D3DCOLOR_XRGB


D3DCOLOR_AYUV

Initializes a color using the (a,y,u,v) values.

#define D3DCOLOR_AYUV(a,y,u,v) D3DCOLOR_ARGB(a,y,u,v)

Parameters

a
Alpha component of the color. This value must be in the range 0 through 255.
y
Luminance component of the color. This value must be in the range 0 through 255.
u
Blue brightness of the color. This value must be in the range 0 through 255.
v
Red brightness of the color. This value must be in the range 0 through 255.

Return Values

Returns the D3DCOLOR value that corresponds to the supplied (y,u,v) values.

Remarks

An RGB color can be reduced to 16 bits per pixel by conversion to luminance and color differences with the following equations:

y (luminance) = 0.299*red + 0.587*green + 0.114*blue
u = blue - luminance
v = red - luminance

See Also

D3DCOLOR_ARGB D3DCOLOR_XYUV

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


D3DCOLOR_COLORVALUE

Initializes a color with the supplied red, green, blue, and alpha floating-point values.

#define D3DCOLOR_COLORVALUE(r,g,b,a) \  D3DCOLOR_RGBA((DWORD)((r)*255.f),(DWORD)((g)*255.f),(DWORD)((b)*255.f),(DWORD)((a)*255.f))

Parameters

r
Red component of the color. This value must be a floating-point value in the range 0.0 through 1.0.
g
Green component of the color. This value must be a floating-point value in the range 0.0 through 1.0.
b
Blue component of the color. This value must be a floating-point value in the range 0.0 through 1.0.
a
Alpha component of the color. This value must be a floating-point value in the range 0.0 through 1.0.

Return Values

Returns the D3DCOLOR value that corresponds to the supplied RGBA values.


D3DCOLOR_RGBA

Initializes a color with the supplied red, green, blue, and alpha values.

#define D3DCOLOR_RGBA(r,g,b,a) D3DCOLOR_ARGB(a,r,g,b)

Parameters

r
Red component of the color. This value must be in the range 0 through 255.
g
Green component of the color. This value must be in the range 0 through 255.
b
Blue component of the color. This value must be in the range 0 through 255.
a
Alpha component of the color. This value must be in the range 0 through 255.

Return Values

Returns the D3DCOLOR value that corresponds to the supplied RGBA values.

See Also

D3DCOLOR_ARGB, D3DCOLOR_XRGB


D3DCOLOR_XRGB

Initializes a color with the supplied red, green, and blue values.

#define D3DCOLOR_XRGB(r,g,b) D3DCOLOR_ARGB(0xff,r,g,b)

Parameters

r
Red component of the color. This value must be in the range 0 through 255.
g
Green component of the color. This value must be in the range 0 through 255.
b
Blue component of the color. This value must be in the range 0 through 255.

Return Values

Returns the D3DCOLOR value that corresponds to the supplied RGB values.

See Also

D3DCOLOR_ARGB, D3DCOLOR_RGBA


D3DCOLOR_XYUV

Initializes a color with the (y, u, v) values.

#define D3DCOLOR_XYUV(y,u,v) D3DCOLOR_ARGB(0xff,y,u,v)

Parameters

y
Luminance component of the color. This value must be in the range 0 through 255.
u
Blue brightness of the color. This value must be in the range 0 through 255.
v
Red brightness of the color. This value must be in the range 0 through 255.

Return Values

Returns the D3DCOLOR value that corresponds to the supplied (y, u, v) values.

Remarks

An RGB color can be reduced to 16 bits per pixel by conversion to luminance and color differences with the following equations:

y (luminance) = 0.299*red + 0.587*green + 0.114*blue
u = blue - luminance
v = red - luminance

See Also

D3DCOLOR_ARGB D3DCOLOR_AYUV

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


D3DDECL_END

Initialize the last vertex element in a vertex declaration array.

#define D3DDECL_END {0xFF,0,D3DDECLTYPE_UNUSED, 0,0,0}

Remarks

This is used to initialize the last vertex element in a vertex declaration array.


D3DFVF_TEXCOORDSIZEN

Constructs bit patterns that are used to identify texture coordinate formats within a FVF description. The results of these macros can be combined within a FVF description by using the OR operator.

#define D3DFVF_TEXCOORDSIZEN(CoordIndex)
#define D3DFVF_TEXCOORDSIZE1(CoordIndex) (D3DFVF_TEXTUREFORMAT1 << (CoordIndex*2 + 16))
#define D3DFVF_TEXCOORDSIZE2(CoordIndex) (D3DFVF_TEXTUREFORMAT2)
#define D3DFVF_TEXCOORDSIZE3(CoordIndex) (D3DFVF_TEXTUREFORMAT3 << (CoordIndex*2 + 16))
#define D3DFVF_TEXCOORDSIZE4(CoordIndex) (D3DFVF_TEXTUREFORMAT4 << (CoordIndex*2 + 16))

Parameters

CoordIndex
Value that identifies the texture coordinate set at which the texture coordinate size (1-, 2-, 3-, or 4Dimensional) applies.

Remarks

The D3DFVF_TEXCOORDSIZEN macros use the following constants.

#define D3DFVF_TEXTUREFORMAT1 3 // one floating point value
#define D3DFVF_TEXTUREFORMAT2 0 // two floating point values
#define D3DFVF_TEXTUREFORMAT3 1 // three floating point values
#define D3DFVF_TEXTUREFORMAT4 2 // four floating point values

The following FVF description identifies a vertex format that has a position; a normal; diffuse and specular colors; and two sets of texture coordinates. The first set of texture coordinates includes a single element, and the second set includes two elements:

DWORD dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE |
              D3DFVF_SPECULAR | D3DFVF_TEX2 |
              D3DFVF_TEXCOORDSIZE1(0) |  // Uses 1D texture coordinates for
                                         // texture coordinate set 1 (index 0).
              D3DFVF_TEXCOORDSIZE2(1);   // And 2D texture coordinates for
                                         // texture coordinate set 2 (index 1).

See Also

D3DFVF


D3DGETDATA_FLUSH

This macro creates the value passed to IDirect3DQuery9::GetData to flush query data.

#define D3DGETDATA_FLUSH (1 << 0)

Remarks

For more information about using queries, see Queries (Direct3D 9).


D3DISSUE_BEGIN

This macro creates a value used by IDirect3DQuery9::Issue to issue a query begin.

#define D3DISSUE_BEGIN (1 << 1)

Remarks

D3DISSUE_BEGIN is valid for the following query type.

  • D3DQUERYTYPE_OCCLUSION

See Also

D3DISSUE_END, D3DGETDATA_FLUSH, D3DQUERYTYPE


D3DISSUE_END

This macro creates a value used by IDirect3DQuery9::Issue to issue a query end.

#define D3DISSUE_END (1 << 0)

Remarks

This macro changes the query state to nonsignaled.

D3DISSUE_END is valid for the following query types.

  • D3DQUERYTYPE_VCACHE
  • D3DQUERYTYPE_ResourceManager
  • D3DQUERYTYPE_VERTEXSTATS
  • D3DQUERYTYPE_EVENT
  • D3DQUERYTYPE_OCCLUSION

See Also

D3DISSUE_BEGIN D3DQUERYTYPE

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


D3DPS_VERSION

Create a pixel shader version token.

#define D3DPS_VERSION (_Major,_Minor)

Remarks

Version Numbers

The version number is a combination of the major version and the minor vertex shader version numbers. Valid numbers are shown in the table.

Major | Minor | Example
1 | 1 | D3DPS_VERSION(1,1)
1 | 2 | D3DPS_VERSION(1,2)
1 | 3 | D3DPS_VERSION(1,3)
1 | 4 | D3DPS_VERSION(1,4)
2 | 0 | D3DPS_VERSION(2,0)
3 | 0 | D3DPS_VERSION(3,0)


D3DTS_WORLD

Identifies the transformation matrix being set as the world transformation matrix.

#define D3DTS_WORLD D3DTS_WORLDMATRIX(0)

Remarks

This macro is provided to facilitate porting existing applications to Direct3D 9

See Also

IDirect3DDevice9::SetTransform, D3DTS_WORLDMATRIX


D3DTS_WORLDMATRIX

Maps indices in the range 0 through 255 to the corresponding transform states.

#define D3DTS_WORLDMATRIX(index) (D3DTRANSFORMSTATETYPE)(index + 256)

Parameters

index
An index value in the range 0 through 255.

Remarks

Transform states in the range 256 through 511 are reserved to store up to 256 matrices that can be indexed using 8-bit indices.

See Also

IDirect3DDevice9::SetTransform


D3DTS_WORLDn

Identifies subsequent transformation matrices that can be used to blend vertices by using the corresponding matrix and a blending (beta) weight value specified in the vertex format.

#define D3DTS_WORLDn
#define D3DTS_WORLD1 D3DTS_WORLDMATRIX(1)
#define D3DTS_WORLD2 D3DTS_WORLDMATRIX(2)
#define D3DTS_WORLD3 D3DTS_WORLDMATRIX(3)

Remarks

These macros are provided to facilitate porting existing applications to Direct3D 9.

See Also

IDirect3DDevice9::SetTransform, D3DTS_WORLDMATRIX


D3DVS_VERSION

Create a vertex shader version number token.

#define D3DVS_VERSION (Major, Minor)

Remarks

Version Numbers

The version number is a combination of the major version and the minor vertex shader version numbers. Valid numbers are shown in the table.

Major | Minor | Example
1 | 1 | D3DVS_VERSION(1,1)
2 | 0 | D3DVS_VERSION(2,0)
3 | 0 | D3DVS_VERSION(3,0)


D3D Structures

This section contains information about the structures used with Direct3D.

  • D3DADAPTER_IDENTIFIER9
  • D3DBOX
  • D3DCAPS9
  • D3DCLIPSTATUS9
  • D3DCOLORVALUE
  • D3DCOMPOSERECTDESC (DirectX 9Ex only)
  • D3DCOMPOSERECTDESTINATION (DirectX 9Ex only)
  • D3DDEVICE_CREATION_PARAMETERS
  • D3DDEVINFO_D3D9BANDWIDTHTIMINGS
  • D3DDEVINFO_D3D9CACHEUTILIZATION
  • D3DDEVINFO_D3D9INTERFACETIMINGS
  • D3DDEVINFO_D3D9PIPELINETIMINGS
  • D3DDEVINFO_D3D9STAGETIMINGS
  • D3DDEVINFO_D3DVERTEXSTATS
  • D3DDEVINFO_ResourceManager
  • D3DDEVINFO_VCACHE
  • D3DDISPLAYMODE
  • D3DDISPLAYMODEEX (DirectX 9Ex only)
  • D3DDISPLAYMODEFILTER (DirectX 9Ex only)
  • D3DGAMMARAMP
  • D3DINDEXBUFFER_DESC
  • D3DLIGHT9
  • D3DLOCKED_BOX
  • D3DLOCKED_RECT
  • D3DMATERIAL9
  • D3DMATRIX
  • D3DPRESENT_PARAMETERS
  • D3DPRESENTSTATS (DirectX 9Ex only)
  • D3DPSHADERCAPS2_0
  • D3DRANGE
  • D3DRASTER_STATUS
  • D3DRECT
  • D3DRECTPATCH_INFO
  • D3DRESOURCESTATS
  • D3DSURFACE_DESC
  • D3DTRIPATCH_INFO
  • D3DVECTOR
  • D3DVERTEXBUFFER_DESC
  • D3DVERTEXELEMENT9
  • D3DVIEWPORT9
  • D3DVOLUME_DESC
  • D3DVSHADERCAPS2_0
  • D3DXF_FILELOADMEMORY
  • PALETTEENTRY
  • XFILECOMPRESSEDANIMATIONSET


D3DADAPTER_IDENTIFIER9

Contains information identifying the adapter.

typedef struct D3DADAPTER_IDENTIFIER9 {
    char Driver[MAX_DEVICE_IDENTIFIER_STRING];
    char Description[MAX_DEVICE_IDENTIFIER_STRING];
    char DeviceName[32];
    LARGE_INTEGER DriverVersion;
    DWORD DriverVersionLowPart;
    DWORD DriverVersionHighPart;
    DWORD VendorId;
    DWORD DeviceId;
    DWORD SubSysId;
    DWORD Revision;
    GUID DeviceIdentifier;
    DWORD WHQLLevel;
} D3DADAPTER_IDENTIFIER9, *LPD3DADAPTER_IDENTIFIER9;

Members

Driver
Used for presentation to the user. This should not be used to identify particular drivers, because many different strings might be associated with the same device and driver from different vendors.
Description
Used for presentation to the user.
DeviceName
Device name for GDI.
DriverVersion
Identify the version of the Direct3D driver. It is legal to do less than and greater than comparisons on the 64-bit signed integer value. However, exercise caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier. See Remarks.
DriverVersionLowPart
Identify the version of the Direct3D driver. It is legal to do < and > comparisons on the 64-bit signed integer value. However, exercise caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier. See Remarks.
DriverVersionHighPart
Identify the version of the Direct3D driver. It is legal to do < and > comparisons on the 64-bit signed integer value. However, exercise caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier. See Remarks.
VendorId
Can be used to help identify a particular chip set. Query this member to identify the manufacturer. The value can be zero if unknown.
DeviceId
Can be used to help identify a particular chip set. Query this member to identify the type of chip set. The value can be zero if unknown.
SubSysId
Can be used to help identify a particular chip set. Query this member to identify the subsystem, typically the particular board. The value can be zero if unknown.
Revision
Can be used to help identify a particular chip set. Query this member to identify the revision level of the chip set. The value can be zero if unknown.
DeviceIdentifier
Can be queried to check changes in the driver and chip set. This GUID is a unique identifier for the driver and chip set pair. Query this member to track changes to the driver and chip set in order to generate a new profile for the graphics subsystem. DeviceIdentifier can also be used to identify particular problematic drivers.
WHQLLevel
Used to determine the Windows Hardware Quality Labs (WHQL) validation level for this driver and device pair. The DWORD is a packed date structure defining the date of the release of the most recent WHQL test passed by the driver. It is legal to perform < and > operations on this value. The following illustrates the date format.
Bits |
31-16 | The year, a decimal number from 1999 upwards.
15-8 | The month, a decimal number from 1 to 12.
7-0 | The day, a decimal number from 1 to 31.

The following values are also used.

0 | Not certified.
1 | WHQL validated, but no date information is available.

Remarks

The following pseudocode example illustrates the version format encoded in the DriverVersion, DriverVersionLowPart, and DriverVersionHighPart members.

Product = HIWORD(DriverVersion.HighPart)
Version = LOWORD(DriverVersion.HighPart)
SubVersion = HIWORD(DriverVersion.LowPart)
Build = LOWORD(DriverVersion.LowPart)

See the Platform SDK for more information about the HIWORD macro, the LOWORD macro, and the LARGE_INTEGER structure.

MAX_DEVICE_IDENTIFIER_STRING is a constant with the following definition.

#define MAX_DEVICE_IDENTIFIER_STRING        512

The VendorId, DeviceId, SubSysId, and Revision members can be used in tandem to identify particular chip sets. However, use these members with caution.


D3DBOX

Defines a volume.

typedef struct D3DBOX {
    UINT Left;
    UINT Top;
    UINT Right;
    UINT Bottom;
    UINT Front;
    UINT Back;
} D3DBOX, *LPD3DBOX;

Members

Left
Position of the left side of the box on the x-axis.
Top
Position of the top of the box on the y-axis.
Right
Position of the right side of the box on the x-axis.
Bottom
Position of the bottom of the box on the y-axis.
Front
Position of the front of the box on the z-axis.
Back
Position of the back of the box on the z-axis.

Remarks

D3DBOX includes the left, top, and front edges; however, the right, bottom, and back edges are not included. For example, a box that is 100 units wide and begins at 0 (thus, including the points up to and including 99) would be expressed with a value of 0 for the Left member and a value of 100 for the Right member. Note that a value of 99 is not used for the Right member.

The restrictions on side ordering observed for D3DBOX are left to right, top to bottom, and front to back.


D3DCAPS9

Represents the capabilities of the hardware exposed through the Direct3D object.

typedef struct D3DCAPS9 {
    D3DDEVTYPE DeviceType;
    UINT AdapterOrdinal;
    DWORD Caps;
    DWORD Caps2;
    DWORD Caps3;
    DWORD PresentationIntervals;
    DWORD CursorCaps;
    DWORD DevCaps;
    DWORD PrimitiveMiscCaps;
    DWORD RasterCaps;
    DWORD ZCmpCaps;
    DWORD SrcBlendCaps;
    DWORD DestBlendCaps;
    DWORD AlphaCmpCaps;
    DWORD ShadeCaps;
    DWORD TextureCaps;
    DWORD TextureFilterCaps;
    DWORD CubeTextureFilterCaps;
    DWORD VolumeTextureFilterCaps;
    DWORD TextureAddressCaps;
    DWORD VolumeTextureAddressCaps;
    DWORD LineCaps;
    DWORD MaxTextureWidth;
    DWORD MaxTextureHeight;
    DWORD MaxVolumeExtent;
    DWORD MaxTextureRepeat;
    DWORD MaxTextureAspectRatio;
    DWORD MaxAnisotropy;
    float MaxVertexW;
    float GuardBandLeft;
    float GuardBandTop;
    float GuardBandRight;
    float GuardBandBottom;
    float ExtentsAdjust;
    DWORD StencilCaps;
    DWORD FVFCaps;
    DWORD TextureOpCaps;
    DWORD MaxTextureBlendStages;
    DWORD MaxSimultaneousTextures;
    DWORD VertexProcessingCaps;
    DWORD MaxActiveLights;
    DWORD MaxUserClipPlanes;
    DWORD MaxVertexBlendMatrices;
    DWORD MaxVertexBlendMatrixIndex;
    float MaxPointSize;
    DWORD MaxPrimitiveCount;
    DWORD MaxVertexIndex;
    DWORD MaxStreams;
    DWORD MaxStreamStride;
    DWORD VertexShaderVersion;
    DWORD MaxVertexShaderConst;
    DWORD PixelShaderVersion;
    float PixelShader1xMaxValue;
    DWORD DevCaps2;
    UINT MasterAdapterOrdinal;
    UINT AdapterOrdinalInGroup;
    UINT NumberOfAdaptersInGroup;
    DWORD DeclTypes;
    DWORD NumSimultaneousRTs;
    DWORD StretchRectFilterCaps;
    D3DVSHADERCAPS2_0 VS20Caps;
    D3DPSHADERCAPS2_0 D3DPSHADERCAPS2_0;
    DWORD VertexTextureFilterCaps;
    DWORD MaxVShaderInstructionsExecuted;
    DWORD MaxPShaderInstructionsExecuted;
    DWORD MaxVertexShader30InstructionSlots;
    DWORD MaxPixelShader30InstructionSlots;
    DWORD Reserved2;
    DWORD Reserved3;
} D3DCAPS9, *LPD3DCAPS9;

Members

DeviceType
Member of the D3DDEVTYPE enumerated type, which identifies what type of resources are used for processing vertices.
AdapterOrdinal
Adapter on which this Direct3D device was created. This ordinal is valid only to pass to methods of the IDirect3D9 interface that created this Direct3D device. The IDirect3D9 interface can always be retrieved by calling IDirect3DDevice9::GetDirect3D.
Caps
The following driver-specific capability.
D3DCAPS_READ_SCANLINE
Display hardware is capable of returning the current scan line.
Caps2
Driver-specific capabilities identified in D3DCAPS2.
Caps3
Driver-specific capabilities identified in D3DCAPS3.
PresentationIntervals
Bit mask of values representing what presentation swap intervals are available.
D3DPRESENT_INTERVAL_IMMEDIATE
The driver supports an immediate presentation swap interval.
D3DPRESENT_INTERVAL_ONE
The driver supports a presentation swap interval of every screen refresh.
D3DPRESENT_INTERVAL_TWO
The driver supports a presentation swap interval of every second screen refresh.
D3DPRESENT_INTERVAL_THREE
The driver supports a presentation swap interval of every third screen refresh.
D3DPRESENT_INTERVAL_FOUR
The driver supports a presentation swap interval of every fourth screen refresh.
CursorCaps
Bit mask indicating what hardware support is available for cursors. Direct3D 9 does not define alpha-blending cursor capabilities.
D3DCURSORCAPS_COLOR
A full-color cursor is supported in hardware. Specifically, this flag indicates that the driver supports at least a hardware color cursor in high-resolution modes (with scan lines greater than or equal to 400).
D3DCURSORCAPS_LOWRES
A full-color cursor is supported in hardware. Specifically, this flag indicates that the driver supports a hardware color cursor in both high-resolution and low-resolution modes (with scan lines less than 400).
DevCaps
Flags identifying the capabilities of the device.
D3DDEVCAPS_CANBLTSYSTONONLOCAL
Device supports blits from system-memory textures to nonlocal video-memory textures.
D3DDEVCAPS_CANRENDERAFTERFLIP
Device can queue rendering commands after a page flip. Applications do not change their behavior if this flag is set; this capability means that the device is relatively fast.
D3DDEVCAPS_DRAWPRIMITIVES2
Device can support at least a DirectX 5-compliant driver.
D3DDEVCAPS_DRAWPRIMITIVES2EX
Device can support at least a DirectX 7-compliant driver.
D3DDEVCAPS_DRAWPRIMTLVERTEX
Device exports an IDirect3DDevice9::DrawPrimitive-aware hal.
D3DDEVCAPS_EXECUTESYSTEMMEMORY
Device can use execute buffers from system memory.
D3DDEVCAPS_EXECUTEVIDEOMEMORY
Device can use execute buffers from video memory.
D3DDEVCAPS_HWRASTERIZATION
Device has hardware acceleration for scene rasterization.
D3DDEVCAPS_HWTRANSFORMANDLIGHT
Device can support transformation and lighting in hardware.
D3DDEVCAPS_NPATCHES
Device supports N patches.
D3DDEVCAPS_PUREDEVICE
Device can support rasterization, transform, lighting, and shading in hardware.
D3DDEVCAPS_QUINTICRTPATCHES
Device supports quintic Bézier curves and B-splines.
D3DDEVCAPS_RTPATCHES
Device supports rectangular and triangular patches.
D3DDEVCAPS_RTPATCHHANDLEZERO
When this device capability is set, the hardware architecture does not require caching of any information, and uncached patches (handle zero) will be drawn as efficiently as cached ones. Note that setting D3DDEVCAPS_RTPATCHHANDLEZERO does not mean that a patch with handle zero can be drawn. A handle-zero patch can always be drawn whether this cap is set or not.
D3DDEVCAPS_SEPARATETEXTUREMEMORIES
Device is texturing from separate memory pools.
D3DDEVCAPS_TEXTURENONLOCALVIDMEM
Device can retrieve textures from non-local video memory.
D3DDEVCAPS_TEXTURESYSTEMMEMORY
Device can retrieve textures from system memory.
D3DDEVCAPS_TEXTUREVIDEOMEMORY
Device can retrieve textures from device memory.
D3DDEVCAPS_TLVERTEXSYSTEMMEMORY
Device can use buffers from system memory for transformed and lit vertices.
D3DDEVCAPS_TLVERTEXVIDEOMEMORY
Device can use buffers from video memory for transformed and lit vertices.
PrimitiveMiscCaps
Miscellaneous driver primitive capabilities. See D3DPMISCCAPS.
RasterCaps
Information on raster-drawing capabilities. This member can be one or more of the following flags.
D3DPRASTERCAPS_ANISOTROPY
Device supports anisotropic filtering.
D3DPRASTERCAPS_COLORPERSPECTIVE
Device iterates colors perspective correctly.
D3DPRASTERCAPS_DITHER
Device can dither to improve color resolution.
D3DPRASTERCAPS_DEPTHBIAS
Device supports legacy depth bias. For true depth bias, see D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS.
D3DPRASTERCAPS_FOGRANGE
Device supports range-based fog. In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene.
D3DPRASTERCAPS_FOGTABLE
Device calculates the fog value by referring to a lookup table containing fog values that are indexed to the depth of a given pixel.
D3DPRASTERCAPS_FOGVERTEX
Device calculates the fog value during the lighting operation and interpolates the fog value during rasterization.
D3DPRASTERCAPS_MIPMAPLODBIAS
Device supports level-of-detail bias adjustments. These bias adjustments enable an application to make a mipmap appear crisper or less sharp than it normally would. For more information about level-of-detail bias in mipmaps, see D3DSAMP_MIPMAPLODBIAS.
D3DPRASTERCAPS_MULTISAMPLE_TOGGLE
Device supports toggling multisampling on and off between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene (using D3DRS_MULTISAMPLEANTIALIAS).
D3DPRASTERCAPS_SCISSORTEST
Device supports scissor test. See Scissor Test (Direct3D 9).
D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS
Device performs true slope-scale based depth bias. This is in contrast to the legacy style depth bias.
D3DPRASTERCAPS_WBUFFER
Device supports depth buffering using w.
D3DPRASTERCAPS_WFOG
Device supports w-based fog. W-based fog is used when a perspective projection matrix is specified, but affine projections still use z-based fog. The system considers a projection matrix that contains a nonzero value in the [3][4] element to be a perspective projection matrix.
D3DPRASTERCAPS_ZBUFFERLESSHSR

Device can perform hidden-surface removal (HSR) without requiring the application to sort polygons and without requiring the allocation of a depth-buffer. This leaves more video memory for textures. The method used to perform HSR is hardware-dependent and is transparent to the application.

Z-bufferless HSR is performed if no depth-buffer surface is associated with the rendering-target surface and the depth-buffer comparison test is enabled (that is, when the state value associated with the D3DRS_ZENABLE enumeration constant is set to TRUE).

D3DPRASTERCAPS_ZFOG
Device supports z-based fog.
D3DPRASTERCAPS_ZTEST
Device can perform z-test operations. This effectively renders a primitive and indicates whether any z pixels have been rendered.
ZCmpCaps
Z-buffer comparison capabilities. This member can be one or more of the following flags.
D3DPCMPCAPS_ALWAYS
Always pass the z-test.
D3DPCMPCAPS_EQUAL
Pass the z-test if the new z equals the current z.
D3DPCMPCAPS_GREATER
Pass the z-test if the new z is greater than the current z.
D3DPCMPCAPS_GREATEREQUAL
Pass the z-test if the new z is greater than or equal to the current z.
D3DPCMPCAPS_LESS
Pass the z-test if the new z is less than the current z.
D3DPCMPCAPS_LESSEQUAL
Pass the z-test if the new z is less than or equal to the current z.
D3DPCMPCAPS_NEVER
Always fail the z-test.
D3DPCMPCAPS_NOTEQUAL
Pass the z-test if the new z does not equal the current z.
SrcBlendCaps
Source-blending capabilities. This member can be one or more of the following flags. (The RGBA values of the source and destination are indicated by the subscripts s and d.)
D3DPBLENDCAPS_BLENDFACTOR
The driver supports both D3DBLEND_BLENDFACTOR and D3DBLEND_INVBLENDFACTOR. See D3DBLEND.
D3DPBLENDCAPS_BOTHINVSRCALPHA

Source blend factor is (1 - As, 1 - As, 1 - As, 1 - As) and destination blend factor is (As, As, As, As); the destination blend selection is overridden.

D3DPBLENDCAPS_BOTHSRCALPHA
The driver supports the D3DBLEND_BOTHSRCALPHA blend mode. (This blend mode is obsolete. For more information, see D3DBLEND.)
D3DPBLENDCAPS_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DPBLENDCAPS_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DPBLENDCAPS_INVDESTALPHA
Blend factor is (1 - Ad, 1 - Ad, 1 - Ad, 1 - Ad).
D3DPBLENDCAPS_INVDESTCOLOR
Blend factor is (1-Rd, 1-Gd, 1-Bd, 1 - Ad).
D3DPBLENDCAPS_INVSRCALPHA
Blend factor is (1 - As, 1 - As, 1 - As, 1 - As).
D3DPBLENDCAPS_INVSRCCOLOR
Blend factor is (1-Rs, 1-Gs, 1-Bs, 1 - As).
D3DPBLENDCAPS_INVSRCCOLOR2
Direct3D 9Ex only - Blend factor is (1 - PSOutColor[1]r, 1 - PSOutColor[1]g, 1 - PSOutColor[1]b, not used)). See Render Target Blending.
D3DPBLENDCAPS_ONE
Blend factor is (1, 1, 1, 1).
D3DPBLENDCAPS_SRCALPHA
Blend factor is (As, As, As, As).
D3DPBLENDCAPS_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1 - Ad).
D3DPBLENDCAPS_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DPBLENDCAPS_SRCCOLOR2
Direct3D 9Ex only - Blend factor is (PSOutColor[1]r, PSOutColor[1]g, PSOutColor[1]b, not used). See Render Target Blending.
D3DPBLENDCAPS_ZERO
Blend factor is (0, 0, 0, 0).
DestBlendCaps
Destination-blending capabilities. This member can be the same capabilities that are defined for the SrcBlendCaps member.
AlphaCmpCaps
Alpha-test comparison capabilities. This member can include the same capability flags defined for the ZCmpCaps member. If this member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests. Otherwise, the flags identify the individual comparisons that are supported for alpha testing.
ShadeCaps
Shading operations capabilities. It is assumed, in general, that if a device supports a given command at all, it supports the D3DSHADE_FLAT mode (as specified in the D3DSHADEMODE enumerated type). This flag specifies whether the driver can also support Gouraud shading and whether alpha color components are supported. When alpha components are not supported, the alpha value of colors generated is implicitly 255. This is the maximum possible alpha (that is, the alpha component is at full intensity).

The color, specular highlights, fog, and alpha interpolants of a triangle each have capability flags that an application can use to find out how they are implemented by the device driver.

This member can be one or more of the following flags.

D3DPSHADECAPS_ALPHAGOURAUDBLEND
Device can support an alpha component for Gouraud-blended transparency (the D3DSHADE_GOURAUD state for the D3DSHADEMODE enumerated type). In this mode, the alpha color component of a primitive is provided at vertices and interpolated across a face along with the other color components.
D3DPSHADECAPS_COLORGOURAUDRGB
Device can support colored Gouraud shading. In this mode, the per-vertex color components (red, green, and blue) are interpolated across a triangle face.
D3DPSHADECAPS_FOGGOURAUD
Device can support fog in the Gouraud shading mode.
D3DPSHADECAPS_SPECULARGOURAUDRGB
Device supports Gouraud shading of specular highlights.
TextureCaps
Miscellaneous texture-mapping capabilities. This member can be one or more of the following flags.
D3DPTEXTURECAPS_ALPHA
Alpha in texture pixels is supported.
D3DPTEXTURECAPS_ALPHAPALETTE
Device can draw alpha from texture palettes.
D3DPTEXTURECAPS_CUBEMAP
Supports cube textures.
D3DPTEXTURECAPS_CUBEMAP_POW2
Device requires that cube texture maps have dimensions specified as powers of two.
D3DPTEXTURECAPS_MIPCUBEMAP
Device supports mipmapped cube textures.
D3DPTEXTURECAPS_MIPMAP
Device supports mipmapped textures.
D3DPTEXTURECAPS_MIPVOLUMEMAP
Device supports mipmapped volume textures.
D3DPTEXTURECAPS_NONPOW2CONDITIONAL

D3DPTEXTURECAPS_POW2 is also set, conditionally supports the use of 2D textures with dimensions that are not powers of two. A device that exposes this capability can use such a texture if all of the following requirements are met.

  • The texture addressing mode for the texture stage is set to D3DTADDRESS_CLAMP.
  • Texture wrapping for the texture stage is disabled (D3DRS_WRAP n set to 0).
  • Mipmapping is not in use (use magnification filter only).
  • Texture formats must not be D3DFMT_DXT1 through D3DFMT_DXT5.

If this flag is not set, and D3DPTEXTURECAPS_POW2 is also not set, then unconditional support is provided for 2D textures with dimensions that are not powers of two.

A texture that is not a power of two cannot be set at a stage that will be read based on a shader computation (such as the bem - ps and texm3x3 - ps instructions in pixel shaders versions 1_0 to 1_3). For example, these textures can be used to store bumps that will be fed into texture reads, but not the environment maps that are used in texbem - ps, texbeml - ps, and texm3x3spec - ps. This means that a texture with dimensions that are not powers of two cannot be addressed or sampled using texture coordinates computed within the shader. This type of operation is known as a dependent read and cannot be performed on these types of textures.

D3DPTEXTURECAPS_NOPROJECTEDBUMPENV
Device does not support a projected bump-environment loopkup operation in programmable and fixed function shaders.
D3DPTEXTURECAPS_PERSPECTIVE
Perspective correction texturing is supported.
D3DPTEXTURECAPS_POW2

If D3DPTEXTURECAPS_NONPOW2CONDITIONAL is not set, all textures must have widths and heights specified as powers of two. This requirement does not apply to either cube textures or volume textures.

If D3DPTEXTURECAPS_NONPOW2CONDITIONAL is also set, conditionally supports the use of 2D textures with dimensions that are not powers of two. See D3DPTEXTURECAPS_NONPOW2CONDITIONAL description.

If this flag is not set, and D3DPTEXTURECAPS_NONPOW2CONDITIONAL is also not set, then unconditional support is provided for 2D textures with dimensions that are not powers of two.

D3DPTEXTURECAPS_PROJECTED
Supports the D3DTTFF_PROJECTED texture transformation flag. When applied, the device divides transformed texture coordinates by the last texture coordinate. If this capability is present, then the projective divide occurs per pixel. If this capability is not present, but the projective divide needs to occur anyway, then it is performed on a per-vertex basis by the Direct3D runtime.
D3DPTEXTURECAPS_SQUAREONLY
All textures must be square.
D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE
Texture indices are not scaled by the texture size prior to interpolation.
D3DPTEXTURECAPS_VOLUMEMAP
Device supports volume textures.
D3DPTEXTURECAPS_VOLUMEMAP_POW2
Device requires that volume texture maps have dimensions specified as powers of two.
TextureFilterCaps
Texture-filtering capabilities for a texture. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending. This member can be any combination of the per-stage texture-filtering flags defined in D3DPTFILTERCAPS.
CubeTextureFilterCaps
Texture-filtering capabilities for a cube texture. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending. This member can be any combination of the per-stage texture-filtering flags defined in D3DPTFILTERCAPS.
VolumeTextureFilterCaps
Texture-filtering capabilities for a volume texture. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending. This member can be any combination of the per-stage texture-filtering flags defined in D3DPTFILTERCAPS.
TextureAddressCaps
Texture-addressing capabilities for texture objects. This member can be one or more of the following flags.
D3DPTADDRESSCAPS_BORDER
Device supports setting coordinates outside the range [0.0, 1.0] to the border color, as specified by the D3DSAMP_BORDERCOLOR texture-stage state.
D3DPTADDRESSCAPS_CLAMP
Device can clamp textures to addresses.
D3DPTADDRESSCAPS_INDEPENDENTUV
Device can separate the texture-addressing modes of the u and v coordinates of the texture. This ability corresponds to the D3DSAMP_ADDRESSU and D3DSAMP_ADDRESSV render-state values.
D3DPTADDRESSCAPS_MIRROR
Device can mirror textures to addresses.
D3DPTADDRESSCAPS_MIRRORONCE
Device can take the absolute value of the texture coordinate (thus, mirroring around 0) and then clamp to the maximum value.
D3DPTADDRESSCAPS_WRAP
Device can wrap textures to addresses.
VolumeTextureAddressCaps
Texture-addressing capabilities for a volume texture. This member can be one or more of the flags defined for the TextureAddressCaps member.
LineCaps
Defines the capabilities for line-drawing primitives.
D3DLINECAPS_ALPHACMP
Supports alpha-test comparisons.
D3DLINECAPS_ANTIALIAS
Antialiased lines are supported.
D3DLINECAPS_BLEND
Supports source-blending.
D3DLINECAPS_FOG
Supports fog.
D3DLINECAPS_TEXTURE
Supports texture-mapping.
D3DLINECAPS_ZTEST
Supports z-buffer comparisons.
MaxTextureWidth
Maximum texture width for this device.
MaxTextureHeight
Maximum texture height for this device.
MaxVolumeExtent
Maximum value for any of the three dimensions (width, height, and depth) of a volume texture.
MaxTextureRepeat
This number represents the maximum range of the integer bits of the post-normalized texture coordinates. A texture coordinate is stored as a 32-bit signed integer using 27 bits to store the integer part and 5 bits for the floating point fraction. The maximum integer index, 227, is used to determine the maximum texture coordinate, depending on how the hardware does texture-coordinate scaling.

Some hardware reports the cap D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE. For this case, the device defers scaling texture coordinates by the texture size until after interpolation and application of the texture address mode, so the number of times a texture can be wrapped is given by the integer value in MaxTextureRepeat.

Less desirably, on some hardware D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is not set and the device scales the texture coordinates by the texture size (using the highest level of detail) prior to interpolation. This limits the number of times a texture can be wrapped to MaxTextureRepeat / texture size.

For example, assume that MaxTextureRepeat is equal to 32k and the size of the texture is 4k. If the hardware sets D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE, then the number of times a texture can be wrapped is equal to MaxTextureRepeat, which is 32k in this example. Otherwise, the number of times a texture can be wrapped is equal to MaxTextureRepeat divided by texture size, which is 32k/4k in this example.

MaxTextureAspectRatio
Maximum texture aspect ratio supported by the hardware, typically a power of 2.
MaxAnisotropy
Maximum valid value for the D3DSAMP_MAXANISOTROPY texture-stage state.
MaxVertexW
Maximum W-based depth value that the device supports.
GuardBandLeft
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
GuardBandTop
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
GuardBandRight
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
GuardBandBottom
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
ExtentsAdjust
Number of pixels to adjust the extents rectangle outward to accommodate antialiasing kernels.
StencilCaps
Flags specifying supported stencil-buffer operations. Stencil operations are assumed to be valid for all three stencil-buffer operation render states (D3DRS_STENCILFAIL, D3DRS_STENCILPASS, and D3DRS_STENCILZFAIL).

For more information, see D3DSTENCILCAPS.

FVFCaps
Flexible vertex format capabilities.
D3DFVFCAPS_DONOTSTRIPELEMENTS
It is preferable that vertex elements not be stripped. That is, if the vertex format contains elements that are not used with the current render states, there is no need to regenerate the vertices. If this capability flag is not present, stripping extraneous elements from the vertex format provides better performance.
D3DFVFCAPS_PSIZE
Point size is determined by either the render state or the vertex data. If an FVF is used, point size can come from point size data in the vertex declaration. Otherwise, point size is determined by the render state D3DRS_POINTSIZE. If the application provides point size in both (the render state and the vertex declaration), the vertex data overrides the render-state data.
D3DFVFCAPS_TEXCOORDCOUNTMASK
Masks the low WORD of FVFCaps. These bits, cast to the WORD data type, describe the total number of texture coordinate sets that the device can simultaneously use for multiple texture blending. (You can use up to eight texture coordinate sets for any vertex, but the device can blend using only the specified number of texture coordinate sets.)
TextureOpCaps
Combination of flags describing the texture operations supported by this device. The following flags are defined.
D3DTEXOPCAPS_ADD
The D3DTOP_ADD texture-blending operation is supported.
D3DTEXOPCAPS_ADDSIGNED
The D3DTOP_ADDSIGNED texture-blending operation is supported.
D3DTEXOPCAPS_ADDSIGNED2X
The D3DTOP_ADDSIGNED2X texture-blending operation is supported.
D3DTEXOPCAPS_ADDSMOOTH
The D3DTOP_ADDSMOOTH texture-blending operation is supported.
D3DTEXOPCAPS_BLENDCURRENTALPHA
The D3DTOP_BLENDCURRENTALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDDIFFUSEALPHA
The D3DTOP_BLENDDIFFUSEALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDFACTORALPHA
The D3DTOP_BLENDFACTORALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHA
The D3DTOP_BLENDTEXTUREALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHAPM
The D3DTOP_BLENDTEXTUREALPHAPM texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAP
The D3DTOP_BUMPENVMAP texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAPLUMINANCE
The D3DTOP_BUMPENVMAPLUMINANCE texture-blending operation is supported.
D3DTEXOPCAPS_DISABLE
The D3DTOP_DISABLE texture-blending operation is supported.
D3DTEXOPCAPS_DOTPRODUCT3
The D3DTOP_DOTPRODUCT3 texture-blending operation is supported.
D3DTEXOPCAPS_LERP
The D3DTOP_LERP texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE
The D3DTOP_MODULATE texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE2X
The D3DTOP_MODULATE2X texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE4X
The D3DTOP_MODULATE4X texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR
The D3DTOP_MODULATEALPHA_ADDCOLOR texture-blending operation is supported.
D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA
The D3DTOP_MODULATECOLOR_ADDALPHA texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR
The D3DTOP_MODULATEINVALPHA_ADDCOLOR texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA
The D3DTOP_MODULATEINVCOLOR_ADDALPHA texture-blending operation is supported.
D3DTEXOPCAPS_MULTIPLYADD
The D3DTOP_MULTIPLYADD texture-blending operation is supported.
D3DTEXOPCAPS_PREMODULATE
The D3DTOP_PREMODULATE texture-blending operation is supported.
D3DTEXOPCAPS_SELECTARG1
The D3DTOP_SELECTARG1 texture-blending operation is supported.
D3DTEXOPCAPS_SELECTARG2
The D3DTOP_SELECTARG2 texture-blending operation is supported.
D3DTEXOPCAPS_SUBTRACT
The D3DTOP_SUBTRACT texture-blending operation is supported.
MaxTextureBlendStages
Maximum number of texture-blending stages supported in the fixed function pipeline. This value is the number of blenders available. In the programmable pixel pipeline, this corresponds to the number of unique texture registers used by pixel shader instructions.
MaxSimultaneousTextures
Maximum number of textures that can be simultaneously bound to the fixed-function pipeline sampler stages. If the same texture is bound to two sampler stages, it counts as two textures.

This value has no meaning in the programmable pipeline where the number of sampler stages is determined by each pixel shader version. Each pixel shader version also determines the number of texture declaration instructions. See Pixel Shaders.

VertexProcessingCaps
Vertex processing capabilities. For a given physical device, this capability might vary across Direct3D devices depending on the parameters supplied to IDirect3D9::CreateDevice. See D3DVTXPCAPS.
MaxActiveLights
Maximum number of lights that can be active simultaneously. For a given physical device, this capability might vary across Direct3D devices depending on the parameters supplied to IDirect3D9::CreateDevice.
MaxUserClipPlanes
Maximum number of user-defined clipping planes supported. This member can be 0. For a given physical device, this capability may vary across Direct3D devices depending on the parameters supplied to IDirect3D9::CreateDevice.
MaxVertexBlendMatrices
Maximum number of matrices that this device can apply when performing multimatrix vertex blending. For a given physical device, this capability may vary across Direct3D devices depending on the parameters supplied to IDirect3D9::CreateDevice.
MaxVertexBlendMatrixIndex
DWORD value that specifies the maximum matrix index that can be indexed into using the per-vertex indices. The number of matrices is MaxVertexBlendMatrixIndex + 1, which is the size of the matrix palette. If normals are present in the vertex data that needs to be blended for lighting, then the number of matrices is half the number specified by this capability flag. If MaxVertexBlendMatrixIndex is set to zero, the driver does not support indexed vertex blending. If this value is not zero then the valid range of indices is zero through MaxVertexBlendMatrixIndex.

A zero value for MaxVertexBlendMatrixIndex indicates that the driver does not support indexed matrices.

When software vertex processing is used, 256 matrices could be used for indexed vertex blending, with or without normal blending.

For a given physical device, this capability may vary across Direct3D devices depending on the parameters supplied to IDirect3D9::CreateDevice.

MaxPointSize
Maximum size of a point primitive. If set to 1.0f then device does not support point size control. The range is greater than or equal to 1.0f.
MaxPrimitiveCount
Maximum number of primitives for each IDirect3DDevice9::DrawPrimitive call. There are two cases:
  • If MaxPrimitiveCount is not equal to 0xffff, you can draw at most MaxPrimitiveCount primitives with each draw call.
  • However, if MaxPrimitiveCount equals 0xffff, you can still draw at most MaxPrimitiveCount primitive, but you may also use no more than MaxPrimitiveCount unique vertices (since each primitive can potentially use three different vertices).
MaxVertexIndex
Maximum size of indices supported for hardware vertex processing. It is possible to create 32-bit index buffers; however, you will not be able to render with the index buffer unless this value is greater than 0x0000FFFF.
MaxStreams
Maximum number of concurrent data streams for IDirect3DDevice9::SetStreamSource. The valid range is 1 to 16. Note that if this value is 0, then the driver is not a Direct3D 9 driver.
MaxStreamStride
Maximum stride for IDirect3DDevice9::SetStreamSource.
VertexShaderVersion
Two numbers that represent the vertex shader main and sub versions. For more information about the instructions supported for each vertex shader version, see Version 1_x, Version 2_0, Version 2_0 Extended, or Version 3_0.
MaxVertexShaderConst
The number of vertex shader Vertex Shader Registers that are reserved for constants.
PixelShaderVersion
Two numbers that represent the pixel shader main and sub versions. For more information about the instructions supported for each pixel shader version, see Version 1_x, Version 2_0, Version 2_0 Extended, or Version 3_0.
PixelShader1xMaxValue
Maximum value of pixel shader arithmetic component. This value indicates the internal range of values supported for pixel color blending operations. Within the range that they report to, implementations must allow data to pass through pixel processing unmodified (unclamped). Normally, the value of this member is an absolute value. For example, a 1.0 indicates that the range is -1.0 to 1, and an 8.0 indicates that the range is -8.0 to 8.0. The value must be >= 1.0 for any hardware that supports pixel shaders.
DevCaps2
Device driver capabilities for adaptive tessellation. For more information, see D3DDEVCAPS2
MasterAdapterOrdinal
This number indicates which device is the master for this subordinate. This number is taken from the same space as the adapter values.

For multihead support, one head will be denoted the master head, and all other heads on the same card will be denoted subordinate heads. If more than one multihead adapter is present in a system, the master and its subordinates from one multihead adapter are called a group.

AdapterOrdinalInGroup
This number indicates the order in which heads are referenced by the API. The value for the master adapter is always 0. These values do not correspond to the adapter ordinals. They apply only to heads within a group.
NumberOfAdaptersInGroup
Number of adapters in this adapter group (only if master). This will be 1 for conventional adapters. The value will be greater than 1 for the master adapter of a multihead card. The value will be 0 for a subordinate adapter of a multihead card. Each card can have at most one master, but may have many subordinates.
DeclTypes
A combination of one or more data types contained in a vertex declaration. See D3DDTCAPS.
NumSimultaneousRTs
Number of simultaneous render targets. This number must be at least one.
StretchRectFilterCaps
Combination of constants that describe the operations supported by IDirect3DDevice9::StretchRect. The flags that may be set in this field are:
Constant | Description
D3DPTFILTERCAPS_MINFPOINT | Device supports point-sample filtering for minifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_POINT.
D3DPTFILTERCAPS_MAGFPOINT | Device supports point-sample filtering for magnifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_POINT.
D3DPTFILTERCAPS_MINFLINEAR | Device supports bilinear interpolation filtering for minifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_LINEAR.
D3DPTFILTERCAPS_MAGFLINEAR | Device supports bilinear interpolation filtering for magnifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_LINEAR.

For more information, see D3DTEXTUREFILTERTYPE and D3DTEXTUREFILTERTYPE.

VS20Caps
Device supports vertex shader version 2_0 extended capability. See D3DVSHADERCAPS2_0.
D3DPSHADERCAPS2_0
Device supports pixel shader version 2_0 extended capability. See D3DPSHADERCAPS2_0.
VertexTextureFilterCaps
Device supports vertex shader texture filter capability. See D3DPTFILTERCAPS.
MaxVShaderInstructionsExecuted
Maximum number of vertex shader instructions that can be run when using flow control. The maximum number of instructions that can be programmed is MaxVertexShader30InstructionSlots.
MaxPShaderInstructionsExecuted
Maximum number of pixel shader instructions that can be run when using flow control. The maximum number of instructions that can be programmed is MaxPixelShader30InstructionSlots.
MaxVertexShader30InstructionSlots
Maximum number of vertex shader instruction slots supported. The maximum value that can be set on this cap is 32768. Devices that support vs_3_0 are required to support at least 512 instruction slots.
MaxPixelShader30InstructionSlots
Maximum number of pixel shader instruction slots supported. The maximum value that can be set on this cap is 32768. Devices that support ps_3_0 are required to support at least 512 instruction slots.
Reserved2
Reserved.
Reserved3
Reserved.

Remarks

The MaxTextureBlendStages and MaxSimultaneousTextures members might seem similar, but they contain different information. The MaxTextureBlendStages member contains the total number of texture-blending stages supported by the current device, and the MaxSimultaneousTextures member describes how many of those stages can have textures bound to them by using the IDirect3DDevice9::SetTexture method.

When the driver fills this structure, it can set values for execute-buffer capabilities, even when the interface being used to retrieve the capabilities (such as IDirect3DDevice9) does not support execute buffers.

In general, performance problems may occur if you use a texture and then modify it during a scene. Ensure that no texture used in the current IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene block is evicted unless absolutely necessary. In the case of extremely high texture usage within a scene, the results are undefined. This occurs when you modify a texture that you have used in the scene and there is no spare texture memory available. For such systems, the contents of the z-buffer become invalid at EndScene. Applications should not call IDirect3DDevice9::UpdateSurface to or from the back buffer on this type of hardware inside a BeginScene/EndScene pair. In addition, applications should not try to access the z-buffer if the D3DPRASTERCAPS_ZBUFFERLESSHSR capability flag is set. Finally, applications should not lock the back buffer or the z-buffer inside a BeginScene/EndScene pair.

The following flags concerning mipmapped textures are not supported in Direct3D 9.

  • D3DPTFILTERCAPS_LINEAR
  • D3DPTFILTERCAPS_LINEARMIPLINEAR
  • D3DPTFILTERCAPS_LINEARMIPNEAREST
  • D3DPTFILTERCAPS_MIPNEAREST
  • D3DPTFILTERCAPS_NEAREST

See Also

IDirect3D9::GetDeviceCaps, IDirect3DDevice9::GetDeviceCaps


D3DCLIPSTATUS9

Describes the current clip status.

typedef struct D3DCLIPSTATUS9 {
    DWORD ClipUnion;
    DWORD ClipIntersection;
} D3DCLIPSTATUS9, *LPD3DCLIPSTATUS9;

Members

ClipUnion
Clip union flags that describe the current clip status. This member can be one or more of the following flags:
D3DCS_ALL
Combination of all clip flags.
D3DCS_LEFT
All vertices are clipped by the left plane of the viewing frustum.
D3DCS_RIGHT
All vertices are clipped by the right plane of the viewing frustum.
D3DCS_TOP
All vertices are clipped by the top plane of the viewing frustum.
D3DCS_BOTTOM
All vertices are clipped by the bottom plane of the viewing frustum.
D3DCS_FRONT
All vertices are clipped by the front plane of the viewing frustum.
D3DCS_BACK
All vertices are clipped by the back plane of the viewing frustum.
D3DCS_PLANE0
Application-defined clipping planes.
D3DCS_PLANE1
Application-defined clipping planes.
D3DCS_PLANE2
Application-defined clipping planes.
D3DCS_PLANE3
Application-defined clipping planes.
D3DCS_PLANE4
Application-defined clipping planes.
D3DCS_PLANE5
Application-defined clipping planes.
ClipIntersection
Clip intersection flags that describe the current clip status. This member can take the same flags as ClipUnion.

Remarks

When clipping is enabled during vertex processing (by IDirect3DDevice9::ProcessVertices, IDirect3DDevice9::DrawPrimitive, or other drawing functions), Direct3D computes a clip code for every vertex. The clip code is a combination of D3DCS_* bits. When a vertex is outside a particular clipping plane, the corresponding bit is set in the clipping code. Direct3D maintains the clip status using D3DCLIPSTATUS9, which has ClipUnion and ClipIntersection members. ClipUnion is a bitwise OR of all vertex clip codes and ClipIntersection is a bitwise AND of all vertex clip codes. Initial values are zero for ClipUnion and 0xFFFFFFFF for ClipIntersection. When D3DRS_CLIPPING is set to FALSE, ClipUnion and ClipIntersection are set to zero. Direct3D updates the clip status during drawing calls. To compute clip status for a particular object, set ClipUnion and ClipIntersection to their initial value and continue drawing.

Clip status is not updated by IDirect3DDevice9::DrawRectPatch and IDirect3DDevice9::DrawTriPatch because there is no software emulation for them.

See Also

IDirect3DDevice9::GetClipStatus, IDirect3DDevice9::SetClipStatus, IDirect3DDevice9::SetClipStatus


D3DCOLOR

Defines the fundamental Direct3D color type.

typedef DWORD D3DCOLOR;

Remarks

A four byte value that typically represents the alpha, red, green, and blue components of a color. It can also represent luminance and brightness.

You can set the D3DCOLOR type using one of the following macros.

  • D3DCOLOR_ARGB
  • D3DCOLOR_AYUV
  • D3DCOLOR_COLORVALUE
  • D3DCOLOR_RGBA
  • D3DCOLOR_XRGB
  • D3DCOLOR_XYUV

Requirements

Header: Declared in D3d9types.h.


D3DCOMPOSERECTDESC (DirectX 9Ex only)

Specifies the rectangle used to enclose glyphs on a monochrome surface.

typedef struct _D3DCOMPOSERECTDESC {
    USHORT X;
    USHORT Y;
    USHORT Width;
    USHORT Height;
} D3DCOMPOSERECTDESC (DirectX 9Ex only);

Members

X
Left coordinate to begin copy at.
Y
Top coordinate to begin copy at.
Width
Number of texels from left coordinate.
Height
Number of texels from the top coordinate.

Remarks

This structure is used in calls to IDirect3DDevice9Ex::ComposeRect to enclose glyphs on the source surface. A vertex buffer (see IDirect3DVertexBuffer9) filled with these structures are created to contain the glyph locations. USHORT members are used to reduce the memory footprint as much as possible.

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Structures


D3DCOMPOSERECTDESTINATION (DirectX 9Ex only)

Specifies the source glyph and location in a monochrome surface to copy glyphs into.

typedef struct _D3DCOMPOSERECTDESTINATION {
    USHORT SrcRectIndex;
    USHORT Reserved;
    USHORT X;
    USHORT Y;
} D3DCOMPOSERECTDESTINATION (DirectX 9Ex only);

Members

SrcRectIndex
Index particular glyph from vertex buffer containing D3DCOMPOSERECTDESC (DirectX 9Ex only) structures.
Reserved
Reserved for alignment purposes.
X
Left coordinate to begin copy at.
Y
Top coordinate to begin copy at.

Remarks

This structure is used in calls to IDirect3DDevice9Ex::ComposeRect to indicate the locaiton glyphs should be copied to and which particular glyph should be copied. A vertex buffer (see IDirect3DVertexBuffer9) filled with these structures are created to contain the glyph locations. USHORT members are used to reduce the memory footprint as much as possible.

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Structures


D3DCOLORVALUE

Describes color values.

typedef struct D3DCOLORVALUE {
    float r;
    float g;
    float b;
    float a;
} D3DCOLORVALUE, *LPD3DCOLORVALUE;

Members

r
Floating-point value specifying the red component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
g
Floating-point value specifying the green component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
b
Floating-point value specifying the blue component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
a
Floating-point value specifying the alpha component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.

Remarks

You can set the members of this structure to values outside the range of 0 through 1 to implement some unusual effects. Values greater than 1 produce strong lights that tend to wash out a scene. Negative values produce dark lights that actually remove light from a scene.


D3DDEVICE_CREATION_PARAMETERS

Describes the creation parameters for a device.

typedef struct D3DDEVICE_CREATION_PARAMETERS {
    UINT AdapterOrdinal;
    D3DDEVTYPE DeviceType;
    HWND hFocusWindow;
    DWORD BehaviorFlags;
} D3DDEVICE_CREATION_PARAMETERS, *LPD3DDEVICE_CREATION_PARAMETERS;

Members

AdapterOrdinal
Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter. Use this ordinal as the Adapter parameter for any of the IDirect3D9 methods. Note that different instances of Direct3D 9.0 objects can use different ordinals. Adapters can enter or leave a system when users, for example, add or remove monitors from a multiple-monitor system or when they hot-swap a laptop. Consequently, use this ordinal only in a Direct3D 9.0 instance known to be valid, that is, either the Direct3D 9.0 that created this IDirect3DDevice9 interface or the Direct3D 9.0 returned from IDirect3DDevice9::GetDirect3D, as called through this IDirect3DDevice9 interface.
DeviceType
Member of the D3DDEVTYPE enumerated type. Denotes the amount of emulated functionality for this device. The value of this parameter mirrors the value passed to the IDirect3D9::CreateDevice call that created this device.
hFocusWindow
Window handle to which focus belongs for this Direct3D device. The value of this parameter mirrors the value passed to the IDirect3D9::CreateDevice call that created this device.
BehaviorFlags
A combination of one or more D3DCREATE constants that control global behavior of the device. These constants mirror the constants passed to IDirect3D9::CreateDevice when the device was created.

See Also

IDirect3DDevice9::GetCreationParameters, IDirect3D9::CreateDevice


D3DDEVINFO_D3D9BANDWIDTHTIMINGS

Throughput metrics for help in understanding the performance of an application.

typedef struct D3DDEVINFO_D3D9BANDWIDTHTIMINGS {
    FLOAT MaxBandwidthUtilized;
    FLOAT FrontEndUploadMemoryUtilizedPercent;
    FLOAT VertexRateUtilizedPercent;
    FLOAT TriangleSetupRateUtilizedPercent;
    FLOAT FillRateUtilizedPercent;
} D3DDEVINFO_D3D9BANDWIDTHTIMINGS, *LPD3DDEVINFO_D3D9BANDWIDTHTIMINGS;

Members

MaxBandwidthUtilized
The bandwidth or maximum data transfer rate from the host CPU to the GPU. This is typically the bandwidth of the PCI or AGP bus which connects the CPU and the GPU.
FrontEndUploadMemoryUtilizedPercent
Memory utilized percentage when uploading data from the host CPU to the GPU.
VertexRateUtilizedPercent
Vertex throughput percentage. This is the number of vertices processed compared to the theoretical maximum vertex processing rate.
TriangleSetupRateUtilizedPercent
Triangle set-up throughput percentage. This is the number of triangles that are set up for rasterization compared to the theoretical maximum triangle set-up rate.
FillRateUtilizedPercent
Pixel fill throughput percentage. This is the number of pixels that are filled compared to the theoretical pixel fill.

Remarks

See Also

IDirect3DQuery9::GetData


D3DDEVINFO_D3D9CACHEUTILIZATION

Measure the cache hit rate performance for textures and indexed vertices.

typedef struct D3DDEVINFO_D3D9CACHEUTILIZATION {
    FLOAT TextureCacheHitRate;
    FLOAT PostTransformVertexCacheHitRate;
} D3DDEVINFO_D3D9CACHEUTILIZATION, *LPD3DDEVINFO_D3D9CACHEUTILIZATION;

Members

TextureCacheHitRate
The hit rate for finding a texture in the texture cache. This assumes there is a texture cache. Increasing the level-of-detail bias to use the most detailed texture, using many large textures, or producing a near random texture access pattern on large textures with custom shader code can dramatically affect the texture cache hit rate.
PostTransformVertexCacheHitRate
The hit rate for finding transformed vertices in the vertex cache. The GPU is designed to transform indexed vertices and may store them in a vertex cache. If you are using meshes, D3DXOptimizeFaces or D3DXOptimizeVertices may result in better vertex cache utilization.

Remarks

An efficient cache is typically closer to a 90 percent hit rate, and an inefficient cache is typically closer to a 10 percent hit rate (although a low percentage is not necessarily a problem).

See Also

IDirect3DQuery9::GetData


D3DDEVINFO_D3D9INTERFACETIMINGS

Percent of time processing data in the driver. These statistics may help identify cases when the driver is waiting for other resources.

typedef struct D3DDEVINFO_D3D9INTERFACETIMINGS {
    FLOAT WaitingForGPUToUseApplicationResourceTimePercent;
    FLOAT WaitingForGPUToAcceptMoreCommandsTimePercent;
    FLOAT WaitingForGPUToStayWithinLatencyTimePercent;
    FLOAT WaitingForGPUExclusiveResourceTimePercent;
    FLOAT WaitingForGPUOtherTimePercent;
} D3DDEVINFO_D3D9INTERFACETIMINGS, *LPD3DDEVINFO_D3D9INTERFACETIMINGS;

Members

WaitingForGPUToUseApplicationResourceTimePercent
Percentage of time the driver spent waiting for the GPU to finish using a locked resource (and D3DLOCK_DONOTWAIT wasn't specified).
WaitingForGPUToAcceptMoreCommandsTimePercent
Percentage of time the driver spent waiting for the GPU to finish processing some commands before the driver could send more. This indicates the driver has run out of room to send commands to the GPU.
WaitingForGPUToStayWithinLatencyTimePercent

Percentage of time the driver spent waiting for the GPU latency to reduce to less than three rendering frames.

If an application is GPU-limited, the driver must stall the CPU until the GPU gets within three frames. This prevents an application from queueing up many seconds' worth of rendering calls which may dramatically increase the latency between when the user inputs new data and when the user sees the results of that input. In general, the driver can track the number of times IDirect3DDevice9::Present is called to prevent queueing up more than three frames of rendering work.

WaitingForGPUExclusiveResourceTimePercent
Percentage of time the driver spent waiting for a resource that cannot be pipelined (that is operated in parallel). An application may want to avoid using a non-pipelined resource for performance reasons.
WaitingForGPUOtherTimePercent
Percentage of time the driver spent waiting for other GPU processing.

Remarks

These metrics help identify when a driver is waiting and what it is waiting for. High percentages are not necessarily a problem.

These system-global metrics may or may not be implemented. Depending on the specific hardware, these metrics may not support multiple queries simultaneously.

See Also

IDirect3DQuery9::GetData


D3DDEVINFO_D3D9PIPELINETIMINGS

Percent of time processing data in the pipeline.

typedef struct D3DDEVINFO_D3D9PIPELINETIMINGS {
    FLOAT VertexProcessingTimePercent;
    FLOAT PixelProcessingTimePercent;
    FLOAT OtherGPUProcessingTimePercent;
    FLOAT GPUIdleTimePercent;
} D3DDEVINFO_D3D9PIPELINETIMINGS, *LPD3DDEVINFO_D3D9PIPELINETIMINGS;

Members

VertexProcessingTimePercent
Percent of time spent running vertex shaders.
PixelProcessingTimePercent
Percent of time spent running pixel shaders.
OtherGPUProcessingTimePercent
Percent of time spent doing other processing.
GPUIdleTimePercent
Percent of time not processing anything.

Remarks

For best performance, a balanced load is recommended.

See Also

IDirect3DQuery9::GetData


D3DDEVINFO_D3D9STAGETIMINGS

Percent of time processing shader data.

typedef struct D3DDEVINFO_D3D9STAGETIMINGS {
    FLOAT MemoryProcessingPercent;
    FLOAT ComputationProcessingPercent;
} D3DDEVINFO_D3D9STAGETIMINGS, *LPD3DDEVINFO_D3D9STAGETIMINGS;

Members

MemoryProcessingPercent
Percent of time in shader spent on memory accesses.
ComputationProcessingPercent
Percent of time processing (moving data around in registers or doing mathematical operations).

Remarks

For best performance, a balanced load is recommended.

See Also

IDirect3DQuery9::GetData


D3DDEVINFO_D3DVERTEXSTATS

Reports the number of triangles that have been processed and clipped by the runtime's software vertex processing.

typedef struct D3DDEVINFO_D3DVERTEXSTATS {
    DWORD NumRenderedTriangles;
    DWORD NumExtraClippingTriangles;
} D3DDEVINFO_D3DVERTEXSTATS, *LPD3DDEVINFO_D3DVERTEXSTATS;

Members

NumRenderedTriangles
Total number of triangles that are not clipped in this frame.
NumExtraClippingTriangles
Number of new triangles generated by clipping.

Remarks

Use the debug runtime and software vertex processing to get the number of non-clipped and clipped primitives for a particular scene. Primitives will typically be clipped based on a guard band (if one is present). The clipping guard band is set with parameters such as GuardBandLeft in D3DCAPS9.


D3DDEVINFO_ResourceManager

Resource usage statistics.

typedef struct D3DDEVINFO_ResourceManager {
    D3DRESOURCESTATS stats[D3DRTYPECOUNT];
} D3DDEVINFO_ResourceManager, *LPD3DDEVINFO_ResourceManager;

Members

stats
Array of resource statistics elements. See D3DRESOURCESTATS.

Remarks

D3DRTYPECOUNT refers to the number of enumerations in D3DRESOURCETYPE.


D3DDEVINFO_VCACHE

Vertex cache optimization hints.

typedef struct D3DDEVINFO_VCACHE {
    DWORD Pattern;
    DWORD OptMethod;
    DWORD CacheSize;
    DWORD MagicNumber;
} D3DDEVINFO_VCACHE, *LPD3DDEVINFO_VCACHE;

Members

Pattern
Bit pattern. Return value must be the FOURCC ('C', 'A', 'C', 'H').
OptMethod
Optimizations method. Use 0 to get the longest strips. Use 1 to optimize the vertex cache usage.
CacheSize
Cache size used as a target for optimization. This is required only if OptMethod is 1.
MagicNumber
Used by internal optimization methods to determine when to restart strips. This cannot be set or modified by a user. This is required only if OptMethod is 1.

See Also

IDirect3DQuery9::GetData


D3DDISPLAYMODE

Describes the display mode.

typedef struct D3DDISPLAYMODE {
    UINT Width;
    UINT Height;
    UINT RefreshRate;
    D3DFORMAT Format;
} D3DDISPLAYMODE, *LPD3DDISPLAYMODE;

Members

Width
Screen width, in pixels.
Height
Screen height, in pixels.
RefreshRate
Refresh rate. The value of 0 indicates an adapter default.
Format
Member of the D3DFORMAT enumerated type, describing the surface format of the display mode.

See Also

IDirect3D9::EnumAdapterModes, IDirect3D9::GetAdapterDisplayMode, IDirect3DDevice9::GetDisplayMode


D3DDISPLAYMODEEX (DirectX 9Ex only)

Information about the properties of a display mode.

typedef struct  {
    UINT Size;
    UINT Width;
    UINT Height;
    UINT RefreshRate;
    D3DFORMAT Format;
    D3DSCANLINEORDERING ScanLineOrdering;
} D3DDISPLAYMODEEX (DirectX 9Ex only);

Members

Size
The size of this structure. This should always be set to sizeof(D3DDISPLAYMODEEX).
Width
Width of the display mode.
Height
Height of the display mode.
RefreshRate
Refresh rate of the display mode.
Format
Format of the display mode. See D3DFORMAT.
ScanLineOrdering
Indicates whether the scanline order is progressive or interlaced. See D3DSCANLINEORDERING (DirectX 9Ex only).

Remarks

This structure is used in various methods to create and manage Direct3D 9Ex devices (IDirect3DDevice9Ex) and swapchains (IDirect3DSwapChain9Ex).

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Structures


D3DDISPLAYMODEFILTER (DirectX 9Ex only)

Specifies types of display modes to filter out.

typedef struct  {
    UINT Size;
    D3DFORMAT Format;
    D3DSCANLINEORDERING ScanLineOrdering;
} D3DDISPLAYMODEFILTER (DirectX 9Ex only);

Members

Size
The size of this structure. This should always be set to sizeof(D3DDISPLAYMODEFILTER).
Format
The display mode format to filter out. See D3DFORMAT.
ScanLineOrdering
Whether the scanline ordering is interlaced or progressive. See D3DSCANLINEORDERING (DirectX 9Ex only).

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Structures


D3DGAMMARAMP

Contains red, green, and blue ramp data.

typedef struct D3DGAMMARAMP {
    WORD red[256];
    WORD green[256];
    WORD blue[256];
} D3DGAMMARAMP, *LPD3DGAMMARAMP;

Members

red
Array of 256 WORD element that describes the red gamma ramp.
green
Array of 256 WORD element that describes the green gamma ramp.
blue
Array of 256 WORD element that describes the blue gamma ramp.

See Also

IDirect3DDevice9::GetGammaRamp, IDirect3DDevice9::SetGammaRamp


D3DINDEXBUFFER_DESC

Describes an index buffer.

typedef struct D3DINDEXBUFFER_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    UINT Size;
} D3DINDEXBUFFER_DESC, *LPD3DINDEXBUFFER_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the index buffer data.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as an index buffer.
Usage
Combination of one or more of the following flags, specifying the usage for this resource.
D3DUSAGE_DONOTCLIP
Set to indicate that the index buffer content will never require clipping.
D3DUSAGE_DYNAMIC

Set to indicate that the index buffer requires dynamic memory use. This is useful for drivers because it enables them to decide where to place the buffer. In general, static index buffers are placed in video memory and dynamic index buffers are placed in AGP memory. Note that there is no separate static usage; if you do not specify D3DUSAGE_DYNAMIC the index buffer is made static. D3DUSAGE_DYNAMIC is strictly enforced through the D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE locking flags. As a result, D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE are only valid on index buffers created with D3DUSAGE_DYNAMIC; they are not valid flags on static vertex buffers.

For more information about using dynamic index buffers, see Using Dynamic Vertex and Index Buffers.

Note that D3DUSAGE_DYNAMIC cannot be specified on managed index buffers. For more information, see Managing Resources (Direct3D 9).

D3DUSAGE_RTPATCHES
Set to indicate when the index buffer is to be used for drawing high-order primitives.
D3DUSAGE_NPATCHES
Set to indicate when the index buffer is to be used for drawing N patches.
D3DUSAGE_POINTS
Set to indicate when the index buffer is to be used for drawing point sprites or indexed point lists.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the buffer is to be used with software processing.
D3DUSAGE_WRITEONLY
Informs the system that the application writes only to the index buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from an index buffer that is created with this capability can result in degraded performance.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this index buffer.
Size
Size of the index buffer, in bytes.

See Also

IDirect3DIndexBuffer9::GetDesc, Index Buffers (Direct3D 9)


D3DLIGHT9

Defines a set of lighting properties.

typedef struct D3DLIGHT9 {
    D3DLIGHTTYPE Type;
    D3DCOLORVALUE Diffuse;
    D3DCOLORVALUE Specular;
    D3DCOLORVALUE Ambient;
    D3DVECTOR Position;
    D3DVECTOR Direction;
    float Range;
    float Falloff;
    float Attenuation0;
    float Attenuation1;
    float Attenuation2;
    float Theta;
    float Phi;
} D3DLIGHT9, *LPD3DLIGHT;

Members

Type
Type of the light source. This value is one of the members of the D3DLIGHTTYPE enumerated type.
Diffuse
Diffuse color emitted by the light. This member is a D3DCOLORVALUE structure.
Specular
Specular color emitted by the light. This member is a D3DCOLORVALUE structure.
Ambient
Ambient color emitted by the light. This member is a D3DCOLORVALUE structure.
Position
Position of the light in world space, specified by a D3DVECTOR structure. This member has no meaning for directional lights and is ignored in that case.
Direction
Direction that the light is pointing in world space, specified by a D3DVECTOR structure. This member has meaning only for directional and spotlights. This vector need not be normalized, but it should have a nonzero length.
Range
Distance beyond which the light has no effect. The maximum allowable value for this member is the square root of FLT_MAX. This member does not affect directional lights.
Falloff

Decrease in illumination between a spotlight's inner cone (the angle specified by Theta) and the outer edge of the outer cone (the angle specified by Phi).

The effect of falloff on the lighting is subtle. Furthermore, a small performance penalty is incurred by shaping the falloff curve. For these reasons, most developers set this value to 1.0.

Attenuation0
Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Properties (Direct3D 9). Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
Attenuation1
Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Properties (Direct3D 9). Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
Attenuation2
Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Properties (Direct3D 9). Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
Theta
Angle, in radians, of a spotlight's inner cone - that is, the fully illuminated spotlight cone. This value must be in the range from 0 through the value specified by Phi.
Phi
Angle, in radians, defining the outer edge of the spotlight's outer cone. Points outside this cone are not lit by the spotlight. This value must be between 0 and pi.

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::SetLight


D3DLOCKED_BOX

Describes a locked box (volume).

typedef struct D3DLOCKED_BOX {
    int RowPitch;
    int SlicePitch;
    void * pBits;
} D3DLOCKED_BOX, *LPD3DLOCKED_BOX;

Members

RowPitch
Byte offset from the left edge of one row to the left edge of the next row.
SlicePitch
Byte offset from the top-left of one slice to the top-left of the next deepest slice.
pBits
Pointer to the beginning of the volume box. If a D3DBOX was provided to the LockBox call, pBits will be appropriately offset from the start of the volume.

Remarks

Volumes can be visualized as being organized into slices of width x height 2D surfaces stacked up to make a width x height x depth volume. For more information, see Volume Texture Resources (Direct3D 9).

See Also

IDirect3DVolume9::LockBox, IDirect3DVolumeTexture9::LockBox


D3DLOCKED_RECT

Describes a locked rectangular region.

typedef struct D3DLOCKED_RECT {
    INT Pitch;
    void * pBits;
} D3DLOCKED_RECT, *LPD3DLOCKED_RECT;

Members

Pitch
Number of bytes in one row of the surface.
pBits
Pointer to the locked bits. If a RECT was provided to the IDirect3DSurface9::LockRect call, pBits will be appropriately offset from the start of the surface.

Remarks

The pitch for DXTn formats is different from what was returned in DirectX 7. It now refers to the number of bytes in a row of blocks. For example, if you have a width of 16, then you will have a pitch of 4 blocks (4*8 for DXT1, 4*16 for DXT2-5.)

See Also

IDirect3DCubeTexture9::LockRect, IDirect3DSurface9::LockRect, IDirect3DTexture9::LockRect


D3DMATERIAL9

Specifies material properties.

typedef struct D3DMATERIAL9 {
    D3DCOLORVALUE Diffuse;
    D3DCOLORVALUE Ambient;
    D3DCOLORVALUE Specular;
    D3DCOLORVALUE Emissive;
    float Power;
} D3DMATERIAL9, *LPD3DMATERIAL9;

Members

Diffuse
Value specifying the diffuse color of the material. See D3DCOLORVALUE.
Ambient
Value specifying the ambient color of the material. See D3DCOLORVALUE.
Specular
Value specifying the specular color of the material. See D3DCOLORVALUE.
Emissive
Value specifying the emissive color of the material. See D3DCOLORVALUE.
Power
Floating-point value specifying the sharpness of specular highlights. The higher the value, the sharper the highlight.

Remarks

To turn off specular highlights, set D3DRS_SPECULARENABLE to FALSE, using D3DRENDERSTATETYPE. This is the fastest option because no specular highlights will be calculated.

For more information about using the lighting engine to calculate specular lighting, see Specular Lighting (Direct3D 9).

See Also

IDirect3DDevice9::GetMaterial, IDirect3DDevice9::SetMaterial, IDirect3DDevice9::SetMaterial


D3DMATRIX

Describes a matrix.

Syntax

typedef struct _D3DMATRIX {
    union {
        struct {
            float        _11, _12, _13, _14;
            float        _21, _22, _23, _24;
            float        _31, _32, _33, _34;
            float        _41, _42, _43, _44;

        };
        float m[4][4];
    };
} D3DMATRIX;

Members

_ij
An array of floats that represent a 4x4 matrix, where i is the row number and j is the column number. For example, _34 means the same as [a34], the component in the third row and fourth column.

Remarks

In Direct3D, the _34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by -1 instead.

See Also

IDirect3DDevice9::GetTransform, IDirect3DDevice9::MultiplyTransform, IDirect3DDevice9::SetTransform, IDirect3DDevice9::SetTransform, D3DXMATRIX, Transforms (Direct3D 9)


D3DPRESENT_PARAMETERS

Describes the presentation parameters.

typedef struct D3DPRESENT_PARAMETERS {
    UINT BackBufferWidth, BackBufferHeight;
    D3DFORMAT BackBufferFormat;
    UINT BackBufferCount;
    D3DMULTISAMPLE_TYPE MultiSampleType;
    DWORD MultiSampleQuality;
    D3DSWAPEFFECT SwapEffect;
    HWND hDeviceWindow;
    BOOL Windowed;
    BOOL EnableAutoDepthStencil;
    D3DFORMAT AutoDepthStencilFormat;
    DWORD Flags;
    UINT FullScreen_RefreshRateInHz;
    UINT PresentationInterval;
} D3DPRESENT_PARAMETERS, *LPD3DPRESENT_PARAMETERS;

Members

BackBufferWidth, BackBufferHeight
Width and height of the new swap chain's back buffers, in pixels. If Windowed is FALSE (the presentation is full-screen), these values must equal the width and height of one of the enumerated display modes found through IDirect3D9::EnumAdapterModes. If Windowed is TRUE and either of these values is zero, the corresponding dimension of the client area of the hDeviceWindow (or the focus window, if hDeviceWindow is NULL) is taken.
BackBufferFormat
The back buffer format. For more information about formats, see D3DFORMAT. This value must be one of the render-target formats as validated by IDirect3D9::CheckDeviceType. You can use IDirect3DDevice9::GetDisplayMode to obtain the current format.

In fact, D3DFMT_UNKNOWN can be specified for the BackBufferFormat while in windowed mode. This tells the runtime to use the current display-mode format and eliminates the need to call IDirect3DDevice9::GetDisplayMode.

For windowed applications, the back buffer format no longer needs to match the display-mode format because color conversion can now be done by the hardware (if the hardware supports color conversion). The set of possible back buffer formats is constrained, but the runtime will allow any valid back buffer format to be presented to any desktop format. (There is the additional requirement that the device be operable in the desktop mode; devices typically do not operate in 8 bits per pixel modes.)

Full-screen applications cannot do color conversion.

BackBufferCount
This value can be between 0 and D3DPRESENT_BACK_BUFFERS_MAX (or D3DPRESENT_BACK_BUFFERS_MAX_EX when using Direct3D 9Ex). Values of 0 are treated as 1. If the number of back buffers cannot be created, the runtime will fail the method call and fill this value with the number of back buffers that could be created. As a result, an application can call the method twice with the same D3DPRESENT_PARAMETERS structure and expect it to work the second time.

The method fails if one back buffer cannot be created. The value of BackBufferCount influences what set of swap effects are allowed. Specifically, any D3DSWAPEFFECT_COPY swap effect requires that there be exactly one back buffer.

MultiSampleType
Member of the D3DMULTISAMPLE_TYPE enumerated type. The value must be D3DMULTISAMPLE_NONE unless SwapEffect has been set to D3DSWAPEFFECT_DISCARD. Multisampling is supported only if the swap effect is D3DSWAPEFFECT_DISCARD.
MultiSampleQuality
Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error D3DERR_INVALIDCALL. Paired values of render targets or of depth stencil surfaces and D3DMULTISAMPLE_TYPE must match.
SwapEffect
Member of the D3DSWAPEFFECT enumerated type. The runtime will guarantee the implied semantics concerning buffer swap behavior; therefore, if Windowed is TRUE and SwapEffect is set to D3DSWAPEFFECT_FLIP, the runtime will create one extra back buffer and copy whichever becomes the front buffer at presentation time.

D3DSWAPEFFECT_COPY requires that BackBufferCount be set to 1.

D3DSWAPEFFECT_DISCARD will be enforced in the debug runtime by filling any buffer with noise after it is presented.

hDeviceWindow
The device window determines the location and size of the back buffer on screen. This is used by Direct3D when the back buffer contents are copied to the front buffer during IDirect3DDevice9::Present.

  • For a full-screen application, this is a handle to the top window (which is the focus window).

    For applications that use multiple full-screen devices (such as a multimonitor system), exactly one device can use the focus window as the device window. All other devices must have unique device windows.

  • For a windowed-mode application, this handle will be the default target window for IDirect3DDevice9::Present. If this handle is NULL, the focus window will be taken.

Note that no attempt is made by the runtime to reflect user changes in window size. The back buffer is not implicitly reset when this window is reset. However, the IDirect3DDevice9::Present method does automatically track window position changes.

Windowed
TRUE if the application runs windowed; FALSE if the application runs full-screen.
EnableAutoDepthStencil
If this value is TRUE, Direct3D will manage depth buffers for the application. The device will create a depth-stencil buffer when it is created. The depth-stencil buffer will be automatically set as the render target of the device. When the device is reset, the depth-stencil buffer will be automatically destroyed and recreated in the new size.

If EnableAutoDepthStencil is TRUE, then AutoDepthStencilFormat must be a valid depth-stencil format.

AutoDepthStencilFormat
Member of the D3DFORMAT enumerated type. The format of the automatic depth-stencil surface that the device will create. This member is ignored unless EnableAutoDepthStencil is TRUE.
Flags
One of the D3DPRESENTFLAG constants.
FullScreen_RefreshRateInHz
The rate at which the display adapter refreshes the screen. The value depends on the mode in which the application is running:
  • For windowed mode, the refresh rate must be 0.
  • For full-screen mode, the refresh rate is one of the refresh rates returned by IDirect3D9::EnumAdapterModes.
PresentationInterval
The maximum rate at which the swap chain's back buffers can be presented to the front buffer. For a detailed explanation of the modes and the intervals that are supported, see D3DPRESENT.

See Also

IDirect3D9::CreateDevice, IDirect3DDevice9::CreateAdditionalSwapChain, IDirect3DDevice9::Present, IDirect3DDevice9::Reset, IDirect3DDevice9::Reset


D3DPRESENTSTATS (DirectX 9Ex only)

Describes swapchain statistics relating to IDirect3DDevice9Ex::PresentEx calls.

typedef struct _D3DPRESENTSTATS {
    UINT PresentCount;
    UINT PresentRefreshCount;
    UINT SyncRefreshCount;
    LARGE_INTEGER SyncQPCTime;
    LARGE_INTEGER SyncGPUTime;
} D3DPRESENTSTATS (DirectX 9Ex only);

Members

PresentCount
Number of completed calls to IDirect3DDevice9Ex::PresentEx or methods that result in such a call.
PresentRefreshCount
Integer that identifies the frame that had a presentation operation. The presentation operation is identified by PresentCount. Incremented each time the display controller outpus a new frame, i.e. at the beginning of each vertical retrace period.
SyncRefreshCount
Integer that identifies the last frame that received a time stamp.
SyncQPCTime
Timestamp of the frame that is identified by SyncRefreshCount. This value is obtained by calling QueryPerformanceCounter.
SyncGPUTime
This value is not used.

Remarks

If an application is not fast enough to keep up with the monitor's refresh rate, possibly due to slow hardware or lack of system resources, then it can experience a graphics glitch. A glitch is a so-called visual hiccup. If a monitor is set to refresh at 60 Hz, and the application can only manage 30 fps, then half of the frames will have glitches.

Applications can detect a glitch by keeping track of SynchRefreshCount. For example, an application might perform the following sequence of actions:

  1. Render to the back buffer.
  2. Call Present.
  3. Call GetPresentStats and store the resulting D3DPRESENTSTATS structure.
  4. Render the next frame to the back buffer.
  5. Call Present.
  6. Call GetPresentStats and store the resulting D3DPRESENTSTATS structure.
  7. Compare the values of SyncRefreshCount from the two stored D3DPRESENTSTATS structures. If the difference is greater than one, then a frame was skipped.

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Structures


D3DPSHADERCAPS2_0

Pixel shader driver caps.

typedef struct D3DPSHADERCAPS2_0 {
    DWORD Caps;
    INT DynamicFlowControlDepth;
    INT NumTemps;
    INT StaticFlowControlDepth;
    INT NumInstructionSlots;
} D3DPSHADERCAPS2_0, *LPD3DPSHADERCAPS2_0;

Members

Caps
Instruction predication is supported if this value is nonzero. See setp_comp - vs.
DynamicFlowControlDepth
Either 0 or 24, which represents the depth of the dynamic flow control instruction nesting. See D3DPSHADERCAPS2_0.
NumTemps
The number of temporary registers supported. See D3DPSHADERCAPS2_0.
StaticFlowControlDepth
The depth of nesting of the loop - vs/rep - vs and call - vs/callnz bool - vs instructions. See D3DPSHADERCAPS2_0.
NumInstructionSlots
The number of instruction slots supported. See D3DPSHADERCAPS2_0.

See Also

D3DCAPS9


D3DRANGE

Defines a range.

typedef struct D3DRANGE {
    UINT Offset;
    UINT Size;
} D3DRANGE, *LPD3DRANGE;

Members

Offset
Offset, in bytes.
Size
Size, in bytes.


D3DRASTER_STATUS

Describes the raster status.

typedef struct D3DRASTER_STATUS {
    BOOL InVBlank;
    UINT ScanLine;
} D3DRASTER_STATUS, *LPD3DRASTER_STATUS;

Members

InVBlank
TRUE if the raster is in the vertical blank period. FALSE if the raster is not in the vertical blank period.
ScanLine
If InVBlank is FALSE, then this value is an integer roughly corresponding to the current scan line painted by the raster. Scan lines are numbered in the same way as Direct3D surface coordinates: 0 is the top of the primary surface, extending to the value (height of the surface - 1) at the bottom of the display.

If InVBlank is TRUE, then this value is set to zero and can be ignored.

See Also

IDirect3DDevice9::GetRasterStatus


D3DRECT

Defines a rectangle.

typedef struct D3DRECT {
    LONG x1, y1;
    LONG x2, y2;
} D3DRECT, *LPD3DRECT;

Members

x1, y1
Coordinates of the upper-left corner of the rectangle.
x2, y2
Coordinates of the lower-right corner of the rectangle.

See Also

IDirect3DDevice9::Clear


D3DRECTPATCH_INFO

Describes a rectangular high-order patch.

typedef struct D3DRECTPATCH_INFO {
    UINT StartVertexOffsetWidth;
    UINT StartVertexOffsetHeight;
    UINT Width;
    UINT Height;
    UINT Stride;
    D3DBASISTYPE Basis;
    D3DDEGREETYPE Degree;
} D3DRECTPATCH_INFO, *LPD3DRECTPATCH_INFO;

Members

StartVertexOffsetWidth
Starting vertex offset width, in number of vertices.
StartVertexOffsetHeight
Starting vertex offset height, in number of vertices.
Width
Width of each vertex, in number of vertices.
Height
Height of each vertex, in number of vertices.
Stride
Width of the imaginary two-dimensional vertex array, which occupies the same space as the vertex buffer. For an example, see the diagram below.
Basis
Member of the D3DBASISTYPE enumerated type, defining the basis type for the rectangular high-order patch.
Value | Order supported | Width and height
D3DBASIS_BEZIER | Linear, cubic, and quintic | Width = height = (DWORD)order + 1
D3DBASIS_BSPLINE | Linear, cubic, and quintic | Width = height > (DWORD)order
D3DBASIS_INTERPOLATE | Cubic | Width = height > (DWORD)order
Degree
Member of the D3DDEGREETYPE enumerated type, defining the degree for the rectangular patch.

Remarks

The following diagram identifies the parameters that specify a rectangle patch.

Rectangular high-order patch with parameters that specify it

Each of the vertices in the vertex buffer is shown as a black dot. In this case, the vertex buffer has 20 vertices in it, 16 of which are in the rectangle patch. The stride is the number of vertices in the width of the vertex buffer, in this case five. The x offset to the first vertex is called the StartIndexVertexWidth and is in this case 1. The y offset to the first patch vertex is called the StartIndexVertexHeight and is in this case 0.

To render a stream of individual rectangular patches (non-mosaic), you should interpret your geometry as a long narrow (1 x N) rectangular patch. The D3DRECTPATCH_INFO structure for such a strip (cubic Bézier) would be set up in the following manner.

D3DRECTPATCH_INFO RectInfo;

RectInfo.Width = 4;
RectInfo.Height = 4;
RectInfo.Stride = 4;
RectInfo.Basis = D3DBASIS_BEZIER;
RectInfo.Order = D3DORDER_CUBIC;
RectInfo.StartVertexOffsetWidth = 0;
RectInfo.StartVertexOffsetHeight = 4*i;  // The variable i is the index of the
//   patch you want to render.

See Also

IDirect3DDevice9::DrawRectPatch, D3DXTessellateRectPatch


D3DRESOURCESTATS

Resource statistics gathered by the D3DDEVINFO_ResourceManager when using the asynchronous query mechanism.

typedef struct D3DRESOURCESTATS {
    BOOL bThrashing;
    DWORD ApproxBytesDownloaded;
    DWORD NumEvicts;
    DWORD NumVidCreates;
    DWORD LastPri;
    DWORD NumUsed;
    DWORD NumUsedInVidMem;
    DWORD WorkingSet;
    DWORD WorkingSetBytes;
    DWORD TotalManaged;
    DWORD TotalBytes;
} D3DRESOURCESTATS, *LPD3DRESOURCESTATS;

Members

bThrashing
Indicates if thrashing is occurring.
ApproxBytesDownloaded
Approximate number of bytes downloaded by the resource manager.
NumEvicts
Number of objects evicted.
NumVidCreates
Number of objects created in video memory.
LastPri
Priority of last object evicted.
NumUsed
Number of objects set to the device.
NumUsedInVidMem
Number of objects set to the device, which are already in video memory.
WorkingSet
Number of objects in video memory.
WorkingSetBytes
Number of bytes in video memory.
TotalManaged
Total number of managed objects.
TotalBytes
Total number of bytes of managed objects.

See Also

Asynchronous Notification (Direct3D 9)


D3DSURFACE_DESC

Describes a surface.

typedef struct D3DSURFACE_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    D3DMULTISAMPLE_TYPE MultiSampleType;
    DWORD MultiSampleQuality;
    UINT Width;
    UINT Height;
} D3DSURFACE_DESC, *LPD3DSURFACE_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a surface.
Usage
Either the D3DUSAGE_DEPTHSTENCIL or D3DUSAGE_RENDERTARGET values. For more information, see D3DUSAGE.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this surface.
MultiSampleType
Member of the D3DMULTISAMPLE_TYPE enumerated type, specifying the levels of full-scene multisampling supported by the surface.
MultiSampleQuality
Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error, D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces and the MultiSample type must all match.
Width
Width of the surface, in pixels.
Height
Height of the surface, in pixels.

See Also

IDirect3DCubeTexture9::GetLevelDesc, IDirect3DSurface9::GetDesc, IDirect3DTexture9::GetLevelDesc


D3DTRIPATCH_INFO

Describes a triangular high-order patch.

typedef struct D3DTRIPATCH_INFO {
    UINT StartVertexOffset;
    UINT NumVertices;
    D3DBASISTYPE Basis;
    D3DDEGREETYPE Degree;
} D3DTRIPATCH_INFO, *LPD3DTRIPATCH_INFO;

Members

StartVertexOffset
Starting vertex offset, in number of vertices.
NumVertices
Number of vertices.
Basis
Member of the D3DBASISTYPE enumerated type, which defines the basis type for the triangular high-order patch. The only valid value for this member is D3DBASIS_BEZIER.
Degree
Member of the D3DDEGREETYPE enumerated type, defining the degree type for the triangular high-order patch.
Value | Number of vertices
D3DDEGREE_CUBIC | 10
D3DDEGREE_LINEAR | 3
D3DDEGREE_QUADRATIC | N/A
D3DDEGREE_QUINTIC | 21

N/A - Not available. Not supported.

Remarks

For example, the following diagram identifies the vertex order and segment numbers for a cubic Bézier triangle patch. The vertex order determines the segment numbers used by IDirect3DDevice9::DrawTriPatch. The offset is the number of bytes to the first triangle patch vertex in the vertex buffer.

Triangular high-order patch with nine vertices

See Also

IDirect3DDevice9::DrawTriPatch, D3DXTessellateTriPatch


D3DVECTOR

Defines a vector.

typedef struct D3DVECTOR {
    float x, y, z;
} D3DVECTOR, *LPD3DVECTOR;

Members

x, y, z
Floating-point values describing the vector.


D3DVERTEXBUFFER_DESC

Describes a vertex buffer.

typedef struct D3DVERTEXBUFFER_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    UINT Size;
    DWORD FVF;
} D3DVERTEXBUFFER_DESC, *LPD3DVERTEXBUFFER_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the vertex buffer data.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a vertex buffer.
Usage
Combination of one or more D3DUSAGE flags.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this vertex buffer.
Size
Size of the vertex buffer, in bytes.
FVF
Combination of D3DFVF that describes the vertex format of the vertices in this buffer.

See Also

IDirect3DVertexBuffer9::GetDesc, Vertex Buffers (Direct3D 9)


D3DVERTEXELEMENT9

Defines the vertex data layout. Each vertex can contain one or more data types, and each data type is described by a vertex element.

typedef struct D3DVERTEXELEMENT9 {
    WORD Stream;
    WORD Offset;
    BYTE Type;
    BYTE Method;
    BYTE Usage;
    BYTE UsageIndex;
} D3DVERTEXELEMENT9, *LPD3DVERTEXELEMENT9;

Members

Stream
Stream number.
Offset
Offset from the beginning of the vertex data to the data associated with the particular data type.
Type
The data type, specified as a D3DDECLTYPE. One of several predefined types that define the data size. Some methods have an implied type.
Method
The method specifies the tessellator processing, which determines how the tessellator interprets (or operates on) the vertex data. For more information, see D3DDECLMETHOD.
Usage
Defines what the data will be used for; that is, the interoperability between vertex data layouts and vertex shaders. Each usage acts to bind a vertex declaration to a vertex shader. In some cases, they have a special interpretation. For example, an element that specifies D3DDECLUSAGE_NORMAL or D3DDECLUSAGE_POSITION is used by the N-patch tessellator to set up tessellation. See D3DDECLUSAGE for a list of the available semantics. D3DDECLUSAGE_TEXCOORD can be used for user-defined fields (which don't have an existing usage defined).
UsageIndex
Modifies the usage data to allow the user to specify multiple usage types.

Remarks

Vertex data is defined using an array of D3DVERTEXELEMENT9 structures. Use D3DDECL_END to declare the last element in the declaration.

See Also

Vertex Declaration (Direct3D 9)


D3DVIEWPORT9

Defines the window dimensions of a render-target surface onto which a 3D volume projects.

typedef struct D3DVIEWPORT9 {
    DWORD X;
    DWORD Y;
    DWORD Width;
    DWORD Height;
    float MinZ;
    float MaxZ;
} D3DVIEWPORT9, *LPD3DVIEWPORT9;

Members

X
Pixel coordinate of the upper-left corner of the viewport on the render-target surface. Unless you want to render to a subset of the surface, this member can be set to 0.
Y
Pixel coordinate of the upper-left corner of the viewport on the render-target surface. Unless you want to render to a subset of the surface, this member can be set to 0.
Width
Width dimension of the clip volume, in pixels. Unless you are rendering only to a subset of the surface, this member should be set to the width dimension of the render-target surface.
Height
Height dimension of the clip volume, in pixels. Unless you are rendering only to a subset of the surface, this member should be set to the height dimension of the render-target surface.
MinZ
Together with MaxZ, value describing the range of depth values into which a scene is to be rendered, the minimum and maximum values of the clip volume. Most applications set this value to 0.0. Clipping is performed after applying the projection matrix.
MaxZ
Together with MinZ, value describing the range of depth values into which a scene is to be rendered, the minimum and maximum values of the clip volume. Most applications set this value to 1.0. Clipping is performed after applying the projection matrix.

Remarks

The X, Y, Width, and Height members describe the position and dimensions of the viewport on the render-target surface. Usually, applications render to the entire target surface; when rendering on a 640 x 480 surface, these members should be 0, 0, 640, and 480, respectively. The MinZ and MaxZ are typically set to 0.0 and 1.0 but can be set to other values to achieve specific effects. For example, you might set them both to 0.0 to force the system to render objects to the foreground of a scene, or both to 1.0 to force the objects into the background.

When the viewport parameters for a device change (because of a call to the IDirect3DDevice9::SetViewport method), the driver builds a new transformation matrix.

See Also

IDirect3DDevice9::GetViewport, IDirect3DDevice9::SetViewport, IDirect3DDevice9::SetViewport


D3DVOLUME_DESC

Describes a volume.

typedef struct D3DVOLUME_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    UINT Width;
    UINT Height;
    UINT Depth;
} D3DVOLUME_DESC, *LPD3DVOLUME_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the volume.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a volume.
Usage
Currently not used. Always returned as 0.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this volume.
Width
Width of the volume, in pixels.
Height
Height of the volume, in pixels.
Depth
Depth of the volume, in pixels.

See Also

IDirect3DVolume9::GetDesc, IDirect3DVolumeTexture9::GetLevelDesc


D3DVSHADERCAPS2_0

Vertex shader caps.

typedef struct D3DVSHADERCAPS2_0 {
    DWORD Caps;
    INT DynamicFlowControlDepth;
    INT NumTemps;
    INT StaticFlowControlDepth;
} D3DVSHADERCAPS2_0, *LPD3DVSHADERCAPS2_0;

Members

Caps
Instruction predication is supported if this value is nonzero. See setp_comp - vs.
DynamicFlowControlDepth
Either 0 or 24, which represents the depth of the dynamic flow control instruction nesting. See D3DVS20CAPS.
NumTemps
The number of temporary registers supported. See D3DVS20CAPS.
StaticFlowControlDepth
The depth of nesting of the loop - vs/rep - vs and call - vs/callnz bool - vs instructions. See D3DVS20CAPS.

See Also

D3DPSHADERCAPS2_0, D3DCAPS9


PALETTEENTRY

Specifies the color and usage of an entry in a logical palette.

typedef struct PALETTEENTRY {
    BYTE peRed;
    BYTE peGreen;
    BYTE peBlue;
    BYTE peFlags;
} PALETTEENTRY, *LPPALETTEENTRY;

Members

peRed
The red intensity value for the palette entry.
peGreen
The green intensity value for the palette entry.
peBlue
The blue intensity value for the palette entry.
peFlags
The alpha intensity value for the palette entry. Note that as of DirectX 8, this member is treated differently than documented in the Platform SDK.


D3D Enumerations

This section describes the Direct3D enumerated types.

  • D3DBACKBUFFER_TYPE
  • D3DBASISTYPE
  • D3DBLEND
  • D3DBLENDOP
  • D3DCMPFUNC
  • D3DCOMPOSERECTSOP (DirectX 9Ex only)
  • D3DCUBEMAP_FACES
  • D3DCULL
  • D3DDEBUGMONITORTOKENS
  • D3DDECLMETHOD
  • D3DDECLTYPE
  • D3DDECLUSAGE
  • D3DDEGREETYPE
  • D3DDEVTYPE
  • D3DDISPLAYROTATION (DirectX 9Ex only)
  • D3DERR
  • D3DFILLMODE
  • D3DFOGMODE
  • D3DFORMAT
  • D3DLIGHTTYPE
  • D3DMATERIALCOLORSOURCE
  • D3DMULTISAMPLE_TYPE
  • D3DPATCHEDGESTYLE
  • D3DPOOL
  • D3DPRIMITIVETYPE
  • D3DQUERYTYPE
  • D3DRENDERSTATETYPE
  • D3DRESOURCETYPE
  • D3DSAMPLER_TEXTURE_TYPE
  • D3DSAMPLERSTATETYPE
  • D3DSCANLINEORDERING (DirectX 9Ex only)
  • D3DSHADEMODE
  • D3DSTATEBLOCKTYPE
  • D3DSTENCILOP
  • D3DSWAPEFFECT
  • D3DTEXTUREADDRESS
  • D3DTEXTUREFILTERTYPE
  • D3DTEXTUREOP
  • D3DTEXTURESTAGESTATETYPE
  • D3DTEXTURETRANSFORMFLAGS
  • D3DTRANSFORMSTATETYPE
  • D3DVERTEXBLENDFLAGS
  • D3DXFERR Return Values
  • D3DZBUFFERTYPE


D3DBACKBUFFER_TYPE

Defines constants that describe the type of back buffer.

typedef enum D3DBACKBUFFER_TYPE
{
    D3DBACKBUFFER_TYPE_MONO = 0,
    D3DBACKBUFFER_TYPE_LEFT = 1,
    D3DBACKBUFFER_TYPE_RIGHT = 2,
    D3DBACKBUFFER_TYPE_FORCE_DWORD = 0x7fffffff,
} D3DBACKBUFFER_TYPE, *LPD3DBACKBUFFER_TYPE;

Constants

D3DBACKBUFFER_TYPE_MONO
Specifies a nonstereo swap chain.
D3DBACKBUFFER_TYPE_LEFT
Specifies the left side of a stereo pair in a swap chain.
D3DBACKBUFFER_TYPE_RIGHT
Specifies the right side of a stereo pair in a swap chain.
D3DBACKBUFFER_TYPE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Direct3D 9 does not support stereo view, so Direct3D does not use the D3DBACKBUFFER_TYPE_LEFT and D3DBACKBUFFER_TYPE_RIGHT values of this enumerated type.

See Also

IDirect3DDevice9::GetBackBuffer, IDirect3DSwapChain9::GetBackBuffer


D3DBASISTYPE

Defines the basis type of a high-order patch surface.

typedef enum D3DBASISTYPE
{
    D3DBASIS_BEZIER = 0,
    D3DBASIS_BSPLINE = 1,
    D3DBASIS_CATMULL_ROM = 2,
    D3DBASIS_FORCE_DWORD = 0x7fffffff,
} D3DBASISTYPE, *LPD3DBASISTYPE;

Constants

D3DBASIS_BEZIER
Input vertices are treated as a series of Bézier patches. The number of vertices specified must be divisible by 4. Portions of the mesh beyond this criterion will not be rendered. Full continuity is assumed between sub-patches in the interior of the surface rendered by each call. Only the vertices at the corners of each sub-patch are guaranteed to lie on the resulting surface.
D3DBASIS_BSPLINE
Input vertices are treated as control points of a B-spline surface. The number of apertures rendered is two fewer than the number of apertures in that direction. In general, the generated surface does not contain the control vertices specified.
D3DBASIS_CATMULL_ROM
An interpolating basis defines the surface so that the surface goes through all the input vertices specified. In DirectX 8, this was D3DBASIS_INTERPOLATE.
D3DBASIS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The members of D3DBASISTYPE specify the formulation to be used in evaluating the high-order patch surface primitive during tessellation.

See Also

D3DRECTPATCH_INFO, D3DTRIPATCH_INFO


D3DBLEND

Defines the supported blend mode.

typedef enum D3DBLEND
{
    D3DBLEND_ZERO = 1,
    D3DBLEND_ONE = 2,
    D3DBLEND_SRCCOLOR = 3,
    D3DBLEND_INVSRCCOLOR = 4,
    D3DBLEND_SRCALPHA = 5,
    D3DBLEND_INVSRCALPHA = 6,
    D3DBLEND_DESTALPHA = 7,
    D3DBLEND_INVDESTALPHA = 8,
    D3DBLEND_DESTCOLOR = 9,
    D3DBLEND_INVDESTCOLOR = 10,
    D3DBLEND_SRCALPHASAT = 11,
    D3DBLEND_BOTHSRCALPHA = 12,
    D3DBLEND_BOTHINVSRCALPHA = 13,
    D3DBLEND_BLENDFACTOR = 14,
    D3DBLEND_INVBLENDFACTOR = 15,
    D3DBLEND_SRCCOLOR2 = 16,
    D3DBLEND_INVSRCCOLOR2 = 17,
    D3DBLEND_FORCE_DWORD = 0x7fffffff,
} D3DBLEND, *LPD3DBLEND;

Constants

D3DBLEND_ZERO
Blend factor is (0, 0, 0, 0).
D3DBLEND_ONE
Blend factor is (1, 1, 1, 1).
D3DBLEND_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DBLEND_INVSRCCOLOR
Blend factor is (1 - Rs, 1 - Gs, 1 - Bs, 1 - As).
D3DBLEND_SRCALPHA
Blend factor is (As, As, As, As).
D3DBLEND_INVSRCALPHA
Blend factor is ( 1 - As, 1 - As, 1 - As, 1 - As).
D3DBLEND_DESTALPHA
Blend factor is (Ad Ad Ad Ad).
D3DBLEND_INVDESTALPHA
Blend factor is (1 - Ad 1 - Ad 1 - Ad 1 - Ad).
D3DBLEND_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DBLEND_INVDESTCOLOR
Blend factor is (1 - Rd, 1 - Gd, 1 - Bd, 1 - Ad).
D3DBLEND_SRCALPHASAT
Blend factor is (f, f, f, 1); where f = min(As, 1 - Ad).
D3DBLEND_BOTHSRCALPHA
Obsolete. Starting with DirectX 6, you can achieve the same effect by setting the source and destination blend factors to D3DBLEND_SRCALPHA and D3DBLEND_INVSRCALPHA in separate calls.
D3DBLEND_BOTHINVSRCALPHA
Source blend factor is (1 - As, 1 - As, 1 - As, 1 - As), and destination blend factor is (As, As, As, As); the destination blend selection is overridden. This blend mode is supported only for the D3DRS_SRCBLEND render state.
D3DBLEND_BLENDFACTOR
Constant color blending factor used by the frame-buffer blender. This blend mode is supported only if D3DPBLENDCAPS_BLENDFACTOR is set in the SrcBlendCaps or DestBlendCaps members of D3DCAPS9.
D3DBLEND_INVBLENDFACTOR
Inverted constant color-blending factor used by the frame-buffer blender. This blend mode is supported only if the D3DPBLENDCAPS_BLENDFACTOR bit is set in the SrcBlendCaps or DestBlendCaps members of D3DCAPS9.
D3DBLEND_SRCCOLOR2
Direct3D9 Ex only - Blend factor is (PSOutColor[1]r, PSOutColor[1]g, PSOutColor[1]b, not used). See Render Target Blending.
D3DBLEND_INVSRCCOLOR2
Direct3D 9Ex only - Blend factor is (1 - PSOutColor[1]r, 1 - PSOutColor[1]g, 1 - PSOutColor[1]b, not used)). See Render Target Blending.
D3DBLEND_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

In the preceding member descriptions, the RGBA values of the source and destination are indicated by the s and d subscripts.

The values in this enumerated type are used by the following render states:

  • D3DRS_DESTBLEND
  • D3DRS_SRCBLEND
  • D3DRS_DESTBLENDALPHA
  • D3DRS_SRCBLENDALPHA

See D3DRENDERSTATETYPE

Render Target Blending

Direct3D 9Ex has improved text rendering capabilities. Rendering clear-type fonts would normally require two passes. To eliminate the second pass, a pixel shader can be used to output two colors, which we can call PSOutColor[0] and PSOutColor[1]. The first color would contain the standard 3 color components (RGB). The second color would contain 3 alpha components (one for each component of the first color).

These new blending modes are only used for text rendering on the first render target.


D3DBLENDOP

Defines the supported blend operations. See Remarks for definitions of terms.

typedef enum D3DBLENDOP
{
    D3DBLENDOP_ADD = 1,
    D3DBLENDOP_SUBTRACT = 2,
    D3DBLENDOP_REVSUBTRACT = 3,
    D3DBLENDOP_MIN = 4,
    D3DBLENDOP_MAX = 5,
    D3DBLENDOP_FORCE_DWORD = 0x7fffffff,
} D3DBLENDOP, *LPD3DBLENDOP;

Constants

D3DBLENDOP_ADD
The result is the destination added to the source. Result = Source + Destination
D3DBLENDOP_SUBTRACT
The result is the destination subtracted from to the source. Result = Source - Destination
D3DBLENDOP_REVSUBTRACT
The result is the source subtracted from the destination. Result = Destination - Source
D3DBLENDOP_MIN
The result is the minimum of the source and destination. Result = MIN(Source, Destination)
D3DBLENDOP_MAX
The result is the maximum of the source and destination. Result = MAX(Source, Destination)
D3DBLENDOP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Source, Destination, and Result are defined as:

Term | Type | Description
Source | Input | Color of the source pixel before the operation.
Destination | Input | Color of the pixel in the destination buffer before the operation.
Result | Output | Returned value that is the blended color resulting from the operation.

This enumerated type defines values used by the following render states:

  • D3DRS_BLENDOP
  • D3DRS_BLENDOPALPHA

See Also

D3DCAPS9, D3DRENDERSTATETYPE


D3DCMPFUNC

Defines the supported compare functions.

typedef enum D3DCMPFUNC
{
    D3DCMP_NEVER = 1,
    D3DCMP_LESS = 2,
    D3DCMP_EQUAL = 3,
    D3DCMP_LESSEQUAL = 4,
    D3DCMP_GREATER = 5,
    D3DCMP_NOTEQUAL = 6,
    D3DCMP_GREATEREQUAL = 7,
    D3DCMP_ALWAYS = 8,
    D3DCMP_FORCE_DWORD = 0x7fffffff,
} D3DCMPFUNC, *LPD3DCMPFUNC;

Constants

D3DCMP_NEVER
Always fail the test.
D3DCMP_LESS
Accept the new pixel if its value is less than the value of the current pixel.
D3DCMP_EQUAL
Accept the new pixel if its value equals the value of the current pixel.
D3DCMP_LESSEQUAL
Accept the new pixel if its value is less than or equal to the value of the current pixel.
D3DCMP_GREATER
Accept the new pixel if its value is greater than the value of the current pixel.
D3DCMP_NOTEQUAL
Accept the new pixel if its value does not equal the value of the current pixel.
D3DCMP_GREATEREQUAL
Accept the new pixel if its value is greater than or equal to the value of the current pixel.
D3DCMP_ALWAYS
Always pass the test.
D3DCMP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The values in this enumerated type define the supported compare functions for the D3DRS_ZFUNC, D3DRS_ALPHAFUNC, and D3DRS_STENCILFUNC render states.

See Also

D3DRENDERSTATETYPE


D3DCOMPOSERECTSOP (DirectX 9Ex only)

Specifies how to combine the glyph data from the source and destination surfaces in a call to IDirect3DDevice9Ex::ComposeRect.

typedef enum _D3DCOMPOSERECTSOP
{
    D3DCOMPOSERECTS_COPY = 1,
    D3DCOMPOSERECTS_OR = 2,
    D3DCOMPOSERECTS_AND = 3,
    D3DCOMPOSERECTS_NEG = 4,
    D3DCOMPOSERECTS_FORCE_DWORD = 0x7fffffff,
} D3DCOMPOSERECTSOP (DirectX 9Ex only);

Constants

D3DCOMPOSERECTS_COPY
Copy the source to the destination.
D3DCOMPOSERECTS_OR
Bitwise OR the source and the destination.
D3DCOMPOSERECTS_AND
Bitwise AND the source and the destination.
D3DCOMPOSERECTS_NEG
Copy the negated source to the destination (Dst & ~Src).
D3DCOMPOSERECTS_FORCE_DWORD
Reserved. Used to force enumeration to 32-bits in size.

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Enumerations


D3DCUBEMAP_FACES

Defines the faces of a cubemap.

typedef enum D3DCUBEMAP_FACES
{
    D3DCUBEMAP_FACE_POSITIVE_X = 0,
    D3DCUBEMAP_FACE_NEGATIVE_X = 1,
    D3DCUBEMAP_FACE_POSITIVE_Y = 2,
    D3DCUBEMAP_FACE_NEGATIVE_Y = 3,
    D3DCUBEMAP_FACE_POSITIVE_Z = 4,
    D3DCUBEMAP_FACE_NEGATIVE_Z = 5,
    D3DCUBEMAP_FACE_FORCE_DWORD = 0xffffffff,
} D3DCUBEMAP_FACES, *LPD3DCUBEMAP_FACES;

Constants

D3DCUBEMAP_FACE_POSITIVE_X
Positive x-face of the cubemap.
D3DCUBEMAP_FACE_NEGATIVE_X
Negative x-face of the cubemap.
D3DCUBEMAP_FACE_POSITIVE_Y
Positive y-face of the cubemap.
D3DCUBEMAP_FACE_NEGATIVE_Y
Negative y-face of the cubemap.
D3DCUBEMAP_FACE_POSITIVE_Z
Positive z-face of the cubemap.
D3DCUBEMAP_FACE_NEGATIVE_Z
Negative z-face of the cubemap.
D3DCUBEMAP_FACE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::GetCubeMapSurface, IDirect3DCubeTexture9::LockRect, IDirect3DCubeTexture9::UnlockRect


D3DCULL

Defines the supported culling modes.

typedef enum D3DCULL
{
    D3DCULL_NONE = 1,
    D3DCULL_CW = 2,
    D3DCULL_CCW = 3,
    D3DCULL_FORCE_DWORD = 0x7fffffff,
} D3DCULL, *LPD3DCULL;

Constants

D3DCULL_NONE
Do not cull back faces.
D3DCULL_CW
Cull back faces with clockwise vertices.
D3DCULL_CCW
Cull back faces with counterclockwise vertices.
D3DCULL_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_CULLMODE render state. The culling modes define how back faces are culled when rendering a geometry.

See Also

D3DCAPS9, D3DRENDERSTATETYPE


D3DDEBUGMONITORTOKENS

Defines the debug monitor tokens.

typedef enum D3DDEBUGMONITORTOKENS
{
    D3DDMT_ENABLE = 0,
    D3DDMT_DISABLE = 1,
    D3DDMT_FORCE_DWORD = 0x7fffffff,
} D3DDEBUGMONITORTOKENS, *LPD3DDEBUGMONITORTOKENS;

Constants

D3DDMT_ENABLE
Enable the debug monitor.
D3DDMT_DISABLE
Disable the debug monitor.
D3DDMT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_DEBUGMONITORTOKEN render state and are only relevant for debug builds.

See Also

D3DRENDERSTATETYPE


D3DDECLMETHOD

Defines the vertex declaration method which is a predefined operation performed by the tessellator (or any procedural geometry routine on the vertex data during tessellation).

typedef enum D3DDECLMETHOD
{
    D3DDECLMETHOD_DEFAULT = 0,
    D3DDECLMETHOD_PARTIALU = 1,
    D3DDECLMETHOD_PARTIALV = 2,
    D3DDECLMETHOD_CROSSUV = 3,
    D3DDECLMETHOD_UV = 4,
    D3DDECLMETHOD_LOOKUP = 5,
    D3DDECLMETHOD_LOOKUPPRESAMPLED = 6,
} D3DDECLMETHOD, *LPD3DDECLMETHOD;

Constants

D3DDECLMETHOD_DEFAULT
Default value. The tessellator copies the vertex data (spline data for patches) as is, with no additional calculations. When the tessellator is used, this element is interpolated. Otherwise vertex data is copied into the input register. The input and output type can be any value, but are always the same type.
D3DDECLMETHOD_PARTIALU
Computes the tangent at a point on the rectangle or triangle patch in the U direction. The input type can be one of the following:
  • D3DDECLTYPE_D3DCOLOR
  • D3DDECLTYPE_FLOAT3
  • D3DDECLTYPE_FLOAT4
  • D3DDECLTYPE_SHORT4
  • D3DDECLTYPE_UBYTE4
The output type is always D3DDECLTYPE_FLOAT3.
D3DDECLMETHOD_PARTIALV
Computes the tangent at a point on the rectangle or triangle patch in the V direction. The input type can be one of the following:
  • D3DDECLTYPE_D3DCOLOR
  • D3DDECLTYPE_FLOAT3
  • D3DDECLTYPE_FLOAT4
  • D3DDECLTYPE_SHORT4
  • D3DDECLTYPE_UBYTE4
The output type is always D3DDECLTYPE_FLOAT3.
D3DDECLMETHOD_CROSSUV
Computes the normal at a point on the rectangle or triangle patch by taking the cross product of two tangents. The input type can be one of the following:
  • D3DDECLTYPE_D3DCOLOR
  • D3DDECLTYPE_FLOAT3
  • D3DDECLTYPE_FLOAT4
  • D3DDECLTYPE_SHORT4
  • D3DDECLTYPE_UBYTE4
The output type is always D3DDECLTYPE_FLOAT3.
D3DDECLMETHOD_UV
Copy out the U, V values at a point on the rectangle or triangle patch. This results in a 2D float. The input type must be set to D3DDECLTYPE_UNUSED. The output data type is always D3DDECLTYPE_FLOAT2. The input stream and offset are also unused (but must be set to 0).
D3DDECLMETHOD_LOOKUP
Look up a displacement map. The input type can be one of the following:
  • D3DDECLTYPE_FLOAT2
  • D3DDECLTYPE_FLOAT3
  • D3DDECLTYPE_FLOAT4
Only the .x and .y components are used for the texture map lookup. The output type is always D3DDECLTYPE_FLOAT1. The device must support displacement mapping. For more information about displacement mapping, see Displacement Mapping (Direct3D 9). This constant is supported only by the programmable pipeline on N-patch data, if N-patches are enabled.
D3DDECLMETHOD_LOOKUPPRESAMPLED
Look up a presampled displacement map. The input type must be set to D3DDECLTYPE_UNUSED; the stream index and the stream offset must be set to 0. The output type for this operation is always D3DDECLTYPE_FLOAT1. The device must support displacement mapping. For more information about displacement mapping, see Displacement Mapping (Direct3D 9). This constant is supported only by the programmable pipeline on N-patch data, if N-patches are enabled. This method can be used only with D3DDECLUSAGE_SAMPLE.

Remarks

The tessellator looks at the method to determine what data to calculate from the vertex data during tessellation. Mesh data should use the default value. Patches can use any of the other implemented types.

Vertex data is declared with an array of D3DVERTEXELEMENT9 structures. Each element in the array contains a vertex declaration method.

In addition to using D3DDECLMETHOD_DEFAULT, a normal mesh can use D3DDECLMETHOD_LOOKUP and D3DDECLMETHOD_LOOKUPPRESAMPLED methods when N-patches are enabled.


D3DDECLTYPE

Defines a vertex declaration data type.

typedef enum D3DDECLTYPE
{
    D3DDECLTYPE_FLOAT1 = 0,
    D3DDECLTYPE_FLOAT2 = 1,
    D3DDECLTYPE_FLOAT3 = 2,
    D3DDECLTYPE_FLOAT4 = 3,
    D3DDECLTYPE_D3DCOLOR = 4,
    D3DDECLTYPE_UBYTE4 = 5,
    D3DDECLTYPE_SHORT2 = 6,
    D3DDECLTYPE_SHORT4 = 7,
    D3DDECLTYPE_UBYTE4N = 8,
    D3DDECLTYPE_SHORT2N = 9,
    D3DDECLTYPE_SHORT4N = 10,
    D3DDECLTYPE_USHORT2N = 11,
    D3DDECLTYPE_USHORT4N = 12,
    D3DDECLTYPE_UDEC3 = 13,
    D3DDECLTYPE_DEC3N = 14,
    D3DDECLTYPE_FLOAT16_2 = 15,
    D3DDECLTYPE_FLOAT16_4 = 16,
    D3DDECLTYPE_UNUSED = 17,
} D3DDECLTYPE, *LPD3DDECLTYPE;

Constants

D3DDECLTYPE_FLOAT1
One-component float expanded to (float, 0, 0, 1).
D3DDECLTYPE_FLOAT2
Two-component float expanded to (float, float, 0, 1).
D3DDECLTYPE_FLOAT3
Three-component float expanded to (float, float, float, 1).
D3DDECLTYPE_FLOAT4
Four-component float expanded to (float, float, float, float).
D3DDECLTYPE_D3DCOLOR
Four-component, packed, unsigned bytes mapped to 0 to 1 range. Input is a D3DCOLOR and is expanded to RGBA order.
D3DDECLTYPE_UBYTE4
Four-component, unsigned byte.
D3DDECLTYPE_SHORT2
Two-component, signed short expanded to (value, value, 0, 1).
D3DDECLTYPE_SHORT4
Four-component, signed short expanded to (value, value, value, value).
D3DDECLTYPE_UBYTE4N
Four-component byte with each byte normalized by dividing with 255.0f.
D3DDECLTYPE_SHORT2N
Normalized, two-component, signed short, expanded to (first short/32767.0, second short/32767.0, 0, 1).
D3DDECLTYPE_SHORT4N
Normalized, four-component, signed short, expanded to (first short/32767.0, second short/32767.0, third short/32767.0, fourth short/32767.0).
D3DDECLTYPE_USHORT2N
Normalized, two-component, unsigned short, expanded to (first short/65535.0, short short/65535.0, 0, 1).
D3DDECLTYPE_USHORT4N
Normalized, four-component, unsigned short, expanded to (first short/65535.0, second short/65535.0, third short/65535.0, fourth short/65535.0).
D3DDECLTYPE_UDEC3
Three-component, unsigned, 10 10 10 format expanded to (value, value, value, 1).
D3DDECLTYPE_DEC3N
Three-component, signed, 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1).
D3DDECLTYPE_FLOAT16_2
Two-component, 16-bit, floating point expanded to (value, value, 0, 1).
D3DDECLTYPE_FLOAT16_4
Four-component, 16-bit, floating point expanded to (value, value, value, value).
D3DDECLTYPE_UNUSED
Type field in the declaration is unused. This is designed for use with D3DDECLMETHOD_UV and D3DDECLMETHOD_LOOKUPPRESAMPLED.

Remarks

Vertex data is declared with an array of D3DVERTEXELEMENT9 structures. Each element in the array contains a vertex declaration data type.

Use the DirectX Caps Viewer Tool tool to see which types are supported on your device.

See Also

D3DDECLMETHOD


D3DDECLUSAGE

Identifies the intended use of vertex data.

typedef enum D3DDECLUSAGE
{
    D3DDECLUSAGE_POSITION = 0,
    D3DDECLUSAGE_BLENDWEIGHT = 1,
    D3DDECLUSAGE_BLENDINDICES = 2,
    D3DDECLUSAGE_NORMAL = 3,
    D3DDECLUSAGE_PSIZE = 4,
    D3DDECLUSAGE_TEXCOORD = 5,
    D3DDECLUSAGE_TANGENT = 6,
    D3DDECLUSAGE_BINORMAL = 7,
    D3DDECLUSAGE_TESSFACTOR = 8,
    D3DDECLUSAGE_POSITIONT = 9,
    D3DDECLUSAGE_COLOR = 10,
    D3DDECLUSAGE_FOG = 11,
    D3DDECLUSAGE_DEPTH = 12,
    D3DDECLUSAGE_SAMPLE = 13,
} D3DDECLUSAGE, *LPD3DDECLUSAGE;

Constants

D3DDECLUSAGE_POSITION
Position data ranging from (-1,-1) to (1,1). Use D3DDECLUSAGE_POSITION with a usage index of 0 to specify untransformed position for fixed function vertex processing and the n-patch tessellator. Use D3DDECLUSAGE_POSITION with a usage index of 1 to specify untransformed position in the fixed function vertex shader for vertex tweening.
D3DDECLUSAGE_BLENDWEIGHT
Blending weight data. Use D3DDECLUSAGE_BLENDWEIGHT with a usage index of 0 to specify the blend weights used in indexed and nonindexed vertex blending.
D3DDECLUSAGE_BLENDINDICES
Blending indices data. Use D3DDECLUSAGE_BLENDINDICES with a usage index of 0 to specify matrix indices for indexed paletted skinning.
D3DDECLUSAGE_NORMAL
Vertex normal data. Use D3DDECLUSAGE_NORMAL with a usage index of 0 to specify vertex normals for fixed function vertex processing and the n-patch tessellator. Use D3DDECLUSAGE_NORMAL with a usage index of 1 to specify vertex normals for fixed function vertex processing for vertex tweening.
D3DDECLUSAGE_PSIZE
Point size data. Use D3DDECLUSAGE_PSIZE with a usage index of 0 to specify the point-size attribute used by the setup engine of the rasterizer to expand a point into a quad for the point-sprite functionality.
D3DDECLUSAGE_TEXCOORD
Texture coordinate data. Use D3DDECLUSAGE_TEXCOORD, n to specify texture coordinates in fixed function vertex processing and in pixel shaders prior to ps_3_0. These can be used to pass user defined data.
D3DDECLUSAGE_TANGENT
Vertex tangent data.
D3DDECLUSAGE_BINORMAL
Vertex binormal data.
D3DDECLUSAGE_TESSFACTOR
Single positive floating point value. Use D3DDECLUSAGE_TESSFACTOR with a usage index of 0 to specify a tessellation factor used in the tessellation unit to control the rate of tessellation. For more information about the data type, see D3DDECLTYPE_FLOAT1.
D3DDECLUSAGE_POSITIONT
Vertex data contains transformed position data ranging from (0,0) to (viewport width, viewport height). Use D3DDECLUSAGE_POSITIONT with a usage index of 0 to specify transformed position. When a declaration containing this is set, the pipeline does not perform vertex processing.
D3DDECLUSAGE_COLOR
Vertex data contains diffuse or specular color. Use D3DDECLUSAGE_COLOR with a usage index of 0 to specify the diffuse color in the fixed function vertex shader and pixel shaders prior to ps_3_0. Use D3DDECLUSAGE_COLOR with a usage index of 1 to specify the specular color in the fixed function vertex shader and pixel shaders prior to ps_3_0.
D3DDECLUSAGE_FOG
Vertex data contains fog data. Use D3DDECLUSAGE_FOG with a usage index of 0 to specify a fog blend value used after pixel shading finishes. This applies to pixel shaders prior to version ps_3_0.
D3DDECLUSAGE_DEPTH
Vertex data contains depth data.
D3DDECLUSAGE_SAMPLE
Vertex data contains sampler data. Use D3DDECLUSAGE_SAMPLE with a usage index of 0 to specify the displacement value to look up. It can be used only with D3DDECLUSAGE_LOOKUPPRESAMPLED or D3DDECLUSAGE_LOOKUP.

Remarks

Vertex data is declared with an array of D3DVERTEXELEMENT9 structures. Each element in the array contains a usage type.

For more information about vertex declarations, see Vertex Declaration (Direct3D 9).

See Also

Vertex Declaration (Direct3D 9)


D3DDEGREETYPE

Defines the degree of the variables in the equation that describes a curve.

typedef enum D3DDEGREETYPE
{
    D3DDEGREE_LINEAR = 1,
    D3DDEGREE_QUADRATIC = 2,
    D3DDEGREE_CUBIC = 3,
    D3DDEGREE_QUINTIC = 5,
    D3DCULL_FORCE_DWORD = 0x7fffffff,
} D3DDEGREETYPE, *LPD3DDEGREETYPE;

Constants

D3DDEGREE_LINEAR
Curve is described by variables of first order.
D3DDEGREE_QUADRATIC
Curve is described by variables of second order.
D3DDEGREE_CUBIC
Curve is described by variables of third order.
D3DDEGREE_QUINTIC
Curve is described by variables of fourth order.
D3DCULL_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The values in this enumeration are used to describe the curves used by rectangle and triangle patches. For more information, see D3DRS_CULLMODE.

See Also

D3DCAPS9, D3DRENDERSTATETYPE


D3DDEVTYPE

Defines device types.

typedef enum D3DDEVTYPE
{
    D3DDEVTYPE_HAL = 1,
    D3DDEVTYPE_NULLREF = 4,
    D3DDEVTYPE_REF = 2,
    D3DDEVTYPE_SW = 3,
    D3DDEVTYPE_FORCE_DWORD = 0xffffffff,
} D3DDEVTYPE, *LPD3DDEVTYPE;

Constants

D3DDEVTYPE_HAL
Hardware rasterization. Shading is done with software, hardware, or mixed transform and lighting.
D3DDEVTYPE_NULLREF
Initialize Direct3D on a computer that has neither hardware nor reference rasterization available, and enable resources for 3D content creation. See Remarks.
D3DDEVTYPE_REF
Direct3D features are implemented in software; however, the reference rasterizer does make use of special CPU instructions whenever it can.
D3DDEVTYPE_SW
A pluggable software device that has been registered with IDirect3D9::RegisterSoftwareDevice.
D3DDEVTYPE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

All methods of the IDirect3D9 interface that take a D3DDEVTYPE device type will fail if D3DDEVTYPE_NULLREF is specified. To use these methods, substitute D3DDEVTYPE_REF in the method call.

A D3DDEVTYPE_REF device should be created in D3DPOOL_SCRATCH memory, unless vertex and index buffers are required. To support vertex and index buffers, create the device in D3DPOOL_SYSTEMMEM memory.

If D3dref9.dll is installed, Direct3D will use the reference rasterizer to create a D3DDEVTYPE_REF device type, even if D3DDEVTYPE_NULLREF is specified. If D3dref9.dll is not available and D3DDEVTYPE_NULLREF is specified, Direct3D will neither render nor present the scene.

See Also

IDirect3D9::CheckDeviceFormat, IDirect3D9::CheckDeviceMultiSampleType, IDirect3D9::CheckDeviceType, IDirect3D9::CreateDevice, IDirect3D9::GetDeviceCaps, D3DDEVICE_CREATION_PARAMETERS


D3DDISPLAYROTATION (DirectX 9Ex only)

Specifies how the monitor being used to display a full-screen application is rotated.

typedef enum D3DDISPLAYROTATION
{
    D3DDISPLAYROTATION_IDENTITY = 1,
    D3DDISPLAYROTATION_90 = 2,
    D3DDISPLAYROTATION_180 = 2,
    D3DDISPLAYROTATION_270 = 2,
} D3DDISPLAYROTATION (DirectX 9Ex only), *LPD3DDISPLAYROTATION;

Constants

D3DDISPLAYROTATION_IDENTITY
Display is not rotated.
D3DDISPLAYROTATION_90
Display is rotated 90 degrees.
D3DDISPLAYROTATION_180
Display is rotated 180 degrees.
D3DDISPLAYROTATION_270
Display is rotated 270 degrees.

Remarks

This enumeration is used in IDirect3D9Ex::GetAdapterDisplayModeEx, IDirect3DDevice9Ex::GetDisplayModeEx, and IDirect3DSwapChain9Ex::GetDisplayModeEx.

Applications may choose to handle monitor rotation themselves by using the D3DPRESENTFLAG_NOAUTOROTATE, in which case, the application will need to know how the monitor is rotated so that it may adjust its rendering accordingly.

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Enumerations


D3DERR

Errors are represented by negative values and cannot be combined. The following is a list of the values that can be returned by Direct3D methods. See the individual method descriptions for lists of the values that each can return. These lists are not necessarily comprehensive.

typedef enum D3DERR
{
    D3D_OK,
    D3DOK_NOAUTOGEN,
    D3DERR_CONFLICTINGRENDERSTATE,
    D3DERR_CONFLICTINGTEXTUREFILTER,
    D3DERR_CONFLICTINGTEXTUREPALETTE,
    D3DERR_DEVICELOST,
    D3DERR_DEVICENOTRESET,
    D3DERR_DRIVERINTERNALERROR,
    D3DERR_DRIVERINVALIDCALL,
    D3DERR_INVALIDCALL,
    D3DERR_INVALIDDEVICE,
    D3DERR_MOREDATA,
    D3DERR_NOTAVAILABLE,
    D3DERR_NOTFOUND,
    D3DERR_OUTOFVIDEOMEMORY,
    D3DERR_TOOMANYOPERATIONS,
    D3DERR_UNSUPPORTEDALPHAARG,
    D3DERR_UNSUPPORTEDALPHAOPERATION,
    D3DERR_UNSUPPORTEDCOLORARG,
    D3DERR_UNSUPPORTEDCOLOROPERATION,
    D3DERR_UNSUPPORTEDFACTORVALUE,
    D3DERR_UNSUPPORTEDTEXTUREFILTER,
    D3DERR_WASSTILLDRAWING,
    D3DERR_WRONGTEXTUREFORMAT,
    E_FAIL,
    E_INVALIDARG,
    E_INVALIDCALL,
    E_NOINTERFACE,
    E_NOTIMPL,
    E_OUTOFMEMORY,
    S_OK,
} D3DERR, *LPD3DERR;

Constants

D3D_OK
No error occurred.
D3DOK_NOAUTOGEN
This is a success code. However, the autogeneration of mipmaps is not supported for this format. This means that resource creation will succeed but the mipmap levels will not be automatically generated.
D3DERR_CONFLICTINGRENDERSTATE
The currently set render states cannot be used together.
D3DERR_CONFLICTINGTEXTUREFILTER
The current texture filters cannot be used together.
D3DERR_CONFLICTINGTEXTUREPALETTE
The current textures cannot be used simultaneously.
D3DERR_DEVICELOST
The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_DEVICENOTRESET
The device has been lost but can be reset at this time.
D3DERR_DRIVERINTERNALERROR
Internal driver error. Applications should destroy and recreate the device when receiving this error. For hints on debugging this error, see Driver Internal Errors (Direct3D 9).
D3DERR_DRIVERINVALIDCALL
Not used.
D3DERR_INVALIDCALL
The method call is invalid. For example, a method's parameter may not be a valid pointer.
D3DERR_INVALIDDEVICE
The requested device type is not valid.
D3DERR_MOREDATA
There is more data available than the specified buffer size can hold.
D3DERR_NOTAVAILABLE
This device does not support the queried technique.
D3DERR_NOTFOUND
The requested item was not found.
D3DERR_OUTOFVIDEOMEMORY
Direct3D does not have enough display memory to perform the operation.
D3DERR_TOOMANYOPERATIONS
The application is requesting more texture-filtering operations than the device supports.
D3DERR_UNSUPPORTEDALPHAARG
The device does not support a specified texture-blending argument for the alpha channel.
D3DERR_UNSUPPORTEDALPHAOPERATION
The device does not support a specified texture-blending operation for the alpha channel.
D3DERR_UNSUPPORTEDCOLORARG
The device does not support a specified texture-blending argument for color values.
D3DERR_UNSUPPORTEDCOLOROPERATION
The device does not support a specified texture-blending operation for color values.
D3DERR_UNSUPPORTEDFACTORVALUE
The device does not support the specified texture factor value. Not used; provided only to support older drivers.
D3DERR_UNSUPPORTEDTEXTUREFILTER
The device does not support the specified texture filter.
D3DERR_WASSTILLDRAWING
The previous blit operation that is transferring information to or from this surface is incomplete.
D3DERR_WRONGTEXTUREFORMAT
The pixel format of the texture surface is not valid.
E_FAIL
An undetermined error occurred inside the Direct3D subsystem.
E_INVALIDARG
An invalid parameter was passed to the returning function.
E_INVALIDCALL
The method call is invalid. For example, a method's parameter may have an invalid value.
E_NOINTERFACE
No object interface is available.
E_NOTIMPL
Not implemented.
E_OUTOFMEMORY
Direct3D could not allocate sufficient memory to complete the call.
S_OK
No error occurred.

Remarks

The facility code _FACD3D is used to generate error codes, as in the following macros.

// Direct3D Errors
#define D3DERR_UNSUPPORTEDFACTORVALUE  MAKE_D3DHRESULT(2079)
#define D3DERR_WASSTILLDRAWING         MAKE_D3DHRESULT(540)

#define _FACD3D                  0x876   // Direct3D facility code
#define MAKE_D3DHRESULT( code )  MAKE_HRESULT( 1, _FACD3D, code )
#define MAKE_D3DSTATUS( code )   MAKE_HRESULT( 0, _FACD3D, code )


D3DFILLMODE

Defines constants describing the fill mode.

typedef enum D3DFILLMODE
{
    D3DFILL_POINT = 1,
    D3DFILL_WIREFRAME = 2,
    D3DFILL_SOLID = 3,
    D3DFILL_FORCE_DWORD = 0x7fffffff,
} D3DFILLMODE, *LPD3DFILLMODE;

Constants

D3DFILL_POINT
Fill points.
D3DFILL_WIREFRAME
Fill wireframes.
D3DFILL_SOLID
Fill solids.
D3DFILL_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_FILLMODE render state.

See Also

D3DRENDERSTATETYPE


D3DFOGMODE

Defines constants that describe the fog mode.

typedef enum D3DFOGMODE
{
    D3DFOG_NONE = 0,
    D3DFOG_EXP = 1,
    D3DFOG_EXP2 = 2,
    D3DFOG_LINEAR = 3,
    D3DFOG_FORCE_DWORD = 0x7fffffff,
} D3DFOGMODE, *LPD3DFOGMODE;

Constants

D3DFOG_NONE
No fog effect.
D3DFOG_EXP

Fog effect intensifies exponentially, according to the following formula.

Fog-effect intensity formula

D3DFOG_EXP2

Fog effect intensifies exponentially with the square of the distance, according to the following formula.

Fog-effect intensity formula

D3DFOG_LINEAR

Fog effect intensifies linearly between the start and end points, according to the following formula.

Fog-effect intensity formula

This is the only fog mode currently supported.

D3DFOG_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_FOGTABLEMODE and D3DRS_FOGVERTEXMODE render states.

Fog can be considered a measure of visibility&mdash;the lower the fog value produced by a fog equation, the less visible an object is.

See Also

D3DRENDERSTATETYPE


D3DFORMAT

Defines the various types of surface formats.

Syntax

typedef enum _D3DFORMAT {
...  (values)
} D3DFORMAT;

There are several types of formats:

  • BackBuffer or Display Formats
  • Buffer Formats
  • DXTn Compressed Texture Formats
  • Floating-Point Formats
  • FOURCC Formats
  • IEEE Formats
  • Mixed Formats
  • Signed Formats
  • Unsigned Formats
  • Other
  • Constant Information

All formats are listed from left to right, most-significant bit to least-significant bit. For example, D3DFORMAT_ARGB is ordered from the most-significant bit channel A (alpha), to the least-significant bit channel B (blue). When traversing surface data, the data is stored in memory from least-significant bit to most-significant bit, which means that the channel order in memory is from least-significant bit (blue) to most-significant bit (alpha).

The default value for formats that contain undefined channels (G16R16, A8, and so on) is 1. The only exception is the A8 format, which is initialized to 000 for the three color channels.

The order of the bits is from the most significant byte first, so D3DFMT_A8L8 indicates that the high byte of this 2-byte format is alpha. D3DFMT_D16 indicates a 16-bit integer value and an application-lockable surface.

Pixel formats have been chosen to enable the expression of hardware-vendor-defined extension formats, as well as to include the well-established FOURCC method. The set of formats understood by the Direct3D runtime is defined by D3DFORMAT.

Note that formats are supplied by independent hardware vendors (IHVs) and many FOURCC codes are not listed. The formats in this enumeration are unique in that they are sanctioned by the runtime, meaning that the reference rasterizer will operate on all these types. IHV-supplied formats will be supported by the individual IHVs on a card-by-card basis.

BackBuffer or Display Formats

These formats are the only valid formats for a back buffer or a display.

Format | Back buffer | Display
A2R10G10B10 | x | x (full-screen mode only)
A8R8G8B8 | x |
X8R8G8B8 | x | x
A1R5G5B5 | x |
X1R5G5B5 | x | x
R5G6B5 | x | x

Buffer Formats

Depth, stencil, vertex, and index buffers each have unique formats.

Buffer flags | Value | Format
D3DFMT_D16_LOCKABLE | 70 | 16-bit z-buffer bit depth.
D3DFMT_D32 | 71 | 32-bit z-buffer bit depth.
D3DFMT_D15S1 | 73 | 16-bit z-buffer bit depth where 15 bits are reserved for the depth channel and 1 bit is reserved for the stencil channel.
D3DFMT_D24S8 | 75 | 32-bit z-buffer bit depth using 24 bits for the depth channel and 8 bits for the stencil channel.
D3DFMT_D24X8 | 77 | 32-bit z-buffer bit depth using 24 bits for the depth channel.
D3DFMT_D24X4S4 | 79 | 32-bit z-buffer bit depth using 24 bits for the depth channel and 4 bits for the stencil channel.
D3DFMT_D32F_LOCKABLE | 82 | A lockable format where the depth value is represented as a standard IEEE floating-point number.
D3DFMT_D24FS8 | 83 | A non-lockable format that contains 24 bits of depth (in a 24-bit floating point format - 20e4) and 8 bits of stencil.
D3DFMT_D32_LOCKABLE | 84 | Direct3D 9Ex only - A lockable 32-bit depth buffer.
D3DFMT_S8_LOCKABLE | 84 | Direct3D 9Ex only - A lockable 8-bit stencil buffer.
D3DFMT_D16 | 80 | 16-bit z-buffer bit depth.
D3DFMT_VERTEXDATA | 100 | Describes a vertex buffer surface.
D3DFMT_INDEX16 | 101 | 16-bit index buffer bit depth.
D3DFMT_INDEX32 | 102 | 32-bit index buffer bit depth.

All depth-stencil formats except D3DFMT_D16_LOCKABLE indicate no particular bit ordering per pixel, and the driver is allowed to consume more than the indicated number of bits-per-depth channel (but not stencil channel).

DXTn Compressed Texture Formats

These flags are used for compressed textures:

DXTn Compressed Texture flags | Value | Format
D3DFMT_DXT1 | MAKEFOURCC('D', 'X', 'T', '1') | DXT1 compression texture format
D3DFMT_DXT2 | MAKEFOURCC('D', 'X', 'T', '2') | DXT2 compression texture format
D3DFMT_DXT3 | MAKEFOURCC('D', 'X', 'T', '3') | DXT3 compression texture format
D3DFMT_DXT4 | MAKEFOURCC('D', 'X', 'T', '4') | DXT4 compression texture format
D3DFMT_DXT5 | MAKEFOURCC('D', 'X', 'T', '5') | DXT5 compression texture format

The runtime will not allow an application to create a surface using a DXTn format unless the surface dimensions are multiples of 4. This applies to offscreen-plain surfaces, render targets, 2D textures, cube textures, and volume textures.

Floating-Point Formats

These flags are used for floating-point surface formats. These 16-bits-per-channel formats are also known as s10e5 formats.

Floating-point flags | Value | Format
D3DFMT_R16F | 111 | 16-bit float format using 16 bits for the red channel.
D3DFMT_G16R16F | 112 | 32-bit float format using 16 bits for the red channel and 16 bits for the green channel.
D3DFMT_A16B16G16R16F | 113 | 64-bit float format using 16 bits for the each channel (alpha, blue, green, red).

FOURCC Formats

Data in a FOURCC format is compressed data.

MAKEFOURCC

A macro for generating four-character codes follows:

#define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
                ((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) |   \
                ((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24 ))

Here are the defined FOURCC formats:

FOURCC flags | Value | Format
D3DFMT_MULTI2_ARGB8 | MAKEFOURCC('M','E','T','1') | MultiElement texture (not compressed)
D3DFMT_G8R8_G8B8 | MAKEFOURCC('G', 'R', 'G', 'B') | A 16-bit packed RGB format analogous to YUY2 (Y0U0, Y1V0, Y2U2, and so on). It requires a pixel pair in order to properly represent the color value. The first pixel in the pair contains 8 bits of green (in the high 8 bits) and 8 bits of red (in the low 8 bits). The second pixel contains 8 bits of green (in the high 8 bits) and 8 bits of blue (in the low 8 bits). Together, the two pixels share the red and blue components, while each has a unique green component (G0R0, G1B0, G2R2, and so on). The texture sampler does not normalize the colors when looking up into a pixel shader; they remain in the range of 0.0f to 255.0f. This is true for all programmable pixel shader models. For the fixed function pixel shader, the hardware should normalize to the 0.f to 1.f range and essentially treat it as the YUY2 texture. Hardware that exposes this format must have the PixelShader1xMaxValue member of D3DCAPS9 set to a value capable of handling that range.
D3DFMT_R8G8_B8G8 | MAKEFOURCC('R', 'G', 'B', 'G') | A 16-bit packed RGB format analogous to UYVY (U0Y0, V0Y1, U2Y2, and so on). It requires a pixel pair in order to properly represent the color value. The first pixel in the pair contains 8 bits of green (in the low 8 bits) and 8 bits of red (in the high 8 bits). The second pixel contains 8 bits of green (in the low 8 bits) and 8 bits of blue (in the high 8 bits). Together, the two pixels share the red and blue components, while each has a unique green component (R0G0, B0G1, R2G2, and so on). The texture sampler does not normalize the colors when looking up into a pixel shader; they remain in the range of 0.0f to 255.0f. This is true for all programmable pixel shader models. For the fixed function pixel shader, the hardware should normalize to the 0.f to 1.f range and essentially treat it as the YUY2 texture. Hardware that exposes this format must have PixelShader1xMaxValue member of D3DCAPS9 set to a value capable of handling that range.
D3DFMT_UYVY | MAKEFOURCC('U', 'Y', 'V', 'Y') | UYVY format (PC98 compliance)
D3DFMT_YUY2 | MAKEFOURCC('Y', 'U', 'Y', '2') | YUY2 format (PC98 compliance)

IEEE Formats

These flags are used for floating-point surface formats. These 32-bits-per-channel formats are also known as s23e8 formats.

Floating-point flags | Value | Format
D3DFMT_R32F | 114 | 32-bit float format using 32 bits for the red channel.
D3DFMT_G32R32F | 115 | 64-bit float format using 32 bits for the red channel and 32 bits for the green channel.
D3DFMT_A32B32G32R32F | 116 | 128-bit float format using 32 bits for the each channel (alpha, blue, green, red).

Mixed Formats

Data in mixed formats can contain a combination of unsigned data and signed data.

Mixed format flags | Value | Format
D3DFMT_L6V5U5 | 61 | 16-bit bump-map format with luminance using 6 bits for luminance, and 5 bits each for v and u.
D3DFMT_X8L8V8U8 | 62 | 32-bit bump-map format with luminance using 8 bits for each channel.
D3DFMT_A2W10V10U10 | 67 | 32-bit bump-map format using 2 bits for alpha and 10 bits each for w, v, and u.

Signed Formats

Data in a signed format can be both positive and negative. Signed formats use combinations of (U), (V), (W), and (Q) data.

Signed format flags | Value | Format
D3DFMT_V8U8 | 60 | 16-bit bump-map format using 8 bits each for u and v data.
D3DFMT_Q8W8V8U8 | 63 | 32-bit bump-map format using 8 bits for each channel.
D3DFMT_V16U16 | 64 | 32-bit bump-map format using 16 bits for each channel.
D3DFMT_Q16W16V16U16 | 110 | 64-bit bump-map format using 16 bits for each component.
D3DFMT_CxV8U8 | 117 | 16-bit normal compression format. The texture sampler computes the C channel from: C = sqrt(1 - U2 - V2).

Unsigned Formats

Data in an unsigned format must be positive. Unsigned formats use combinations of (R)ed, (G)reen, (B)lue, (A)lpha, (L)uminance, and (P)alette data. Palette data is also referred to as color indexed data because the data is used to index a color palette.

Unsigned format flags | Value | Format
D3DFMT_R8G8B8 | 20 | 24-bit RGB pixel format with 8 bits per channel.
D3DFMT_A8R8G8B8 | 21 | 32-bit ARGB pixel format with alpha, using 8 bits per channel.
D3DFMT_X8R8G8B8 | 22 | 32-bit RGB pixel format, where 8 bits are reserved for each color.
D3DFMT_R5G6B5 | 23 | 16-bit RGB pixel format with 5 bits for red, 6 bits for green, and 5 bits for blue.
D3DFMT_X1R5G5B5 | 24 | 16-bit pixel format where 5 bits are reserved for each color.
D3DFMT_A1R5G5B5 | 25 | 16-bit pixel format where 5 bits are reserved for each color and 1 bit is reserved for alpha.
D3DFMT_A4R4G4B4 | 26 | 16-bit ARGB pixel format with 4 bits for each channel.
D3DFMT_R3G3B2 | 27 | 8-bit RGB texture format using 3 bits for red, 3 bits for green, and 2 bits for blue.
D3DFMT_A8 | 28 | 8-bit alpha only.
D3DFMT_A8R3G3B2 | 29 | 16-bit ARGB texture format using 8 bits for alpha, 3 bits each for red and green, and 2 bits for blue.
D3DFMT_X4R4G4B4 | 30 | 16-bit RGB pixel format using 4 bits for each color.
D3DFMT_A2B10G10R10 | 31 | 32-bit pixel format using 10 bits for each color and 2 bits for alpha.
D3DFMT_A8B8G8R8 | 32 | 32-bit ARGB pixel format with alpha, using 8 bits per channel.
D3DFMT_X8B8G8R8 | 33 | 32-bit RGB pixel format, where 8 bits are reserved for each color.
D3DFMT_G16R16 | 34 | 32-bit pixel format using 16 bits each for green and red.
D3DFMT_A2R10G10B10 | 35 | 32-bit pixel format using 10 bits each for red, green, and blue, and 2 bits for alpha.
D3DFMT_A16B16G16R16 | 36 | 64-bit pixel format using 16 bits for each component.
D3DFMT_A8P8 | 40 | 8-bit color indexed with 8 bits of alpha.
D3DFMT_P8 | 41 | 8-bit color indexed.
D3DFMT_L8 | 50 | 8-bit luminance only.
D3DFMT_L16 | 81 | 16-bit luminance only.
D3DFMT_A8L8 | 51 | 16-bit using 8 bits each for alpha and luminance.
D3DFMT_A4L4 | 52 | 8-bit using 4 bits each for alpha and luminance.
D3DFMT_A1 | 118 | Direct3D 9Ex only - 1-bit monochrome.
D3DFMT_BINARYBUFFER | 199 | Direct3D 9Ex only - Binary format indicating that the data has no inherent type.

Other

This flag is used for undefined formats.

Other flags | Value | Format
D3DFMT_UNKNOWN | 0 | Surface format is unknown

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98


D3DLIGHTTYPE

Defines the light type.

typedef enum D3DLIGHTTYPE
{
    D3DLIGHT_POINT = 1,
    D3DLIGHT_SPOT = 2,
    D3DLIGHT_DIRECTIONAL = 3,
    D3DLIGHT_FORCE_DWORD = 0x7fffffff,
} D3DLIGHTTYPE, *LPD3DLIGHTTYPE;

Constants

D3DLIGHT_POINT
Light is a point source. The light has a position in space and radiates light in all directions.
D3DLIGHT_SPOT
Light is a spotlight source. This light is like a point light, except that the illumination is limited to a cone. This light type has a direction and several other parameters that determine the shape of the cone it produces. For information about these parameters, see the D3DLIGHT9 structure.
D3DLIGHT_DIRECTIONAL
Light is a directional light source. This is equivalent to using a point light source at an infinite distance.
D3DLIGHT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Directional lights are slightly faster than point light sources, but point lights look a little better. Spotlights offer interesting visual effects but are computationally time-consuming.

See Also

D3DLIGHT9


D3DMATERIALCOLORSOURCE

Defines the location at which a color or color component must be accessed for lighting calculations.

typedef enum D3DMATERIALCOLORSOURCE
{
    D3DMCS_MATERIAL = 0,
    D3DMCS_COLOR1 = 1,
    D3DMCS_COLOR2 = 2,
    D3DMCS_FORCE_DWORD = 0x7fffffff,
} D3DMATERIALCOLORSOURCE, *LPD3DMATERIALCOLORSOURCE;

Constants

D3DMCS_MATERIAL
Use the color from the current material.
D3DMCS_COLOR1
Use the diffuse vertex color.
D3DMCS_COLOR2
Use the specular vertex color.
D3DMCS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

These flags are used to set the value of the following render states in the D3DRENDERSTATETYPE enumerated type.

  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE

See Also

D3DRENDERSTATETYPE


D3DMULTISAMPLE_TYPE

Defines the levels of full-scene multisampling that the device can apply.

typedef enum D3DMULTISAMPLE_TYPE
{
    D3DMULTISAMPLE_NONE = 0,
    D3DMULTISAMPLE_NONMASKABLE  = 1,
    D3DMULTISAMPLE_2_SAMPLES = 2,
    D3DMULTISAMPLE_3_SAMPLES = 3,
    D3DMULTISAMPLE_4_SAMPLES = 4,
    D3DMULTISAMPLE_5_SAMPLES = 5,
    D3DMULTISAMPLE_6_SAMPLES = 6,
    D3DMULTISAMPLE_7_SAMPLES = 7,
    D3DMULTISAMPLE_8_SAMPLES = 8,
    D3DMULTISAMPLE_9__SAMPLES = 9,
    D3DMULTISAMPLE_10_SAMPLES = 10,
    D3DMULTISAMPLE_11_SAMPLES = 11,
    D3DMULTISAMPLE_12_SAMPLES = 12,
    D3DMULTISAMPLE_13_SAMPLES = 13,
    D3DMULTISAMPLE_14_SAMPLES = 14,
    D3DMULTISAMPLE_15_SAMPLES = 15,
    D3DMULTISAMPLE_16_SAMPLES = 16,
    D3DMULTISAMPLE_FORCE_DWORD = 0xffffffff,
} D3DMULTISAMPLE_TYPE, *LPD3DMULTISAMPLE_TYPE;

Constants

D3DMULTISAMPLE_NONE
No level of full-scene multisampling is available.
D3DMULTISAMPLE_NONMASKABLE
Enables the multisample quality value. See Remarks.
D3DMULTISAMPLE_2_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_3_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_4_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_5_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_6_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_7_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_8_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_9__SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_10_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_11_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_12_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_13_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_14_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_15_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_16_SAMPLES
Level of full-scene multisampling available.
D3DMULTISAMPLE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

In addition to enabling full-scene multisampling at IDirect3DDevice9::Reset time, there will be render states that turn various aspects on and off at fine-grained levels.

Multisampling is valid only on a swap chain that is being created or reset with the D3DSWAPEFFECT_DISCARD swap effect.

The multisample antialiasing value can be set with the parameters (or sub-parameters) in the following methods.

Method | Parameters | Sub-parameters
IDirect3D9::CheckDeviceMultiSampleType | MultiSampleType and pQualityLevels |
IDirect3D9::CreateDevice | pPresentationParameters | MultiSampleType and pQualityLevels
IDirect3DDevice9::CreateAdditionalSwapChain | pPresentationParameters | MultiSampleType and pQualityLevels
IDirect3DDevice9::CreateDepthStencilSurface | MultiSampleType and pQualityLevels |
IDirect3DDevice9::CreateRenderTarget | MultiSampleType and pQualityLevels |
IDirect3DDevice9::Reset | pPresentationParameters | MultiSampleType and pQualityLevels

It is not good practice to switch from one multisample type to another to raise the quality of the antialiasing.

D3DMULTISAMPLE_NONE enables swap effects other than discarding, locking, and so on.

Whether the display device supports maskable multisampling (more than one sample for a multiple-sample render-target format plus antialias support) or just non-maskable multisampling (only antialias support), the driver for the device provides the number of quality levels for the D3DMULTISAMPLE_NONMASKABLE multiple-sample type. Applications that just use multisampling for antialiasing purposes only need to query for the number of non-maskable multiple-sample quality levels that the driver supports.

The quality levels supported by the device can be obtained with the pQualityLevels parameter of IDirect3D9::CheckDeviceMultiSampleType. Quality levels used by the application are set with the MultiSampleQuality parameter of IDirect3DDevice9::CreateDepthStencilSurface and IDirect3DDevice9::CreateRenderTarget.

See D3DRS_MULTISAMPLEMASK for discussion of maskable multisampling.

See Also

D3DPRESENT_PARAMETERS, D3DSURFACE_DESC


D3DPATCHEDGESTYLE

Defines whether the current tessellation mode is discrete or continuous.

typedef enum D3DPATCHEDGESTYLE
{
    D3DPATCHEDGE_DISCRETE = 0,
    D3DPATCHEDGE_CONTINUOUS = 1,
    D3DPATCHEDGE_FORCE_DWORD = 0x7fffffff,
} D3DPATCHEDGESTYLE, *LPD3DPATCHEDGESTYLE;

Constants

D3DPATCHEDGE_DISCRETE
Discrete edge style. In discrete mode, you can specify float tessellation but it will be truncated to integers.
D3DPATCHEDGE_CONTINUOUS
Continuous edge style. In continuous mode, tessellation is specified as float values that can be smoothly varied to reduce "popping" artifacts.
D3DPATCHEDGE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Note that continuous tessellation produces a completely different tessellation pattern from the discrete one for the same tessellation values (this is more apparent in wireframe mode). Thus, 4.0 continuous is not the same as 4 discrete.


D3DPOOL

Defines the memory class that holds the buffers for a resource.

typedef enum D3DPOOL
{
    D3DPOOL_DEFAULT = 0,
    D3DPOOL_MANAGED = 1,
    D3DPOOL_SYSTEMMEM = 2,
    D3DPOOL_SCRATCH = 3,
    D3DPOOL_FORCE_DWORD = 0x7fffffff,
} D3DPOOL, *LPD3DPOOL;

Constants

D3DPOOL_DEFAULT
Resources are placed in the memory pool most appropriate for the set of usages requested for the given resource. This is usually video memory, including both local video memory and AGP memory. The D3DPOOL_DEFAULT pool is separate from D3DPOOL_MANAGED and D3DPOOL_SYSTEMMEM, and it specifies that the resource is placed in the preferred memory for device access. Note that D3DPOOL_DEFAULT never indicates that either D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM should be chosen as the memory pool type for this resource. Textures placed in the D3DPOOL_DEFAULT pool cannot be locked unless they are dynamic textures or they are private, FOURCC, driver formats. To access unlockable textures, you must use functions such as IDirect3DDevice9::UpdateSurface, IDirect3DDevice9::UpdateTexture, IDirect3DDevice9::GetFrontBufferData, and IDirect3DDevice9::GetRenderTargetData. D3DPOOL_MANAGED is probably a better choice than D3DPOOL_DEFAULT for most applications. Note that some textures created in driver-proprietary pixel formats, unknown to the Direct3D runtime, can be locked. Also note that - unlike textures - swap chain back buffers, render targets, vertex buffers, and index buffers can be locked. When a device is lost, resources created using D3DPOOL_DEFAULT must be released before calling IDirect3DDevice9::Reset. For more information, see Lost Devices (Direct3D 9).

When creating resources with D3DPOOL_DEFAULT, if video card memory is already committed, managed resources will be evicted to free enough memory to satisfy the request.

D3DPOOL_MANAGED
Resources are copied automatically to device-accessible memory as needed. Managed resources are backed by system memory and do not need to be recreated when a device is lost. See Managing Resources (Direct3D 9) for more information. Managed resources can be locked. Only the system-memory copy is directly modified. Direct3D copies your changes to driver-accessible memory as needed.
D3DPOOL_SYSTEMMEM
Resources are placed in memory that is not typically accessible by the Direct3D device. This memory allocation consumes system RAM but does not reduce pageable RAM. These resources do not need to be recreated when a device is lost. Resources in this pool can be locked and can be used as the source for a IDirect3DDevice9::UpdateSurface or IDirect3DDevice9::UpdateTexture operation to a memory resource created with D3DPOOL_DEFAULT.
D3DPOOL_SCRATCH
Resources are placed in system RAM and do not need to be recreated when a device is lost. These resources are not bound by device size or format restrictions. Because of this, these resources cannot be accessed by the Direct3D device nor set as textures or render targets. However, these resources can always be created, locked, and copied.
D3DPOOL_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

All pool types are valid with all resources. This includes: vertex buffers, index buffers, textures, and surfaces.

The following tables indicate restrictions on pool types for render targets, depth stencils, and dynamic and mipmap usages. An x indicates a compatible combination; lack of an x indicates incompatibility.

Pool | D3DUSAGE_RENDERTARGET | D3DUSAGE_DEPTHSTENCIL
D3DPOOL_DEFAULT | x | x
D3DPOOL_MANAGED |  |
D3DPOOL_SCRATCH |  |
D3DPOOL_SYSTEMMEM |  |
Pool | D3DUSAGE_DYNAMIC | D3DUSAGE_AUTOGENMIPMAP
D3DPOOL_DEFAULT | x | x
D3DPOOL_MANAGED |  | x
D3DPOOL_SCRATCH |  |
D3DPOOL_SYSTEMMEM | x |

For more information about usage types, see D3DUSAGE.

Pools cannot be mixed for different objects contained within one resource (mip levels in a mipmap) and, when a pool is chosen, it cannot be changed.

Applications should use D3DPOOL_MANAGED for most static resources because this saves the application from having to deal with lost devices. (Managed resources are restored by the runtime.) This is especially beneficial for unified memory architecture (UMA) systems. Other dynamic resources are not a good match for D3DPOOL_MANAGED. In fact, index buffers and vertex buffers cannot be created using D3DPOOL_MANAGED together with D3DUSAGE_DYNAMIC.

For dynamic textures, it is sometimes desirable to use a pair of video memory and system memory textures, allocating the video memory using D3DPOOL_DEFAULT and the system memory using D3DPOOL_SYSTEMMEM. You can lock and modify the bits of the system memory texture using a locking method. Then you can update the video memory texture using IDirect3DDevice9::UpdateTexture.

See Also

D3DUSAGE, IDirect3DDevice9::CreateCubeTexture, IDirect3DDevice9::CreateIndexBuffer, IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateVolumeTexture, IDirect3DDevice9::CreateVertexBuffer, D3DINDEXBUFFER_DESC, D3DSURFACE_DESC, D3DVERTEXBUFFER_DESC, D3DVOLUME_DESC


D3DPRIMITIVETYPE

Defines the primitives supported by Direct3D.

typedef enum D3DPRIMITIVETYPE
{
    D3DPT_POINTLIST = 1,
    D3DPT_LINELIST = 2,
    D3DPT_LINESTRIP = 3,
    D3DPT_TRIANGLELIST = 4,
    D3DPT_TRIANGLESTRIP = 5,
    D3DPT_TRIANGLEFAN = 6,
    D3DPT_FORCE_DWORD = 0x7fffffff,
} D3DPRIMITIVETYPE, *LPD3DPRIMITIVETYPE;

Constants

D3DPT_POINTLIST
Renders the vertices as a collection of isolated points. This value is unsupported for indexed primitives.
D3DPT_LINELIST
Renders the vertices as a list of isolated straight line segments.
D3DPT_LINESTRIP
Renders the vertices as a single polyline.
D3DPT_TRIANGLELIST

Renders the specified vertices as a sequence of isolated triangles. Each group of three vertices defines a separate triangle.

Back-face culling is affected by the current winding-order render state.

D3DPT_TRIANGLESTRIP
Renders the vertices as a triangle strip. The backface-culling flag is automatically flipped on even-numbered triangles.
D3DPT_TRIANGLEFAN
Renders the vertices as a triangle fan.
D3DPT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Using Triangle Strips (Direct3D 9) or Triangle Fans (Direct3D 9) is often more efficient than using triangle lists because fewer vertices are duplicated.

See Also

IDirect3DDevice9::DrawIndexedPrimitive, IDirect3DDevice9::DrawIndexedPrimitiveUP, IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawPrimitiveUP


D3DQUERYTYPE

Identifies the query type. For information about queries, see Queries (Direct3D 9)

typedef enum D3DQUERYTYPE
{
    D3DQUERYTYPE_VCACHE = 4,
    D3DQUERYTYPE_ResourceManager = 5,
    D3DQUERYTYPE_VERTEXSTATS = 6,
    D3DQUERYTYPE_EVENT = 8,
    D3DQUERYTYPE_OCCLUSION = 9,
    D3DQUERYTYPE_TIMESTAMP = 10,
    D3DQUERYTYPE_TIMESTAMPDISJOINT = 11,
    D3DQUERYTYPE_TIMESTAMPFREQ = 12,
    D3DQUERYTYPE_PIPELINETIMINGS = 13,
    D3DQUERYTYPE_INTERFACETIMINGS = 14,
    D3DQUERYTYPE_VERTEXTIMINGS = 15,
    D3DQUERYTYPE_PIXELTIMINGS = 16,
    D3DQUERYTYPE_BANDWIDTHTIMINGS = 17,
    D3DQUERYTYPE_CACHEUTILIZATION = 18,
} D3DQUERYTYPE, *LPD3DQUERYTYPE;

Constants

D3DQUERYTYPE_VCACHE
Query for driver hints about data layout for vertex caching.
D3DQUERYTYPE_ResourceManager
Query the resource manager. For this query, the device behavior flags must include D3DCREATE_DISABLE_DRIVER_MANAGEMENT.
D3DQUERYTYPE_VERTEXSTATS
Query vertex statistics.
D3DQUERYTYPE_EVENT
Query for any and all asynchronous events that have been issued from API calls.
D3DQUERYTYPE_OCCLUSION
An occlusion query returns the number of pixels that pass z-testing. These pixels are for primitives drawn between the issue of D3DISSUE_BEGIN and D3DISSUE_END. This enables an application to check the occlusion result against 0. Zero is fully occluded, which means the pixels are not visible from the current camera position.
D3DQUERYTYPE_TIMESTAMP
Returns a 64-bit timestamp.
D3DQUERYTYPE_TIMESTAMPDISJOINT
Use this query to notify an application if the counter frequency has changed from the D3DQUERYTYPE_TIMESTAMP.
D3DQUERYTYPE_TIMESTAMPFREQ
This query result is TRUE if the values from D3DQUERYTYPE_TIMESTAMP queries cannot be guaranteed to be continuous throughout the duration of the D3DQUERYTYPE_TIMESTAMPDISJOINT query. Otherwise, the query result is FALSE.
D3DQUERYTYPE_PIPELINETIMINGS
Percent of time processing pipeline data.
D3DQUERYTYPE_INTERFACETIMINGS
Percent of time processing data in the driver.
D3DQUERYTYPE_VERTEXTIMINGS
Percent of time processing vertex shader data.
D3DQUERYTYPE_PIXELTIMINGS
Percent of time processing pixel shader data.
D3DQUERYTYPE_BANDWIDTHTIMINGS
Throughput measurement comparisons for help in understanding the performance of an application.
D3DQUERYTYPE_CACHEUTILIZATION
Measure the cache hit-rate performance for textures and indexed vertices.

See Also

IDirect3DDevice9::CreateQuery


D3DRENDERSTATETYPE

Render states define set-up states for all kinds of vertex and pixel processing. Some render states set up vertex processing, and some set up pixel processing (see Render States (Direct3D 9)). Render states can be saved and restored using stateblocks (see State Blocks Save and Restore State (Direct3D 9)).

typedef enum D3DRENDERSTATETYPE
{
    D3DRS_ZENABLE = 7,
    D3DRS_FILLMODE = 8,
    D3DRS_SHADEMODE = 9,
    D3DRS_ZWRITEENABLE = 14,
    D3DRS_ALPHATESTENABLE = 15,
    D3DRS_LASTPIXEL = 16,
    D3DRS_SRCBLEND = 19,
    D3DRS_DESTBLEND = 20,
    D3DRS_CULLMODE = 22,
    D3DRS_ZFUNC = 23,
    D3DRS_ALPHAREF = 24,
    D3DRS_ALPHAFUNC = 25,
    D3DRS_DITHERENABLE = 26,
    D3DRS_ALPHABLENDENABLE = 27,
    D3DRS_FOGENABLE = 28,
    D3DRS_SPECULARENABLE = 29,
    D3DRS_FOGCOLOR = 34,
    D3DRS_FOGTABLEMODE = 35,
    D3DRS_FOGSTART = 36,
    D3DRS_FOGEND = 37,
    D3DRS_FOGDENSITY = 38,
    D3DRS_RANGEFOGENABLE = 48,
    D3DRS_STENCILENABLE = 52,
    D3DRS_STENCILFAIL = 53,
    D3DRS_STENCILZFAIL = 54,
    D3DRS_STENCILPASS = 55,
    D3DRS_STENCILFUNC = 56,
    D3DRS_STENCILREF = 57,
    D3DRS_STENCILMASK = 58,
    D3DRS_STENCILWRITEMASK = 59,
    D3DRS_TEXTUREFACTOR = 60,
    D3DRS_WRAP0 = 128,
    D3DRS_WRAP1 = 129,
    D3DRS_WRAP2 = 130,
    D3DRS_WRAP3 = 131,
    D3DRS_WRAP4 = 132,
    D3DRS_WRAP5 = 133,
    D3DRS_WRAP6 = 134,
    D3DRS_WRAP7 = 135,
    D3DRS_CLIPPING = 136,
    D3DRS_LIGHTING = 137,
    D3DRS_AMBIENT = 139,
    D3DRS_FOGVERTEXMODE = 140,
    D3DRS_COLORVERTEX = 141,
    D3DRS_LOCALVIEWER = 142,
    D3DRS_NORMALIZENORMALS = 143,
    D3DRS_DIFFUSEMATERIALSOURCE = 145,
    D3DRS_SPECULARMATERIALSOURCE = 146,
    D3DRS_AMBIENTMATERIALSOURCE = 147,
    D3DRS_EMISSIVEMATERIALSOURCE = 148,
    D3DRS_VERTEXBLEND = 151,
    D3DRS_CLIPPLANEENABLE = 152,
    D3DRS_POINTSIZE = 154,
    D3DRS_POINTSIZE_MIN = 155,
    D3DRS_POINTSPRITEENABLE = 156,
    D3DRS_POINTSCALEENABLE = 157,
    D3DRS_POINTSCALE_A = 158,
    D3DRS_POINTSCALE_B = 159,
    D3DRS_POINTSCALE_C = 160,
    D3DRS_MULTISAMPLEANTIALIAS = 161,
    D3DRS_MULTISAMPLEMASK = 162,
    D3DRS_PATCHEDGESTYLE = 163,
    D3DRS_DEBUGMONITORTOKEN = 165,
    D3DRS_POINTSIZE_MAX = 166,
    D3DRS_INDEXEDVERTEXBLENDENABLE = 167,
    D3DRS_COLORWRITEENABLE = 168,
    D3DRS_TWEENFACTOR = 170,
    D3DRS_BLENDOP = 171,
    D3DRS_POSITIONDEGREE = 172,
    D3DRS_NORMALDEGREE = 173,
    D3DRS_SCISSORTESTENABLE = 174,
    D3DRS_SLOPESCALEDEPTHBIAS = 175,
    D3DRS_ANTIALIASEDLINEENABLE = 176,
    D3DRS_MINTESSELLATIONLEVEL = 178,
    D3DRS_MAXTESSELLATIONLEVEL = 179,
    D3DRS_ADAPTIVETESS_X = 180,
    D3DRS_ADAPTIVETESS_Y = 181,
    D3DRS_ADAPTIVETESS_Z = 182,
    D3DRS_ADAPTIVETESS_W = 183,
    D3DRS_ENABLEADAPTIVETESSELLATION = 184,
    D3DRS_TWOSIDEDSTENCILMODE = 185,
    D3DRS_CCW_STENCILFAIL = 186,
    D3DRS_CCW_STENCILZFAIL = 187,
    D3DRS_CCW_STENCILPASS = 188,
    D3DRS_CCW_STENCILFUNC = 189,
    D3DRS_COLORWRITEENABLE1 = 190,
    D3DRS_COLORWRITEENABLE2 = 191,
    D3DRS_COLORWRITEENABLE3 = 192,
    D3DRS_BLENDFACTOR = 193,
    D3DRS_SRGBWRITEENABLE = 194,
    D3DRS_DEPTHBIAS = 195,
    D3DRS_WRAP8 = 198,
    D3DRS_WRAP9 = 199,
    D3DRS_WRAP10 = 200,
    D3DRS_WRAP11 = 201,
    D3DRS_WRAP12 = 202,
    D3DRS_WRAP13 = 203,
    D3DRS_WRAP14 = 204,
    D3DRS_WRAP15 = 205,
    D3DRS_SEPARATEALPHABLENDENABLE = 206,
    D3DRS_SRCBLENDALPHA = 207,
    D3DRS_DESTBLENDALPHA = 208,
    D3DRS_BLENDOPALPHA = 209,
    D3DRS_FORCE_DWORD = 0x7fffffff,
} D3DRENDERSTATETYPE, *LPD3DRENDERSTATETYPE;

Constants

D3DRS_ZENABLE
Depth-buffering state as one member of the D3DZBUFFERTYPE enumerated type. Set this state to D3DZB_TRUE to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE to disable depth buffering.

The default value for this render state is D3DZB_TRUE if a depth stencil was created along with the swap chain by setting the EnableAutoDepthStencil member of the D3DPRESENT_PARAMETERS structure to TRUE, and D3DZB_FALSE otherwise.

D3DRS_FILLMODE
One or more members of the D3DFILLMODE enumerated type. The default value is D3DFILL_SOLID.
D3DRS_SHADEMODE
One or more members of the D3DSHADEMODE enumerated type. The default value is D3DSHADE_GOURAUD.
D3DRS_ZWRITEENABLE
TRUE to enable the application to write to the depth buffer. The default value is TRUE. This member enables an application to prevent the system from updating the depth buffer with new depth values. If FALSE, depth comparisons are still made according to the render state D3DRS_ZFUNC, assuming that depth buffering is taking place, but depth values are not written to the buffer.
D3DRS_ALPHATESTENABLE
TRUE to enable per pixel alpha testing. If the test passes, the pixel is processed by the frame buffer. Otherwise, all frame-buffer processing is skipped for the pixel.

The test is done by comparing the incoming alpha value with the reference alpha value, using the comparison function provided by the D3DRS_ALPHAFUNC render state. The reference alpha value is determined by the value set for D3DRS_ALPHAREF. For more information, see Alpha Testing State (Direct3D 9).

The default value of this parameter is FALSE.

D3DRS_LASTPIXEL
The default value is TRUE, which enables drawing of the last pixel in a line. To prevent drawing of the last pixel, set this value to FALSE. For more information, see Outline and Fill State (Direct3D 9).
D3DRS_SRCBLEND
One member of the D3DBLEND enumerated type. The default value is D3DBLEND_ONE.
D3DRS_DESTBLEND
One member of the D3DBLEND enumerated type. The default value is D3DBLEND_ZERO.
D3DRS_CULLMODE
Specifies how back-facing triangles are culled, if at all. This can be set to one member of the D3DCULL enumerated type. The default value is D3DCULL_CCW.
D3DRS_ZFUNC
One member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_LESSEQUAL. This member enables an application to accept or reject a pixel, based on its distance from the camera.

The depth value of the pixel is compared with the depth-buffer value. If the depth value of the pixel passes the comparison function, the pixel is written.

The depth value is written to the depth buffer only if the render state is TRUE.

Software rasterizers and many hardware accelerators work faster if the depth test fails, because there is no need to filter and modulate the texture if the pixel is not going to be rendered.

D3DRS_ALPHAREF
Value that specifies a reference alpha value against which pixels are tested when alpha testing is enabled. This is an 8-bit value placed in the low 8 bits of the DWORD render-state value. Values can range from 0x00000000 through 0x000000FF. The default value is 0.
D3DRS_ALPHAFUNC
One member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS. This member enables an application to accept or reject a pixel, based on its alpha value.
D3DRS_DITHERENABLE
TRUE to enable dithering. The default value is FALSE.
D3DRS_ALPHABLENDENABLE
TRUE to enable alpha-blended transparency. The default value is FALSE.

The type of alpha blending is determined by the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states.

D3DRS_FOGENABLE
TRUE to enable fog blending. The default value is FALSE. For more information about using fog blending, see Fog.
D3DRS_SPECULARENABLE
TRUE to enable specular highlights. The default value is FALSE.

Specular highlights are calculated as though every vertex in the object being lit is at the object's origin. This gives the expected results as long as the object is modeled around the origin and the distance from the light to the object is relatively large. In other cases, the results as undefined.

When this member is set to TRUE, the specular color is added to the base color after the texture cascade but before alpha blending.

D3DRS_FOGCOLOR
Value whose type is D3DCOLOR. The default value is 0. For more information about fog color, see Fog Color (Direct3D 9).
D3DRS_FOGTABLEMODE
The fog formula to be used for pixel fog. Set to one of the members of the D3DFOGMODE enumerated type. The default value is D3DFOG_NONE. For more information about pixel fog, see Pixel Fog (Direct3D 9).
D3DRS_FOGSTART
Depth at which pixel or vertex fog effects begin for linear fog mode. The default value is 0.0f. Depth is specified in world space for vertex fog and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations and world-world space when the system is using eye-relative fog (w-fog). For more information, see Fog Parameters (Direct3D 9) and Eye-Relative vs. Z-based Depth.

Values for the this render state are floating-point values. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_FOGSTART,
                         *((DWORD*) (&fFogStart)));
D3DRS_FOGEND
Depth at which pixel or vertex fog effects end for linear fog mode. The default value is 1.0f. Depth is specified in world space for vertex fog and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations and in world space when the system is using eye-relative fog (w-fog). For more information, see Fog Parameters (Direct3D 9) and Eye-Relative vs. Z-based Depth.

Values for this render state are floating-point values. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

m_pDevice9->SetRenderState(D3DRS_FOGEND, *((DWORD*) (&fFogEnd)));
D3DRS_FOGDENSITY
Fog density for pixel or vertex fog used in the exponential fog modes (D3DFOG_EXP and D3DFOG_EXP2). Valid density values range from 0.0 through 1.0. The default value is 1.0. For more information, see Fog Parameters (Direct3D 9).

Values for this render state are floating-point values. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

    m_pDevice9->SetRenderState(D3DRS_FOGDENSITY, *((DWORD*) (&fFogDensity)));
D3DRS_RANGEFOGENABLE
TRUE to enable range-based vertex fog. The default value is FALSE, in which case the system uses depth-based fog. In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene. In range-based fog, all fog methods work as usual, except that they use range instead of depth in the computations.

Range is the correct factor to use for fog computations, but depth is commonly used instead because range is time-consuming to compute and depth is generally already available. Using depth to calculate fog has the undesirable effect of having the fogginess of peripheral objects change as the viewer's eye moves - in this case, the depth changes and the range remains constant.

Because no hardware currently supports per-pixel range-based fog, range correction is offered only for vertex fog.

For more information, see Vertex Fog (Direct3D 9).

D3DRS_STENCILENABLE
TRUE to enable stenciling, or FALSE to disable stenciling. The default value is FALSE. For more information, see Stencil Buffer Techniques (Direct3D 9).
D3DRS_STENCILFAIL
Stencil operation to perform if the stencil test fails. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.
D3DRS_STENCILZFAIL
Stencil operation to perform if the stencil test passes and the depth test (z-test) fails. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.
D3DRS_STENCILPASS
Stencil operation to perform if both the stencil and the depth (z) tests pass. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.
D3DRS_STENCILFUNC
Comparison function for the stencil test. Values are from the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS.

The comparison function is used to compare the reference value to a stencil buffer entry. This comparison applies only to the bits in the reference value and stencil buffer entry that are set in the stencil mask (set by the D3DRS_STENCILMASK render state). If TRUE, the stencil test passes.

D3DRS_STENCILREF
An int reference value for the stencil test. The default value is 0.
D3DRS_STENCILMASK
Mask applied to the reference value and each stencil buffer entry to determine the significant bits for the stencil test. The default mask is 0xFFFFFFFF.
D3DRS_STENCILWRITEMASK
Write mask applied to values written into the stencil buffer. The default mask is 0xFFFFFFFF.
D3DRS_TEXTUREFACTOR
Color used for multiple-texture blending with the D3DTA_TFACTOR texture-blending argument or the D3DTOP_BLENDFACTORALPHA texture-blending operation. The associated value is a D3DCOLOR variable. The default value is opaque white (0xFFFFFFFF).
D3DRS_WRAP0
Texture-wrapping behavior for multiple sets of texture coordinates. Valid values for this render state can be any combination of the D3DWRAPCOORD_0 (or D3DWRAP_U), D3DWRAPCOORD_1 (or D3DWRAP_V), D3DWRAPCOORD_2 (or D3DWRAP_W), and D3DWRAPCOORD_3 flags. These cause the system to wrap in the direction of the first, second, third, and fourth dimensions, sometimes referred to as the s, t, r, and q directions, for a given texture. The default value for this render state is 0 (wrapping disabled in all directions).
D3DRS_WRAP1
See D3DRS_WRAP0.
D3DRS_WRAP2
See D3DRS_WRAP0.
D3DRS_WRAP3
See D3DRS_WRAP0.
D3DRS_WRAP4
See D3DRS_WRAP0.
D3DRS_WRAP5
See D3DRS_WRAP0.
D3DRS_WRAP6
See D3DRS_WRAP0.
D3DRS_WRAP7
See D3DRS_WRAP0.
D3DRS_CLIPPING
TRUE to enable primitive clipping by Direct3D, or FALSE to disable it. The default value is TRUE.
D3DRS_LIGHTING
TRUE to enable Direct3D lighting, or FALSE to disable it. The default value is TRUE. Only vertices that include a vertex normal are properly lit; vertices that do not contain a normal employ a dot product of 0 in all lighting calculations.
D3DRS_AMBIENT
Ambient light color. This value is of type D3DCOLOR. The default value is 0.
D3DRS_FOGVERTEXMODE
Fog formula to be used for vertex fog. Set to one member of the D3DFOGMODE enumerated type. The default value is D3DFOG_NONE.
D3DRS_COLORVERTEX
TRUE to enable per-vertex color or FALSE to disable it. The default value is TRUE. Enabling per-vertex color allows the system to include the color defined for individual vertices in its lighting calculations.

For more information, see the following render states:

  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE
D3DRS_LOCALVIEWER
TRUE to enable camera-relative specular highlights, or FALSE to use orthogonal specular highlights. The default value is TRUE. Applications that use orthogonal projection should specify false.
D3DRS_NORMALIZENORMALS
TRUE to enable automatic normalization of vertex normals, or FALSE to disable it. The default value is FALSE. Enabling this feature causes the system to normalize the vertex normals for vertices after transforming them to camera space, which can be computationally time-consuming.
D3DRS_DIFFUSEMATERIALSOURCE
Diffuse color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR1. The value for this render state is used only if the D3DRS_COLORVERTEX render state is set to TRUE.
D3DRS_SPECULARMATERIALSOURCE
Specular color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR2.
D3DRS_AMBIENTMATERIALSOURCE
Ambient color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_MATERIAL.
D3DRS_EMISSIVEMATERIALSOURCE
Emissive color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_MATERIAL.
D3DRS_VERTEXBLEND
Number of matrices to use to perform geometry blending, if any. Valid values are members of the D3DVERTEXBLENDFLAGS enumerated type. The default value is D3DVBF_DISABLE.
D3DRS_CLIPPLANEENABLE
Enables or disables user-defined clipping planes. Valid values are any DWORD in which the status of each bit (set or not set) toggles the activation state of a corresponding user-defined clipping plane. The least significant bit (bit 0) controls the first clipping plane at index 0, and subsequent bits control the activation of clipping planes at higher indexes. If a bit is set, the system applies the appropriate clipping plane during scene rendering. The default value is 0.

The D3DCLIPPLANEn macros are defined to provide a convenient way to enable clipping planes.

D3DRS_POINTSIZE
A float value that specifies the size to use for point size computation in cases where point size is not specified for each vertex. This value is not used when the vertex contains point size. This value is in screen space units if D3DRS_POINTSCALEENABLE is FALSE; otherwise this value is in world space units. The default value is the value a driver returns. If a driver returns 0 or 1, the default value is 64, which allows software point size emulation. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.
m_pDevice9->SetRenderState(D3DRS_POINTSIZE, *((DWORD*)&pointSize));
D3DRS_POINTSIZE_MIN
A float value that specifies the minimum size of point primitives. Point primitives are clamped to this size during rendering. Setting this to values smaller than 1.0 results in points dropping out when the point does not cover a pixel center and antialiasing is disabled or being rendered with reduced intensity when antialiasing is enabled. The default value is 1.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.
m_pDevice9->SetRenderState(D3DRS_POINTSIZE_MIN, *((DWORD*)&pointSizeMin));
D3DRS_POINTSPRITEENABLE
bool value. When TRUE, texture coordinates of point primitives are set so that full textures are mapped on each point. When FALSE, the vertex texture coordinates are used for the entire point. The default value is FALSE. You can achieve DirectX 7 style single-pixel points by setting D3DRS_POINTSCALEENABLE to FALSE and D3DRS_POINTSIZE to 1.0, which are the default values.
D3DRS_POINTSCALEENABLE
bool value that controls computation of size for point primitives. When TRUE, the point size is interpreted as a camera space value and is scaled by the distance function and the frustum to viewport y-axis scaling to compute the final screen-space point size. When FALSE, the point size is interpreted as screen space and used directly. The default value is FALSE.
D3DRS_POINTSCALE_A
A float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 1.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.
m_pDevice9->SetRenderState(D3DRS_POINTSCALE_A, *((DWORD*)&pointScaleA));
D3DRS_POINTSCALE_B
A float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 0.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.
m_pDevice9->SetRenderState(D3DRS_POINTSCALE_B, *((DWORD*)&pointScaleB));
D3DRS_POINTSCALE_C
A float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 0.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.
m_pDevice9->SetRenderState(D3DRS_POINTSCALE_C, *((DWORD*)&pointScaleC));
D3DRS_MULTISAMPLEANTIALIAS
bool value that determines how individual samples are computed when using a multisample render-target buffer. When set to TRUE, the multiple samples are computed so that full-scene antialiasing is performed by sampling at different sample positions for each multiple sample. When set to FALSE, the multiple samples are all written with the same sample value, sampled at the pixel center, which allows non-antialiased rendering to a multisample buffer. This render state has no effect when rendering to a single sample buffer. The default value is TRUE.
D3DRS_MULTISAMPLEMASK
Each bit in this mask, starting at the least significant bit (LSB), controls modification of one of the samples in a multisample render target. Thus, for an 8-sample render target, the low byte contains the eight write enables for each of the eight samples. This render state has no effect when rendering to a single sample buffer. The default value is 0xFFFFFFFF.

This render state enables use of a multisample buffer as an accumulation buffer, doing multipass rendering of geometry where each pass updates a subset of samples.

If there are n multisamples and k enabled samples, the resulting intensity of the rendered image should be k/n. Each component RGB of every pixel is factored by k/n.

D3DRS_PATCHEDGESTYLE
Sets whether patch edges will use float style tessellation. Possible values are defined by the D3DPATCHEDGESTYLE enumerated type. The default value is D3DPATCHEDGE_DISCRETE.
D3DRS_DEBUGMONITORTOKEN
Set only for debugging the monitor. Possible values are defined by the D3DDEBUGMONITORTOKENS enumerated type. Note that if D3DRS_DEBUGMONITORTOKEN is set, the call is treated as passing a token to the debug monitor. For example, if - after passing D3DDMT_ENABLE or D3DDMT_DISABLE to D3DRS_DEBUGMONITORTOKEN - other token values are passed in, the state (enabled or disabled) of the debug monitor will still persist.

This state is only useful for debug builds. The debug monitor defaults to D3DDMT_ENABLE.

D3DRS_POINTSIZE_MAX
A float value that specifies the maximum size to which point sprites will be clamped. The value must be less than or equal to the MaxPointSize member of D3DCAPS9 and greater than or equal to D3DRS_POINTSIZE_MIN. The default value is 64.0. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.
m_pDevice9->SetRenderState(D3DRS_PONTSIZE_MAX, *((DWORD*)&pointSizeMax));
D3DRS_INDEXEDVERTEXBLENDENABLE
bool value that enables or disables indexed vertex blending. The default value is FALSE. When set to TRUE, indexed vertex blending is enabled. When set to FALSE, indexed vertex blending is disabled. If this render state is enabled, the user must pass matrix indices as a packed DWORDwith every vertex. When the render state is disabled and vertex blending is enabled through the D3DRS_VERTEXBLEND state, it is equivalent to having matrix indices 0, 1, 2, 3 in every vertex.
D3DRS_COLORWRITEENABLE
UINT value that enables a per-channel write for the render-target color buffer. A set bit results in the color channel being updated during 3D rendering. A clear bit results in the color channel being unaffected. This functionality is available if the D3DPMISCCAPS_COLORWRITEENABLE capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. This render state does not affect the clear operation. The default value is 0x0000000F.

Valid values for this render state can be any combination of the D3DCOLORWRITEENABLE_ALPHA, D3DCOLORWRITEENABLE_BLUE, D3DCOLORWRITEENABLE_GREEN, or D3DCOLORWRITEENABLE_RED flags.

D3DRS_TWEENFACTOR
A float value that controls the tween factor. The default value is 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.
m_pDevice9->SetRenderState(D3DRS_TWEENFACTOR, *((DWORD*)&TweenFactor));
D3DRS_BLENDOP
Value used to select the arithmetic operation applied when the alpha blending render state, D3DRS_ALPHABLENDENABLE, is set to TRUE. Valid values are defined by the D3DBLENDOP enumerated type. The default value is D3DBLENDOP_ADD.

If the D3DPMISCCAPS_BLENDOP device capability is not supported, then D3DBLENDOP_ADD is performed.

D3DRS_POSITIONDEGREE
N-patch position interpolation degree. The values can be D3DDEGREE_CUBIC (default) or D3DDEGREE_LINEAR. For more information, see D3DDEGREETYPE.
D3DRS_NORMALDEGREE
N-patch normal interpolation degree. The values can be D3DDEGREE_LINEAR (default) or D3DDEGREE_QUADRATIC. For more information, see D3DDEGREETYPE.
D3DRS_SCISSORTESTENABLE
TRUE to enable scissor testing and FALSE to disable it. The default value is FALSE.
D3DRS_SLOPESCALEDEPTHBIAS
Used to determine how much bias can be applied to co-planar primitives to reduce z-fighting. The default value is 0.

bias = (max * D3DRS_SLOPESCALEDEPTHBIAS) + D3DRS_DEPTHBIAS.

where max is the maximum depth slope of the triangle being rendered.

D3DRS_ANTIALIASEDLINEENABLE

TRUE to enable line antialiasing, FALSE to disable line antialiasing. The default value is FALSE.

When rendering to a multisample render target, D3DRS_ANTIALIASEDLINEENABLE is ignored and all lines are rendered aliased. Use ID3DXLine for antialiased line rendering in a multisample render target.

D3DRS_MINTESSELLATIONLEVEL
Minimum tessellation level. The default value is 1.0f. See Tessellation (Direct3D 9).
D3DRS_MAXTESSELLATIONLEVEL
Maximum tessellation level. The default value is 1.0f. See Tessellation (Direct3D 9).
D3DRS_ADAPTIVETESS_X
Amount to adaptively tessellate, in the x direction. Default value is 0.0f. See Adaptive Tessellation.
D3DRS_ADAPTIVETESS_Y
Amount to adaptively tessellate, in the y direction. Default value is 0.0f. See Adaptive_Tessellation.
D3DRS_ADAPTIVETESS_Z
Amount to adaptively tessellate, in the z direction. Default value is 1.0f. See Adaptive_Tessellation.
D3DRS_ADAPTIVETESS_W
Amount to adaptively tessellate, in the w direction. Default value is 0.0f. See Adaptive_Tessellation.
D3DRS_ENABLEADAPTIVETESSELLATION
TRUE to enable adaptive tessellation, FALSE to disable it. The default value is FALSE. See Adaptive_Tessellation.
D3DRS_TWOSIDEDSTENCILMODE

TRUE enables two-sided stenciling, FALSE disables it. The default value is FALSE. The application should set D3DRS_CULLMODE to D3DCULL_NONE to enable two-sided stencil mode. If the triangle winding order is clockwise, the D3DRS_STENCIL* operations will be used. If the winding order is counterclockwise, the D3DRS_CCW_STENCIL* operations will be used.

To see if two-sided stencil is supported, check the StencilCaps member of D3DCAPS9 for D3DSTENCILCAPS_TWOSIDED. See also D3DSTENCILCAPS.

D3DRS_CCW_STENCILFAIL
Stencil operation to perform if CCW stencil test fails. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.
D3DRS_CCW_STENCILZFAIL
Stencil operation to perform if CCW stencil test passes and z-test fails. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.
D3DRS_CCW_STENCILPASS
Stencil operation to perform if both CCW stencil and z-tests pass. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.
D3DRS_CCW_STENCILFUNC
The comparison function. CCW stencil test passes if ((ref & mask) stencil function (stencil & mask)) is true. Values are from the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS.
D3DRS_COLORWRITEENABLE1
Additional ColorWriteEnable values for the devices. See D3DRS_COLORWRITEENABLE. This functionality is available if the D3DPMISCCAPS_INDEPENDENTWRITEMASKS capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. The default value is 0x0000000f.
D3DRS_COLORWRITEENABLE2
Additional ColorWriteEnable values for the devices. See D3DRS_COLORWRITEENABLE. This functionality is available if the D3DPMISCCAPS_INDEPENDENTWRITEMASKS capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. The default value is 0x0000000f.
D3DRS_COLORWRITEENABLE3
Additional ColorWriteEnable values for the devices. See D3DRS_COLORWRITEENABLE. This functionality is available if the D3DPMISCCAPS_INDEPENDENTWRITEMASKS capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. The default value is 0x0000000f.
D3DRS_BLENDFACTOR
D3DCOLOR used for a constant blend-factor during alpha blending. This functionality is available if the D3DPBLENDCAPS_BLENDFACTOR capabilities bit is set in the SrcBlendCaps member of D3DCAPS9 or the DestBlendCaps member of D3DCAPS9. See D3DRENDERSTATETYPE. The default value is 0xffffffff.
D3DRS_SRGBWRITEENABLE
Enable render-target writes to be gamma corrected to sRGB. The format must expose D3DUSAGE_SRGBWRITE. The default value is 0.
D3DRS_DEPTHBIAS
A floating-point value that is used for comparison of depth values. See Depth Bias (Direct3D 9). The default value is 0.
D3DRS_WRAP8
See D3DRS_WRAP0.
D3DRS_WRAP9
See D3DRS_WRAP0.
D3DRS_WRAP10
See D3DRS_WRAP0.
D3DRS_WRAP11
See D3DRS_WRAP0.
D3DRS_WRAP12
See D3DRS_WRAP0.
D3DRS_WRAP13
See D3DRS_WRAP0.
D3DRS_WRAP14
See D3DRS_WRAP0.
D3DRS_WRAP15
See D3DRS_WRAP0.
D3DRS_SEPARATEALPHABLENDENABLE

TRUE enables the separate blend mode for the alpha channel. The default value is FALSE.

When set to false, the render-target blending factors and operations applied to alpha are forced to be the same as those defined for color. This mode is effectively hardwired to false on implementations that don't set the cap D3DPMISCCAPS_SEPARATEALPHABLEND. See D3DPMISCCAPS.

The type of separate alpha blending is determined by the D3DRS_SRCBLENDALPHA and D3DRS_DESTBLENDALPHA render states.

D3DRS_SRCBLENDALPHA
One member of the D3DBLEND enumerated type. This value is ignored unless D3DRS_SEPARATEALPHABLENDENABLE is true. The default value is D3DBLEND_ONE.
D3DRS_DESTBLENDALPHA
One member of the D3DBLEND enumerated type. This value is ignored unless D3DRS_SEPARATEALPHABLENDENABLE is true. The default value is D3DBLEND_ZERO.
D3DRS_BLENDOPALPHA

Value used to select the arithmetic operation applied to separate alpha blending when the render state, D3DRS_SEPARATEALPHABLENDENABLE, is set to TRUE.

Valid values are defined by the D3DBLENDOP enumerated type. The default value is D3DBLENDOP_ADD.

If the D3DPMISCCAPS_BLENDOP device capability is not supported, then D3DBLENDOP_ADD is performed. See D3DPMISCCAPS.

D3DRS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Render States
ps_1_1 to ps_1_3 4 texture samplers

Direct3D defines the D3DRENDERSTATE_WRAPBIAS constant as a convenience for applications to enable or disable texture wrapping, based on the zero-based integer of a texture coordinate set (rather than explicitly using one of the D3DRS_WRAP n state values). Add the D3DRENDERSTATE_WRAPBIAS value to the zero-based index of a texture coordinate set to calculate the D3DRS_WRAP n value that corresponds to that index, as shown in the following example.

// Enable U/V wrapping for textures that use the texture
// coordinate set at the index within the dwIndex variable

HRESULT hr = pd3dDevice->SetRenderState(
dwIndex + D3DRENDERSTATE_WRAPBIAS,
D3DWRAPCOORD_0 | D3DWRAPCOORD_1);

// If dwIndex is 3, the value that results from
// the addition equals D3DRS_WRAP3 (131)

See Also

IDirect3DDevice9::GetRenderState, IDirect3DDevice9::SetRenderState


D3DRESOURCETYPE

Defines resource types.

typedef enum D3DRESOURCETYPE
{
    D3DRTYPE_SURFACE = 1,
    D3DRTYPE_VOLUME = 2,
    D3DRTYPE_TEXTURE = 3,
    D3DRTYPE_VOLUMETEXTURE = 4,
    D3DRTYPE_CubeTexture = 5,
    D3DRTYPE_VERTEXBUFFER = 6,
    D3DRTYPE_INDEXBUFFER = 7,
    D3DRTYPE_FORCE_DWORD = 0x7fffffff,
} D3DRESOURCETYPE, *LPD3DRESOURCETYPE;

Constants

D3DRTYPE_SURFACE
Surface resource.
D3DRTYPE_VOLUME
Volume resource.
D3DRTYPE_TEXTURE
Texture resource.
D3DRTYPE_VOLUMETEXTURE
Volume texture resource.
D3DRTYPE_CubeTexture
Cube texture resource.
D3DRTYPE_VERTEXBUFFER
Vertex buffer resource.
D3DRTYPE_INDEXBUFFER
Index buffer resource.
D3DRTYPE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

See Also

IDirect3DResource9::GetType


D3DSAMPLER_TEXTURE_TYPE

Defines the sampler texture types for vertex shaders.

typedef enum D3DSAMPLER_TEXTURE_TYPE
{
    D3DSTT_UNKNOWN,
    D3DSTT_1D,
    D3DSTT_2D,
    D3DSTT_CUBE,
    D3DSTT_VOLUME,
    D3DSTT_FORCE_DWORD,
} D3DSAMPLER_TEXTURE_TYPE, *LPD3DSAMPLER_TEXTURE_TYPE;

Constants

D3DSTT_UNKNOWN
Uninitialized value. The value of this element is D3DSP_TEXTURETYPE_SHIFT.
D3DSTT_1D
Declaring a 1D texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 2.
D3DSTT_2D
Declaring a 2D texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 4.
D3DSTT_CUBE
Declaring a cube texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 8.
D3DSTT_VOLUME
Declaring a volume texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 16.
D3DSTT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.


D3DSAMPLERSTATETYPE

Sampler states define texture sampling operations such as texture addressing and texture filtering. Some sampler states set-up vertex processing, and some set-up pixel processing. Sampler states can be saved and restored using stateblocks (see State Blocks Save and Restore State (Direct3D 9)).

typedef enum D3DSAMPLERSTATETYPE
{
    D3DSAMP_ADDRESSU = 1,
    D3DSAMP_ADDRESSV = 2,
    D3DSAMP_ADDRESSW = 3,
    D3DSAMP_BORDERCOLOR = 4,
    D3DSAMP_MAGFILTER = 5,
    D3DSAMP_MINFILTER = 6,
    D3DSAMP_MIPFILTER = 7,
    D3DSAMP_MIPMAPLODBIAS = 8,
    D3DSAMP_MAXMIPLEVEL = 9,
    D3DSAMP_MAXANISOTROPY = 10,
    D3DSAMP_SRGBTEXTURE = 11,
    D3DSAMP_ELEMENTINDEX = 12,
    D3DSAMP_DMAPOFFSET = 13,
    D3DSAMP_FORCE_DWORD = 0x7fffffff,
} D3DSAMPLERSTATETYPE, *LPD3DSAMPLERSTATETYPE;

Constants

D3DSAMP_ADDRESSU
Texture-address mode for the u coordinate. The default is D3DTADDRESS_WRAP. For more information, see D3DTEXTUREADDRESS.
D3DSAMP_ADDRESSV
Texture-address mode for the v coordinate. The default is D3DTADDRESS_WRAP. For more information, see D3DTEXTUREADDRESS.
D3DSAMP_ADDRESSW
Texture-address mode for the w coordinate. The default is D3DTADDRESS_WRAP. For more information, see D3DTEXTUREADDRESS.
D3DSAMP_BORDERCOLOR
Border color or type D3DCOLOR. The default color is 0x00000000.
D3DSAMP_MAGFILTER
Magnification filter of type D3DTEXTUREFILTERTYPE. The default value is D3DTEXF_POINT.
D3DSAMP_MINFILTER
Minification filter of type D3DTEXTUREFILTERTYPE. The default value is D3DTEXF_POINT.
D3DSAMP_MIPFILTER
Mipmap filter to use during minification. See D3DTEXTUREFILTERTYPE. The default value is D3DTEXF_NONE.
D3DSAMP_MIPMAPLODBIAS
Mipmap level-of-detail bias. The default value is zero.
D3DSAMP_MAXMIPLEVEL
level-of-detail index of largest map to use. Values range from 0 to (n - 1) where 0 is the largest. The default value is zero.
D3DSAMP_MAXANISOTROPY
DWORD maximum anisotropy. The default value is 1.
D3DSAMP_SRGBTEXTURE
Gamma correction value. The default value is 0, which means gamma is 1.0 and no correction is required. Otherwise, this value means that the sampler should assume gamma of 2.2 on the content and convert it to linear (gamma 1.0) before presenting it to the pixel shader.
D3DSAMP_ELEMENTINDEX
When a multielement texture is assigned to the sampler, this indicates which element index to use. The default value is 0.
D3DSAMP_DMAPOFFSET
Vertex offset in the presampled displacement map. This is a constant used by the tessellator, its default value is 0.
D3DSAMP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.


D3DSCANLINEORDERING (DirectX 9Ex only)

Flags indicating the method the rasterizer uses to create an image on a surface.

typedef enum D3DSCANLINEORDERING
{
    D3DSCANLINEORDERING_PROGRESSIVE = 1,
    D3DSCANLINEORDERING_INTERLACED = 2,
} D3DSCANLINEORDERING (DirectX 9Ex only), *LPD3DSCANLINEORDERING;

Constants

D3DSCANLINEORDERING_PROGRESSIVE
The image is created from the first scanline to the last without skipping any.
D3DSCANLINEORDERING_INTERLACED
The image is created using the interlaced method in which odd-numbered lines are drawn on odd-numbered passes and even lines are drawn on even-numbered passes.

Remarks

This enumeration is used as a member in D3DDISPLAYMODEFILTER (DirectX 9Ex only) and D3DDISPLAYMODEEX (DirectX 9Ex only).

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Enumerations


D3DSHADEMODE

Defines constants that describe the supported shading modes.

typedef enum D3DSHADEMODE
{
    D3DSHADE_FLAT = 1,
    D3DSHADE_GOURAUD = 2,
    D3DSHADE_PHONG = 3,
    D3DSHADE_FORCE_DWORD = 0x7fffffff,
} D3DSHADEMODE, *LPD3DSHADEMODE;

Constants

D3DSHADE_FLAT
Flat shading mode. The color and specular component of the first vertex in the triangle are used to determine the color and specular component of the face. These colors remain constant across the triangle; that is, they are not interpolated. The specular alpha is interpolated. See Remarks.
D3DSHADE_GOURAUD
Gouraud shading mode. The color and specular components of the face are determined by a linear interpolation between all three of the triangle's vertices.
D3DSHADE_PHONG
Not supported.
D3DSHADE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The first vertex of a triangle for flat shading mode is defined in the following manner.

  • For a triangle list, the first vertex of the triangle i is i * 3.
  • For a triangle strip, the first vertex of the triangle i is vertex i.
  • For a triangle fan, the first vertex of the triangle i is vertex i + 1.

The members of this enumerated type define the vales for the D3DRS_SHADEMODE render state.

See Also

D3DRENDERSTATETYPE


D3DSTATEBLOCKTYPE

Predefined sets of pipeline state used by state blocks (see State Blocks Save and Restore State (Direct3D 9)).

typedef enum D3DSTATEBLOCKTYPE
{
    D3DSBT_ALL = 1,
    D3DSBT_PIXELSTATE = 2,
    D3DSBT_VERTEXSTATE = 2,
    D3DSBT_FORCE_DWORD = 0xffffffff,
} D3DSTATEBLOCKTYPE, *LPD3DSTATEBLOCKTYPE;

Constants

D3DSBT_ALL
Capture the current device state.
D3DSBT_PIXELSTATE
Capture the current pixel state.
D3DSBT_VERTEXSTATE
Capture the current vertex state.
D3DSBT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

As the diagram below shows, vertex and pixel state are both subsets of device state.

There are only a few states that are considered both vertex and pixel state. These states are:

  • Render state: D3DRS_FOGDENSITY
  • Render state: D3DRS_FOGSTART
  • Render state: D3DRS_FOGEND
  • Texture state: D3DTSS_TEXCOORDINDEX
  • Texture state: D3DTSS_TEXTURETRANSFORMFLAGS

See Also

IDirect3DDevice9::CreateStateBlock, IDirect3DDevice9::CreateStateBlock


D3DSTENCILOP

Defines stencil-buffer operations.

typedef enum D3DSTENCILOP
{
    D3DSTENCILOP_KEEP = 1,
    D3DSTENCILOP_ZERO = 2,
    D3DSTENCILOP_REPLACE = 3,
    D3DSTENCILOP_INCRSAT = 4,
    D3DSTENCILOP_DECRSAT = 5,
    D3DSTENCILOP_INVERT = 6,
    D3DSTENCILOP_INCR = 7,
    D3DSTENCILOP_DECR = 8,
    D3DSTENCILOP_FORCE_DWORD = 0x7fffffff,
} D3DSTENCILOP, *LPD3DSTENCILOP;

Constants

D3DSTENCILOP_KEEP
Do not update the entry in the stencil buffer. This is the default value.
D3DSTENCILOP_ZERO
Set the stencil-buffer entry to 0.
D3DSTENCILOP_REPLACE
Replace the stencil-buffer entry with a reference value.
D3DSTENCILOP_INCRSAT
Increment the stencil-buffer entry, clamping to the maximum value.
D3DSTENCILOP_DECRSAT
Decrement the stencil-buffer entry, clamping to zero.
D3DSTENCILOP_INVERT
Invert the bits in the stencil-buffer entry.
D3DSTENCILOP_INCR
Increment the stencil-buffer entry, wrapping to zero if the new value exceeds the maximum value.
D3DSTENCILOP_DECR
Decrement the stencil-buffer entry, wrapping to the maximum value if the new value is less than zero.
D3DSTENCILOP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Stencil-buffer entries are integer values ranging from 0 through 2n - 1, where n is the bit depth of the stencil buffer.


D3DSWAPEFFECT

Defines swap effects.

typedef enum D3DSWAPEFFECT
{
    D3DSWAPEFFECT_DISCARD = 1,
    D3DSWAPEFFECT_FLIP = 2,
    D3DSWAPEFFECT_COPY = 3,
    D3DSWAPEFFECT_FORCE_DWORD = 0xFFFFFFFF,
} D3DSWAPEFFECT, *LPD3DSWAPEFFECT;

Constants

D3DSWAPEFFECT_DISCARD
When a swap chain is created with a swap effect of D3DSWAPEFFECT_FLIP or D3DSWAPEFFECT_COPY, the runtime will guarantee that an IDirect3DDevice9::Present operation will not affect the content of any of the back buffers. Unfortunately, meeting this guarantee can involve substantial video memory or processing overheads, especially when implementing flip semantics for a windowed swap chain or copy semantics for a full-screen swap chain. An application may use the D3DSWAPEFFECT_DISCARD swap effect to avoid these overheads and to enable the display driver to select the most efficient presentation technique for the swap chain. This is also the only swap effect that may be used when specifying a value other than D3DMULTISAMPLE_NONE for the MultiSampleType member of D3DPRESENT_PARAMETERS.

Like a swap chain that uses D3DSWAPEFFECT_FLIP, a swap chain that uses D3DSWAPEFFECT_DISCARD might include more than one back buffer, any of which may be accessed using IDirect3DDevice9::GetBackBuffer or IDirect3DSwapChain9::GetBackBuffer. The swap chain is best envisaged as a queue in which 0 always indexes the back buffer that will be displayed by the next Present operation and from which buffers are discarded when they have been displayed.

An application that uses this swap effect cannot make any assumptions about the contents of a discarded back buffer and should therefore update an entire back buffer before invoking a Present operation that would display it. Although this is not enforced, the debug version of the runtime will overwrite the contents of discarded back buffers with random data to enable developers to verify that their applications are updating the entire back buffer surfaces correctly.

D3DSWAPEFFECT_FLIP
The swap chain might include multiple back buffers and is best envisaged as a circular queue that includes the front buffer. Within this queue, the back buffers are always numbered sequentially from 0 to (n - 1), where n is the number of back buffers, so that 0 denotes the least recently presented buffer. When Present is invoked, the queue is "rotated" so that the front buffer becomes back buffer (n - 1), while the back buffer 0 becomes the new front buffer.
D3DSWAPEFFECT_COPY

This swap effect may be specified only for a swap chain comprising a single back buffer. Whether the swap chain is windowed or full-screen, the runtime will guarantee the semantics implied by a copy-based Present operation, namely that the operation leaves the content of the back buffer unchanged, instead of replacing it with the content of the front buffer as a flip-based Present operation would.

For a full-screen swap chain, the runtime uses a combination of flip operations and copy operations, supported if necessary by hidden back buffers, to accomplish the Present operation. Accordingly, the presentation is synchronized with the display adapter's vertical retrace and its rate is constrained by the chosen presentation interval. A swap chain specified with the D3DPRESENT_INTERVAL_IMMEDIATE flag is the only exception. (Refer to the description of the PresentationIntervals member of the D3DPRESENT_PARAMETERS structure.) In this case, a Present operation copies the back buffer content directly to the front buffer without waiting for the vertical retrace.

D3DSWAPEFFECT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The state of the back buffer after a call to Present is well-defined by each of these swap effects, and whether the Direct3D device was created with a full-screen swap chain or a windowed swap chain has no effect on this state. In particular, the D3DSWAPEFFECT_FLIP swap effect operates the same whether windowed or full-screen, and the Direct3D runtime guarantees this by creating extra buffers. As a result, it is recommended that applications use D3DSWAPEFFECT_DISCARD whenever possible to avoid any such penalties. This is because this swap effect will always be the most efficient in terms of memory consumption and performance.

Applications that use D3DSWAPEFFECT_FLIP or D3DSWAPEFFECT_DISCARD should not expect full-screen destination alpha to work. This means that the D3DRS_DESTBLEND render state will not work as expected because full-screen swap chains with these swap effects do not have an explicit pixel format from the driver's point of view. The driver infers that they should take on the display format, which does not have an alpha channel. To work around this, take the following steps:

  • Use D3DSWAPEFFECT_COPY.
  • Check the D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD flag in the Caps3 member of the D3DCAPS9 structure. This flag indicates whether the driver can do alpha blending when D3DSWAPEFFECT_FLIP or D3DSWAPEFFECT_DISCARD is used.

See Also

IDirect3DDevice9::Reset, IDirect3DDevice9::Reset, D3DPRESENT_PARAMETERS


D3DTEXTUREADDRESS

Defines constants that describe the supported texture-addressing modes.

typedef enum D3DTEXTUREADDRESS
{
    D3DTADDRESS_WRAP = 1,
    D3DTADDRESS_MIRROR = 2,
    D3DTADDRESS_CLAMP = 3,
    D3DTADDRESS_BORDER = 4,
    D3DTADDRESS_MIRRORONCE = 5,
    D3DTADDRESS_FORCE_DWORD = 0x7fffffff,
} D3DTEXTUREADDRESS, *LPD3DTEXTUREADDRESS;

Constants

D3DTADDRESS_WRAP
Tile the texture at every integer junction. For example, for u values between 0 and 3, the texture is repeated three times; no mirroring is performed.
D3DTADDRESS_MIRROR
Similar to D3DTADDRESS_WRAP, except that the texture is flipped at every integer junction. For u values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is flipped (mirrored); between 2 and 3, the texture is normal again; and so on.
D3DTADDRESS_CLAMP
Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively.
D3DTADDRESS_BORDER
Texture coordinates outside the range [0.0, 1.0] are set to the border color.
D3DTADDRESS_MIRRORONCE
Similar to D3DTADDRESS_MIRROR and D3DTADDRESS_CLAMP. Takes the absolute value of the texture coordinate (thus, mirroring around 0), and then clamps to the maximum value. The most common usage is for volume textures, where support for the full D3DTADDRESS_MIRRORONCE texture-addressing mode is not necessary, but the data is symmetric around the one axis.
D3DTADDRESS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

See Also

D3DSAMPLERSTATETYPE


D3DTEXTUREFILTERTYPE

Defines texture filtering modes for a texture stage.

typedef enum D3DTEXTUREFILTERTYPE
{
    D3DTEXF_NONE = 0,
    D3DTEXF_POINT = 1,
    D3DTEXF_LINEAR = 2,
    D3DTEXF_ANISOTROPIC = 3,
    D3DTEXF_PYRAMIDALQUAD = 6,
    D3DTEXF_GAUSSIANQUAD = 7,
    D3DTEXF_CONVOLUTIONMONO = 8,
    D3DTEXF_FORCE_DWORD = 0x7fffffff,
} D3DTEXTUREFILTERTYPE, *LPD3DTEXTUREFILTERTYPE;

Constants

D3DTEXF_NONE
Mipmapping disabled. The rasterizer should use the magnification filter instead.
D3DTEXF_POINT
Point filtering used as a texture magnification or minification filter. The texel with coordinates nearest to the desired pixel value is used. The texture filter to be used between mipmap levels is nearest-point mipmap filtering. The rasterizer uses the color from the texel of the nearest mipmap texture.
D3DTEXF_LINEAR
Bilinear interpolation filtering used as a texture magnification or minification filter. A weighted average of a 2 x 2 area of texels surrounding the desired pixel is used. The texture filter to use between mipmap levels is trilinear mipmap interpolation. The rasterizer linearly interpolates pixel color, using the texels of the two nearest mipmap textures.
D3DTEXF_ANISOTROPIC
Anisotropic texture filtering used as a texture magnification or minification filter. Compensates for distortion caused by the difference in angle between the texture polygon and the plane of the screen.
D3DTEXF_PYRAMIDALQUAD
A 4-sample tent filter used as a texture magnification or minification filter.
D3DTEXF_GAUSSIANQUAD
A 4-sample Gaussian filter used as a texture magnification or minification filter.
D3DTEXF_CONVOLUTIONMONO
Direct3D 9Ex only - Convolution filter for monochrome textures. See D3DFMT_A1
D3DTEXF_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

To check if a format supports texture filter types other than D3DTEXF_POINT (which is always supported), call IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_FILTER.

Set a texture stage's magnification filter by calling IDirect3DDevice9::SetSamplerState with the D3DSAMP_MAGFILTER value as the second parameter and one member of this enumeration as the third parameter.

Set a texture stage's minification filter by calling IDirect3DDevice9::SetSamplerState with the D3DSAMP_MINFILTER value as the second parameter and one member of this enumeration as the third parameter.

Set the texture filter to use between-mipmap levels by calling IDirect3DDevice9::SetSamplerState with the D3DSAMP_MIPFILTER value as the second parameter and one member of this enumeration as the third parameter.

Not all valid filtering modes for a device will apply to volume maps. In general, D3DTEXF_POINT and D3DTEXF_LINEAR magnification filters will be supported for volume maps. If D3DPTEXTURECAPS_MIPVOLUMEMAP is set, then the D3DTEXF_POINT mipmap filter and D3DTEXF_POINT and D3DTEXF_LINEAR minification filters will be supported for volume maps. The device may or may not support the D3DTEXF_LINEAR mipmap filter for volume maps. Devices that support anisotropic filtering for 2D maps do not necessarily support anisotropic filtering for volume maps. However, applications that enable anisotropic filtering will receive the best available filtering (probably linear) if anisotropic filtering is not supported.

See Also

ID3DXPatchMesh::GetDisplaceParam, ID3DXPatchMesh::SetDisplaceParam, D3DSAMPLERSTATETYPE


D3DTEXTUREOP

Defines per-stage texture-blending operations.

typedef enum D3DTEXTUREOP
{
    D3DTOP_DISABLE = 1,
    D3DTOP_SELECTARG1 = 2,
    D3DTOP_SELECTARG2 = 3,
    D3DTOP_MODULATE = 4,
    D3DTOP_MODULATE2X = 5,
    D3DTOP_MODULATE4X = 6,
    D3DTOP_ADD = 7,
    D3DTOP_ADDSIGNED = 8,
    D3DTOP_ADDSIGNED2X = 9,
    D3DTOP_SUBTRACT = 10,
    D3DTOP_ADDSMOOTH = 11,
    D3DTOP_BLENDDIFFUSEALPHA = 12,
    D3DTOP_BLENDTEXTUREALPHA = 13,
    D3DTOP_BLENDFACTORALPHA = 14,
    D3DTOP_BLENDTEXTUREALPHAPM = 15,
    D3DTOP_BLENDCURRENTALPHA = 16,
    D3DTOP_PREMODULATE = 17,
    D3DTOP_MODULATEALPHA_ADDCOLOR = 18,
    D3DTOP_MODULATECOLOR_ADDALPHA = 19,
    D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20,
    D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21,
    D3DTOP_BUMPENVMAP = 22,
    D3DTOP_BUMPENVMAPLUMINANCE = 23,
    D3DTOP_DOTPRODUCT3 = 24,
    D3DTOP_MULTIPLYADD = 25,
    D3DTOP_LERP = 26,
    D3DTOP_FORCE_DWORD = 0x7fffffff,
} D3DTEXTUREOP, *LPD3DTEXTUREOP;

Constants

D3DTOP_DISABLE
Disables output from this texture stage and all stages with a higher index. To disable texture mapping, set this as the color operation for the first texture stage (stage 0). Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.
D3DTOP_SELECTARG1
Use this texture stage's first color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture-stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

D3DTOP_SELECTARG2
Use this texture stage's second color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

D3DTOP_MODULATE
Multiply the components of the arguments.

D3DTOP_MODULATE2X
Multiply the components of the arguments, and shift the products to the left 1 bit (effectively multiplying them by 2) for brightening.

D3DTOP_MODULATE4X
Multiply the components of the arguments, and shift the products to the left 2 bits (effectively multiplying them by 4) for brightening.

D3DTOP_ADD
Add the components of the arguments.

D3DTOP_ADDSIGNED
Add the components of the arguments with a - 0.5 bias, making the effective range of values from - 0.5 through 0.5.

D3DTOP_ADDSIGNED2X
Add the components of the arguments with a - 0.5 bias, and shift the products to the left 1 bit.

D3DTOP_SUBTRACT
Subtract the components of the second argument from those of the first argument.

D3DTOP_ADDSMOOTH
Add the first and second arguments; then subtract their product from the sum.

D3DTOP_BLENDDIFFUSEALPHA
Linearly blend this texture stage, using the interpolated alpha from each vertex.

D3DTOP_BLENDTEXTUREALPHA
Linearly blend this texture stage, using the alpha from this stage's texture.

D3DTOP_BLENDFACTORALPHA
Linearly blend this texture stage, using a scalar alpha set with the D3DRS_TEXTUREFACTOR render state.

D3DTOP_BLENDTEXTUREALPHAPM
Linearly blend a texture stage that uses a premultiplied alpha.

D3DTOP_BLENDCURRENTALPHA
Linearly blend this texture stage, using the alpha taken from the previous texture stage.

D3DTOP_PREMODULATE
D3DTOP_PREMODULATE is set in stage n. The output of stage n is arg1. Additionally, if there is a texture in stage n + 1, any D3DTA_CURRENT in stage n + 1 is premultiplied by texture in stage n + 1.
D3DTOP_MODULATEALPHA_ADDCOLOR
Modulate the color of the second argument, using the alpha of the first argument; then add the result to argument one. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATECOLOR_ADDALPHA
Modulate the arguments; then add the alpha of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVALPHA_ADDCOLOR
Similar to D3DTOP_MODULATEALPHA_ADDCOLOR, but use the inverse of the alpha of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVCOLOR_ADDALPHA
Similar to D3DTOP_MODULATECOLOR_ADDALPHA, but use the inverse of the color of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_BUMPENVMAP
Perform per-pixel bump mapping, using the environment map in the next texture stage, without luminance. This operation is supported only for color operations (D3DTSS_COLOROP).
D3DTOP_BUMPENVMAPLUMINANCE
Perform per-pixel bump mapping, using the environment map in the next texture stage, with luminance. This operation is supported only for color operations (D3DTSS_COLOROP).
D3DTOP_DOTPRODUCT3
Modulate the components of each argument as signed components, add their products; then replicate the sum to all color channels, including alpha. This operation is supported for color and alpha operations.

In DirectX 6 and DirectX 7, multitexture operations the above inputs are all shifted down by half (y = x - 0.5) before use to simulate signed data, and the scalar result is automatically clamped to positive values and replicated to all three output channels. Also, note that as a color operation this does not updated the alpha it just updates the RGB components.

However, in DirectX 8.1 shaders you can specify that the output be routed to the .rgb or the .a components or both (the default). You can also specify a separate scalar operation on the alpha channel.

D3DTOP_MULTIPLYADD
Performs a multiply-accumulate operation. It takes the last two arguments, multiplies them together, and adds them to the remaining input/source argument, and places that into the result.

SRGBA = Arg1 + Arg2 * Arg3

D3DTOP_LERP
Linearly interpolates between the second and third source arguments by a proportion specified in the first source argument.

SRGBA = (Arg1) * Arg2 + (1- Arg1) * Arg3.

D3DTOP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The members of this type are used when setting color or alpha operations by using the D3DTSS_COLOROP or D3DTSS_ALPHAOP values with the IDirect3DDevice9::SetTextureStageState method.

In the above formulas, SRGBA is the RGBA color produced by a texture operation, and Arg1, Arg2, and Arg3 represent the complete RGBA color of the texture arguments. Individual components of an argument are shown with subscripts. For example, the alpha component for argument 1 would be shown as Arg1A.

See Also

D3DTEXTURESTAGESTATETYPE


D3DTEXTURESTAGESTATETYPE

Texture stage states define multi-blender texture operations. Some sampler states set up vertex processing, and some set up pixel processing. Texture stage states can be saved and restored using stateblocks (see State Blocks Save and Restore State (Direct3D 9)).

typedef enum D3DTEXTURESTAGESTATETYPE
{
    D3DTSS_COLOROP = 1,
    D3DTSS_COLORARG1 = 2,
    D3DTSS_COLORARG2 = 3,
    D3DTSS_ALPHAOP = 4,
    D3DTSS_ALPHAARG1 = 5,
    D3DTSS_ALPHAARG2 = 6,
    D3DTSS_BUMPENVMAT00 = 7,
    D3DTSS_BUMPENVMAT01 = 8,
    D3DTSS_BUMPENVMAT10 = 9,
    D3DTSS_BUMPENVMAT11 = 10,
    D3DTSS_TEXCOORDINDEX = 11,
    D3DTSS_BUMPENVLSCALE = 22,
    D3DTSS_BUMPENVLOFFSET = 23,
    D3DTSS_TEXTURETRANSFORMFLAGS = 24,
    D3DTSS_COLORARG0 = 26,
    D3DTSS_ALPHAARG0 = 27,
    D3DTSS_RESULTARG = 28,
    D3DTSS_CONSTANT = 32,
    D3DTSS_FORCE_DWORD = 0x7fffffff,
} D3DTEXTURESTAGESTATETYPE, *LPD3DTEXTURESTAGESTATETYPE;

Constants

D3DTSS_COLOROP
Texture-stage state is a texture color blending operation identified by one member of the D3DTEXTUREOP enumerated type. The default value for the first texture stage (stage 0) is D3DTOP_MODULATE; for all other stages the default is D3DTOP_DISABLE.
D3DTSS_COLORARG1
Texture-stage state is the first color argument for the stage, identified by one of the D3DTA. The default argument is D3DTA_TEXTURE.

Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).

D3DTSS_COLORARG2
Texture-stage state is the second color argument for the stage, identified by D3DTA. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0)
D3DTSS_ALPHAOP
Texture-stage state is a texture alpha blending operation identified by one member of the D3DTEXTUREOP enumerated type. The default value for the first texture stage (stage 0) is D3DTOP_SELECTARG1, and for all other stages the default is D3DTOP_DISABLE.
D3DTSS_ALPHAARG1
Texture-stage state is the first alpha argument for the stage, identified by by D3DTA. The default argument is D3DTA_TEXTURE. If no texture is set for this stage, the default argument is D3DTA_DIFFUSE. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).
D3DTSS_ALPHAARG2
Texture-stage state is the second alpha argument for the stage, identified by by D3DTA. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).
D3DTSS_BUMPENVMAT00
Texture-stage state is a floating-point value for the [0][0] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_BUMPENVMAT01
Texture-stage state is a floating-point value for the [0][1] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_BUMPENVMAT10
Texture-stage state is a floating-point value for the [1][0] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_BUMPENVMAT11
Texture-stage state is a floating-point value for the [1][1] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_TEXCOORDINDEX
Index of the texture coordinate set to use with this texture stage. You can specify up to eight sets of texture coordinates per vertex. If a vertex does not include a set of texture coordinates at the specified index, the system defaults to the u and v coordinates (0,0).

When rendering using vertex shaders, each stage's texture coordinate index must be set to its default value. The default index for each stage is equal to the stage index. Set this state to the zero-based index of the coordinate set for each vertex that this texture stage uses.

Additionally, applications can include, as logical OR with the index being set, one of the constants to request that Direct3D automatically generate the input texture coordinates for a texture transformation. For a list of all the constants, see D3DTSS_TCI.

With the exception of D3DTSS_TCI_PASSTHRU, which resolves to zero, if any of the following values is included with the index being set, the system uses the index strictly to determine texture wrapping mode. These flags are most useful when performing environment mapping.

D3DTSS_BUMPENVLSCALE
Floating-point scale value for bump-map luminance. The default value is 0.0.
D3DTSS_BUMPENVLOFFSET
Floating-point offset value for bump-map luminance. The default value is 0.0.
D3DTSS_TEXTURETRANSFORMFLAGS
Member of the D3DTEXTURETRANSFORMFLAGS enumerated type that controls the transformation of texture coordinates for this texture stage. The default value is D3DTTFF_DISABLE.
D3DTSS_COLORARG0
Settings for the third color operand for triadic operations (multiply, add, and linearly interpolate), identified by D3DTA. This setting is supported if the D3DTEXOPCAPS_MULTIPLYADD or D3DTEXOPCAPS_LERP device capabilities are present. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).
D3DTSS_ALPHAARG0
Settings for the alpha channel selector operand for triadic operations (multiply, add, and linearly interpolate), identified by D3DTA. This setting is supported if the D3DTEXOPCAPS_MULTIPLYADD or D3DTEXOPCAPS_LERP device capabilities are present. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default argument is (0.0, 0.0, 0.0, 0.0).
D3DTSS_RESULTARG
Setting to select destination register for the result of this stage, identified by D3DTA. This value can be set to D3DTA_CURRENT (the default value) or to D3DTA_TEMP, which is a single temporary register that can be read into subsequent stages as an input argument. The final color passed to the fog blender and frame buffer is taken from D3DTA_CURRENT, so the last active texture stage state must be set to write to current. This setting is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present.
D3DTSS_CONSTANT
Per-stage constant color. To see if a device supports a per-stage constant color, see the D3DPMISCCAPS_PERSTAGECONSTANT constant in D3DPMISCCAPS. D3DTSS_CONSTANT is used by D3DTA_CONSTANT. See D3DTA.
D3DTSS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Members of this enumerated type are used with the IDirect3DDevice9::GetTextureStageState and IDirect3DDevice9::SetTextureStageState methods to retrieve and set texture state values.

The valid range of values for the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, and D3DTSS_BUMPENVMAT11 bump-mapping matrix coefficients is greater than or equal to -8.0 and less than 8.0. This range, expressed in mathematical notation is (-8.0,8.0).

See Also

IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState


D3DTEXTURETRANSFORMFLAGS

Defines texture coordinate transformation values.

typedef enum D3DTEXTURETRANSFORMFLAGS
{
    D3DTTFF_DISABLE = 0,
    D3DTTFF_COUNT1 = 1,
    D3DTTFF_COUNT2 = 2,
    D3DTTFF_COUNT3 = 3,
    D3DTTFF_COUNT4 = 4,
    D3DTTFF_PROJECTED = 256,
    D3DTTFF_FORCE_DWORD = 0x7fffffff,
} D3DTEXTURETRANSFORMFLAGS, *LPD3DTEXTURETRANSFORMFLAGS;

Constants

D3DTTFF_DISABLE
Texture coordinates are passed directly to the rasterizer.
D3DTTFF_COUNT1
The rasterizer should expect 1D texture coordinates. This value is used by fixed function vertex processing; it should be set to 0 when using a programmable vertex shader.
D3DTTFF_COUNT2
The rasterizer should expect 2D texture coordinates. This value is used by fixed function vertex processing; it should be set to 0 when using a programmable vertex shader.
D3DTTFF_COUNT3
The rasterizer should expect 3D texture coordinates. This value is used by fixed function vertex processing; it should be set to 0 when using a programmable vertex shader.
D3DTTFF_COUNT4
The rasterizer should expect 4D texture coordinates. This value is used by fixed function vertex processing; it should be set to 0 when using a programmable vertex shader.
D3DTTFF_PROJECTED
This flag is honored by the fixed function pixel pipeline, as well as the programmable pixel pipeline in versions ps_1_1 to ps_1_3. When texture projection is enabled for a texture stage, all four floating point values must be written to the corresponding texture register. Each texture coordinate is divided by the last element before being passed to the rasterizer. For example, if this flag is specified with the D3DTTFF_COUNT3 flag, the first and second texture coordinates are divided by the third coordinate before being passed to the rasterizer.
D3DTTFF_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Texture coordinates can be transformed using a 4 x 4 matrix before the results are passed to the rasterizer. The texture coordinate transforms are set by calling IDirect3DDevice9::SetTextureStageState, and by passing in the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state and one of the values from D3DTEXTURETRANSFORMFLAGS. For more information about texture transforms, see Texture Coordinate Transformations (Direct3D 9).

See Also

D3DTEXTURESTAGESTATETYPE


D3DTRANSFORMSTATETYPE

Defines constants that describe transformation state values.

typedef enum D3DTRANSFORMSTATETYPE
{
    D3DTS_VIEW = 2,
    D3DTS_PROJECTION = 3,
    D3DTS_TEXTURE0 = 16,
    D3DTS_TEXTURE1 = 17,
    D3DTS_TEXTURE2 = 18,
    D3DTS_TEXTURE3 = 19,
    D3DTS_TEXTURE4 = 20,
    D3DTS_TEXTURE5 = 21,
    D3DTS_TEXTURE6 = 22,
    D3DTS_TEXTURE7 = 23,
    D3DTS_FORCE_DWORD = 0x7fffffff,
} D3DTRANSFORMSTATETYPE, *LPD3DTRANSFORMSTATETYPE;

Constants

D3DTS_VIEW
Identifies the transformation matrix being set as the view transformation matrix. The default value is NULL (the identity matrix).
D3DTS_PROJECTION
Identifies the transformation matrix being set as the projection transformation matrix. The default value is NULL (the identity matrix).
D3DTS_TEXTURE0
Identifies the transformation matrix being set for the specified texture stage.
D3DTS_TEXTURE1
Identifies the transformation matrix being set for the specified texture stage.
D3DTS_TEXTURE2
Identifies the transformation matrix being set for the specified texture stage.
D3DTS_TEXTURE3
Identifies the transformation matrix being set for the specified texture stage.
D3DTS_TEXTURE4
Identifies the transformation matrix being set for the specified texture stage.
D3DTS_TEXTURE5
Identifies the transformation matrix being set for the specified texture stage.
D3DTS_TEXTURE6
Identifies the transformation matrix being set for the specified texture stage.
D3DTS_TEXTURE7
Identifies the transformation matrix being set for the specified texture stage.
D3DTS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The transform states in the range 256 through 511 are reserved to store up to 256 world matrices that can be indexed using the D3DTS_WORLDMATRIX and D3DTS_WORLD macros.

Macros |
D3DTS_WORLD | Equivalent to D3DTS_WORLDMATRIX(0).
D3DTS_WORLDMATRIX (index) | Identifies the transform matrix to set for the world matrix at index. Multiple world matrices are used only for vertex blending. Otherwise only D3DTS_WORLD is used.

See Also

IDirect3DDevice9::GetTransform, IDirect3DDevice9::MultiplyTransform, IDirect3DDevice9::SetTransform, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX


D3DVERTEXBLENDFLAGS

Defines flags used to control the number or matrices that the system applies when performing multimatrix vertex blending.

typedef enum D3DVERTEXBLENDFLAGS
{
    D3DVBF_DISABLE = 0,
    D3DVBF_1WEIGHTS = 1,
    D3DVBF_2WEIGHTS = 2,
    D3DVBF_3WEIGHTS = 3,
    D3DVBF_TWEENING = 255,
    D3DVBF_0WEIGHTS = 256,
} D3DVERTEXBLENDFLAGS, *LPD3DVERTEXBLENDFLAGS;

Constants

D3DVBF_DISABLE
Disable vertex blending; apply only the world matrix set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation state is 0.
D3DVBF_1WEIGHTS
Enable vertex blending between the two matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0 and 1.
D3DVBF_2WEIGHTS
Enable vertex blending between the three matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0, 1, and 2.
D3DVBF_3WEIGHTS
Enable vertex blending between the four matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0, 1, 2, and 3.
D3DVBF_TWEENING
Vertex blending is done by using the value assigned to D3DRS_TWEENFACTOR.
D3DVBF_0WEIGHTS
Use a single matrix with a weight of 1.0.

Remarks

Members of this type are used with the D3DRS_VERTEXBLEND render state.

Geometry blending (multimatrix vertex blending) requires that your application use a vertex format that has blending (beta) weights for each vertex.

See Also

D3DRENDERSTATETYPE, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX


D3DZBUFFERTYPE

Defines constants that describe depth-buffer formats.

typedef enum D3DZBUFFERTYPE
{
    D3DZB_FALSE = 0,
    D3DZB_TRUE = 1,
    D3DZB_USEW = 2,
    D3DZB_FORCE_DWORD = 0x7fffffff,
} D3DZBUFFERTYPE, *LPD3DZBUFFERTYPE;

Constants

D3DZB_FALSE
Disable depth buffering.
D3DZB_TRUE
Enable z-buffering.
D3DZB_USEW
Enable w-buffering.
D3DZB_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Members of this enumerated type are used with the D3DRS_ZENABLE render state.

See Also

D3DRENDERSTATETYPE


D3D Constants

This section contains reference information for the constants defined in Direct3D.

  • D3D9_RESOURCE_PRIORITY (DirectX 9Ex only) - Specify the priority of a resource
  • D3DADAPTER_DEFAULT - Primary display adapter constant
  • D3DCAPS2 - Driver capability flags
  • D3DCAPS3 - Driver capability flags
  • D3DCLEAR - Stencil clear constants
  • D3DCOMPOSERECTS_MAXNUMRECTS (DirectX 9Ex only) - Maximum number of text glyphs to compose
  • D3DCONVOLUTIONMONO (DirectX 9Ex only) - Maximum dimensions of texture convolution filters.
  • D3DCREATE - Device creation constants
  • D3DCURSORCAPS - Device cursor constants
  • D3DDEVCAPS2 - Driver capability constants
  • D3DDTCAPS - Vertex data constants
  • D3DENUM - Enumeration constants
  • D3DFVF - Flexible vertex format constants
  • D3DLOCK - Locking constants
  • D3DPMISCCAPS - Driver primitive constants
  • D3DPRESENT - Presentation timing constants
  • D3DPRESENT_BACK_BUFFERS - Back buffer quantity constants
  • D3DPRESENTFLAG - Presentation constants
  • D3DPSHADERCAPS2_0 - Pixel shader "2_0 Extended" constants
  • D3DPTFILTERCAPS - Texture filtering constants
  • D3DSTENCILCAPS - Driver stencil capability flags
  • D3DTA - Texture argument constants
  • D3DTSS_TCI - Texture coordinate constants
  • D3DUSAGE - Resource usage constants
  • D3DUSAGE_QUERY - Resource query usage constants
  • D3DVS20CAPS - Vertex shader "2_0 Extended" constants
  • D3DVERTEXTEXTURESAMPLER - Vertex shader samplers
  • D3DVTXPCAPS - Device create constants
  • Device State Return Codes - Some possible device return codes
  • Other Direct3D Constants - Other constants


D3D9_RESOURCE_PRIORITY (DirectX 9Ex only)

Constants used to set the priority of a resource in IDirect3DResource9::SetPriority.

#define | Description
D3D9_RESOURCE_PRIORITY_DISCARD | The resource has the lowest priority possible.
D3D9_RESOURCE_PRIORITY_LOW | The resource is scheduled with low priority.
D3D9_RESOURCE_PRIORITY_NORMAL | The resource is scheduled with normal priority.
D3D9_RESOURCE_PRIORITY_HIGH | The resource is scheduled with high priority.
D3D9_RESOURCE_PRIORITY_MAXIMUM | The resource has the maximum priority possible.

Remarks

Values other than D3D9_RESOURCE_PRIORITY_DISCARD and D3D9_RESOURCE_PRIORITY_MAXIMUM are treated as hints by the scheduler.

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Constants


D3DADAPTER_DEFAULT

Specifies the primary display adapter.

#define | Value | Description
D3DADAPTER_DEFAULT | 0 | Used to specify the primary display adapter.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98


D3DCAPS2

Driver capability flags.

#define | Value | Description
D3DCAPS2_CANAUTOGENMIPMAP | 0x40000000L | The driver is capable of automatically generating mipmaps. For more information, see Automatic Generation of Mipmaps (Direct3D 9).
D3DCAPS2_CANCALIBRATEGAMMA | 0x00100000L | The system has a calibrator installed that can automatically adjust the gamma ramp so that the result is identical on all systems that have a calibrator. To invoke the calibrator when setting new gamma levels, use the D3DSGR_CALIBRATE flag when calling IDirect3DDevice9::SetGammaRamp. Calibrating gamma ramps incurs some processing overhead and should not be used frequently.
D3DCAPS2_CANSHARERESOURCE | 0x80000000L | Direct3D 9Ex only - The device can create sharable resources. Methods that create resources can set non-NULL values for their pSharedHandle parameters.
D3DCAPS2_CANMANAGERESOURCE | 0x10000000L | The driver is capable of managing resources. On such drivers, D3DPOOL_MANAGED resources will be managed by the driver. To have Direct3D override the driver so that Direct3D manages resources, use the D3DCREATE_DISABLE_DRIVER_MANAGEMENT flag when calling IDirect3D9::CreateDevice.
D3DCAPS2_DYNAMICTEXTURES | 0x20000000L | The driver supports dynamic textures.
D3DCAPS2_FULLSCREENGAMMA | 0x00020000L | The driver supports dynamic gamma ramp adjustment in full-screen mode.
D3DCAPS2_RESERVED | 0x02000000L | Reserved; not used.

These constants are used by the D3CAPS2 member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DCAPS3

Driver capability flags.

#define | Value | Description
D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD 0x00000020L Indicates that the device can respect the D3DRS_ALPHABLENDENABLE render state in full-screen mode while using the FLIP or DISCARD swap effect. This only applies when the D3DRS_SRCBLEND or D3DRS_DESTBLEND states are set to one of the following:
  • D3DBLEND_DESTALPHA
  • D3DBLEND_INVDESTALPHA
  • D3DBLEND_DESTCOLOR
  • D3DBLEND_INVDESTCOLOR
D3DCAPS3_COPY_TO_VIDMEM | 0x00000100L | Device can accelerate a memory copy from system memory to local video memory. This cap guarantees that IDirect3DDevice9::UpdateSurface and IDirect3DDevice9::UpdateTexture calls will be hardware accelerated. If this cap is absent, these calls will succeed but will be slower.
D3DCAPS3_COPY_TO_SYSTEMMEM | 0x00000200L | Device can accelerate a memory copy from local video memory to system memory. This cap guarantees that IDirect3DDevice9::GetRenderTargetData calls will be hardware accelerated. If this cap is absent, this call will succeed but will be slower.
D3DCAPS3_LINEAR_TO_SRGB_PresentATION | 0x00000080L | Indicates that the device can perform gamma correction from a windowed back buffer (containing linear content) to an sRGB desktop.
D3DCAPS3_RESERVED | 0x8000001fL | Reserved; not used.

These constants are used by the D3CAPS3 member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DCLEAR

These flags identify a surface to reset when calling IDirect3DDevice9::Clear.

#define | Description
D3DCLEAR_STENCIL | Clear the stencil buffer.
D3DCLEAR_TARGET | Clear a render target, or all targets in a multiple render target. See Multiple Render Targets (Direct3D 9).
D3DCLEAR_ZBUFFER | Clear the depth buffer.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98


D3DCOMPOSERECTS_MAXNUMRECTS (DirectX 9Ex only)

Specifies the maximum number of rectangles used in composing glyphs in IDirect3DDevice9Ex::ComposeRect.

#define | Description
D3DCOMPOSERECTS_MAXNUMRECTS | Maximum number of rectangle glyphs to compose together in a text string. See IDirect3DDevice9Ex::ComposeRect.

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Constants


D3DCONVOLUTIONMONO (DirectX 9Ex only)

Specifies the maximum dimensions of texture convolution filters.

#define | Value | Description
D3DCONVOLUTIONMONO_MAXHEIGHT | 7 | Maximum height of a monochrome texture convolution filter.
D3DCONVOLUTIONMONO_MAXWIDTH | 7 | Maximum width of a monochrome texture convolution filter.

Requirements

Header: Declared in D3d9types.h.

See Also

D3D Constants


D3DCREATE

A combination of one or more flags that control the device create behavior.

#define | Description
D3DCREATE_ADAPTERGROUP_DEVICE | Application asks the device to drive all the heads that this master adapter owns. The flag is illegal on nonmaster adapters. If this flag is set, the presentation parameters passed to IDirect3D9::CreateDevice should point to an array of D3DPRESENT_PARAMETERS. The number of elements in D3DPRESENT_PARAMETERS should equal the number of adapters defined by the NumberOfAdaptersInGroup member of the D3DCAPS9 structure. The DirectX runtime will assign each element to each head in the numerical order specified by the AdapterOrdinalInGroup member of D3DCAPS9.
D3DCREATE_DISABLE_DRIVER_MANAGEMENT | Direct3D will manage resources instead of the driver. Direct3D calls will not fail for resource errors such as insufficient video memory.
D3DCREATE_DISABLE_DRIVER_MANAGEMENT_EX | Like D3DCREATE_DISABLE_DRIVER_MANAGEMENT, Direct3D will manage resources instead of the driver. Unlike D3DCREATE_DISABLE_DRIVER_MANAGEMENT, D3DCREATE_DISABLE_DRIVER_MANAGEMENT_EX will return errors for conditions such as insufficient video memory.
D3DCREATE_DISABLE_PRINTSCREEN | Direct3D 9Ex only - Causes the runtime not register hotkeys for Printscreen, Ctrl-Printscreen and Alt-Printscreen to capture the desktop or window content.
D3DCREATE_DISABLE_PSGP_THREADING | Direct3D 9Ex only - Restrict computation to the main application thread. If the flag is not set, the runtime may perform software vertex processing and other computations in worker thread to improve performance on multi-processor systems.
D3DCREATE_ENABLE_PRESENTSTATS | Direct3D 9Ex only - Enables the gathering of present statistics on the device. Calls to IDirect3DSwapChain9Ex::GetPresentStatistics will return valid data.
D3DCREATE_FPU_PRESERVE | Forces Direct3D to not change the floating-point unit control word, running the pipeline using the precision of the calling thread. Without this flag, Direct3D defaults to setting the floating-point unit to single-precision round-to-nearest mode. Using this flag with the floating-point unit in double-precision mode will reduce Direct3D performance. This flag exists for those applications that want to set their own floating-point unit control word and/or stay with double-precision. Note Portions of Direct3D assume floating-point unit exceptions are masked. Unmasking such exceptions may lead to undefined behavior.
D3DCREATE_HARDWARE_VERTEXPROCESSING | Specifies hardware vertex processing.
D3DCREATE_MIXED_VERTEXPROCESSING | Specifies mixed (both software and hardware) vertex processing.
D3DCREATE_MULTITHREADED | Indicates that the application requests Direct3D to be multithread safe. This makes a Direct3D thread take ownership of its global critical section more frequently, which can degrade performance. If an application processes window messages in one thread while making D3D API calls in another, the application must use this flag when creating the device. This window must also be destroyed before unloading d3d9.dll.
D3DCREATE_NOWINDOWCHANGES | Indicates that Direct3D must not alter the focus window in any way. Note If this flag is set, the application must fully support all focus management events, such as ALT+TAB and mouse click events.
D3DCREATE_PUREDEVICE | Specifies that Direct3D does not support Get* calls for anything that can be stored in state blocks. It also tells Direct3D not to provide any emulation services for vertex processing. This means that if the device does not support vertex processing, then the application can use only post-transformed vertices.
D3DCREATE_SCREENSAVER | Direct3D 9Ex only - Allows screensavers during a fullscreen application. Without this flag, Direct3D will disable screensavers for as long as the calling application is fullscreen. If the calling application is already a screensaver, this flag has no effect.
D3DCREATE_SOFTWARE_VERTEXPROCESSING | Specifies software vertex processing.

D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags. At least one of these vertex processing flags must be specified when calling IDirect3D9::CreateDevice.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98


D3DCURSORCAPS

Driver cursor capability flags.

#define | Value | Description
D3DCURSORCAPS_COLOR | 0x00000001L | The driver supports hardware color cursor in at least high resolution modes (height >= 400).
D3DCURSORCAPS_LOWRES | 0x00000002L | The driver supports hardware color cursor in low resolution modes (height < 400).

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DDEVCAPS2

D3DDEVCAPS2 driver capability flags.

#define | Description
D3DDEVCAPS2_ADAPTIVETESSRTPATCH | Device supports adaptive tessellation of RT-patches
D3DDEVCAPS2_ADAPTIVETESSNPATCH | Device supports adaptive tessellation of N-patches.
D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES | Device supports IDirect3DDevice9::StretchRect using a texture as the source.
D3DDEVCAPS2_DMAPNPATCH | Device supports displacement maps for N-patches.
D3DDEVCAPS2_PRESAMPLEDDMAPNPATCH | Device supports presampled displacement maps for N-patches. For more information about displacement mapping, see Displacement Mapping (Direct3D 9).
D3DDEVCAPS2_STREAMOFFSET | Device supports stream offsets.
D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET | Multiple vertex elements can share the same offset in a stream if D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET is set by the device and the vertex declaration does not have an element with D3DDECLUSAGE_POSITIONT0.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DDTCAPS

Constants describing the vertex data types supported by a device.

#define | Value | Description
D3DDTCAPS_UBYTE4 | 0x00000001L | 4D unsigned byte.
D3DDTCAPS_UBYTE4N | 0x00000002L | Normalized, 4D unsigned byte. Each of the four bytes is normalized by dividing to 255.0.
D3DDTCAPS_SHORT2N | 0x00000004L | Normalized, 2D signed short, expanded to (first byte/32767.0, second byte/32767.0, 0, 1).
D3DDTCAPS_SHORT4N | 0x00000008L | Normalized, 4D signed short, expanded to (first byte/32767.0, second byte/32767.0, third byte/32767.0, fourth byte/32767.0).
D3DDTCAPS_USHORT2N | 0x00000010L | Normalized, 2D unsigned short, expanded to (first byte/65535.0, second byte/65535.0, 0, 1).
D3DDTCAPS_USHORT4N | 0x00000020L | Normalized 4D unsigned short, expanded to (first byte/65535.0, second byte/65535.0, third byte/65535.0, fourth byte/65535.0).
D3DDTCAPS_UDEC3 | 0x00000040L | 3D unsigned 10 10 10 format expanded to (value, value, value, 1).
D3DDTCAPS_DEC3N | 0x00000080L | 3D signed 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1).
D3DDTCAPS_FLOAT16_2 | 0x00000100L | 2D 16-bit floating point numbers.
D3DDTCAPS_FLOAT16_4 | 0x00000200L | 4D 16-bit floating point numbers.

These constants are used by the DeclTypes member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DENUM

Driver capability flag.

#define | Value | Description
D3DENUM_WHQL_LEVEL | 0x00000002L | Microsoft Windows Hardware Quality Labs (WHQL) driver testing. This is a time-consuming test requiring a one-second or two-second time penalty. This constant is used by the WHQLLevel member of D3DADAPTER_IDENTIFIER9.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98


D3DFVF

Flexible Vertex Format Constants, or FVF codes, are used to describe the contents of vertices interleaved in a single data stream that will be processed by the fixed-function pipeline.

Vertex Data Flags

The following flags describe a vertex format. For information regarding vertex formats, see Fixed Function FVF Codes (Direct3D 9).

#define | Description | Data order and type
D3DFVF_DIFFUSE | Vertex format includes a diffuse color component. | DWORD in ARGB order. See D3DCOLOR_ARGB.
D3DFVF_NORMAL | Vertex format includes a vertex normal vector. This flag cannot be used with the D3DFVF_XYZRHW flag. | float, float, float
D3DFVF_PSIZE | Vertex format specified in point size. This size is expressed in camera space units for vertices that are not transformed and lit, and in device-space units for transformed and lit vertices. | float
D3DFVF_SPECULAR | Vertex format includes a specular color component. | DWORD in ARGB order. See D3DCOLOR_ARGB.
D3DFVF_XYZ | Vertex format includes the position of an untransformed vertex. This flag cannot be used with the D3DFVF_XYZRHW flag. | float, float, float.
D3DFVF_XYZRHW | Vertex format includes the position of a transformed vertex. This flag cannot be used with the D3DFVF_XYZ or D3DFVF_NORMAL flags. | float, float, float, float.
D3DFVF_XYZB1 through D3DFVF_XYZB5 | Vertex format contains position data, and a corresponding number of weighting (beta) values to use for multimatrix vertex blending operations. Currently, Direct3D can blend with up to three weighting values and four blending matrices. For more information about using blending matrices, see Indexed Vertex Blending (Direct3D 9). | 1, 2, or 3 floats. When D3DFVF_LASTBETA_UBYTE4 is used, the last blending weight is treated as a DWORD.
D3DFVF_XYZW | Vertex format contains transformed and clipped (x, y, z, w) data. ProcessVertices does not invoke the clipper, instead outputting data in clip coordinates. This constant is designed for, and can only be used with, the programmable vertex pipeline. | float, float, float, float

Texture Flags

The following flags describe texture flags used by the fixed-function pipeline.

#define | Description
D3DFVF_TEX0 - D3DFVF_TEX8 | Number of texture coordinate sets for this vertex. The actual values for these flags are not sequential.
D3DFVF_TEXCOORDSIZEN(coordIndex) | Define a texture coordinate data set. n indicates the dimension of the texture coordinates. coordIndex indicates texture coordinate index number. See D3DFVF_TEXCOORDSIZEN and Texture coordinates and Texture Stages.

Mask Flags

The following flags describe mask flags used by the fixed-function pipeline.

#define | Description
D3DFVF_POSITION_MASK | Mask for position bits.
D3DFVF_RESERVED0, D3DFVF_RESERVED2 | Mask values for reserved bits in the FVF. Do not use.
D3DFVF_TEXCOUNT_MASK | Mask value for texture flag bits.

Miscellaneous Flags

The following flags describe a variety of flags used by the fixed-function pipeline.

#define | Description
D3DFVF_LASTBETA_D3DCOLOR | The last beta field in the vertex position data will be of type D3DCOLOR. The data in the beta fields are used with matrix palette skinning to specify matrix indices.
D3DFVF_LASTBETA_UBYTE4 The last beta field in the vertex position data will be of type UBYTE4. The data in the beta fields are used with matrix palette skinning to specify matrix indices.
// Given the following vertex data definition:
struct VERTEXPOSITION
{
   float pos[3];
   union
   {
      float beta[5];
      struct
      {
         float weights[4];
         DWORD MatrixIndices;  // Used as UBYTEs
      }
   }
};

Given the FVF is declared as: D3DFVF_XYZB5 | D3DFVF_LASTBETA_UBYTE4. Weight and MatrixIndices are included in beta[5], where D3DFVF_LASTBETA_UBYTE4 says to interpret the last DWORD in beta[5] as type UBYTE4.
D3DFVF_TEXCOUNT_SHIFT The number of bits by which to shift an integer value that identifies the number of texture coordinates for a vertex. This value might be used as shown below.
DWORD dwNumTextures = 1;  // Vertex has only one set of coordinates.

// Shift the value for use when creating a
//   flexible vertex format (FVF) combination.
dwFVF = dwNumTextures << D3DFVF_TEXCOUNT_SHIFT;

// Now, create an FVF combination using the shifted value.

Examples

The following examples show other common flag combinations.

// Untransformed vertex for lit, untextured, Gouraud-shaded content.
dwFVF = ( D3DFVF_XYZ | D3DFVF_DIFFUSE );

// Untransformed vertex for unlit, untextured, Gouraud-shaded
//   content with diffuse material color specified per vertex.
dwFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE );

// Untransformed vertex for light-map-based lighting.
dwFVF = ( D3DFVF_XYZ | D3DFVF_TEX2 );

// Transformed vertex for light-map-based lighting with shared rhw.
dwFVF = ( D3DFVF_XYZRHW | D3DFVF_TEX2 );

// Heavyweight vertex for unlit, colored content with two
//   sets of texture coordinates.
dwFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE |
          D3DFVF_SPECULAR | D3DFVF_TEX2 );

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

See Also

Fixed Function FVF Codes (Direct3D 9), Geometry Blending (Direct3D 9)


D3DLOCK

A combination of zero or more locking options that describe the type of lock to perform.

#define | Description
D3DLOCK_DISCARD | The application discards all memory within the locked region. For vertex and index buffers, the entire buffer will be discarded. This option is only valid when the resource is created with dynamic usage (see D3DUSAGE).
D3DLOCK_DONOTWAIT | Allows an application to gain back CPU cycles if the driver cannot lock the surface immediately. If this flag is set and the driver cannot lock the surface immediately, the lock call will return D3DERR_WASSTILLDRAWING. This flag can only be used when locking a surface created using IDirect3DDevice9::CreateOffscreenPlainSurface, IDirect3DDevice9::CreateRenderTarget, or IDirect3DDevice9::CreateDepthStencilSurface. This flag can also be used with a back buffer.
D3DLOCK_NO_DIRTY_UPDATE | By default, a lock on a resource adds a dirty region to that resource. This option prevents any changes to the dirty state of the resource. Applications should use this option when they have additional information about the set of regions changed during the lock operation.
D3DLOCK_NOOVERWRITE | Indicates that memory that was referred to in a drawing call since the last lock without this flag will not be modified during the lock. This can enable optimizations when the application is appending data to a resource. Specifying this flag enables the driver to return immediately if the resource is in use, otherwise, the driver must finish using the resource before returning from locking.
D3DLOCK_NOSYSLOCK

The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This option causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is time consuming, but can enable the system to perform other duties, such as moving the mouse cursor. This option is useful for long-duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.
D3DLOCK_READONLY | The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

See Also

IDirect3DCubeTexture9::LockRect, IDirect3DIndexBuffer9::Lock, IDirect3DSurface9::LockRect, IDirect3DTexture9::LockRect, IDirect3DVertexBuffer9::Lock, IDirect3DVolume9::LockBox, IDirect3DVolumeTexture9::LockBox, ID3DXBaseMesh::LockIndexBuffer, ID3DXBaseMesh::LockVertexBuffer, ID3DXBaseMesh::LockVertexBuffer, ID3DXMesh::LockAttributeBuffer, ID3DXPatchMesh::LockAttributeBuffer, ID3DXPatchMesh::LockIndexBuffer, ID3DXPatchMesh::LockVertexBuffer


D3DPMISCCAPS

Miscellaneous driver primitive capability flags.

#define | Value | Description
D3DPMISCCAPS_MASKZ | 0x00000002L | Device can enable and disable modification of the depth buffer on pixel operations.
D3DPMISCCAPS_CULLNONE | 0x00000010L | The driver does not perform triangle culling. This corresponds to the D3DCULL_NONE member of the D3DCULL enumerated type.
D3DPMISCCAPS_CULLCW | 0x00000020L | The driver supports clockwise triangle culling through the D3DRS_CULLMODE state. (This applies only to triangle primitives.) This flag corresponds to the D3DCULL_CW member of the D3DCULL enumerated type.
D3DPMISCCAPS_CULLCCW | 0x00000040L | The driver supports counterclockwise culling through the D3DRS_CULLMODE state. (This applies only to triangle primitives.) This flag corresponds to the D3DCULL_CCW member of the D3DCULL enumerated type.
D3DPMISCCAPS_COLORWRITEENABLE | 0x00000100L | Device supports per-channel writes for the render-target color buffer through the D3DRS_COLORWRITEENABLE state.
D3DPMISCCAPS_CLIPPLANESCALEDPOINTS | 0x00000200L | Device correctly clips scaled points of size greater than 1.0 to user-defined clipping planes.
D3DPMISCCAPS_CLIPTLVERTS | 0x00000200L | Device clips post-transformed vertex primitives. Specify D3DUSAGE_DONOTCLIP when the pipeline should not do any clipping. For this case, additional software clipping may need to be performed at draw time, requiring the vertex buffer to be in system memory.
D3DPMISCCAPS_TSSARGTEMP | 0x00000400L | Device supports D3DTA for temporary register.
D3DPMISCCAPS_BLENDOP | 0x00000800L | Device supports alpha-blending operations other than D3DBLENDOP_ADD.
D3DPMISCCAPS_NULLREFERENCE | 0x00000100L | A reference device that does not render.
D3DPMISCCAPS_INDEPENDENTWRITEMASKS | 0x00004000L | Device supports independent write masks for multiple element textures or multiple render targets.
D3DPMISCCAPS_PERSTAGECONSTANT | 0x00008000L | Device supports per-stage constants. See D3DTSS_CONSTANT in D3DTEXTURESTAGESTATETYPE.
D3DPMISCCAPS_POSTBLENDSRGBCONVERT | 0x00200000L | Direct3D 9Ex only - Device supports conversion to sRGB after blending.
D3DPMISCCAPS_FOGANDSPECULARALPHA | 0x00010000L | Device supports separate fog and specular alpha. Many devices use the specular alpha channel to store the fog factor.
D3DPMISCCAPS_SEPARATEALPHABLEND | 0x00020000L | Device supports separate blend settings for the alpha channel.
D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS | 0x00040000L | Device supports different bit depths for multiple render targets.
D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING | 0x00080000L | Device supports post-pixel shader operations for multiple render targets.
D3DPMISCCAPS_FOGVERTEXCLAMPED | 0x00100000L | Device clamps fog blend factor per vertex.

These constants are used by the PrimitiveMiscCaps member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DPRESENT

Describes the relationship between the adapter refresh rate and the rate at which IDirect3DDevice9::Present or IDirect3DSwapChain9::Present operations are completed. These values also serve as flag values for the PresentationIntervals field of D3DCAPS9.

#define | Description
D3DPRESENT_DONOTFLIP | Direct3D 9Ex only - Use the front buffer as both the source and target surface during rendering. A frame synch is scheduled but the displayed surface does not change. This flag is only available in fullscreen mode.
D3DPRESENT_DONOTWAIT | A presentation cannot be scheduled by a hal device. If this flag is set in a call to IDirect3DSwapChain9::Present, and the hardware is busy processing or waiting for a vertical sync interval, then Present will return D3DERR_WASSTILLDRAWING to indicate that the blit operation is incomplete.
D3DPRESENT_FLIPRESTART | Direct3D 9Ex only - The application will discard all previously queued frames and presents the current frame next. This is useful in situations where the queued frames are out of sync with other aspects of the application (for example, audio or external UI).
D3DPRESENT_INTERVAL_DEFAULT | This is nearly equivalent to D3DPRESENT_INTERVAL_ONE. See remarks.
D3DPRESENT_INTERVAL_ONE | The driver will wait for the vertical retrace period (the runtime will "beam follow" to prevent tearing). IDirect3DDevice9::Present operations will not be affected more frequently than the screen refresh; the runtime will complete at most one Present operation per adapter refresh period. This is equivalent to using D3DSWAPEFFECT_COPYVSYNC in DirectX 8.1. This option is always available for both windowed and full-screen swap chains. See remarks.
D3DPRESENT_INTERVAL_TWO | The driver will wait for the vertical retrace period. IDirect3DDevice9::Present operations will not be affected more frequently than every second screen refresh. Check the PresentationIntervals cap (see D3DCAPS9) to see if D3DPRESENT_INTERVAL_TWO is supported by the driver.
D3DPRESENT_INTERVAL_THREE | The driver will wait for the vertical retrace period. IDirect3DDevice9::Present operations will not be affected more frequently than every third screen refresh. Check the PresentationIntervals cap (see D3DCAPS9) to see if D3DPRESENT_INTERVAL_THREE is supported by the driver.
D3DPRESENT_INTERVAL_FOUR | The driver will wait for the vertical retrace period. IDirect3DDevice9::Present operations will not be affected more frequently than every fourth screen refresh. Check the PresentationIntervals member (see D3DCAPS9) to see if D3DPRESENT_INTERVAL_FOUR is supported by the driver.
D3DPRESENT_INTERVAL_IMMEDIATE | The runtime updates the window client area immediately and might do so more than once during the adapter refresh period. This is equivalent to using D3DSWAPEFFECT_COPY in DirectX 8. IDirect3DDevice9::Present operations might be affected immediately. This option is always available for both windowed and full-screen swap chains. See remarks.
D3DPRESENT_LINEAR_CONTENT The content of the back buffer to be presented is in the linear color space.
  • The presentation will implicitly convert from linear space to sRGB (gamma = 2.2). This is the only conversion that is supported.
  • Because this flag represents a property of the content of the back buffer, the flag can be specified during an IDirect3DSwapChain9::Present call. In other words, an application can present linear content in one frame, and then switch to corrected content in the next.
  • This flag is ignored when the swap chain is full screen. (Note that this flag is available only on the explicit swap chain version of IDirect3DSwapChain9::Present. The IDirect3DDevice9::Present method does not take a flags parameter.)
  • This flag is always accepted, but will only take effect when the driver exposes >D3DCAPS3_LINEAR_TO_SRGB_PresentATION.
  • The only back buffer format supported is X8R8G8B8.
See Windowed Swap Chains.
D3DPRESENT_VIDEO_RESTRICT_TO_MONITOR | Direct3D 9Ex only - Clips the rendered contents to the monitor/device the adapter is targeting, shows thumbnails for the content in the Flip3D view and taskbar thumbnails on other monitors. See Desktop Window Manager for further details on this feature of Windows Vista. If you are not running in desktop composition mode, the flag gives the same behavior as D3DPRESENTFLAG_DEVICECLIP.

Remarks

Windowed mode supports D3DPRESENT_INTERVAL_DEFAULT, D3DPRESENT_INTERVAL_IMMEDIATE, and D3DPRESENT_INTERVAL_ONE. D3DPRESENT_INTERVAL_DEFAULT and the D3DPRESENT_INTERVAL_ONE are nearly equivalent (see the information regarding timer resolution below). They perform similarly to COPY_VSYNC in that there is only one present per frame, and they prevent tearing with beam-following. In contrast, D3DPRESENT_INTERVAL_IMMEDIATE will attempt to provide an unlimited presentation rate.

Full-screen mode supports similar usage as windowed mode by supporting D3DPRESENT_INTERVAL_IMMEDIATE regardless of the refresh rate or swap effect. D3DPRESENT_INTERVAL_DEFAULT uses the default system timer resolution whereas the D3DPRESENT_INTERVAL_ONE calls timeBeginPeriod to enhance system timer resolution. This improves the quality of vertical sync, but consumes slightly more processing time. Both parameters attempt to synchronize vertically.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98


D3DPRESENT_BACK_BUFFERS

Specifies the number of back buffers that can be used by the device.

#define | Value | Description
D3DPRESENT_BACK_BUFFERS_MAX | 3 | Maximum number of back buffers supported in Direct3D 9.
D3DPRESENT_BACK_BUFFERS_MAX_EX | 30 | Maximum number of back buffers supported in Direct3D 9Ex.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98


D3DPRESENTFLAG

Constants used by D3DPRESENT_PARAMETERS.

#define | Value | Description
D3DPRESENTFLAG_DEVICECLIP | 0x00000004 | Clip a windowed IDirect3DDevice9::Present blit into the window client area, within the monitor screen area of the video adapter that created the Direct3D device. This constant works on Windows 2000 and Windows XP only.
D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL 0x00000002 Set this flag when the device or swap chain is created to enable z-buffer discarding. If this flag is set, the contents of the depth stencil buffer will be invalid after calling either IDirect3DDevice9::Present, or IDirect3DDevice9::SetDepthStencilSurface with a different depth surface.

Discarding z-buffer data can increase performance and is driver dependent. The debug runtime will enforce discarding by clearing the z-buffer to some constant value after calling either IDirect3DDevice9::Present, or IDirect3DDevice9::SetDepthStencilSurface with a different depth surface.

Discarding z-buffer data is illegal for all lockable formats, D3DFMT_D16_LOCKABLE and D3DFMT_D32F_LOCKABLE. Any use of IDirect3D9::CreateDevice specifying a lockable format and z-buffer discarding will fail. For more information about formats, see D3DFORMAT.
D3DPRESENTFLAG_LOCKABLE_BACKBUFFER 0x00000001 Set this flag if the application requires the ability to lock the back buffer directly. Note that back buffers are not lockable unless the application specifies D3DPRESENTFLAG_LOCKABLE_BACKBUFFER when calling IDirect3D9::CreateDevice or IDirect3DDevice9::Reset. Lockable back buffers incur a performance cost on some graphics hardware configurations.

Performing a lock operation (or using IDirect3DDevice9::UpdateSurface to write) on the lockable back buffer decreases performance on many cards. In this case, consider using textured triangles to move data to the back buffer.
D3DPRESENTFLAG_NOAUTOROTATE 0x00000020

Direct3D 9Ex only - By default, full-screen applications will honor the current rotation settings of a display monitor automatically. This is handled with a rotating copy operation during presentation, which is not ver efficient. This flag is used by an application that would like to own the mechanism of display rotation.The methods IDirect3DSwapChain9Ex::GetDisplayModeEx and IDirect3D9Ex::GetAdapterDisplayModeEx should be used to to find the current rotation setting.

When the rotation settings are not D3DDISPLAYROTATION_IDENTITY, the application must achieve rotation on it's own (possibly using a rotated view matrix). The backbuffer Width and Height parameters in IDirect3D9Ex::CreateDeviceEx and IDirect3DDevice9Ex::ResetEx must be use landscape orientation, while the fullscreen display mode structure should be equivalent to what is returned from IDirect3D9Ex::EnumAdapterModesEx (i.e. Width and Height are swapped when rotated 90 and 270 degrees).

The application should be cautious about a number of issues when taking on the responsability of rotation: when using Lock on rotated render targets, upper-left corner assumptions no longer hold true, the render target SURFACE_DESC will remain landscape (as implied by the creation parameters), and GDI window, mouse coordinates, and such need to be properly translated when used with the Direct3D render target and scene.

D3DPRESENTFLAG_UNPRUNEDMODE | 0x00000040 | Direct3D 9Ex only - Use this flag to specify any RAW display mode enumerated by the display adapter even though Direct3D may have indicated the mode is invalid. The application should implement this in a robust manner in case the desired mode really is invalid.
D3DPRESENTFLAG_VIDEO | 0x00000010 | This is a hint to the driver that the back buffers will contain video data.

These constants are used by D3DPRESENT_PARAMETERS.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98


D3DD3DPSHADERCAPS2_0

Pixel shader capability flags.

#define | Value | Description
D3DD3DPSHADERCAPS2_0_ARBITRARYSWIZZLE | (1 << 0) | Arbitrary swizzling is supported.
D3DD3DPSHADERCAPS2_0_GRADIENTINSTRUCTIONS | (1 << 1) | Gradient instructions are supported.
D3DD3DPSHADERCAPS2_0_PREDICATION | (1 << 2) | Instruction predication is supported. See setp_comp - ps.
D3DD3DPSHADERCAPS2_0_NODEPENDENTREADLIMIT | (1 << 3) | There is no limit on the number of dependent reads per instruction.
D3DD3DPSHADERCAPS2_0_NOTEXINSTRUCTIONLIMIT | (1 << 4) | There is no limit on the number of tex instructions.
D3DPS20_MAX_DYNAMICFLOWCONTROLDEPTH | 24 | The maximum level of nesting of dynamic flow control instructions (break, breakc, ifc).
D3DPS20_MIN_DYNAMICFLOWCONTROLDEPTH | 0 | The minimum level of nesting of dynamic flow control instructions (break, breakc, ifc).
D3DPS20_MAX_NUMTEMPS | 32 | The driver will support at most this many temporary register.
D3DPS20_MIN_NUMTEMPS | 12 | The driver will support at least this many temporary register.
D3DPS20_MAX_STATICFLOWCONTROLDEPTH | 4 | The maximum depth of nesting of the loop - vs/rep - vs and call - vs/callnz bool - vs instructions.
D3DPS20_MIN_STATICFLOWCONTROLDEPTH | 1 | The minimum depth of nesting of the loop - vs/rep - vs and call - vs/callnz bool - vs instructions.
D3DPS20_MAX_NUMINSTRUCTIONSLOTS | 512 | The driver will support at most this many instructions.
D3DPS20_MIN_NUMINSTRUCTIONSLOTS | 96 | The driver will support at least this many instructions.

These constants are used by the D3DPSHADERCAPS2_0 member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

See Also

D3DPSHADERCAPS2_0


D3DPTFILTERCAPS

Texture filtering constants.

#define | Description
D3DPTFILTERCAPS_CONVOLUTIONMONO | Direct3D 9Ex only - Device supports monochrome convolution filtering. This filter is represented by the D3DTEXF_CONVOLUTIONMONO member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFPOINT | Device supports per-stage point-sample filtering for magnifying textures. The point-sample magnification filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFLINEAR | Device supports per-stage bilinear interpolation filtering for magnifying mipmaps. The bilinear interpolation mipmapping filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFANISOTROPIC | Device supports per-stage anisotropic filtering for magnifying textures. The anisotropic magnification filter is represented by the D3DTEXF_ANISOTROPIC member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD | Device supports per-stage pyramidal sample filtering for magnifying textures. The pyramidal magnifying filter is represented by the D3DTEXF_PYRAMIDALQUAD member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFGAUSSIANQUAD | Device supports per-stage Gaussian quad filtering for magnifying textures.
D3DPTFILTERCAPS_MINFPOINT | Device supports per-stage point-sample filtering for minifying textures. The point-sample minification filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFLINEAR | Device supports per-stage linear filtering for minifying textures. The linear minification filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFANISOTROPIC | Device supports per-stage anisotropic filtering for minifying textures. The anisotropic minification filter is represented by the D3DTEXF_ANISOTROPIC member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFPYRAMIDALQUAD | Device supports per-stage pyramidal sample filtering for minifying textures.
D3DPTFILTERCAPS_MINFGAUSSIANQUAD | Device supports per-stage Gaussian quad filtering for minifying textures.
D3DPTFILTERCAPS_MIPFPOINT | Device supports per-stage point-sample filtering for mipmaps. The point-sample mipmapping filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MIPFLINEAR | Device supports per-stage bilinear interpolation filtering for mipmaps. The bilinear interpolation mipmapping filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.

These constants are used by TextureFilterCaps, CubeTextureFilterCaps, VolumeTextureFilterCaps, and VertexTextureFilterCaps members of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DSTENCILCAPS

Driver stencil capability flags.

#define | Value | Description
D3DSTENCILCAPS_KEEP | 0x00000001L | Do not update the entry in the stencil buffer. This is the default value.
D3DSTENCILCAPS_ZERO | 0x00000002L | Set the stencil-buffer entry to 0.
D3DSTENCILCAPS_REPLACE | 0x00000004L | Replace the stencil-buffer entry with reference value.
D3DSTENCILCAPS_INCRSAT | 0x00000008L | Increment the stencil-buffer entry, clamping to the maximum value.
D3DSTENCILCAPS_DECRSAT | 0x00000010L | Decrement the stencil-buffer entry, clamping to zero.
D3DSTENCILCAPS_INVERT | 0x00000020L | Invert the bits in the stencil-buffer entry.
D3DSTENCILCAPS_INCR | 0x00000040L | Increment the stencil-buffer entry, wrapping to zero if the new value exceeds the maximum value.
D3DSTENCILCAPS_DECR | 0x00000080L | Decrement the stencil-buffer entry, wrapping to the maximum value if the new value is less than zero.
D3DSTENCILCAPS_TWOSIDED | 0x00000100L | The device supports two-sided stencil.

Stencil-buffer entries are integer values ranging from 0 through 2n - 1, where n is the bit depth of the stencil buffer.

These constants are used by the StencilCaps member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DTA

Texture argument constants are used as values for the following members of the D3DTEXTURESTAGESTATETYPE enumerated type:

  • D3DTSS_ALPHAARG0
  • D3DTSS_ALPHAARG1
  • D3DTSS_ALPHAARG2
  • D3DTSS_COLORARG0
  • D3DTSS_COLORARG1
  • D3DTSS_COLORARG2
  • D3DTSS_RESULTARG

Set and retrieve texture arguments by calling the IDirect3DDevice9::SetTextureStageState and IDirect3DDevice9::GetTextureStageState methods.

Argument flags

You can combine an argument flag with a modifier, but two argument flags cannot be combined.

#define | Description
D3DTA_CONSTANT | Select a constant from a texture stage. The default value is 0xffffffff.
D3DTA_CURRENT | The texture argument is the result of the previous blending stage. In the first texture stage (stage 0), this argument is equivalent to D3DTA_DIFFUSE. If the previous blending stage uses a bump-map texture (the D3DTOP_BUMPENVMAP operation), the system chooses the texture from the stage before the bump-map texture. If s represents the current texture stage and s - 1 contains a bump-map texture, this argument becomes the result output by texture stage s - 2. Permissions are read/write.
D3DTA_DIFFUSE | The texture argument is the diffuse color interpolated from vertex components during Gouraud shading. If the vertex does not contain a diffuse color, the default color is 0xffffffff. Permissions are read-only.
D3DTA_SELECTMASK | Mask value for all arguments; not used when setting texture arguments.
D3DTA_SPECULAR | The texture argument is the specular color interpolated from vertex components during Gouraud shading. If the vertex does not contain a specular color, the default color is 0xffffffff. Permissions are read-only.
D3DTA_TEMP | The texture argument is a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0). Permissions are read/write.
D3DTA_TEXTURE | The texture argument is the texture color for this texture stage. Permissions are read-only.
D3DTA_TFACTOR | The texture argument is the texture factor set in a previous call to the IDirect3DDevice9::SetRenderState with the D3DRS_TEXTUREFACTOR render-state value. Permissions are read-only.

Modifier flags

An argument flag may be combined with one of the following modifier flags.

#define | Description
D3DTA_ALPHAREPLICATE | Replicate the alpha information to all color channels before the operation completes. This is a read modifier.
D3DTA_COMPLEMENT | Take the complement of the argument x, (1.0 - x). This is a read modifier.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98


D3DTSS_TCI

Driver texture coordinate capability flags.

#define | Value | Description
D3DTSS_TCI_PASSTHRU | 0x00000000L | Use the specified texture coordinates contained within the vertex format. This value resolves to zero.
D3DTSS_TCI_CAMERASPACENORMAL | 0x00010000L | Use the vertex normal, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEPOSITION | 0x00020000L | Use the vertex position, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR | 0x00030000L | Use the reflection vector, transformed to camera space, as the input texture coordinate for this stage's texture transformation. The reflection vector is computed from the input vertex position and normal vector.
D3DTSS_TCI_SPHEREMAP | 0x00040000L | Use the specified texture coordinates for sphere mapping.

These constants are used by D3DTSS_TEXCOORDINDEX.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DUSAGE

Usage options that identify how resources are to be used.

Usages

The following table summarizes the available usage options.

#define | Description
D3DUSAGE_AUTOGENMIPMAP | The resource will automatically generate mipmaps. See Automatic Generation of Mipmaps (Direct3D 9). Automatic generation of mipmaps is not supported for volume textures and depth stencil surfaces/textures. This usage is not valid for a resource in system memory (D3DPOOL_SYSTEMMEM).
D3DUSAGE_DEPTHSTENCIL | The resource will be a depth stencil buffer. D3DUSAGE_DEPTHSTENCIL can only be used with D3DPOOL_DEFAULT.
D3DUSAGE_DMAP | The resource will be a displacement map.
D3DUSAGE_DONOTCLIP | Set to indicate that the vertex buffer content will never require clipping. When rendering with buffers that have this flag set, the D3DRS_CLIPPING render state must be set to false.
D3DUSAGE_DYNAMIC

Set to indicate that the vertex buffer requires dynamic memory use. This is useful for drivers because it enables them to decide where to place the buffer. In general, static vertex buffers are placed in video memory and dynamic vertex buffers are placed in AGP memory. Note that there is no separate static use. If you do not specify D3DUSAGE_DYNAMIC, the vertex buffer is made static. D3DUSAGE_DYNAMIC is strictly enforced through the D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE locking flags. As a result, D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE are valid only on vertex buffers created with D3DUSAGE_DYNAMIC. They are not valid flags on static vertex buffers. For more information, see Managing Resources (Direct3D 9).

For more information about using dynamic vertex buffers, see Performance Optimizations (Direct3D 9).

D3DUSAGE_DYNAMIC and D3DPOOL_MANAGED are incompatible and should not be used together. See D3DPOOL.

Textures can specify D3DUSAGE_DYNAMIC. However, managed textures cannot use D3DUSAGE_DYNAMIC. For more information about dynamic textures, see Using Dynamic Textures.

D3DUSAGE_NONSECURE | Direct3D 9Ex only - Allow a shared surface created by a secure application to be opened by a non-secure application that has the shared handle.
D3DUSAGE_NPATCHES | Set to indicate that the vertex buffer is to be used for drawing N-patches.
D3DUSAGE_POINTS | Set to indicate that the vertex or index buffer will be used for drawing point sprites. The buffer will be loaded in system memory if software vertex processing is needed to emulate point sprites.
D3DUSAGE_RENDERTARGET | The resource will be a render target. D3DUSAGE_RENDERTARGET can only be used with D3DPOOL_DEFAULT.
D3DUSAGE_RTPATCHES | Set to indicate that the vertex buffer is to be used for drawing high-order primitives.
D3DUSAGE_SOFTWAREPROCESSING

If this flag is used, vertex processing is done in software. If this flag is not used, vertex processing is done in hardware.

The D3DUSAGE_SOFTWAREPROCESSING flag can be set when mixed-mode or software vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING / D3DCREATE_SOFTWARE_VERTEXPROCESSING) is enabled for that device. D3DUSAGE_SOFTWAREPROCESSING must be set for buffers to be used with software vertex processing in mixed mode, but it should not be set for the best possible performance when using hardware index processing in mixed mode (D3DCREATE_HARDWARE_VERTEXPROCESSING). However, setting D3DUSAGE_SOFTWAREPROCESSING is the only option when a single buffer is used with both hardware and software vertex processing. D3DUSAGE_SOFTWAREPROCESSING is allowed for mixed and software devices.

D3DUSAGE_SOFTWAREPROCESSING is used with IDirect3D9::CheckDeviceFormat to find out if a particular texture format can be used as a vertex texture during software vertex processing. If it can, the texture must be created in D3DPOOL_SCRATCH.
D3DUSAGE_TEXTAPI | Direct3D 9Ex only - This usage flag must be specified for vertex buffers and source surfaces, used in calls to IDirect3DDevice9Ex::ComposeRect. Textures created with this usage flag cannot be used for texture filtering. Vertex buffers, created with this usage flag, cannot be used as input stream sources.
D3DUSAGE_WRITEONLY | Informs the system that the application writes only to the vertex buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from a vertex buffer that is created with this capability will fail. Buffers created with D3DPOOL_DEFAULT that do not specify D3DUSAGE_WRITEONLY might suffer a severe performance penalty.

Usage and Resource Combinations

Usages are either specified when a resource is created, or specified with IDirect3D9::CheckDeviceType to test the capability of an existing resource. The following table identifies which usages can be applied to which resource types.

Usage | Vertex buffer create | Index buffer create | Texture create | Cube texture create | Volume texture create | Surface create | Check device format
D3DUSAGE_AUTOGENMIPMAP |  |  | x | x |  |  | x
D3DUSAGE_DEPTHSTENCIL |  |  | x | x |  | x | x
D3DUSAGE_DMAP |  |  | x |  |  |  | x
D3DUSAGE_DONOTCLIP | x | x |  |  |  |  |
D3DUSAGE_DYNAMIC | x | x | x | x | x |  | x
D3DUSAGE_NONSECURE | x | x | x | x | x | x | x
D3DUSAGE_NPATCHES | x | x |  |  |  |  |
D3DUSAGE_POINTS | x | x |  |  |  |  |
D3DUSAGE_RTPATCHES | x | x |  |  |  |  |
D3DUSAGE_RENDERTARGET |  |  | x | x |  | x | x
D3DUSAGE_SOFTWAREPROCESSING | x | x | x | x | x |  | x
D3DUSAGE_TEXTAPI | x |  | x |  |  |  |
D3DUSAGE_WRITEONLY | x | x |  |  |  |  |

Use IDirect3D9::CheckDeviceFormat to check hardware support for these usages.

Each of the resource creation methods is listed here.

  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateDepthStencilSurface
  • IDirect3DDevice9::CreateIndexBuffer
  • IDirect3DDevice9::CreateOffscreenPlainSurface
  • IDirect3DDevice9::CreateRenderTarget
  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVertexBuffer
  • IDirect3DDevice9::CreateVolumeTexture

The D3DXCreatexxx texturing functions also use some of these constant values for resource creation.

For more information about pool types and their restrictions with certain usages, see D3DPOOL.

Requirements

Header: Declared in D3d9types.h.

See Also

D3DUSAGE_QUERY, D3DDECLUSAGE, D3DPOOL


D3DUSAGE_QUERY

These options identify query resource types.

#define | Description
D3DUSAGE_QUERY_FILTER | Query the resource format to see if it supports texture filter types other than D3DTEXF_POINT (which is always supported).
D3DUSAGE_QUERY_LEGACYBUMPMAP | Query the resource about a legacy bump map.
D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING | Query the resource to verify support for post pixel shader blending support. If IDirect3D9::CheckDeviceFormat fails with D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, post pixel blending operations are not supported. These include alpha test, pixel fog, render-target blending, color write enable, and dithering.
D3DUSAGE_QUERY_SRGBREAD | Query the resource to verify if a texture supports gamma correction during a read operation.
D3DUSAGE_QUERY_SRGBWRITE | Query the resource to verify if a texture supports gamma correction during a write operation.
D3DUSAGE_QUERY_VERTEXTEXTURE | Query the resource to verify support for vertex shader texture sampling.
D3DUSAGE_QUERY_WRAPANDMIP | Query the resource to verify support for texture wrapping and mip-mapping.

Use IDirect3D9::CheckDeviceFormat to query hardware support for these usages, and some other usages listed in D3DUSAGE.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98


D3DVERTEXTEXTURESAMPLER

Vertex texture sampler constants.

These constants identify the texture samplers used by vertex shaders.

#define | Description
D3DVERTEXTEXTURESAMPLER0 | (D3DDMAPSAMPLER+1)
D3DVERTEXTEXTURESAMPLER1 | (D3DDMAPSAMPLER+2)
D3DVERTEXTEXTURESAMPLER2 | (D3DDMAPSAMPLER+3)
D3DVERTEXTEXTURESAMPLER3 | (D3DDMAPSAMPLER+4)

D3DDMAPSAMPLER

This is an internal constant used by the texture sampler in the tessellator.

#define | Description
D3DDMAPSAMPLER | 256, which is the maximum number of texture samplers.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98


D3DVS20CAPS

Vertex shader caps constants. These constants are used by the VS20Caps member of D3DCAPS9.

#define | Value | Description
D3DVS20CAPS_PREDICATION | (1 << 0) | Instruction predication is supported. See setp_comp - vs.
D3DVS20_MAX_DYNAMICFLOWCONTROLDEPTH | 24 | The maximum level of nesting of dynamic flow control instructions (break - vs, break_comp - vs, breakp - vs, if_comp - vs, if_comp - vs, if pred - vs).
D3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH | 0 | The minimum level of nesting of dynamic flow control instructions (break - vs, break_comp - vs, breakp - vs, if_comp - vs, if_comp - vs, if pred - vs).
D3DVS20_MAX_NUMTEMPS | 32 | The maximum number of temporary registers supported.
D3DVS20_MIN_NUMTEMPS | 12 | The minimum number of temporary registers supported.
D3DVS20_MAX_STATICFLOWCONTROLDEPTH | 4 | The maximum depth of nesting of the loop - vs/rep - vs and call - vs/callnz bool - vs instructions.
D3DVS20_MIN_STATICFLOWCONTROLDEPTH | 1 | The minimum depth of nesting of the loop - vs/rep - vs and call - vs/callnz bool - vs instructions.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

See Also

D3DVSHADERCAPS2_0


D3DVTXPCAPS

A combination of one or more flags that control the device create behavior.

#define | Description
D3DVTXPCAPS_DIRECTIONALLIGHTS | Device can do directional lights.
D3DVTXPCAPS_LOCALVIEWER | Device can do local viewer.
D3DVTXPCAPS_MATERIALSOURCE7 | When this cap is set, the device supports the color material states: D3DRS_AMBIENTMATERIALSOURCE, D3DRS_DIFFUSEMATERIALSOURCE, D3DRS_EMISSIVEMATERIALSOURCE, and D3DRS_SPECULARMATERIALSOURCE.
D3DVTXPCAPS_NO_TEXGEN_NONLOCALVIEWER | Device does not support texture generation in non-local viewer mode.
D3DVTXPCAPS_POSITIONALLIGHTS | Device can do positional lights (includes point and spot).
D3DVTXPCAPS_TEXGEN | Device can do texgen.
D3DVTXPCAPS_TEXGEN_SPHEREMAP | Device supports D3DTSS_TCI_SPHEREMAP.
D3DVTXPCAPS_TWEENING | Device can do vertex tweening.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


Device State Return Codes

A list of some of the possible return codes for methods and functions.

#define | Description
D3DERR_DEVICELOST | A Direct 3D device object other than the one that returned this code caused the hardware adapter to be reset by the OS. Delete all video memory objects (surfaces, textures, state blocks) and call Reset() to return the device to a default state. If the application continues rendering without a reset, the rendering calls will succeed.
D3DERR_DEVICEHUNG | The device that returned this code caused the hardware adapter to be reset by the OS. Most applications should destroy the device and quit. Applications that must continue should destroy all video memory objects (surfaces, textures, state blocks etc) and call Reset() to put the device in a default state. If the application then continues rendering in the same way, the device will return to this state.
D3DERR_DEVICEREMOVED | The hardware adapter has been removed. Application must destroy the device, do enumeration of adapters and create another D3D device. If application continues rendering without calling Reset, the rendering calls will succeed.
S_OK | The device is running normally and can be used for rendering.
S_PRESENT_OCCLUDED

The presentation area is occluded. Occlusion means that the presentation window is minimized or another device entered the fullscreen mode on the same monitor as the presentation window and the presentation window is completely on that monitor. Occlusion will not occur if the client area is covered by another Window.

Occluded applications can continue rendering and all calls will succeed, but the occluded presentation window will not be updated. Preferably the application should stop rendering to the presentation window using the device and keep calling IDirect3DDevice9Ex::CheckDeviceState until S_OK or S_PRESENT_MODE_CHANGED returns.
S_PRESENT_MODE_CHANGED | The desktop display mode has been changed. The application can continue rendering, but there might be color conversion/stretching. Pick a back buffer format similar to the current display mode, and call Reset to recreate the swap chains. The device will leave this state after a Reset is called.


Other Direct3D Constants

SDK Version

#define
D3D_SDK_VERSION
D3D9b_SDK_VERSION

These #defines are declared in d3d9.h.

Other Constants

The following table lists constants that are used internally:

#define | Value | Description
D3D_MAX_SIMULTANEOUS_RENDERTARGETS | 4 | The maximum number of rendertargets.
D3DDMAPSAMPLER | 256 | The maximum number of displacement map samples.
D3DDP_MAXTEXCOORD | 8 | The maximum number of texture coordinates.
MAXD3DDECLLENGTH | 64 (does not include "end" marker vertex element) | Maximum number of elements in a vertex declaration.
MAXD3DDECLUSAGEINDEX | 15 | The maximum index (0-15) that can be used in a vertex declaration.

These #defines are declared in d3d9types.h.

Constant Information

Minimum operating system Windows 98


D3DX Reference

This section contains reference information for the API elements provided by the D3DX utility library. Reference material is divided into the following categories.

  • D3DX Interfaces
  • D3DX Functions
  • Callback Functions
  • Macros
  • D3DX Structures
  • D3DX Enumerations
  • Reference


D3DX Interfaces

This section contains reference information for the component object model (COM) interfaces provided by the D3DX utility library. The following interfaces are used with the D3DX utility library.

  • ID3DXAllocateHierarchy
  • ID3DXAnimationCallbackHandler
  • ID3DXAnimationController
  • ID3DXAnimationSet
  • ID3DXBaseEffect
  • ID3DXBaseMesh
  • ID3DXBuffer
  • ID3DXCompressedAnimationSet
  • ID3DXConstantTable
  • ID3DXEffect
  • ID3DXEffectCompiler
  • ID3DXEffectPool
  • ID3DXEffectStateManager
  • ID3DXFont
  • ID3DXFragmentLinker
  • ID3DXInclude
  • ID3DXKeyframedAnimationSet
  • ID3DXLine
  • ID3DXLoadUserData
  • ID3DXMATRIXStack
  • ID3DXMesh
  • ID3DXPatchMesh
  • ID3DXPMesh
  • ID3DXPRTBuffer
  • ID3DXPRTCompBuffer
  • ID3DXPRTEngine
  • ID3DXRenderToEnvMap
  • ID3DXRenderToSurface
  • ID3DXSaveUserData
  • ID3DXSkinInfo
  • ID3DXSPMesh
  • ID3DXSprite
  • ID3DXTextureGutterHelper
  • ID3DXTextureShader


ID3DXAllocateHierarchy

This interface is implemented by the application to allocate or free frame and mesh container objects. Methods on this are called during loading and destroying frame hierarchies.

ID3DXAllocateHierarchy Members

Method | Description
ID3DXAllocateHierarchy::CreateFrame | Requests allocation of a frame object.
ID3DXAllocateHierarchy::CreateMeshContainer | Requests allocation of a mesh container object.
ID3DXAllocateHierarchy::DestroyFrame | Requests deallocation of a frame object.
ID3DXAllocateHierarchy::DestroyMeshContainer | Requests deallocation of a mesh container object.

Remarks

The LPD3DXALLOCATEHIERARCHY type is defined as a pointer to this interface.

typedef interface ID3DXAllocateHierarchy ID3DXAllocateHierarchy;
typedef interface ID3DXAllocateHierarchy *LPD3DXALLOCATEHIERARCHY;

Requirements

Header: Declared in D3dx9anim.h.

Library: Use D3dx9.lib.


ID3DXAllocateHierarchy::CreateFrame

Requests allocation of a frame object.

HRESULT CreateFrame(
  LPCSTR Name,
  LPD3DXFRAME * ppNewFrame
);

Parameters

Name
[in] Name of the frame to be created.
ppNewFrame
[out, retval] Returns the created frame object.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAllocateHierarchy::CreateMeshContainer

Requests allocation of a mesh container object.

HRESULT CreateMeshContainer(
  LPCSTR Name,
  CONST D3DXMESHDATA * pMeshData,
  CONST D3DXMATERIAL * pMaterials,
  CONST D3DXEFFECTINSTANCE * pEffectInstances,
  DWORD NumMaterials,
  CONST DWORD * pAdjacency,
  LPD3DXSKININFO pSkinInfo,
  LPD3DXMESHCONTAINER * ppNewMeshContainer
);

Parameters

Name
[in] Name of the mesh.
pMeshData
[in] Pointer to the mesh data structure. See D3DXMESHDATA.
pMaterials
[in] Array of materials used in the mesh.
pEffectInstances
[in] Array of effect instances used in the mesh. See D3DXEFFECTINSTANCE.
NumMaterials
[in] Number of materials in the materials array.
pAdjacency
[in] Adjacency array for the mesh.
pSkinInfo
[in] Pointer to the skin mesh object if skin data is found. See ID3DXSkinInfo.
ppNewMeshContainer
[out, retval] Returns the created mesh container. See D3DXMESHCONTAINER.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAllocateHierarchy::DestroyFrame

Requests deallocation of a frame object.

HRESULT DestroyFrame(
  LPD3DXFRAME pFrameToFree
);

Parameters

pFrameToFree
[in] Pointer to the frame to be deallocated.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAllocateHierarchy::DestroyMeshContainer

Requests deallocation of a mesh container object.

HRESULT DestroyMeshContainer(
  LPD3DXMESHCONTAINER pMeshContainerToFree
);

Parameters

pMeshContainerToFree
[in] Pointer to the mesh container object to be deallocated.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationCallbackHandler

An application implements this interface to handle callbacks in animation sets generated by calls to ID3DXAnimationController::AdvanceTime.

ID3DXAnimationCallbackHandler Members

Method | Description
ID3DXAnimationCallbackHandler::HandleCallback | The application implements this method. This method is called when a callback occurs for an animation set in one of the tracks during a call to ID3DXAnimationController::AdvanceTime.

Remarks

The LPD3DXANIMATIONCALLBACKHANDLER type is defined as a pointer to this interface.

typedef interface ID3DXAnimationCallbackHandler ID3DXAnimationCallbackHandler;
typedef interface ID3DXAnimationCallbackHandler *LPD3DXANIMATIONCALLBACKHANDLER;

Requirements

Header: Declared in D3dx9anim.h.

Library: Use D3dx9.lib.


ID3DXAnimationCallbackHandler::HandleCallback

The application implements this method. This method is called when a callback occurs for an animation set in one of the tracks during a call to ID3DXAnimationController::AdvanceTime.

HRESULT HandleCallback(
  UINT Track,
  LPVOID pCallbackData
);

Parameters

Track
[in] Identifier of the track on which the callback occurs.
pCallbackData
[in] Pointer to user-owned callback data.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController

This interface is used to control animation functionality, connecting animation sets with the transformation frames that are being animated. The interface has methods to mix multiple animations and to modify blending parameters over time to enable smooth transitions and other effects.

ID3DXAnimationController Members

Method | Description
ID3DXAnimationController::AdvanceTime | Animates the mesh and advances the global animation time by a specified amount.
ID3DXAnimationController::CloneAnimationController | Clones, or copies, an animation controller.
ID3DXAnimationController::GetAnimationSet | Gets an animation set.
ID3DXAnimationController::GetAnimationSetByName | Gets an animation set, given its name.
ID3DXAnimationController::GetCurrentPriorityBlend | Returns an event handle to a priority blend event that is currently running.
ID3DXAnimationController::GetCurrentTrackEvent | Returns an event handle to the event currently running on the specified animation track.
ID3DXAnimationController::GetEventDesc | Gets a description of a specified animation event.
ID3DXAnimationController::GetMaxNumAnimationOutputs | Get the maximum number of animation outputs the animation controller can support.
ID3DXAnimationController::GetMaxNumAnimationSets | Gets the maximum number of animation sets the animation controller can support.
ID3DXAnimationController::GetMaxNumEvents | Gets the maximum number of events the animation controller can support.
ID3DXAnimationController::GetMaxNumTracks | Gets the maximum number of tracks in the animation controller.
ID3DXAnimationController::GetNumAnimationSets | Returns the number of animation sets currently registered in the animation controller.
ID3DXAnimationController::GetPriorityBlend | Gets the current priority blending weight used by the animation controller.
ID3DXAnimationController::GetTime | Gets the global animation time.
ID3DXAnimationController::GetTrackAnimationSet | Gets the animation set for the given track.
ID3DXAnimationController::GetTrackDesc | Gets the track description.
ID3DXAnimationController::GetUpcomingPriorityBlend | Returns an event handle to the next priority blend event scheduled to occur after a specified event.
ID3DXAnimationController::GetUpcomingTrackEvent | Returns an event handle to the next event scheduled to occur after a specified event on an animation track.
ID3DXAnimationController::KeyPriorityBlend | Sets blending event keys for the specified animation track.
ID3DXAnimationController::KeyTrackEnable | Sets an event key that enables or disables an animation track.
ID3DXAnimationController::KeyTrackPosition | Sets an event key that changes the local time of an animation track.
ID3DXAnimationController::KeyTrackSpeed | Sets an event key that changes the rate of play of an animation track.
ID3DXAnimationController::KeyTrackWeight | Sets an event key that changes the weight of an animation track. The weight is used as a multiplier when combining multiple tracks together.
ID3DXAnimationController::RegisterAnimationOutput | Adds an animation output to the animation controller and registers pointers for scale, rotate, and translate (SRT) transformations.
ID3DXAnimationController::RegisterAnimationSet | Adds an animation set to the animation controller.
ID3DXAnimationController::ResetTime | Resets the global animation time to zero. Any pending events will retain their original schedules, but in the new timeframe.
ID3DXAnimationController::SetPriorityBlend | Sets the priority blending weight used by the animation controller.
ID3DXAnimationController::SetTrackAnimationSet | Applies the animation set to the specified track.
ID3DXAnimationController::SetTrackDesc | Sets the track description.
ID3DXAnimationController::SetTrackEnable | Enables or disables a track in the animation controller.
ID3DXAnimationController::SetTrackPosition | Sets the track to the specified local animation time.
ID3DXAnimationController::SetTrackPriority | Sets the priority blending weight for the specified animation track.
ID3DXAnimationController::SetTrackSpeed | Sets the track speed. The track speed is similar to a multiplier that is used to speed up or slow down the playback of the track.
ID3DXAnimationController::SetTrackWeight | Sets the track weight. The weight is used to determine how to blend multiple tracks together.
ID3DXAnimationController::UnkeyAllPriorityBlends | Removes all scheduled priority blend events from the animation controller.
ID3DXAnimationController::UnkeyAllTrackEvents | Removes all events from a specified animation track.
ID3DXAnimationController::UnkeyEvent | Removes a specified event from an animation track, preventing the execution of the event.
ID3DXAnimationController::UnregisterAnimationSet | Removes an animation set from the animation controller.
ID3DXAnimationController::ValidateEvent | Checks whether a specified event handle is valid and the animation event has not yet completed.

Remarks

Create an animation controller object with D3DXCreateAnimationController.

The LPD3DXANIMATIONCONTROLLER type is defined as a pointer to the ID3DXAnimationController interface.

typedef interface ID3DXAnimationController ID3DXAnimationController;
typedef interface ID3DXAnimationController *LPD3DXANIMATIONCONTROLLER;

The D3DXEVENTHANDLE type is defined as an event handle to animation controller events.

typedef DWORD D3DXEVENTHANDLE;

The LPD3DXEVENTHANDLE type is defined as a pointer to an event handle to animation controller events.

typedef D3DXEVENTHANDLE *LPD3DXEVENTHANDLE;

Requirements

Header: Declared in D3dx9anim.h.

Library: Use D3dx9.lib.


ID3DXAnimationController::AdvanceTime

Animates the mesh and advances the global animation time by a specified amount.

HRESULT AdvanceTime(
  DOUBLE TimeDelta,
  LPD3DXANIMATIONCALLBACKHANDLER pCallbackHandler
);

Parameters

TimeDelta
[in] Amount, in seconds, by which to advance the global animation time. TimeDelta value must be non-negative or zero.
pCallbackHandler
[in] Pointer to a user-defined animation callback handler interface, ID3DXAnimationCallbackHandler.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::CloneAnimationController

Clones, or copies, an animation controller.

HRESULT CloneAnimationController(
  UINT MaxNumAnimationOutputs,
  UINT MaxNumAnimationSets,
  UINT MaxNumTracks,
  UINT MaxNumEvents,
  LPD3DXANIMATIONCONTROLLER * ppAnimController
);

Parameters

MaxNumAnimationOutputs
[in] Maximum number of animation outputs the controller can support.
MaxNumAnimationSets
[in] Maximum number of animation sets the controller can support.
MaxNumTracks
[in] Maximum number of tracks the controller can support.
MaxNumEvents
[in] Maximum number of events the controller can support.
ppAnimController
[in] Address of a pointer to the cloned ID3DXAnimationController animation controller.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetAnimationSet

Gets an animation set.

HRESULT GetAnimationSet(
  UINT Index,
  LPD3DXANIMATIONSET * ppAnimSet
);

Parameters

Index
[in] Index of the animation set.
ppAnimSet
[out] Pointer to the ID3DXAnimationSet animation set.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

The animation controller contains an array of animation sets. This method returns one of them at the given index.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetAnimationSetByName

Gets an animation set, given its name.

HRESULT GetAnimationSetByName(
  LPCSTR pName,
  LPD3DXANIMATIONSET * ppAnimSet
);

Parameters

pName
[in] String containing the name of the animation set.
ppAnimSet
[out] Pointer to the ID3DXAnimationSet animation set.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

The animation controller contains an array of animation sets. This method returns an animation set that has the given name.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetCurrentPriorityBlend

Returns an event handle to a priority blend event that is currently running.

D3DXEVENTHANDLE GetCurrentPriorityBlend();

Parameters

None.

Return Values

Event handle to the currently running priority blend event. NULL is returned if no priority blend event is currently running.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetCurrentTrackEvent

Returns an event handle to the event currently running on the specified animation track.

D3DXEVENTHANDLE GetCurrentTrackEvent(
  UINT Track,
  D3DXEVENT_TYPE EventType
);

Parameters

Track
[in] Track identifier.
EventType
[in] Type of event to query.

Return Values

Event handle to the event currently running on the specified track. NULL is returned if no event is running on the specified track.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetEventDesc

Gets a description of a specified animation event.

HRESULT GetEventDesc(
  D3DXEVENTHANDLE hEvent,
  LPD3DXEVENT_DESC pDesc
);

Parameters

hEvent
[in] Event handle to an animation event to describe.
pDesc
[out] Pointer to a D3DXEVENT_DESC structure that contains a description of the animation event.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetMaxNumAnimationOutputs

Get the maximum number of animation outputs the animation controller can support.

UINT GetMaxNumAnimationOutputs();

Parameters

None.

Return Values

The maximum number of animation outputs the controller can manage.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetMaxNumAnimationSets

Gets the maximum number of animation sets the animation controller can support.

UINT GetMaxNumAnimationSets();

Parameters

None.

Return Values

The maximum number of animation sets the controller can manage.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetMaxNumEvents

Gets the maximum number of events the animation controller can support.

UINT GetMaxNumEvents();

Parameters

None.

Return Values

The maximum number of events the controller can manage.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetMaxNumTracks

Gets the maximum number of tracks in the animation controller.

UINT GetMaxNumTracks();

Parameters

None.

Return Values

Number of tracks.

Remarks

The maximum number of tracks the controller can manage.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetNumAnimationSets

Returns the number of animation sets currently registered in the animation controller.

UINT GetNumAnimationSets();

Parameters

None.

Return Values

Number of animation sets.

Remarks

The controller contains any number of animations sets and tracks. Animation sets can be registered with ID3DXAnimationController::RegisterAnimationOutput. An animation controller created by a call to D3DXLoadMeshHierarchyFromX will automatically register loaded animation sets.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetPriorityBlend

Gets the current priority blending weight used by the animation controller.

FLOAT GetPriorityBlend();

Parameters

None.

Return Values

Returns the current priority blending weight.

Remarks

The priority blending weight is used to blend high and low priority tracks together.

Requirements

Header: Declared in D3dx9anim.h.

See Also

ID3DXAnimationController::SetPriorityBlend


ID3DXAnimationController::GetTime

Gets the global animation time.

DOUBLE GetTime();

Parameters

None.

Return Values

Returns the global animation time.

Remarks

Animations are designed using a local animation time and mixed into global time with ID3DXAnimationController::AdvanceTime.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetTrackAnimationSet

Gets the animation set for the given track.

HRESULT GetTrackAnimationSet(
  UINT Track,
  LPD3DXANIMATIONSET * ppAnimSet
);

Parameters

Track
[in] Track identifier.
ppAnimSet
[out] Pointer to the ID3DXAnimationSet animation set for the given track.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetTrackDesc

Gets the track description.

HRESULT GetTrackDesc(
  UINT Track,
  LPD3DXTRACK_DESC pDesc
);

Parameters

Track
[in] Track identifier.
pDesc
[out] Pointer to the track description. See D3DXTRACK_DESC.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetUpcomingPriorityBlend

Returns an event handle to the next priority blend event scheduled to occur after a specified event.

D3DXEVENTHANDLE GetUpcomingPriorityBlend(
  D3DXEVENTHANDLE hEvent
);

Parameters

hEvent
[in] Event handle to a specified event after which to search for a following priority blend event. If set to NULL, then the method will return the next scheduled priority blend event.

Return Values

Event handle to the next scheduled priority blend event. NULL is returned if no new priority blend event is scheduled.

Remarks

This method can be used iteratively to locate a desired priority blend event by repeatedly passing in NULL for hEvent.

Note Do not iterate further after the method has returned NULL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::GetUpcomingTrackEvent

Returns an event handle to the next event scheduled to occur after a specified event on an animation track.

D3DXEVENTHANDLE GetUpcomingTrackEvent(
  UINT Track,
  D3DXEVENTHANDLE hEvent
);

Parameters

Track
[in] Track identifier.
hEvent
[in] Event handle to a specified event after which to search for a following event. If set to NULL, then the method will return the next scheduled event.

Return Values

Event handle to the next event scheduled to run on the specified track. NULL is returned if no new event is scheduled.

Remarks

This method can be used iteratively to locate a desired event by repeatedly passing in NULL for hEvent.

Note Do not iterate further after the method has returned NULL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::KeyPriorityBlend

Sets blending event keys for the specified animation track.

D3DXEVENTHANDLE KeyPriorityBlend(
  FLOAT NewBlendWeight,
  DOUBLE StartTime,
  DOUBLE Duration,
  D3DXTRANSITION_TYPE Transition
);

Parameters

NewBlendWeight
[in] Number between 0 and 1 that is used to blend tracks together.
StartTime
[in] Global time to start the blend.
Duration
[in] Global time duration of the blend.
Transition
[in] Specifies the transition type used for the duration of the blend. See D3DXTRANSITION_TYPE.

Return Values

Event handle to the priority blend event. NULL is returned if one or more of the input parameters is invalid, or no free event is available.

Remarks

The animation controller blends in three phases: low priority tracks are blended first, high priority tracks are blended second, and then the results of both are blended.

Requirements

Header: Declared in D3dx9anim.h.

See Also

ID3DXAnimationController::SetPriorityBlend


ID3DXAnimationController::KeyTrackEnable

Sets an event key that enables or disables an animation track.

D3DXEVENTHANDLE KeyTrackEnable(
  UINT Track,
  BOOL NewEnable,
  DOUBLE StartTime
);

Parameters

Track
[in] Identifier of the animation track to modify.
NewEnable
[in] Enable flag. Set this to TRUE to enable the animation track, or to FALSE to disable the track.
StartTime
[in] Global time key. Specifies the global time when the change will take place.

Return Values

Event handle to the priority blend event. NULL is returned if Track is invalid.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::KeyTrackPosition

Sets an event key that changes the local time of an animation track.

D3DXEVENTHANDLE KeyTrackPosition(
  UINT Track,
  DOUBLE NewPosition,
  DOUBLE StartTime
);

Parameters

Track
[in] Identifier of the track to modify.
NewPosition
[in] New local time of the animation track.
StartTime
[in] Global time key. Specifies the global time when the change will take place.

Return Values

Event handle to the priority blend event. NULL is returned if Track is invalid, or if no free event is available.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::KeyTrackSpeed

Sets an event key that changes the rate of play of an animation track.

D3DXEVENTHANDLE KeyTrackSpeed(
  UINT Track,
  FLOAT NewSpeed,
  DOUBLE StartTime,
  DOUBLE Duration,
  D3DXTRANSITION_TYPE Transition
);

Parameters

Track
[in] Identifier of the track to modify.
NewSpeed
[in] New speed of the animation track.
StartTime
[in] Global time key. Specifies the global time when the change will take place.
Duration
[in] Transition time, which specifies how long the smooth transition will take to complete.
Transition
[in] Specifies the transition type used for transitioning between speeds. See D3DXTRANSITION_TYPE.

Return Values

Event handle to the priority blend event. NULL is returned if one or more of the input parameters is invalid, or no free event is available.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::KeyTrackWeight

Sets an event key that changes the weight of an animation track. The weight is used as a multiplier when combining multiple tracks together.

D3DXEVENTHANDLE KeyTrackWeight(
  UINT Track,
  FLOAT NewWeight,
  DOUBLE StartTime,
  DOUBLE Duration,
  D3DXTRANSITION_TYPE Transition
);

Parameters

Track
[in] Identifier of the track to modify.
NewWeight
[in] New weight of the track.
StartTime
[in] Global time key. Specifies the global time when the change will take place.
Duration
[in] Transition time, which specifies how long the smooth transition will take to complete.
Transition
[in] Specifies the transition type used for transitioning between weights. See D3DXTRANSITION_TYPE.

Return Values

Event handle to the priority blend event. NULL is returned if one or more of the input parameters is invalid, or no free event is available.

Remarks

The weight is used like a multiplier to determine how much of this track to blend together with other tracks.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::RegisterAnimationOutput

Adds an animation output to the animation controller and registers pointers for scale, rotate, and translate (SRT) transformations.

HRESULT RegisterAnimationOutput(
  LPCSTR Name,
  D3DXMATRIX * pMatrix,
  D3DXVECTOR3 * pScale,
  D3DXQUATERNION * pRotation,
  D3DXVECTOR3 * pTranslation
);

Parameters

Name
[in] Name of the animation output.
pMatrix
[in] Pointer to a D3DXMATRIX structure containing SRT transformation data. Can be NULL.
pScale
[in] Pointer to a D3DXVECTOR3 vector that describes the scale of the animation set. Can be NULL.
pRotation
[in] Pointer to a D3DXQUATERNION quaternion that describes the rotation of the animation set. Can be NULL.
pTranslation
[in] Pointer to a D3DXVECTOR3 vector that describes the translation of the animation set. Can be NULL.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

If the animation output is already registered, pMatrix will be filled with the input transformation data.

Animation sets created with D3DXLoadMeshHierarchyFromX automatically register all loaded animation sets.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::RegisterAnimationSet

Adds an animation set to the animation controller.

HRESULT RegisterAnimationSet(
  LPD3DXANIMATIONSET pAnimSet
);

Parameters

pAnimSet
[in] Pointer to the ID3DXAnimationSet animation set to add.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::ResetTime

Resets the global animation time to zero. Any pending events will retain their original schedules, but in the new timeframe.

HRESULT ResetTime();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

This method is typically used when the global animation time value is nearing the maximum precision of DOUBLE storage, or 264 - 1.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::SetPriorityBlend

Sets the priority blending weight used by the animation controller.

HRESULT SetPriorityBlend(
  FLOAT BlendWeight
);

Parameters

BlendWeight
[in] Priority blending weight used by the animation controller.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL.

Remarks

The blend weight is used to blend high and low priority tracks together.

Requirements

Header: Declared in D3dx9anim.h.

See Also

ID3DXAnimationController::GetPriorityBlend


ID3DXAnimationController::SetTrackAnimationSet

Applies the animation set to the specified track.

HRESULT SetTrackAnimationSet(
  UINT Track,
  LPD3DXANIMATIONSET pAnimSet
);

Parameters

Track
[in] Identifier of the track to which the animation set is applied.
pAnimSet
[in] Pointer to the ID3DXAnimationSet animation set to be added to the track.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This method sets the animation set to the specified track for mixing. The animation set for each track is blended according to the track weight and speed when ID3DXAnimationController::AdvanceTime is called.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::SetTrackDesc

Sets the track description.

HRESULT SetTrackDesc(
  UINT Track,
  LPD3DXTRACK_DESC pDesc
);

Parameters

Track
[in] Identifier of the track to modify.
pDesc
[in] Description of the track.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::SetTrackEnable

Enables or disables a track in the animation controller.

HRESULT SetTrackEnable(
  UINT Track,
  BOOL Enable
);

Parameters

Track
[in] Identifier of the track to be mixed.
Enable
[in] Enable value. Set to TRUE to enable this track in the controller, or to FALSE to prevent it from being mixed.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

To mix a track with other tracks, the Enable flag must be set to TRUE. Conversely, setting the flag to FALSE will prevent the track from being mixed with other tracks.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::SetTrackPosition

Sets the track to the specified local animation time.

HRESULT SetTrackPosition(
  UINT Track,
  DOUBLE Position
);

Parameters

Track
[in] Track identifier.
Position
[in] Local animation time value to assign to the track.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::SetTrackPriority

Sets the priority blending weight for the specified animation track.

HRESULT SetTrackPriority(
  UINT Track,
  D3DXPRIORITY_TYPE Priority
);

Parameters

Track
[in] Track identifier.
Priority
[in] Track priority. This parameter should be set to one of the constants from D3DXPRIORITY_TYPE.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::SetTrackSpeed

Sets the track speed. The track speed is similar to a multiplier that is used to speed up or slow down the playback of the track.

HRESULT SetTrackSpeed(
  UINT Track,
  FLOAT Speed
);

Parameters

Track
[in] Identifier of the track to set the speed on.
Speed
[in] New speed.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::SetTrackWeight

Sets the track weight. The weight is used to determine how to blend multiple tracks together.

HRESULT SetTrackWeight(
  UINT Track,
  FLOAT Weight
);

Parameters

Track
[in] Identifier of the track to set the weight on.
Weight
[in] Weight value.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::UnkeyAllPriorityBlends

Removes all scheduled priority blend events from the animation controller.

HRESULT UnkeyAllPriorityBlends();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::UnkeyAllTrackEvents

Removes all events from a specified animation track.

HRESULT UnkeyAllTrackEvents(
  UINT Track
);

Parameters

Track
[in] Identifier of the track on which all events should be removed.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

This method prevents the execution of all events previously scheduled on the track, and discards all data associated with those events.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::UnkeyEvent

Removes a specified event from an animation track, preventing the execution of the event.

HRESULT UnkeyEvent(
  D3DXEVENTHANDLE hEvent
);

Parameters

hEvent
[in] Event handle to the event to be removed from the animation track.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::UnregisterAnimationSet

Removes an animation set from the animation controller.

HRESULT UnregisterAnimationSet(
  LPD3DXANIMATIONSET pAnimSet
);

Parameters

pAnimSet
[in] Pointer to the ID3DXAnimationSet animation set to remove.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, D3DERR_NOTFOUND.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationController::ValidateEvent

Checks whether a specified event handle is valid and the animation event has not yet completed.

HRESULT ValidateEvent(
  D3DXEVENTHANDLE hEvent
);

Parameters

hEvent
[in] Event handle to an animation event.

Return Values

Returns S_OK if the event handle is valid and the event has not yet completed.

Returns E_FAIL if the event handle is invalid and/or the event has completed.

Remarks

The method will indicate that an event handle is valid even if the event is running but has not yet completed.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationSet

This interface encapsulates the minimum functionality required of an animation set by an animation controller. Advanced users might want to implement this interface themselves to suit their specialized needs; for most users, however, the derived ID3DXCompressedAnimationSet and ID3DXKeyframedAnimationSet interfaces should suffice.

ID3DXAnimationSet
ID3DXCompressedAnimationSet
ID3DXKeyframedAnimationSet

ID3DXAnimationSet Members

Method | Description
ID3DXAnimationSet::GetAnimationIndexByName | Gets the index of an animation, given its name.
ID3DXAnimationSet::GetAnimationNameByIndex | Gets the name of an animation, given its index.
ID3DXAnimationSet::GetCallback | Gets information about a specific callback in the animation set.
ID3DXAnimationSet::GetName | Gets the animation set name.
ID3DXAnimationSet::GetNumAnimations | Gets the number of animations in the animation set.
ID3DXAnimationSet::GetPeriod | Gets the period of the animation set.
ID3DXAnimationSet::GetPeriodicPosition | Returns time position in the local timeframe of an animation set.
ID3DXAnimationSet::GetSRT | Gets the scale, rotation, and translation values of the animation set.

Remarks

An animation set consists of animations for many nodes for the same animation.

The LPD3DXANIMATIONSET type is defined as a pointer to this interface.

typedef interface ID3DXAnimationSet ID3DXAnimationSet;
typedef interface ID3DXAnimationSet *LPD3DXANIMATIONSET;

Requirements

Header: Declared in D3dx9anim.h.

Library: Use D3dx9.lib.


ID3DXAnimationSet::GetAnimationIndexByName

Gets the index of an animation, given its name.

HRESULT GetAnimationIndexByName(
  LPCSTR pName,
  UINT * pIndex
);

Parameters

pName
[in] Name of the animation.
pIndex
[out] Pointer to the animation index.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationSet::GetAnimationNameByIndex

Gets the name of an animation, given its index.

HRESULT GetAnimationNameByIndex(
  UINT Index,
  LPCSTR * ppName
);

Parameters

Index
[in] Index of the animation.
ppName
[out] Address of a pointer to a string that receives the animation name.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationSet::GetCallback

Gets information about a specific callback in the animation set.

HRESULT GetCallback(
  DOUBLE Position,
  DWORD Flags,
  DOUBLE * pCallbackPosition,
  LPVOID * ppCallbackData
);

Parameters

Position
[in] Position from which to find callbacks.
Flags
[in] Callback search flags. This parameter can be set to a combination of one or more flags from D3DXCALLBACK_SEARCH_FLAGS.
pCallbackPosition
[out] Pointer to the position of the callback.
ppCallbackData
[out] Address of the callback data pointer.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationSet::GetName

Gets the animation set name.

LPCSTR GetName();

Parameters

None.

Return Values

Name of the animation set.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationSet::GetNumAnimations

Gets the number of animations in the animation set.

UINT GetNumAnimations();

Parameters

None.

Return Values

Number of animations in the animation set.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationSet::GetPeriod

Gets the period of the animation set.

DOUBLE GetPeriod();

Parameters

None.

Return Values

Period of the animation set.

Remarks

The period is the range of time that the animation key frames are valid. For looping animations, this is the period of the loop. The time units that the key frames are specified in (for example, seconds) is determined by the application.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationSet::GetPeriodicPosition

Returns time position in the local timeframe of an animation set.

DOUBLE GetPeriodicPosition(
  DOUBLE Position
);

Parameters

Position
[in] Local time of the animation set.

Return Values

Time position as measured in the timeframe of the animation set. This value will be bounded by the period of the animation set.

Remarks

The time position returned by this method can be used as the PeriodicPosition parameter of ID3DXAnimationSet::GetSRT.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXAnimationSet::GetSRT

Gets the scale, rotation, and translation values of the animation set.

HRESULT GetSRT(
  DOUBLE PeriodicPosition,
  UINT Animation,
  D3DXVECTOR3 * pScale,
  D3DXQUATERNION * pRotation,
  D3DXVECTOR3 * pTranslation
);

Parameters

PeriodicPosition
[in] Position of the animation set. The position can be obtained by calling ID3DXAnimationSet::GetPeriodicPosition.
Animation
[in] Animation index.
pScale
[out] Pointer to the D3DXVECTOR3 vector that describes the scale of the animation set.
pRotation
[out] Pointer to the D3DXQUATERNION quaternion that describes the rotation of the animation set.
pTranslation
[out] Pointer to the D3DXVECTOR3 vector that describes the translation of the animation set.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXBaseMesh

Applications use the methods of the ID3DXBaseMesh interface to manipulate and query mesh and progressive mesh objects.

ID3DXBaseMesh
ID3DXMesh
ID3DXPMesh

ID3DXBaseMesh Members

Method | Description
ID3DXBaseMesh::CloneMesh | Clones a mesh using a declarator.
ID3DXBaseMesh::CloneMeshFVF | Clones a mesh using a flexible vertex format (FVF) code.
ID3DXBaseMesh::ConvertAdjacencyToPointReps | Converts mesh adjacency information to an array of point representatives.
ID3DXBaseMesh::ConvertPointRepsToAdjacency | Converts point representative data to mesh adjacency information.
ID3DXBaseMesh::DrawSubset | Draws a subset of a mesh.
ID3DXBaseMesh::GenerateAdjacency | Generate a list of mesh edges, as well as a list of faces that share each edge.
ID3DXBaseMesh::GetAttributeTable | Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.
ID3DXBaseMesh::GetDeclaration | Retrieves a declaration describing the vertices in the mesh.
ID3DXBaseMesh::GetDevice | Retrieves the device associated with the mesh.
ID3DXBaseMesh::GetFVF | Gets the fixed function vertex value.
ID3DXBaseMesh::GetIndexBuffer | Retrieves the data in an index buffer.
ID3DXBaseMesh::GetNumBytesPerVertex | Gets the number of bytes per vertex.
ID3DXBaseMesh::GetNumFaces | Retrieves the number of faces in the mesh.
ID3DXBaseMesh::GetNumVertices | Retrieves the number of vertices in the mesh.
ID3DXBaseMesh::GetOptions | Retrieves the mesh options enabled for this mesh at creation time.
ID3DXBaseMesh::GetVertexBuffer | Retrieves the vertex buffer associated with the mesh.
ID3DXBaseMesh::LockIndexBuffer | Locks an index buffer and obtains a pointer to the index buffer memory.
ID3DXBaseMesh::LockVertexBuffer | Locks a vertex buffer and obtains a pointer to the vertex buffer memory.
ID3DXBaseMesh::UnlockIndexBuffer | Unlocks an index buffer.
ID3DXBaseMesh::UnlockVertexBuffer | Unlocks a vertex buffer.
ID3DXBaseMesh::UpdateSemantics | This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Remarks

A mesh is an object made up of a set of polygonal faces. A mesh defines a set of vertices and a set of faces (the faces are defined in terms of the vertices and normals of the mesh).

The LPD3DXBASEMESH type is defined as a pointer to the ID3DXBaseMesh interface.

typedef struct ID3DXBaseMesh *LPD3DXBASEMESH;

See Also

ID3DXMesh, ID3DXPMesh

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXBaseMesh::CloneMesh

Clones a mesh using a declarator.

HRESULT CloneMesh(
  DWORD Options,
  CONST D3DVERTEXELEMENT9 * pDeclaration,
  LPDIRECT3DDEVICE9 pDevice,
  LPD3DXMESH * ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
pDeclaration
[in] An array of D3DVERTEXELEMENT9 elements, which specify the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3D texture coordinate as a binormal or tangent or vice versa.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXBaseMesh::CloneMeshFVF, D3DXDeclaratorFromFVF


ID3DXBaseMesh::CloneMeshFVF

Clones a mesh using a flexible vertex format (FVF) code.

HRESULT CloneMeshFVF(
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE9 pDevice,
  LPD3DXMESH * ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, which specifies the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

ID3DXBaseMesh::CloneMeshFVF is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3D texture coordinate as a binormal or tangent or vice versa.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXFVFFromDeclarator


ID3DXBaseMesh::ConvertAdjacencyToPointReps

Converts mesh adjacency information to an array of point representatives.

HRESULT ConvertAdjacencyToPointReps(
  CONST DWORD* pAdjacency,
  DWORD* pPRep
);

Parameters

pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).
pPRep
[in, out] Pointer to an array of one DWORD per vertex of the mesh that will be filled with point representative data.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::ConvertPointRepsToAdjacency

Converts point representative data to mesh adjacency information.

HRESULT ConvertPointRepsToAdjacency(
  CONST DWORD* pPRep,
  DWORD* pAdjacency
);

Parameters

pPRep
[in] Pointer to an array of one DWORD per vertex of the mesh that contains point representative data. This parameter is optional. Supplying a NULL value will cause this parameter to be interpreted as an "identity" array.
pAdjacency
[in, out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::DrawSubset

Draws a subset of a mesh.

HRESULT DrawSubset(
  DWORD AttribId
);

Parameters

AttribId
[in] DWORD that specifies which subset of the mesh to draw. This value is used to differentiate faces in a mesh as belonging to one or more attribute groups.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The subset that is specified by AttribId will be rendered by the IDirect3DDevice9::DrawIndexedPrimitive method, using the D3DPT_TRIANGLELIST primitive type, so an index buffer must be properly initialized.

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::GenerateAdjacency

Generate a list of mesh edges, as well as a list of faces that share each edge.

HRESULT GenerateAdjacency(
  FLOAT Epsilon,
  DWORD * pAdjacency
);

Parameters

Epsilon
[in] Specifies that vertices that differ in position by less than epsilon should be treated as coincident.
pAdjacency
[in] Pointer to an array of three DWORDs per face to be filled with the indices of adjacent faces. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized for better drawing performance.

The order of the entries in the adjacency buffer is determined by the order of the vertex indices in the index buffer. The adjacent triangle 0 always corresponds to the edge between the indices of the corners 0 and 1. The adjacent triangle 1 always corresponds to the edge between the indices of the corners 1 and 2 while the adjacent triangle 2 corresponds to the edge between the indices of the corners 2 and 0.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXMesh::Optimize, ID3DXMesh::OptimizeInplace


ID3DXBaseMesh::GetAttributeTable

Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.

HRESULT GetAttributeTable(
  D3DXATTRIBUTERANGE * pAttribTable,
  DWORD * pAttribTableSize
);

Parameters

pAttribTable
[in, out] Pointer to an array of D3DXATTRIBUTERANGE structures, representing the entries in the mesh's attribute table. Specify NULL to retrieve the value for pAttribTableSize.
pAttribTableSize
[in, out] Pointer to either the number of entries stored in pAttribTable or a value to be filled in with the number of entries stored in the attribute table for the mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is created by ID3DXMesh::Optimize and passing D3DXMESHOPT_ATTRSORT for the Flags parameter.

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier when drawing the frame.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

HRESULT GetDeclaration(
  D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::GetDevice

Retrieves the device associated with the mesh.

HRESULT GetDevice(
  LPDIRECT3DDEVICE9 * ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::GetFVF

Gets the fixed function vertex value.

DWORD GetFVF();

Parameters

None.

Return Values

Returns the flexible vertex format (FVF) codes.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::GetIndexBuffer

Retrieves the data in an index buffer.

HRESULT GetIndexBuffer(
  LPDIRECT3DINDEXBUFFER9 * ppIB
);

Parameters

ppIB
[out, retval] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the index buffer object associated with the mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::GetNumBytesPerVertex

Gets the number of bytes per vertex.

DWORD GetNumBytesPerVertex();

Parameters

None.

Return Values

Returns the number of bytes per vertex.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::GetNumFaces

Retrieves the number of faces in the mesh.

DWORD GetNumFaces();

Parameters

None.

Return Values

Returns the number of faces in the mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::GetNumVertices

Retrieves the number of vertices in the mesh.

DWORD GetNumVertices();

Parameters

None.

Return Values

Returns the number of vertices in the mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::GetOptions

Retrieves the mesh options enabled for this mesh at creation time.

DWORD GetOptions();

Return Values

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

Value | Description
D3DXMESH_32BIT | Use 32-bit indices.
D3DXMESH_DONOTCLIP | Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC | Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES | Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES | Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement.
D3DXMESH_MANAGED | Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS | Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED | Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM | Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED | Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY | Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::GetVertexBuffer

Retrieves the vertex buffer associated with the mesh.

HRESULT GetVertexBuffer(
  LPDIRECT3DVERTEXBUFFER9 * ppVB
);

Parameters

ppVB
[out, retval] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the vertex buffer object associated with the mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::LockIndexBuffer

Locks an index buffer and obtains a pointer to the index buffer memory.

HRESULT LockIndexBuffer(
  DWORD Flags,
  LPVOID * ppData
);

Parameters

Flags

Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:

  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
[in] For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the index data. The count of indices in this buffer will be equal to ID3DXBaseMesh::GetNumFaces * 3.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::LockVertexBuffer

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

HRESULT LockVertexBuffer(
  DWORD Flags,
  LPVOID * ppData
);

Parameters

Flags

Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:

  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE
[in] For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the vertex data.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::UnlockIndexBuffer

Unlocks an index buffer.

HRESULT UnlockIndexBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::UnlockVertexBuffer

Unlocks a vertex buffer.

HRESULT UnlockVertexBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBaseMesh::UpdateSemantics

This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

HRESULT UpdateSemantics(
  D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] An array of D3DVERTEXELEMENT9 elements, describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics is a method for updating the vertex declaration with different semantic information, without changing the layout of the vertex buffer. For example, use it to relabel a 3D texture coordinate as a binormal or tangent, or vice versa.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXBaseMesh::CloneMeshFVF, D3DXDeclaratorFromFVF


ID3DXBuffer

The ID3DXBuffer interface is used as a data buffer, storing vertex, adjacency, and material information during mesh optimization and loading operations. The buffer object is used to return arbitrary length data. Also, buffer objects are used to return object code and error messages in methods that assemble vertex and pixel shaders.

ID3DXBuffer Members

Method | Description
ID3DXBuffer::GetBufferPointer | Retrieves a pointer to the data in the buffer.
ID3DXBuffer::GetBufferSize | Retrieves the total size of the data in the buffer.

Remarks

The ID3DXBuffer interface is obtained by calling the D3DXCreateBuffer function.

The LPD3DXBUFFER type is defined as a pointer to the ID3DXBuffer interface.

typedef interface ID3DXBuffer ID3DXBuffer;
typedef interface ID3DXBuffer *LPD3DXBUFFER;

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXBuffer::GetBufferPointer

Retrieves a pointer to the data in the buffer.

LPVOID GetBufferPointer();

Parameters

None.

Return Values

Returns a pointer to the data in the buffer.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXBuffer::GetBufferSize

Retrieves the total size of the data in the buffer.

DWORD GetBufferSize();

Parameters

None.

Return Values

Returns the total size of the data in the buffer, in bytes.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXCompressedAnimationSet

An application uses the methods of this interface to implement a key frame animation set stored in a compressed data format.

ID3DXAnimationSet
ID3DXCompressedAnimationSet
ID3DXKeyframedAnimationSet

ID3DXCompressedAnimationSet Members

Method | Description
ID3DXCompressedAnimationSet::GetCallbackKeys | Fills an array with callback key data used for key frame animation.
ID3DXCompressedAnimationSet::GetCompressedData | Gets the data buffer that stores compressed key frame animation data.
ID3DXCompressedAnimationSet::GetNumCallbackKeys | Gets the number of callback keys in the animation set.
ID3DXCompressedAnimationSet::GetPlaybackType | Gets the type of the animation set playback loop.
ID3DXCompressedAnimationSet::GetSourceTicksPerSecond | Gets the number of animation key frame ticks that occur per second.

Remarks

Create a compressed-format key frame animation set with D3DXCreateCompressedAnimationSet.

The LPD3DXCOMPRESSEDANIMATIONSET type is defined as a pointer to this interface.

typedef interface ID3DXCompressedAnimationSet ID3DXCompressedAnimationSet;
typedef interface ID3DXCompressedAnimationSet *LPD3DXCOMPRESSEDANIMATIONSET;

Requirements

Header: Declared in D3dx9anim.h.

Library: Use D3dx9.lib.


ID3DXCompressedAnimationSet::GetCallbackKeys

Fills an array with callback key data used for key frame animation.

HRESULT GetCallbackKeys(
  LPD3DXKEY_CALLBACK pCallbackKeys
);

Parameters

pCallbackKeys
[out] Pointer to a user-allocated array of D3DXKEY_CALLBACK structures that the method is to fill with callback data.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.

See Also

ID3DXCompressedAnimationSet::GetNumCallbackKeys


ID3DXCompressedAnimationSet::GetCompressedData

Gets the data buffer that stores compressed key frame animation data.

HRESULT GetCompressedData(
  LPD3DXBUFFER * ppCompressedData
);

Parameters

ppCompressedData
[out] Address of a pointer to the ID3DXBuffer data buffer that receives compressed key frame animation data.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXCompressedAnimationSet::GetNumCallbackKeys

Gets the number of callback keys in the animation set.

UINT GetNumCallbackKeys();

Parameters

None.

Return Values

Number of callback keys in the animation set.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXCompressedAnimationSet::GetPlaybackType

Gets the type of the animation set playback loop.

D3DXPLAYBACK_TYPE GetPlaybackType();

Parameters

None.

Return Values

Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXCompressedAnimationSet::GetSourceTicksPerSecond

Gets the number of animation key frame ticks that occur per second.

DOUBLE GetSourceTicksPerSecond();

Parameters

None.

Return Values

Number of animation key frame ticks that occur per second.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXConstantTable

The ID3DXConstantTable interface is used to access the constant table. This table contains the variables that are used by high-level language shaders and effects.

ID3DXConstantTable Members

Method | Description
ID3DXConstantTable::GetBufferPointer | Gets a pointer to the buffer that contains the constant table.
ID3DXConstantTable::GetBufferSize | Gets the buffer size of the constant table.
ID3DXConstantTable::GetConstant | Gets a constant by looking up its index.
ID3DXConstantTable::GetConstantByName | Gets a constant by looking up its name.
ID3DXConstantTable::GetConstantDesc | Gets a pointer to an array of constant descriptions in the constant table.
ID3DXConstantTable::GetConstantElement | Gets a constant from an array of constants. An array is made up of elements.
ID3DXConstantTable::GetDesc | Gets a description of the constant table.
ID3DXConstantTable::GetSamplerIndex | Returns the sampler index.
ID3DXConstantTable::SetBool | Sets a Boolean value.
ID3DXConstantTable::SetBoolArray | Sets an array of Boolean values.
ID3DXConstantTable::SetDefaults | Sets the constants to their default values. The default values are declared in the variable declarations in the shader.
ID3DXConstantTable::SetFloat | Sets a floating-point number.
ID3DXConstantTable::SetFloatArray | Sets an array of floating-point numbers.
ID3DXConstantTable::SetInt | Sets an integer value.
ID3DXConstantTable::SetIntArray | Sets an array of integers.
ID3DXConstantTable::SetMatrix | Sets a nontransposed matrix.
ID3DXConstantTable::SetMatrixArray | Sets an array of nontransposed matrices.
ID3DXConstantTable::SetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
ID3DXConstantTable::SetMatrixTranspose | Sets a transposed matrix.
ID3DXConstantTable::SetMatrixTransposeArray | Sets an array of transposed matrices.
ID3DXConstantTable::SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
ID3DXConstantTable::SetValue | Sets the contents of the buffer to the constant table.
ID3DXConstantTable::SetVector | Sets a 4D vector.
ID3DXConstantTable::SetVectorArray | Sets an array of 4D vectors.

Remarks

The LPD3DXCONSTANTTABLE type is defined as a pointer to the ID3DXConstantTable interface.

typedef interface ID3DXConstantTable ID3DXConstantTable;
typedef interface ID3DXConstantTable *LPD3DXCONSTANTTABLE;

Requirements

Header: Declared in D3DX9Shader.h.

Library: Use D3dx9.lib.


ID3DXConstantTable::GetBufferPointer

Gets a pointer to the buffer that contains the constant table.

LPVOID GetBufferPointer();

Parameters

None.

Return Values

Returns a pointer the buffer.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXConstantTable::GetBufferSize


ID3DXConstantTable::GetBufferSize

Gets the buffer size of the constant table.

DWORD GetBufferSize();

Parameters

None.

Return Values

Returns the size of the buffer, in bytes.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::GetConstant

Gets a constant by looking up its index.

D3DXHANDLE GetConstant(
  D3DXHANDLE hConstant,
  UINT Index
);

Parameters

hConstant
[in] Unique identifier to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
Index
[in] Zero-based index of the constant.

Return Values

Returns a unique identifier to the constant.

Remarks

To get a constant from an array of constants, use ID3DXConstantTable::GetConstantElement.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::GetConstantByName

Gets a constant by looking up its name.

D3DXHANDLE GetConstantByName(
  D3DXHANDLE hConstant,
  LPCSTR pName
);

Parameters

hConstant
[in] Unique identifier to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
pName
[in] Name of the constant.

Return Values

Returns a unique identifier to the constant.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::GetConstantDesc

Gets a pointer to an array of constant descriptions in the constant table.

HRESULT GetConstantDesc(
  D3DXHANDLE hConstant,
  D3DXCONSTANT_DESC * pDesc,
  UINT * pCount
);

Parameters

hConstant
[in] Unique identifier to a constant. See D3DXHANDLE.
pDesc
[in, out] Returns a pointer to an array of descriptions. See D3DXCONSTANT_DESC.
pCount
[in, out] The input supplied must be the maximum size of the array. The output is the number of elements that are filled in the array when the function returns.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

ID3DXConstantTable::GetConstantDesc will sometimes return a D3DXCONSTANT_DESC with a Register_Count of 0. This will happen with a constant appears in more than one Register_Set but does not have space in that register set allocated.

Because a sampler can appear more than once in a constant table, this method can return an array of descriptions, each one with a different register index.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXConstantTable::GetDesc


ID3DXConstantTable::GetConstantElement

Gets a constant from an array of constants. An array is made up of elements.

D3DXHANDLE GetConstantElement(
  D3DXHANDLE hConstant,
  UINT Index
);

Parameters

hConstant
[in] Unique identifier to the array of constants. This value may not be NULL.
Index
[in] Zero-based index of the element in the array.

Return Values

Returns a unique identifier to the element constant.

Remarks

To get a constant that is not part of an array, use ID3DXConstantTable::GetConstant or ID3DXConstantTable::GetConstantByName.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::GetDesc

Gets a description of the constant table.

HRESULT GetDesc(
  D3DXCONSTANTTABLE_DESC* pDesc
);

Parameters

pDesc
[in] Description of the constant table. See D3DXCONSTANTTABLE_DESC.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXConstantTable::GetConstantDesc


ID3DXConstantTable::GetSamplerIndex

Returns the sampler index.

UINT GetSamplerIndex(
  D3DXHANDLE hConstant
);

Parameters

hConstant
[out] The sampler handle.

Return Values

Returns the sampler index number from the constant table.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetBool

Sets a Boolean value.

HRESULT SetBool(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  BOOL b
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
b
[in] Boolean value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetBoolArray

Sets an array of Boolean values.

HRESULT SetBoolArray(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST BOOL* pB,
  UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pB
[in] Array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetDefaults

Sets the constants to their default values. The default values are declared in the variable declarations in the shader.

HRESULT SetDefaults(
  LPDIRECT3DDEVICE9 pDevice
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetFloat

Sets a floating-point number.

HRESULT SetFloat(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  FLOAT f
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
f
[in] Floating-point number.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetFloatArray

Sets an array of floating-point numbers.

HRESULT SetFloatArray(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST FLOAT* pf,
  UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pf
[in] Array of floating-point numbers.
Count
[in] Number of floating-point values in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetInt

Sets an integer value.

HRESULT SetInt(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  INT n
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
n
[in] Integer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetIntArray

Sets an array of integers.

HRESULT SetIntArray(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST INT* pn,
  UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetMatrix

Sets a nontransposed matrix.

HRESULT SetMatrix(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX* pMatrix
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the matrix of constants. See D3DXHANDLE.
pMatrix
[in] Pointer to a nontransposed matrix. See D3DXMATRIX.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetMatrixArray

Sets an array of nontransposed matrices.

HRESULT SetMatrixArray(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX* pMatrix,
  UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of constant matrices. See D3DXHANDLE.
pMatrix
[in] Array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetMatrixPointerArray

Sets an array of pointers to nontransposed matrices.

HRESULT SetMatrixPointerArray(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX ** ppMatrix,
  UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to an array of constant matrices. See D3DXHANDLE.
ppMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetMatrixTranspose

Sets a transposed matrix.

HRESULT SetMatrixTranspose(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX* pMatrix
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the matrix of constants. See D3DXHANDLE.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetMatrixTransposeArray

Sets an array of transposed matrices.

HRESULT SetMatrixTransposeArray(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX* pMatrix,
  UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of matrix constants. See D3DXHANDLE.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetMatrixTransposePointerArray

Sets an array of pointers to transposed matrices.

HRESULT SetMatrixTransposePointerArray(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX** ppMatrix,
  UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of matrix constants. See D3DXHANDLE.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetValue

Sets the contents of the buffer to the constant table.

HRESULT SetValue(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  LPCVOID pData,
  UINT Bytes
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to a constant. See D3DXHANDLE.
pData
[in] Buffer containing data.
Bytes
[in] Size of the buffer, in bytes.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetVector

Sets a 4D vector.

HRESULT SetVector(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST D3DXVECTOR4* pVector
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the vector constant. See D3DXHANDLE.
pVector
[in] Pointer to a 4D vector.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXConstantTable::SetVectorArray

Sets an array of 4D vectors.

HRESULT SetVectorArray(
  LPDIRECT3DDEVICE9 pDevice,
  D3DXHANDLE hConstant,
  CONST D3DXVECTOR4* pVector,
  UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of vector constants. See D3DXHANDLE.
pVector
[in] Array of 4D vectors.
Count
[in] Number of vectors in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFont

The ID3DXFont interface encapsulates the textures and resources needed to render a specific font on a specific device.

ID3DXFont Members

Method | Description
ID3DXFont::DrawText | Draws formatted text. This method supports ANSI and Unicode strings.
ID3DXFont::GetDC | Returns a handle to a display device context (DC) that has the font set.
ID3DXFont::GetDesc | Gets a description of the current font object. GetDescW and GetDescA are identical to this method, except that a pointer is returned to a D3DXFONT_DESCD3DXFONT_DESCW
ID3DXFont::GetDevice | Retrieves the Direct3D device associated with the font object.
ID3DXFont::GetGlyphData | Returns information about the placement and orientation of a glyph in a character cell.
ID3DXFont::GetTextMetrics | Retrieves font characteristics that are identified in a TEXTMETRIC structure. This method supports ANSI and Unicode compiler settings.
ID3DXFont::OnLostDevice | Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost, or before resetting a device.
ID3DXFont::OnResetDevice | Use this method to re-acquire resources and save initial state.
ID3DXFont::PreloadCharacters | Loads a series of characters into video memory to improve the efficiency of rendering to the device.
ID3DXFont::PreloadGlyphs | Loads a series of glyphs into video memory to improve the efficiency of rendering to the device.
ID3DXFont::PreloadText | Loads formatted text into video memory to improve the efficiency of rendering to the device. This method supports ANSI and Unicode strings.

Remarks

The ID3DXFont interface is obtained by calling D3DXCreateFont or D3DXCreateFontIndirect.

The LPD3DXFONT type is defined as a pointer to the ID3DXFont interface.

typedef interface ID3DXFont ID3DXFont;
typedef interface ID3DXFont *LPD3DXFONT;

Requirements

Header: Declared in D3dx9core.h.

Library: Use D3dx9.lib.


ID3DXFont::DrawText

Draws formatted text. This method supports ANSI and Unicode strings.

INT DrawText(
  LPD3DXSPRITE pSprite,
  LPCTSTR pString,
  INT Count,
  LPRECT pRect,
  DWORD Format,
  D3DCOLOR Color
);

Parameters

pSprite
[in] Pointer to an ID3DXSprite object that contains the string. Can be NULL, in which case Direct3D will render the string with its own sprite object. To improve efficiency, a sprite object should be specified if ID3DXFont::DrawText is to be called more than once in a row.
pString
[in] Pointer to a string to draw.If the Count parameter is -1, the string must be null-terminated.
Count
[in] Specifies the number of characters in the string. If Count is -1, then the pString parameter is assumed to be a pointer to a null-terminated string and ID3DXFont::DrawText computes the character count automatically.
pRect
[in] Pointer to a RECT structure that contains the rectangle, in logical coordinates, in which the text is to be formatted. As with any RECT object, the coordinate value of the rectangle's right side must be greater than that of its left side. Likewise, the coordinate value of the bottom must be greater than that of the top.
Format
[in] Specifies the method of formatting the text. It can be any combination of the following values:
DT_BOTTOM
Justifies the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.
DT_CALCRECT
Determines the width and height of the rectangle. If there are multiple lines of text, ID3DXFont::DrawText uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, ID3DXFont::DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, ID3DXFont::DrawText returns the height of the formatted text but does not draw the text.
DT_CENTER
Centers text horizontally in the rectangle.
DT_EXPANDTABS
Expands tab characters. The default number of characters per tab is eight.
DT_LEFT
Aligns text to the left.
DT_NOCLIP
Draws without clipping. ID3DXFont::DrawText is somewhat faster when DT_NOCLIP is used.
DT_RIGHT
Aligns text to the right.
DT_RTLREADING
Displays text in right-to-left reading order for bidirectional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.
DT_SINGLELINE
Displays text on a single line only. Carriage returns and line feeds do not break the line.
DT_TOP
Top-justifies text.
DT_VCENTER
Centers text vertically (single line only).
DT_WORDBREAK
Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.
Color
[in] Color of the text. For more information, see D3DCOLOR.

Return Values

If the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from pRect (top to the bottom) of the drawn text. If the function fails, the return value is zero.

Remarks

The parameters of this method are very similar to those of the GDI DrawText function.

This method supports both ANSI and Unicode strings.

This method must be called inside a IDirect3DDevice9::BeginScene ... IDirect3DDevice9::EndScene block. The only exception is when an application calls ID3DXFont::DrawText with DT_CALCRECT to calculate the size of a given block of text.

Unless the DT_NOCLIP format is used, this method clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified.

If the selected font is too large for the rectangle, this method does not attempt to substitute a smaller font.

This method supports only fonts whose escapement and orientation are both zero.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFont::GetDC

Returns a handle to a display device context (DC) that has the font set.

HDC GetDC();

Parameters

None.

Return Values

Handle to a display DC.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFont::GetDesc

Gets a description of the current font object. GetDescW and GetDescA are identical to this method, except that a pointer is returned to a D3DXFONT_DESCW or D3DXFONT_DESCA structure, respectively.

HRESULT GetDesc(
  D3DXFONT_DESC * pDesc
);

Parameters

pDesc
[out] Pointer to a D3DXFONT_DESC structure that describes the font object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

This method describes Unicode font objects if UNICODE is defined. Otherwise GetDescA is called, which returns a pointer to the D3DXFONT_DESCA structure.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFont::GetDevice

Retrieves the Direct3D device associated with the font object.

HRESULT GetDevice(
  LPDIRECT3DDEVICE9 * ppDevice
);

Parameters

ppDevice
[out] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the font object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFont::GetGlyphData

Returns information about the placement and orientation of a glyph in a character cell.

HRESULT GetGlyphData(
  UINT Glyph,
  LPDIRECT3DTEXTURE9 * ppTexture,
  RECT * pBlackBox,
  POINT * pCellInc
);

Parameters

Glyph
[in] Glyph identifier.
ppTexture
[out] Address of a pointer to a IDirect3DTexture9 object that contains the glyph.
pBlackBox
[out] Pointer to the smallest rectangle object that completely encloses the glyph. See RECT.
pCellInc
[out] Pointer to the two-dimensional vector that connects the origin of the current character cell to the origin of the next character cell. See POINT.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFont::GetTextMetrics

Retrieves font characteristics that are identified in a TEXTMETRIC structure. This method supports ANSI and Unicode compiler settings.

BOOL GetTextMetrics(
  TEXTMETRIC * pTextMetrics
);

Parameters

pTextMetrics
[out] Pointer to a TEXTMETRIC structure, which contains font properties.

Return Values

Nonzero if the function is successful; otherwise 0.

Remarks

The compiler setting also determines the structure type. If Unicode is defined, the function returns a TEXTMETRICW structure. Otherwise, the function call returns a TEXTMETRICA structure.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFont::OnLostDevice

Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost, or before resetting a device.

HRESULT OnLostDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method should be called whenever the device is lost or before the user calls IDirect3DDevice9::Reset. Even if the device was not actually lost, ID3DXFont::OnLostDevice is responsible for freeing stateblocks and other resources that may need to be released before resetting the device. As a result, the font object cannot be used again before calling IDirect3DDevice9::Reset and then ID3DXFont::OnResetDevice.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFont::OnResetDevice

Use this method to re-acquire resources and save initial state.

HRESULT OnResetDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXFont::OnResetDevice should be called each time the device is reset (using IDirect3DDevice9::Reset), before any other methods are called. This is a good place to re-acquire video-memory resources and capture state blocks.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFont::PreloadCharacters

Loads a series of characters into video memory to improve the efficiency of rendering to the device.

HRESULT PreloadCharacters(
  UINT First,
  UINT Last
);

Parameters

First
[in] ID of the first character to be loaded into video memory.
Last
[in] ID of the last character to be loaded into video memory.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

This method generates textures containing glyphs that represent the input characters. The glyphs are drawn as a series of triangles.

Characters will not be rendered to the device; ID3DXFont::DrawText must still be called to render the characters. However, by pre-loading characters into video memory, ID3DXFont::DrawText will use substantially fewer CPU resources.

This method internally converts characters to glyphs using the GDI function GetCharacterPlacement.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFont::PreloadGlyphs

Loads a series of glyphs into video memory to improve the efficiency of rendering to the device.

HRESULT PreloadGlyphs(
  UINT First,
  UINT Last
);

Parameters

First
[in] ID of the first glyph to be loaded into video memory.
Last
[in] ID of the last glyph to be loaded into video memory.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

This method generates textures that contain the input glyphs. The glyphs are drawn as a series of triangles.

Glyphs will not be rendered to the device; ID3DXFont::DrawText must still be called to render the glyphs. However, by pre-loading glyphs into video memory, ID3DXFont::DrawText will use substantially fewer CPU resources.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFont::PreloadText

Loads formatted text into video memory to improve the efficiency of rendering to the device. This method supports ANSI and Unicode strings.

HRESULT PreloadText(
  LPCTSTR * pString,
  INT Count
);

Parameters

pString
[in] Pointer to a string of characters to be loaded into video memory. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR; otherwise, the data type resolves to LPCSTR. See Remarks.
Count
[in] Number of characters in the text string.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to PreloadTextW. Otherwise, the function call resolves to PreloadTextA because ANSI strings are being used.

This method generates textures that contain glyphs that represent the input text. The glyphs are drawn as a series of triangles.

Text will not be rendered to the device; ID3DXFont::DrawText must still be called to render the text. However, by preloading text into video memory, ID3DXFont::DrawText will use substantially fewer CPU resources.

This method internally converts characters to glyphs using the GDI function GetCharacterPlacement.

Requirements

Header: Declared in D3dx9core.h.


ID3DXFragmentLinker

The ID3DXFragmentLinker interface is used to link shader fragments at runtime.

ID3DXFragmentLinker Members

Method | Description
ID3DXFragmentLinker::AddFragments | Add the fragments from a buffer to the fragment linker.
ID3DXFragmentLinker::ClearCache | Clear the fragment linker cache.
ID3DXFragmentLinker::GetAllFragments | Allocates a buffer and copies the fragment data into it.
ID3DXFragmentLinker::GetDevice | Get the device.
ID3DXFragmentLinker::GetFragment | Create a buffer containing a linker fragment. This can be used for saving the fragment to disk.
ID3DXFragmentLinker::GetFragmentDesc | Get the D3DXFRAGMENT_DESC structure which describes the named fragment.
ID3DXFragmentLinker::GetFragmentHandleByIndex | Get a fragment handle by index.
ID3DXFragmentLinker::GetFragmentHandleByName | Get a fragment handle by name.
ID3DXFragmentLinker::GetNumberOfFragments | Get the number of fragments in the linker.
ID3DXFragmentLinker::LinkPixelShader | Link a compiled pixel shader at run time. This is a very lightweight operation.
ID3DXFragmentLinker::LinkShader | Link a compiled shader at run time. This is a very lightweight operation.
ID3DXFragmentLinker::LinkVertexShader | Link a compiled vertex shader at run time. This is a very lightweight operation.

Remarks

The LPD3DXFRAGMENTLINKER type is defined as a pointer to the ID3DXFragmentLinker interface.

typedef ID3DXFragmentLinker *LPD3DXFRAGMENTLINKER;

Requirements

Header: Declared in D3DX9Shader.h.

Library: Use D3dx9.lib.


ID3DXFragmentLinker::AddFragments

Add the fragments from a buffer to the fragment linker.

HRESULT AddFragments(
  CONST DWORD* pFragments
);

Parameters

pFragments
[in] Pointer to a buffer containing shader fragments. See D3DXGatherFragments.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DXERR_DUPLICATENAMEDFRAGMENT, E_FAIL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::ClearCache

Clear the fragment linker cache.

HRESULT ClearCache();

Parameters

None.

Return Values

This method always returns the value S_OK.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::GetAllFragments

Allocates a buffer and copies the fragment data into it.

HRESULT GetAllFragments(
  LPD3DXBUFFER* ppBuffer
);

Parameters

ppBuffer
[out] Returns a buffer containing compiled shader fragments. See ID3DXBuffer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::GetDevice

Get the device.

HRESULT GetDevice(
  LPDIRECT3DDEVICE9* ppDevice
);

Parameters

ppDevice
[out] Get a pointer to the IDirect3DDevice9 object, which represents the device.

Return Values

This method always returns the value S_OK.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::GetFragment

Create a buffer containing a linker fragment. This can be used for saving the fragment to disk.

HRESULT GetFragment(
  D3DXHANDLE Name,
  LPD3DXBUFFER* ppBuffer
);

Parameters

Name
[in] Unique identifier to the fragment name. See Handles.
ppBuffer
[out] Returns a buffer containing a compiled shader fragment. See ID3DXBuffer.

Return Values

If the method succeeds, the return value is S_OK. If the arguments are invalid, the method will return D3DERR_INVALIDCALL. If the method fails, the return value can be E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::GetFragmentDesc

Get the D3DXFRAGMENT_DESC structure which describes the named fragment.

HRESULT GetFragmentDesc(
  D3DXHANDLE Name,
  LPD3DXFRAGMENT_DESC FragDesc
);

Parameters

Name
[in] Unique identifier to the fragment name. See Handles.
FragDesc
[in] Returns a description of the fragment. See D3DXFRAGMENT_DESC.

Return Values

This method always returns the value S_OK.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::GetFragmentHandleByIndex

Get a fragment handle by index.

D3DXHANDLE GetFragmentHandleByIndex(
  UINT Index
);

Parameters

Index
[in] Zero-based index for the fragment.

Return Values

Unique identifier to the fragment. See Handles. A return value of (D3DX_HANDLE)0 means that no entry for the index was found.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::GetFragmentHandleByName

Get a fragment handle by name.

D3DXHANDLE GetFragmentHandleByName(
  LPCSTR Name
);

Parameters

Name
[in] Fragment name.

Return Values

Unique identifier to the fragment. See Handles. A return value of (D3DX_HANDLE)0 means that no entry for the name was found.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::GetNumberOfFragments

Get the number of fragments in the linker.

UINT GetNumberOfFragments();

Parameters

None.

Return Values

Returns the number of fragments.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::LinkPixelShader

Link a compiled pixel shader at run time. This is a very lightweight operation.

HRESULT LinkPixelShader(
  LPCSTR pProfile,
  DWORD Flags,
  CONST D3DXHANDLE * rgFragmentHandles,
  UINT cFragments,
  LPDIRECT3DPIXELSHADER9 * pPShader,
  LPD3DXBUFFER * ppErrorMsgs
);

Parameters

pProfile
[in] Pointer to a pixel shader profile which detemines the shader instruction set. See D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Link options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
rgFragmentHandles
[in] An array of pixel shader fragment handles. See Handles.
cFragments
[in] Number of fragments to be linked.
pPShader
[out] Pointer to a pixel shader. See IDirect3DPixelShader9.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: E_FAIL, D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::LinkShader

Link a compiled shader at run time. This is a very lightweight operation.

HRESULT LinkShader(
  LPCSTR pProfile,
  DWORD Flags,
  CONST D3DXHANDLE * rgFragmentHandles,
  UINT cFragments,
  LPD3DXBUFFER* ppBuffer,
  LPD3DXBUFFER * ppErrorMsgs
);

Parameters

pProfile
[in] Pointer to a shader profile which detemines the shader instruction set. See D3DXGetVertexShaderProfile or D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Link options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
rgFragmentHandles
[in] An array of shader fragment handles. See Handles.
cFragments
[in] Number of fragments to be linked.
ppBuffer
[out] Pointer to a buffer that contains compiled shader code. See ID3DXBuffer.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: E_FAIL, D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXFragmentLinker::LinkVertexShader

Link a compiled vertex shader at run time. This is a very lightweight operation.

HRESULT LinkVertexShader(
  LPCSTR pProfile,
  DWORD Flags,
  CONST D3DXHANDLE * rgFragmentHandles,
  UINT cFragments,
  LPDIRECT3DVERTEXSHADER9* pVShader,
  LPD3DXBUFFER * ppErrorMsgs
);

Parameters

pProfile
[in] Pointer to a vertex shader profile which detemines the shader instruction set. See D3DXGetVertexShaderProfile for a list of the profiles available.
Flags
[in] Link options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
rgFragmentHandles
[in] An array of vertex shader fragment handles. See Handles.
cFragments
[in] Number of fragments to be linked.
pVShader
[out] Pointer to a vertex shader. See IDirect3DVertexShader9.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: E_FAIL, D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXKeyframedAnimationSet

An application uses the methods of this interface to implement a key frame animation set.

ID3DXAnimationSet
ID3DXCompressedAnimationSet
ID3DXKeyframedAnimationSet

ID3DXKeyframedAnimationSet Members

Method | Description
ID3DXKeyframedAnimationSet::Compress | Transforms animations in an animation set into a compressed format and returns a pointer to the buffer that stores the compressed data.
ID3DXKeyframedAnimationSet::GetCallbackKey | Gets information about a specific callback in the animation set.
ID3DXKeyframedAnimationSet::GetCallbackKeys | Fills an array with callback key data used for key frame animation.
ID3DXKeyframedAnimationSet::GetNumCallbackKeys | Gets the number of callback keys in the animation set.
ID3DXKeyframedAnimationSet::GetNumRotationKeys | Gets the number of rotation keys in the specified key frame animation.
ID3DXKeyframedAnimationSet::GetNumScaleKeys | Gets the number of scale keys in the specified key frame animation.
ID3DXKeyframedAnimationSet::GetNumTranslationKeys | Gets the number of translation keys in the specified key frame animation.
ID3DXKeyframedAnimationSet::GetPlaybackType | Gets the type of the animation set playback loop.
ID3DXKeyframedAnimationSet::GetRotationKey | Get rotation information for a specific key frame in the animation set.
ID3DXKeyframedAnimationSet::GetRotationKeys | Fills an array with rotational key data used for key frame animation.
ID3DXKeyframedAnimationSet::GetScaleKey | Get scale information for a specific key frame in the animation set.
ID3DXKeyframedAnimationSet::GetScaleKeys | Fills an array with scale key data used for key frame animation.
ID3DXKeyframedAnimationSet::GetSourceTicksPerSecond | Gets the number of animation key frame ticks that occur per second.
ID3DXKeyframedAnimationSet::GetTranslationKey | Get translation information for a specific key frame in the animation set.
ID3DXKeyframedAnimationSet::GetTranslationKeys | Fills an array with translational key data used for key frame animation.
ID3DXKeyframedAnimationSet::RegisterAnimationSRTKeys | Register the scale, rotate, and translate (SRT) key frame data for an animation.
ID3DXKeyframedAnimationSet::SetCallbackKey | Sets information about a specific callback in the animation set.
ID3DXKeyframedAnimationSet::SetRotationKey | Set rotation information for a specific key frame in the animation set.
ID3DXKeyframedAnimationSet::SetScaleKey | Set scale information for a specific key frame in the animation set.
ID3DXKeyframedAnimationSet::SetTranslationKey | Set translation information for a specific key frame in the animation set.
ID3DXKeyframedAnimationSet::UnregisterAnimation | Remove the animation data from the animation set.
ID3DXKeyframedAnimationSet::UnregisterRotationKey | Removes the rotation data at the specified key frame.
ID3DXKeyframedAnimationSet::UnregisterScaleKey | Removes the scale data at the specified key frame.
ID3DXKeyframedAnimationSet::UnregisterTranslationKey | Removes the translation data at the specified key frame.

Remarks

Create a keyframed animation set with D3DXCreateKeyframedAnimationSet.

The LPD3DXKEYFRAMEDANIMATIONSET type is defined as a pointer to this interface.

typedef interface ID3DXKeyframedAnimationSet ID3DXKeyframedAnimationSet;
typedef interface ID3DXKeyframedAnimationSet *LPD3DXKEYFRAMEDANIMATIONSET;

Requirements

Header: Declared in D3dx9anim.h.

Library: Use D3dx9.lib.


ID3DXKeyframedAnimationSet::Compress

Transforms animations in an animation set into a compressed format and returns a pointer to the buffer that stores the compressed data.

HRESULT Compress(
  DWORD Flags,
  FLOAT Lossiness,
  LPD3DXFRAME pHierarchy,
  LPD3DXBUFFER * ppCompressedData
);

Parameters

Flags
[in] One of the D3DXCOMPRESSION_FLAGS values that define the compression mode used for storing compressed animation set data. D3DXCOMPRESS_DEFAULT is the only value currently supported.
Lossiness
[in] Desired compression loss ratio, in the range from 0 to 1.
pHierarchy
[in] Pointer to a D3DXFRAME transformation frame hierarchy. Can be NULL.
ppCompressedData
[out] Address of a pointer to the ID3DXBuffer compressed animation set.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetCallbackKey

Gets information about a specific callback in the animation set.

HRESULT GetCallbackKey(
  UINT Animation,
  LPD3DXKEY_CALLBACK pCallbackKeys
);

Parameters

Animation
[in] Animation index.
pCallbackKeys
[out] Pointer to the callback function.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetCallbackKeys

Fills an array with callback key data used for key frame animation.

HRESULT GetCallbackKeys(
  LPD3DXKEY_CALLBACK pCallbackKeys
);

Parameters

pCallbackKeys
[out] Pointer to a user-allocated array of D3DXKEY_CALLBACK structures that the method is to fill with callback data.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.

See Also

ID3DXKeyframedAnimationSet::GetNumCallbackKeys


ID3DXKeyframedAnimationSet::GetNumCallbackKeys

Gets the number of callback keys in the animation set.

UINT GetNumCallbackKeys();

Parameters

None.

Return Values

Number of callback keys in the animation set.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetNumRotationKeys

Gets the number of rotation keys in the specified key frame animation.

UINT GetNumRotationKeys(
  UINT Animation
);

Parameters

Animation
[in] Animation index.

Return Values

Number of rotation keys in the specified key frame animation.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetNumScaleKeys

Gets the number of scale keys in the specified key frame animation.

UINT GetNumScaleKeys(
  UINT Animation
);

Parameters

Animation
[in] Animation index.

Return Values

Number of scale keys in the specified key frame animation.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetNumTranslationKeys

Gets the number of translation keys in the specified key frame animation.

UINT GetNumTranslationKeys(
  UINT Animation
);

Parameters

Animation
[in] Animation index.

Return Values

Number of translation keys in the specified key frame animation.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetPlaybackType

Gets the type of the animation set playback loop.

D3DXPLAYBACK_TYPE GetPlaybackType();

Parameters

None.

Return Values

Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetRotationKey

Get rotation information for a specific key frame in the animation set.

HRESULT GetRotationKey(
  UINT Animation,
  UINT Key,
  LPD3DXKEY_QUATERNION pRotationKeys
);

Parameters

Animation
[in] Animation index.
Key
[in] Key frame.
pRotationKeys
[in] Pointer to the rotation data. See D3DXKEY_QUATERNION.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetRotationKeys

Fills an array with rotational key data used for key frame animation.

HRESULT GetRotationKeys(
  UINT Animation,
  LPD3DXKEY_QUATERNION pRotationKeys
);

Parameters

Animation
[in] Animation index.
pRotationKeys
[in] Pointer to a user-allocated array of D3DXKEY_QUATERNION quaternions that the method is to fill with animation rotation data.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.

See Also

ID3DXKeyframedAnimationSet::GetNumRotationKeys


ID3DXKeyframedAnimationSet::GetScaleKey

Get scale information for a specific key frame in the animation set.

HRESULT GetScaleKey(
  UINT Animation,
  UINT Key,
  LPD3DXKEY_VECTOR3 pScaleKeys
);

Parameters

Animation
[in] Animation index.
Key
[in] Key frame.
pScaleKeys
[in] Pointer to the scale data. See D3DXKEY_VECTOR3.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetScaleKeys

Fills an array with scale key data used for key frame animation.

HRESULT GetScaleKeys(
  UINT Animation,
  LPD3DXKEY_VECTOR3 pScaleKeys
);

Parameters

Animation
[in] Animation index.
pScaleKeys
[in] Pointer to a user-allocated array of D3DXKEY_VECTOR3 vectors that the method is to fill with animation scale data.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.

See Also

ID3DXKeyframedAnimationSet::GetNumScaleKeys


ID3DXKeyframedAnimationSet::GetSourceTicksPerSecond

Gets the number of animation key frame ticks that occur per second.

DOUBLE GetSourceTicksPerSecond();

Parameters

None.

Return Values

Number of animation key frame ticks that occur per second.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetTranslationKey

Get translation information for a specific key frame in the animation set.

HRESULT GetTranslationKey(
  UINT Animation,
  UINT Key,
  LPD3DXKEY_VECTOR3 pTranslationKey
);

Parameters

Animation
[in] Animation index.
Key
[in] Key Frame.
pTranslationKey
[out] Pointer to the rotation information. See D3DXKEY_VECTOR3.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::GetTranslationKeys

Fills an array with translational key data used for key frame animation.

HRESULT GetTranslationKeys(
  UINT Animation,
  LPD3DXKEY_VECTOR3 pTranslationKeys
);

Parameters

Animation
[in] Animation index.
pTranslationKeys
[in] Pointer to a user-allocated array of D3DXKEY_VECTOR3 vectors that the method is to fill with animation translation data.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.

See Also

ID3DXKeyframedAnimationSet::GetNumTranslationKeys


ID3DXKeyframedAnimationSet::RegisterAnimationSRTKeys

Register the scale, rotate, and translate (SRT) key frame data for an animation.

HRESULT RegisterAnimationSRTKeys(
  LPCSTR pName,
  UINT NumScaleKeys,
  UINT NumRotationKeys,
  UINT NumTranslationKeys,
  CONST LPD3DXKEY_VECTOR3 * pScaleKeys,
  CONST LPD3DXKEY_QUATERNION * pRotationKeys,
  CONST LPD3DXKEY_VECTOR3 * pTranslationKeys,
  DWORD * pAnimationIndex
);

Parameters

pName
[in] Pointer to the animation name.
NumScaleKeys
[in] Number of scale keys.
NumRotationKeys
[in] Number of rotation keys.
NumTranslationKeys
[in] Number of translation keys.
pScaleKeys
[in] Address of a pointer to a user-allocated array of D3DXKEY_VECTOR3 vectors that the method fills with scale data.
pRotationKeys
[in] Address of a pointer to a user-allocated array of D3DXKEY_QUATERNION quaternions that the method fills with rotation data.
pTranslationKeys
[in] Address of a pointer to a user-allocated array of D3DXKEY_VECTOR3 vectors that the method fills with translation data.
pAnimationIndex
[out] Returns the animation index.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned:

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3dx9anim.h.

See Also

ID3DXKeyframedAnimationSet::GetNumScaleKeys, ID3DXKeyframedAnimationSet::GetNumRotationKeys, ID3DXKeyframedAnimationSet::GetNumTranslationKeys


ID3DXKeyframedAnimationSet::SetCallbackKey

Sets information about a specific callback in the animation set.

HRESULT SetCallbackKey(
  UINT Animation,
  LPD3DXKEY_CALLBACK pCallbackKeys
);

Parameters

Animation
[in] Animation index.
pCallbackKeys
[out] Pointer to the callback function.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::SetRotationKey

Set rotation information for a specific key frame in the animation set.

HRESULT SetRotationKey(
  UINT Animation,
  UINT Key,
  LPD3DXKEY_QUATERNION pRotationKeys
);

Parameters

Animation
[in] Animation index.
Key
[in] Key frame.
pRotationKeys
[in] Pointer to the rotation data. See D3DXKEY_VECTOR3.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::SetScaleKey

Set scale information for a specific key frame in the animation set.

HRESULT SetScaleKey(
  UINT Animation,
  UINT Key,
  LPD3DXKEY_VECTOR3 pScaleKeys
);

Parameters

Animation
[in] Animation index.
Key
[in] Key frame.
pScaleKeys
[in] Pointer to the scale data. See D3DXKEY_VECTOR3.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::SetTranslationKey

Set translation information for a specific key frame in the animation set.

HRESULT SetTranslationKey(
  UINT Animation,
  UINT Key,
  LPD3DXKEY_VECTOR3 pTranslationKey
);

Parameters

Animation
[in] Animation index.
Key
[in] Key Frame.
pTranslationKey
[in] Pointer to the translation data. See D3DXKEY_VECTOR3.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::UnregisterAnimation

Remove the animation data from the animation set.

HRESULT UnregisterAnimation(
  UINT Index
);

Parameters

Index
[in] The animation index.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::UnregisterRotationKey

Removes the rotation data at the specified key frame.

HRESULT UnregisterRotationKey(
  UINT Animation,
  UINT Key
);

Parameters

Animation
[in] Animation identifier.
Key
[in] Key frame.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

This method is slow and should not be used after an animation has begun to play.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::UnregisterScaleKey

Removes the scale data at the specified key frame.

HRESULT UnregisterScaleKey(
  UINT Animation,
  UINT Key
);

Parameters

Animation
[in] Animation identifier.
Key
[in] Key frame.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

This method is slow and should not be used after an animation has begun to play.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXKeyframedAnimationSet::UnregisterTranslationKey

Removes the translation data at the specified key frame.

HRESULT UnregisterTranslationKey(
  UINT Animation,
  UINT Key
);

Parameters

Animation
[in] Animation identifier.
Key
[in] Key frame.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DERR_INVALIDCALL.

Remarks

This method is slow and should not be used after an animation has begun to play.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXLine

The ID3DXLine interface implements line drawing using textured triangles.

ID3DXLine Members

Method | Description
ID3DXLine::Begin | Prepares a device for drawing lines.
ID3DXLine::Draw | Draws a line strip in screen space. Input is in the form of an array that defines points (of D3DXVECTOR2) on the line strip.
ID3DXLine::DrawTransform | Draws a line strip in screen space with a specified input transformation matrix.
ID3DXLine::End | Restores the device state to how it was when ID3DXLine::Begin was called.
ID3DXLine::GetAntialias | Gets the line antialiasing state.
ID3DXLine::GetDevice | Retrieves the Direct3D device associated with the line object.
ID3DXLine::GetGLLines | Gets the OpenGL-style line-drawing mode.
ID3DXLine::GetPattern | Gets the line stipple pattern.
ID3DXLine::GetPatternScale | Gets the stipple-pattern scale value.
ID3DXLine::GetWidth | Gets the thickness of the line.
ID3DXLine::OnLostDevice | Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost, or before resetting a device.
ID3DXLine::OnResetDevice | Use this method to re-acquire resources and save initial state.
ID3DXLine::SetAntialias | Toggles line antialiasing.
ID3DXLine::SetGLLines | Toggles the mode to draw OpenGL-style lines.
ID3DXLine::SetPattern | Applies a stipple pattern to the line.
ID3DXLine::SetPatternScale | Stretches the stipple pattern along the line direction.
ID3DXLine::SetWidth | Specifies the thickness of the line.

Remarks

Create a line drawing object with D3DXCreateLine.

The LPD3DXLINE type is defined as a pointer to the ID3DXLine interface.

typedef interface ID3DXLine ID3DXLine;
typedef interface ID3DXLine *LPD3DXLINE;

Requirements

Header: Declared in D3dx9core.h.

Library: Use D3dx9.lib.


ID3DXLine::Begin

Prepares a device for drawing lines.

HRESULT Begin();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

Calling ID3DXLine::Begin is optional. If called outside of a ID3DXLine::Begin/ID3DXLine::End sequence, the draw functions will internally call ID3DXLine::Begin and ID3DXLine::End. To avoid extra overhead, this method should be used if more than one draw function will be called successively.

This method must be called from inside an IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene sequence.

ID3DXLine::Begin cannot be used as a substitute for either IDirect3DDevice9::BeginScene or ID3DXRenderToSurface::BeginScene.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLine::Draw

Draws a line strip in screen space. Input is in the form of an array that defines points (of D3DXVECTOR2) on the line strip.

HRESULT Draw(
  CONST D3DXVECTOR2* pVertexList,
  DWORD dwVertexListCount,
  D3DCOLOR Color
);

Parameters

pVertexList
[in] Array of vertices that make up the line. See D3DXVECTOR2.
dwVertexListCount
[in] Number of vertices in the vertex list.
Color
[in] Color of the line. See D3DCOLOR.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLine::DrawTransform

Draws a line strip in screen space with a specified input transformation matrix.

HRESULT DrawTransform(
  CONST D3DXVECTOR3* pVertexList,
  DWORD dwVertexListCount,
  CONST D3DXMATRIX* pTransform,
  D3DCOLOR Color
);

Parameters

pVertexList
[in] Array of vertices that make up the line. See D3DXVECTOR3.
dwVertexListCount
[in] Number of vertices in the vertex list.
pTransform
[in] A scale, rotate, and translate (SRT) matrix for transforming the points. See D3DXMATRIX. If this matrix is a projection matrix, any stippled lines will be drawn with a perspective-correct stippling pattern. Or, you can transform the vertices and use ID3DXLine::Draw to draw the line with a nonperspective-correct stipple pattern.
Color
[in] Color of the line. See D3DCOLOR.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLine::End

Restores the device state to how it was when ID3DXLine::Begin was called.

HRESULT End();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

ID3DXLine::End cannot be used as a substitute for either IDirect3DDevice9::EndScene or ID3DXRenderToSurface::EndScene.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXLine::Begin


ID3DXLine::GetAntialias

Gets the line antialiasing state.

BOOL GetAntialias();

Parameters

None.

Return Values

Returns the antialiasing switch value. TRUE means antialiasing is on, and FALSE means antialiasing is off.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLine::GetDevice

Retrieves the Direct3D device associated with the line object.

HRESULT GetDevice(
  LPDIRECT3DDEVICE9 * ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the line object.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLine::GetGLLines

Gets the OpenGL-style line-drawing mode.

BOOL GetGLLines();

Parameters

None.

Return Values

Returns TRUE if OpenGL-style lines are enabled, and FALSE if Direct3D-style lines are enabled.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXLine::SetGLLines


ID3DXLine::GetPattern

Gets the line stipple pattern.

DWORD GetPattern();

Parameters

None.

Return Values

Returns the line stipple pattern: 1 is opaque, 0 is transparent.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXLine::SetPattern


ID3DXLine::GetPatternScale

Gets the stipple-pattern scale value.

FLOAT GetPatternScale();

Parameters

None.

Return Values

Returns the value used to scale the stipple-pattern. 1.0f is the default value and represents no scaling. A value less than 1.0f shrinks the pattern, and a value greater than 1.0 stretches the pattern.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXLine::SetPatternScale


ID3DXLine::GetWidth

Gets the thickness of the line.

FLOAT GetWidth();

Parameters

None.

Return Values

The line thickness.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXLine::SetWidth


ID3DXLine::OnLostDevice

Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost, or before resetting a device.

HRESULT OnLostDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method should be called whenever the device is lost or before the user calls IDirect3DDevice9::Reset. Even if the device was not actually lost, ID3DXLine::OnLostDevice is responsible for freeing stateblocks and other resources that may need to be released before resetting the device. As a result, the font object cannot be used again before calling IDirect3DDevice9::Reset and then ID3DXLine::OnResetDevice.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLine::OnResetDevice

Use this method to re-acquire resources and save initial state.

HRESULT OnResetDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXLine::OnResetDevice should be called each time the device is reset (using IDirect3DDevice9::Reset), before any other methods are called. This is a good place to re-acquire video-memory resources and capture state blocks.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLine::SetAntialias

Toggles line antialiasing.

HRESULT SetAntialias(
  BOOL bAntiAlias
);

Parameters

bAntiAlias
[in] Toggles antialiasing on and off. TRUE turns antialiasing on, and FALSE turns antialiasing off.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXLine::GetAntialias


ID3DXLine::SetGLLines

Toggles the mode to draw OpenGL-style lines.

HRESULT SetGLLines(
  BOOL bGLLines
);

Parameters

bGLLines
[in] Toggles OpenGL-style line drawing. TRUE enables OpenGL-style lines, and FALSE enables Direct3D-style lines.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLine::SetPattern

Applies a stipple pattern to the line.

HRESULT SetPattern(
  DWORD dwPattern
);

Parameters

dwPattern
[in] Describes the stipple pattern: 1 is opaque, 0 is transparent.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLine::SetPatternScale

Stretches the stipple pattern along the line direction.

HRESULT SetPatternScale(
  FLOAT fPatternScale
);

Parameters

fPatternScale
[in] Stipple pattern scaling value. 1.0f is the default value and represents no scaling. A value less than 1.0f shrinks the pattern, and a value greater than 1.0 stretches the pattern.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLine::SetWidth

Specifies the thickness of the line.

HRESULT SetWidth(
  FLOAT fWidth
);

Parameters

fWidth
[in] Describes the line width.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3dx9core.h.


ID3DXLoadUserData

This interface is implemented by the application to save any additional user data embedded in .x files. An instance of this interface is passed to D3DXLoadMeshHierarchyFromX, and D3DX calls the appropriate method on this interface every time the appropriate data is encountered. For example, for each frame object in the .x file, ID3DXLoadUserData::LoadFrameChildData is called and passed the child data.

ID3DXLoadUserData Members

Method | Description
ID3DXLoadUserData::LoadFrameChildData | Load frame child data from a .x file.
ID3DXLoadUserData::LoadMeshChildData | Load mesh child data from a .x file.
ID3DXLoadUserData::LoadTopLevelData | Load top level data from a .x file.

Remarks

The LPD3DXLOADUSERDATA type is defined as a pointer to this interface.

typedef interface ID3DXLoadUserData ID3DXLoadUserData;
typedef interface ID3DXLoadUserData *LPD3DXLOADUSERDATA;

Requirements

Header: Declared in D3dx9anim.h.

Library: Use D3dx9.lib.


ID3DXLoadUserData::LoadFrameChildData

Load frame child data from a .x file.

HRESULT LoadFrameChildData(
  LPD3DXFRAME pFrame,
  LPD3DXFILEDATA pXofChildData
);

Parameters

pFrame
[in] Pointer to a mesh container. See D3DXFRAME.
pXofChildData
[in] Pointer to a .x file data structure. This is defined in Dxfile.h.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXLoadUserData::LoadMeshChildData

Load mesh child data from a .x file.

HRESULT LoadMeshChildData(
  LPD3DXMESHCONTAINER pMeshContainer,
  LPD3DXFILEDATA pXofChildData
);

Parameters

pMeshContainer
[in] Pointer to a mesh container. See D3DXMESHCONTAINER.
pXofChildData
[in] Pointer to a .x file data structure. This is defined in Dxfile.h.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXLoadUserData::LoadTopLevelData

Load top level data from a .x file.

HRESULT LoadTopLevelData(
  LPD3DXFILEDATA pXofChildData
);

Parameters

pXofChildData
[in] Pointer to a .x file data structure. This is defined in Dxfile.h.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXMATRIXStack

Applications use the methods of the ID3DXMATRIXStack interface to manipulate a matrix stack.

ID3DXMATRIXStack Members

Method | Description
ID3DXMATRIXStack::GetTop | Retrieves the current matrix at the top of the stack.
ID3DXMATRIXStack::LoadIdentity | Loads identity in the current matrix.
ID3DXMATRIXStack::LoadMatrix | Loads the given matrix into the current matrix.
ID3DXMATRIXStack::MultMatrix | Determines the product of the current matrix and the given matrix.
ID3DXMATRIXStack::MultMatrixLocal | Determines the product of the given matrix and the current matrix.
ID3DXMATRIXStack::Pop | Removes the current matrix from the top of the stack.
ID3DXMATRIXStack::Push | Adds a matrix to the stack.
ID3DXMATRIXStack::RotateAxis | Rotates (relative to world coordinate space) around an arbitrary axis.
ID3DXMATRIXStack::RotateAxisLocal | Rotates (relative to the object's local coordinate space) around an arbitrary axis.
ID3DXMATRIXStack::RotateYawPitchRoll | Rotates (relative to world coordinate space) around an arbitrary axis.
ID3DXMATRIXStack::RotateYawPitchRollLocal | Rotates (relative to the object's local coordinate space) around an arbitrary axis.
ID3DXMATRIXStack::Scale | Scale the current matrix about the world coordinate origin.
ID3DXMATRIXStack::ScaleLocal | Scale the current matrix about the object origin.
ID3DXMATRIXStack::Translate | Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).
ID3DXMATRIXStack::TranslateLocal | Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.

Remarks

The ID3DXMATRIXStack interface is obtained by calling the D3DXCreateMatrixStack function.

The LPD3DXMATRIXSTACK type is defined as a pointer to the ID3DXMATRIXStack interface.

typedef interface ID3DXMATRIXStack ID3DXMATRIXStack;
typedef interface ID3DXMATRIXStack *LPD3DXMATRIXSTACK;

Requirements

Header: Declared in D3dx9math.h.

Library: Use D3dx9.lib.


ID3DXMATRIXStack::GetTop

Retrieves the current matrix at the top of the stack.

D3DXMATRIX * GetTop();

Parameters

None.

Return Values

This method returns a pointer to a D3DXMATRIX structure representing the current matrix.

Remarks

The D3DXMATRIX pointer returned by this method is not guaranteed to be valid after subsequent stack operations.

Note that this method does not remove the current matrix from the top of the stack; rather, it just returns the current matrix.

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::Pop, ID3DXMATRIXStack::Push


ID3DXMATRIXStack::LoadIdentity

Loads identity in the current matrix.

HRESULT LoadIdentity();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The identity matrix is a matrix in which all coefficients are 0.0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1.0. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4x4 matrix.

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::LoadMatrix


ID3DXMATRIXStack::LoadMatrix

Loads the given matrix into the current matrix.

HRESULT LoadMatrix(
  CONST D3DXMATRIX * pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure loaded into the current matrix.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Note that this method does not add an item to the stack; rather, it replaces the current matrix with the supplied matrix.

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::LoadIdentity


ID3DXMATRIXStack::MultMatrix

Determines the product of the current matrix and the given matrix.

HRESULT MultMatrix(
  CONST D3DXMATRIX * pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin).

m_pstack[m_currentPos] = m_pstack[m_currentPos] * (*pMat);

This method does not add an item to the stack, it replaces the current matrix with the product of the current matrix and the given matrix.

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::MultMatrixLocal


ID3DXMATRIXStack::MultMatrixLocal

Determines the product of the given matrix and the current matrix.

HRESULT MultMatrixLocal(
  CONST D3DXMATRIX * pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object).

m_pstack[m_currentPos] = (*pMat) * m_pstack[m_currentPos];

This method does not add an item to the stack, it replaces the current matrix with the product of the given matrix and the current matrix.

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::MultMatrix


ID3DXMATRIXStack::Pop

Removes the current matrix from the top of the stack.

HRESULT Pop();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

Note that this method decrements the count of items on the stack by 1, effectively removing the current matrix from the top of the stack and promoting a matrix to the top of the stack. If the current count of items on the stack is 0, then this method returns without performing any action. If the current count of items on the stack is 1, then this method empties the stack.

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::GetTop, ID3DXMATRIXStack::Push


ID3DXMATRIXStack::Push

Adds a matrix to the stack.

HRESULT Push();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method increments the count of items on the stack by 1, duplicating the current matrix. The stack will grow dynamically as more items are added.

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::GetTop, ID3DXMATRIXStack::Pop


ID3DXMATRIXStack::RotateAxis

Rotates (relative to world coordinate space) around an arbitrary axis.

HRESULT RotateAxis(
  CONST D3DXVECTOR3 * pV,
  FLOAT Angle
);

Parameters

pV
[in] Pointer to the arbitrary axis of rotation. See D3DXVECTOR3.
Angle
[in] Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:

D3DXMATRIX tmp;
D3DXMatrixRotationAxis( &tmp, pV, angle );
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixRotationAxis, ID3DXMATRIXStack::RotateAxisLocal, ID3DXMATRIXStack::RotateYawPitchRoll, ID3DXMATRIXStack::RotateYawPitchRollLocal


ID3DXMATRIXStack::RotateAxisLocal

Rotates (relative to the object's local coordinate space) around an arbitrary axis.

HRESULT RotateAxisLocal(
  CONST D3DXVECTOR3 * pV,
  FLOAT Angle
);

Parameters

pV
[in] Pointer to the arbitrary axis of rotation. See D3DXVECTOR3.
Angle
[in] Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:

D3DXMATRIX tmp;
D3DXMatrixRotationAxis( &tmp, pV, angle );
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixRotationAxis, ID3DXMATRIXStack::RotateAxis, ID3DXMATRIXStack::RotateYawPitchRoll, ID3DXMATRIXStack::RotateYawPitchRollLocal


ID3DXMATRIXStack::RotateYawPitchRoll

Rotates (relative to world coordinate space) around an arbitrary axis.

HRESULT RotateYawPitchRoll(
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

Yaw
[in] The yaw around the y-axis in radians.
Pitch
[in] The pitch around the x-axis in radians.
Roll
[in] The roll around the z-axis in radians.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:

D3DXMATRIX tmp;
D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixRotationAxis, ID3DXMATRIXStack::RotateAxis, ID3DXMATRIXStack::RotateAxisLocal, ID3DXMATRIXStack::RotateYawPitchRollLocal


ID3DXMATRIXStack::RotateYawPitchRollLocal

Rotates (relative to the object's local coordinate space) around an arbitrary axis.

HRESULT RotateYawPitchRollLocal(
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

Yaw
[in] The yaw around the y-axis in radians.
Pitch
[in] The pitch around the x-axis in radians.
Roll
[in] The roll around the z-axis in radians.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:

D3DXMATRIX tmp;
D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixRotationAxis, ID3DXMATRIXStack::RotateAxis, ID3DXMATRIXStack::RotateAxisLocal, ID3DXMATRIXStack::RotateYawPitchRoll


ID3DXMATRIXStack::Scale

Scale the current matrix about the world coordinate origin.

HRESULT Scale(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The scaling component in the x-direction.
y
[in] The scaling component in the y-direction.
z
[in] The scaling component in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed scale matrix. The transformation is about the current world origin.

D3DXMATRIX tmp;
D3DXMatrixScaling(&tmp, x, y, z);
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::ScaleLocal


ID3DXMATRIXStack::ScaleLocal

Scale the current matrix about the object origin.

HRESULT ScaleLocal(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The scaling component in the x-direction.
y
[in] The scaling component in the y-direction.
z
[in] The scaling component in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed scale matrix. The transformation is about the local origin of the object.

D3DXMATRIX tmp;
D3DXMatrixScaling(&tmp, x, y, z);
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::Scale


ID3DXMATRIXStack::Translate

Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).

HRESULT Translate(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The translation factor in the x-direction.
y
[in] The translation factor in the y-direction.
z
[in] The translation factor in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed translation matrix (transformation is about the current world origin).

D3DXMATRIX tmp;
D3DXMatrixTranslation( &tmp, x, y, z );
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::TranslateLocal


ID3DXMATRIXStack::TranslateLocal

Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.

HRESULT TranslateLocal(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The translation factor in the x-direction.
y
[in] The translation factor in the y-direction.
z
[in] The translation factor in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed translation matrix (transformation is about the local origin of the object).

D3DXMATRIX tmp;
D3DXMatrixTranslation( &tmp, x, y, z );
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Header: Declared in D3dx9math.h.

See Also

ID3DXMATRIXStack::Translate


ID3DXMesh

Applications use the methods of the ID3DXMesh interface to manipulate mesh objects.

ID3DXBaseMesh
ID3DXMesh
ID3DXPMesh

ID3DXMesh Members

Method | Description
ID3DXMesh::LockAttributeBuffer | Locks the mesh buffer that contains the mesh attribute data, and returns a pointer to it.
ID3DXMesh::Optimize | Generates a new mesh with reordered faces and vertices to optimize drawing performance.
ID3DXMesh::OptimizeInplace | Generates a mesh with reordered faces and vertices to optimize drawing performance. This method reorders the existing mesh.
ID3DXMesh::SetAttributeTable | Sets the attribute table for a mesh and the number of entries stored in the table.
ID3DXMesh::UnlockAttributeBuffer | Unlocks an attribute buffer.

Remarks

To obtain the ID3DXMesh interface, call either the D3DXCreateMesh or D3DXCreateMeshFVF function.

This interface inherits additional functionality from the ID3DXBaseMesh interface.

The LPD3DXMESH type is defined as a pointer to the ID3DXMesh interface.

typedef struct ID3DXMesh *LPD3DXMESH;

See Also

Mesh Functions

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXMesh::LockAttributeBuffer

Locks the mesh buffer that contains the mesh attribute data, and returns a pointer to it.

HRESULT LockAttributeBuffer(
  DWORD Flags,
  DWORD ** ppData
);

Parameters

Flags

Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:

  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
[in] For a description of the flags, see D3DLOCK.

ppData
[out] Address of a pointer to a buffer containing a DWORD for each face in the mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If ID3DXMesh::Optimize has been called, the mesh will also have an attribute table that can be accessed using the ID3DXBaseMesh::GetAttributeTable method.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXMesh::UnlockAttributeBuffer, ID3DXBaseMesh::GetAttributeTable, ID3DXMesh::SetAttributeTable


ID3DXMesh::Optimize

Generates a new mesh with reordered faces and vertices to optimize drawing performance.

HRESULT Optimize(
  DWORD Flags,
  CONST DWORD * pAdjacencyIn,
  DWORD * pAdjacencyOut,
  DWORD * pFaceRemap,
  LPD3DXBUFFER * ppVertexRemap,
  LPD3DXMESH * ppOptMesh
);

Parameters

Flags
[in] Specifies the type of optimization to perform. This parameter can be set to a combination of one or more flags from D3DXMESHOPT and D3DXMESH (except D3DXMESH_32BIT, D3DXMESH_IB_WRITEONLY, and D3DXMESH_WRITEONLY).
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specifies the three neighbors for each face in the source mesh. If the edge has no adjacent faces, the value is 0xffffffff. See Remarks.
pAdjacencyOut
[in, out] Pointer to an array of three DWORDs per face that specifies the three neighbors for each face in the optimized mesh. If the edge has no adjacent faces, the value is 0xffffffff.
pFaceRemap
[in, out] An array of DWORDs, one per face, that identifies the original mesh face that corresponds to each face in the optimized mesh. If the value supplied for this argument is NULL, face remap data is not returned.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, which contains a DWORD for each vertex that specifies how the new vertices map to the old vertices. This remap is useful if you need to alter external data based on the new vertex mapping.
ppOptMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the optimized mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This method generates a new mesh. Before running Optimize, an application must generate an adjacency buffer by calling ID3DXBaseMesh::GenerateAdjacency. The adjacency buffer contains adjacency data, such as a list of edges and the faces that are adjacent to each other.

This method is very similar to the ID3DXBaseMesh::CloneMesh method, except that it can perform optimization while generating the new clone of the mesh. The output mesh inherits all of the creation parameters of the input mesh.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXMesh::OptimizeInplace


ID3DXMesh::OptimizeInplace

Generates a mesh with reordered faces and vertices to optimize drawing performance. This method reorders the existing mesh.

HRESULT OptimizeInplace(
  DWORD Flags,
  CONST DWORD * pAdjacencyIn,
  DWORD * pAdjacencyOut,
  DWORD * pFaceRemap,
  LPD3DXBUFFER * ppVertexRemap
);

Parameters

Flags
[in] Combination of one or more D3DXMESHOPT flags, specifying the type of optimization to perform.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specifies the three neighbors for each face in the source mesh. If the edge has no adjacent faces, the value is 0xffffffff.
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face that specifies the three neighbors for each face in the optimized mesh. If the edge has no adjacent faces, the value is 0xffffffff. If the value supplied for this argument is NULL, adjacency data is not returned.
pFaceRemap
[out] An array of DWORDs, one per face, that identifies the original mesh face that corresponds to each face in the optimized mesh. If the value supplied for this argument is NULL, face remap data is not returned.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, which contains a DWORD for each vertex that specifies how the new vertices map to the old vertices. This remap is useful if you need to alter external data based on the new vertex mapping. If the value supplied for this argument is NULL, vertex remap data is not returned.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_CANNOTATTRSORT, E_OUTOFMEMORY.

Remarks

Before running ID3DXMesh::OptimizeInplace, an application must generate an adjacency buffer by calling ID3DXBaseMesh::GenerateAdjacency. The adjacency buffer contains adjacency data, such as a list of edges and the faces that are adjacent to each other.

Note This method will fail if the mesh is sharing its vertex buffer with another mesh, unless the D3DXMESHOPT_IGNOREVERTS is set in Flags.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXMesh::Optimize


ID3DXMesh::SetAttributeTable

Sets the attribute table for a mesh and the number of entries stored in the table.

HRESULT SetAttributeTable(
  CONST D3DXATTRIBUTERANGE * pAttribTable,
  DWORD cAttribTableSize
);

Parameters

pAttribTable
[in] Pointer to an array of D3DXATTRIBUTERANGE structures, representing the entries in the mesh attribute table.
cAttribTableSize
[in] Number of attributes in the mesh attribute table.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

If an application keeps track of the information in an attribute table, and rearranges the table as a result of changes to attributes or faces, this method allows the application to update the attribute tables instead of calling ID3DXMesh::Optimize again.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXMesh::LockAttributeBuffer, ID3DXMesh::LockAttributeBuffer


ID3DXMesh::UnlockAttributeBuffer

Unlocks an attribute buffer.

HRESULT UnlockAttributeBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXMesh::LockAttributeBuffer


ID3DXPatchMesh

This interface encapsulates patch mesh functionality.

ID3DXPatchMesh Members

Method | Description
ID3DXPatchMesh::CloneMesh | Creates a new patch mesh with the specified vertex declaration.
ID3DXPatchMesh::GenerateAdjacency | Generate a list of mesh edges and the patches that share each edge.
ID3DXPatchMesh::GetControlVerticesPerPatch | Gets the number of control vertices per patch.
ID3DXPatchMesh::GetDeclaration | Gets the vertex declaration.
ID3DXPatchMesh::GetDevice | Gets the device that created the mesh.
ID3DXPatchMesh::GetDisplaceParam | Gets mesh geometry displacement parameters.
ID3DXPatchMesh::GetIndexBuffer | Gets the mesh index buffer.
ID3DXPatchMesh::GetNumPatches | Gets the number of patches in the mesh.
ID3DXPatchMesh::GetNumVertices | Gets the number of vertices in the mesh.
ID3DXPatchMesh::GetOptions | Gets the type of patch.
ID3DXPatchMesh::GetPatchInfo | Gets the attributes of the patch.
ID3DXPatchMesh::GetTessSize | Gets the size of the tessellated mesh, given a tessellation level.
ID3DXPatchMesh::GetVertexBuffer | Gets the mesh vertex buffer.
ID3DXPatchMesh::LockAttributeBuffer | Locks the attribute buffer.
ID3DXPatchMesh::LockIndexBuffer | Lock the index buffer.
ID3DXPatchMesh::LockVertexBuffer | Lock the vertex buffer.
ID3DXPatchMesh::Optimize | Optimizes the patch mesh for efficient tessellation.
ID3DXPatchMesh::SetDisplaceParam | Sets mesh geometry displacement parameters.
ID3DXPatchMesh::Tessellate | Performs uniform tessellation based on the tessellation level.
ID3DXPatchMesh::TessellateAdaptive | Performs adaptive tessellation based on the z-based adaptive tessellation criterion.
ID3DXPatchMesh::UnlockAttributeBuffer | Unlock the attribute buffer.
ID3DXPatchMesh::UnlockIndexBuffer | Unlock the index buffer.
ID3DXPatchMesh::UnlockVertexBuffer | Unlock the vertex buffer.

Remarks

A patch mesh is a mesh that consists of a series of patches.

To obtain the ID3DXPatchMesh interface, call the D3DXCreatePatchMesh function.

The LPD3DXPATCHMESH type is defined as a pointer to the ID3DXPatchMesh interface, as follows:

typedef struct ID3DXPatchMesh *LPD3DXPATCHMESH;

See Also

Mesh Functions

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXPatchMesh::CloneMesh

Creates a new patch mesh with the specified vertex declaration.

HRESULT CloneMesh(
  DWORD Options,
  CONST D3DVERTEXELEMENT9 * pDecl,
  LPD3DXPATCHMESH * pMesh
);

Parameters

Options
[in] Combination of one or more D3DXMESH flags that specify creation options for the mesh.
pDecl
[in] Array of D3DVERTEXELEMENT9 elements that specify the vertex format for the vertices in the output mesh.
pMesh
[out, retval] Address of a pointer to an ID3DXPatchMesh interface that represents the cloned mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

ID3DXPatchMesh::CloneMesh converts the vertex buffer to the new vertex declaration. Entries in the vertex declaration that are new to the original mesh are set to 0. If the current mesh has adjacency, the new mesh will also have adjacency.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GenerateAdjacency

Generate a list of mesh edges and the patches that share each edge.

HRESULT GenerateAdjacency(
  FLOAT fTolerance
);

Parameters

fTolerance
[in] Specifies that vertices that differ in position by less than the tolerance should be treated as coincident.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized for better drawing performance. This method determines which patches are adjacent (within the provided tolerance). This information is used internally to optimize tessellation.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPatchMesh::Optimize


ID3DXPatchMesh::GetControlVerticesPerPatch

Gets the number of control vertices per patch.

DWORD GetControlVerticesPerPatch();

Parameters

None.

Return Values

The number of control vertices per patch.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GetDeclaration

Gets the vertex declaration.

HRESULT GetDeclaration(
  LPD3DVERTEXELEMENT9 pDeclaration[MAX_FVF_DECL_SIZE]
);

Parameters

pDeclaration
[out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The dimension of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GetDevice

Gets the device that created the mesh.

HRESULT GetDevice(
  LPDIRECT3DDEVICE9* ppDevice
);

Parameters

ppDevice
[out] Pointer to the device.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GetDisplaceParam

Gets mesh geometry displacement parameters.

HRESULT GetDisplaceParam(
  LPDIRECT3DBASETEXTURE9* Texture,
  D3DTEXTUREFILTERTYPE* MinFilter,
  D3DTEXTUREFILTERTYPE* MagFilter,
  D3DTEXTUREFILTERTYPE* MipFilter,
  D3DTEXTUREADDRESS* Wrap,
  DWORD* dwLODBias
);

Parameters

Texture
[in] Texture containing the displacement data.
MinFilter
[in] Minification level. For more information, see D3DTEXTUREFILTERTYPE.
MagFilter
[in] Magnification level. For more information, see D3DTEXTUREFILTERTYPE.
MipFilter
[in] Mip filter level. For more information, see D3DTEXTUREFILTERTYPE.
Wrap
[in] Texture address wrap mode. For more information, see D3DTEXTUREADDRESS.
dwLODBias
[in] Level of detail bias value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Displacement maps can only be 2D textures. Mipmapping is ignored for nonadaptive tessellation.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GetIndexBuffer

Gets the mesh index buffer.

HRESULT GetIndexBuffer(
  LPDIRECT3DINDEXBUFFER9 * ppIB
);

Parameters

ppIB
[out, retval] Pointer to the index buffer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The index buffer contains the vertex ordering in the vertex buffer. The index buffer is used to access the vertex buffer when the mesh is rendered.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GetNumPatches

Gets the number of patches in the mesh.

DWORD GetNumPatches();

Parameters

None.

Return Values

The number of patches.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GetNumVertices

Gets the number of vertices in the mesh.

DWORD GetNumVertices();

Parameters

None.

Return Values

The number of vertices.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GetOptions

Gets the type of patch.

DWORD GetOptions();

Parameters

None.

Return Values

The patch type.

Remarks

For more information about patch types, see D3DXPATCHMESHTYPE.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GetPatchInfo

Gets the attributes of the patch.

HRESULT GetPatchInfo(
  LPD3DXPATCHINFO PatchInfo
);

Parameters

PatchInfo
[out, retval] Pointer to the structures containing the patch attributes. For more information about patch attributes, see D3DXPATCHINFO.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GetTessSize

Gets the size of the tessellated mesh, given a tessellation level.

HRESULT GetTessSize(
  FLOAT fTessLevel,
  DWORD Adaptive,
  DWORD * NumTriangles,
  DWORD * NumVertices
);

Parameters

fTessLevel
[in] Tessellation level.
Adaptive
[in] Adaptive tessellation. For adaptive tessellation, set this value to TRUE and set fTessLevel to the maximum tessellation value. This will result in the maximum mesh size necessary for adaptive tessellation.
NumTriangles
[out] Pointer to the number of triangles generated by the tessellated mesh.
NumVertices
[out] Pointer to the number of vertices generated by the tessellated mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This method assumes uniform tessellation.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::GetVertexBuffer

Gets the mesh vertex buffer.

HRESULT GetVertexBuffer(
  LPDIRECT3DVERTEXBUFFER9 * ppVB
);

Parameters

ppVB
[out] Pointer to the vertex buffer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This method assumes uniform tessellation.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::LockAttributeBuffer

Locks the attribute buffer.

HRESULT LockAttributeBuffer(
  DWORD flags,
  DWORD ** ppData
);

Parameters

flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
For a description of the flags, see D3DLOCK.
ppData
[out, retval] Address of a pointer to a buffer containing a DWORD for each face in the mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The attribute buffer is usually locked, written to, and then unlocked for reading.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::LockIndexBuffer

Lock the index buffer.

HRESULT LockIndexBuffer(
  DWORD flags,
  LPVOID * ppData
);

Parameters

flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
For a description of the flags, see D3DLOCK.
ppData
[out, retval] VOID* pointer to a memory buffer containing the returned index data.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The index buffer is usually locked, written to, and then unlocked for reading. Patch mesh index buffers are 16-bit buffers.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXCreatePatchMesh


ID3DXPatchMesh::LockVertexBuffer

Lock the vertex buffer.

HRESULT LockVertexBuffer(
  DWORD flags,
  LPVOID * ppData
);

Parameters

flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE
For a description of the flags, see D3DLOCK.
ppData
[out, retval] VOID* pointer to a memory buffer containing the returned vertex data.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The vertex buffer is usually locked, written to, and then unlocked for reading.

Patch meshes use 16-bit index buffers.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::Optimize

Optimizes the patch mesh for efficient tessellation.

HRESULT Optimize(
  DWORD Flags
);

Parameters

Flags
[in] Currently unused.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_CANNOTATTRSORT.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized (reordered) for better drawing performance. This method determines which patches are adjacent (within the provided tolerance).

Adjacency information is also used to optimize tessellation. Generate adjacency information once and tessellate repeatedly by calling ID3DXPatchMesh::Tessellate. The optimization performed is independent of the actual tessellation level used. However, if the mesh vertices are changed, you must regenerate the adjacency information.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPatchMesh::GenerateAdjacency


ID3DXPatchMesh::SetDisplaceParam

Sets mesh geometry displacement parameters.

HRESULT SetDisplaceParam(
  LPDIRECT3DBASETEXTURE9 Texture,
  D3DTEXTUREFILTERTYPE MinFilter,
  D3DTEXTUREFILTERTYPE MagFilter,
  D3DTEXTUREFILTERTYPE MipFilter,
  D3DTEXTUREADDRESS Wrap,
  DWORD dwLODBias
);

Parameters

Texture
[in] Texture containing the displacement data.
MinFilter
[in] Minification level. For more information, see D3DTEXTUREFILTERTYPE.
MagFilter
[in] Magnification level. For more information, see D3DTEXTUREFILTERTYPE.
MipFilter
[in] Mip filter level. For more information, see D3DTEXTUREFILTERTYPE.
Wrap
[in] Texture address wrap mode. For more information, see D3DTEXTUREADDRESS
dwLODBias
[in] Level of detail bias value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Displacement maps can only be 2D textures. Mipmapping is ignored for nonadaptive tessellation.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::Tessellate

Performs uniform tessellation based on the tessellation level.

HRESULT Tessellate(
  FLOAT fTessLevel,
  LPD3DXMESH pMesh
);

Parameters

fTessLevel
[in] Tessellation level. This is the number of vertices introduced between existing vertices. The range of this float parameter is 0 < fTessLevel <= 32.
pMesh
[in] Resulting tessellated mesh. See ID3DXMesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This function will perform more efficiently if the patch mesh has been optimized using ID3DXPatchMesh::Optimize.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::TessellateAdaptive

Performs adaptive tessellation based on the z-based adaptive tessellation criterion.

HRESULT TessellateAdaptive(
  CONST D3DXVECTOR4* pTrans,
  DWORD dwMaxTessLevel,
  DWORD dwMinTessLevel,
  LPD3DXMESH pMesh
);

Parameters

pTrans
[in] Specifies a 4D vector that is dotted with the vertices to get the per-vertex adaptive tessellation amount. Each edge is tessellated to the average value of the tessellation levels for the two vertices it connects.
dwMaxTessLevel
[in] Maximum limit for adaptive tessellation. This is the number of vertices introduced between existing vertices. This integer value can range from 1 to 32, inclusive.
dwMinTessLevel
[in] Minimum limit for adaptive tessellation. This is the number of vertices introduced between existing vertices. This integer value can range from 1 to 32, inclusive.
pMesh
[in] Resulting tessellated mesh. See ID3DXMesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This function will perform more efficiently if the patch mesh has been optimized using ID3DXPatchMesh::Optimize.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::UnlockAttributeBuffer

Unlock the attribute buffer.

HRESULT UnlockAttributeBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The attribute buffer is usually locked, written to, and then unlocked for reading.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::UnlockIndexBuffer

Unlock the index buffer.

HRESULT UnlockIndexBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The index buffer is usually locked, written to, and then unlocked for reading.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPatchMesh::UnlockVertexBuffer

Unlock the vertex buffer.

HRESULT UnlockVertexBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The vertex buffer is usually locked, written to, and then unlocked for reading.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPMesh

Applications use the methods of the ID3DXPMesh interface to manipulate progressive mesh objects. A progressive mesh enables progressive refinement of the mesh object.

ID3DXBaseMesh
ID3DXMesh
ID3DXPMesh

ID3DXPMesh Members

Method | Description
ID3DXPMesh::ClonePMesh | Clones a progressive mesh using a declarator.
ID3DXPMesh::ClonePMeshFVF | Clones a progressive mesh using a flexible vertex format (FVF) code.
ID3DXPMesh::GenerateVertexHistory | Generates an immediate ancestor for each vertex when it is removed by a vertex split. Allows generation of a geomorph.
ID3DXPMesh::GetAdjacency | Returns the face adjacency array of the mesh.
ID3DXPMesh::GetMaxFaces | Retrieves the maximum number of faces that the progressive mesh supports.
ID3DXPMesh::GetMaxVertices | Retrieves the maximum number of vertices that the progressive mesh supports.
ID3DXPMesh::GetMinFaces | Retrieves the minimum number of faces that the progressive mesh supports.
ID3DXPMesh::GetMinVertices | Retrieves the minimum number of vertices that the progressive mesh supports.
ID3DXPMesh::Optimize | Generates an output mesh with reordered faces and vertices to optimize performance.
ID3DXPMesh::OptimizeBaseLOD | Optimizes the base level of detail (LOD) part of an ID3DXPMesh object.
ID3DXPMesh::Save | Saves the progressive mesh to the specified stream object.
ID3DXPMesh::SetNumFaces | Sets the current level of detail to as close to the specified number of faces as possible.
ID3DXPMesh::SetNumVertices | Sets the current level of detail to as close to the specified number of vertices as possible.
ID3DXPMesh::TrimByFaces | Modifies the minimum and maximum level of detail (LOD) of an ID3DXPMesh object.
ID3DXPMesh::TrimByVertices | Modifies the minimum and maximum level of detail (LOD) of an ID3DXPMesh object.

Remarks

To obtain the ID3DXPMesh interface, call the D3DXGeneratePMesh function. Or, create a progressive mesh with D3DXCreatePMeshFromStream.

This interface inherits additional functionality from the ID3DXBaseMesh interface.

The LPD3DXPMESH type is defined as a pointer to the ID3DXPMesh interface, as shown below.

typedef struct ID3DXPMesh *LPD3DXPMESH;

See Also

Mesh Functions

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXPMesh::ClonePMesh

Clones a progressive mesh using a declarator.

HRESULT ClonePMesh(
  DWORD Options,
  CONST D3DVERTEXELEMENT9 * pDeclaration,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LpD3DDeviceXPMESH * ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements describing the vertex format for the returned mesh. This parameter must map directly to an flexible vertex format (FVF).
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXBaseMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXPMesh::ClonePMeshFVF

Clones a progressive mesh using a flexible vertex format (FVF) code.

HRESULT ClonePMeshFVF(
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LPD3DXPMESH * ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, specifying the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

ID3DXPMesh::ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXBaseMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXPMesh::GenerateVertexHistory

Generates an immediate ancestor for each vertex when it is removed by a vertex split. Allows generation of a geomorph.

HRESULT GenerateVertexHistory(
  DWORD * pVertexHistory
);

Parameters

pVertexHistory
[in] Pointer to an array of parent vertices that were used to form the current vertex. Cannot be NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The vertex buffer must be equal to or greater than the maximum number of vertices in the progressive mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPMesh::GetAdjacency

Returns the face adjacency array of the mesh.

HRESULT GetAdjacency(
  DWORD * pAdjacency
);

Parameters

pAdjacency
[out] Pointer to the returned face adjacency array of the mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh. If the edge has no adjacent faces, the value is 0xffffffff. The size of the adjacency array is the maximum number of faces multiplied by 3.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPMesh::GetMaxFaces


ID3DXPMesh::GetMaxFaces

Retrieves the maximum number of faces that the progressive mesh supports.

DWORD GetMaxFaces();

Parameters

None.

Return Values

Returns the maximum number of faces supported by the progressive mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPMesh::GetMaxVertices

Retrieves the maximum number of vertices that the progressive mesh supports.

DWORD GetMaxVertices();

Parameters

None.

Return Values

Returns the maximum number of vertices supported by the progressive mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPMesh::GetMinFaces

Retrieves the minimum number of faces that the progressive mesh supports.

DWORD GetMinFaces();

Parameters

None.

Return Values

Returns the minimum number of faces supported by the progressive mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPMesh::GetMinVertices

Retrieves the minimum number of vertices that the progressive mesh supports.

DWORD GetMinVertices();

Parameters

None.

Return Values

Returns the minimum number of vertices supported by the progressive mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPMesh::Optimize

Generates an output mesh with reordered faces and vertices to optimize performance.

HRESULT Optimize(
  DWORD Flags,
  DWORD * pAdjacencyOut,
  DWORD * pFaceRemap,
  LPD3DXBUFFER * ppVertexRemap,
  LPD3DXMESH * ppOptMesh
);

Parameters

Flags
[in] Specifies the type of optimization to perform. This parameter can be set to a combination of one or more flags from D3DXMESHOPT and D3DXMESH (except D3DXMESH32_BIT, D3DXMESH_IB_WRITEONLY, and D3DXMESH_WRITEONLY).
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face that specifies the three neighbors for each face in the optimized mesh. If the edge has no adjacent faces, the value is 0xffffffff.
pFaceRemap
[out] An array of DWORDs, one per face, that identifies the original mesh face that corresponds to each face in the optimized mesh. If the value supplied for this argument is NULL, face remap data is not returned.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, which contains a DWORD for each vertex that specifies how the new vertices map to the old vertices. This remap is useful if you need to alter external data based on the new vertex mapping.
ppOptMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the optimized mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized (reordered) for better drawing performance. This method determines which patches are adjacent (within the provided tolerance).

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXBaseMesh::GenerateAdjacency, ID3DXPMesh::OptimizeBaseLOD


ID3DXPMesh::OptimizeBaseLOD

Optimizes the base level of detail (LOD) part of an ID3DXPMesh object.

HRESULT OptimizeBaseLOD(
  DWORD Flags,
  DWORD * pFaceRemap
);

Parameters

Flags
[in] Combination of one or more flags from the D3DXMESHOPT enumeration that specifies the type of optimization to perform.
pFaceRemap
[in] An array of DWORDs, one per face, that identifies the original mesh face that corresponds to each face in the optimized mesh. If the value supplied for this argument is NULL, face remap data is not returned.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized (reordered) for better drawing performance. This method determines which patches are adjacent (within the provided tolerance).

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXBaseMesh::GenerateAdjacency, ID3DXPMesh::Optimize


ID3DXPMesh::Save

Saves the progressive mesh to the specified stream object.

HRESULT Save(
  IStream * pStream,
  CONST D3DXMATERIAL * pMaterials,
  CONST D3DXEFFECTINSTANCE* pEffectInstances,
  DWORD NumMaterials
);

Parameters

pStream
[in] Pointer to an IStream interface, representing the stream object to which the file data is written.
pMaterials
[in] Pointer to an array of D3DXMATERIAL structures, containing material information to be saved in the stream object.
pEffectInstances
[in] Pointer to an array of effect instances, one per attribute group in the mesh. An effect instance is a particular instance of state information used to initialize an effect. For more information, see D3DXEFFECTINSTANCE.
NumMaterials
[in] Number of D3DXMATERIAL structures in the pMaterials array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

For more information about the IStream interface, see the Platform SDK.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPMesh::SetNumFaces

Sets the current level of detail to as close to the specified number of faces as possible.

HRESULT SetNumFaces(
  DWORD Faces
);

Parameters

Faces
[in] Target number of faces. This value specifies the desired change in the level of detail (LOD).

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the number of faces is greater than the maximum number of faces, it is capped at the maximum number of faces returned by ID3DXPMesh::GetMaxFaces. If the number of faces is less than the minimum number of faces, it is capped at the minimum number of faces returned by ID3DXPMesh::GetMinFaces.

The number of faces after this call may be off by one because some edge collapse may introduce or remove one face or two. For example, if you try setting the number of faces to an intermediate value such as 5, when 4 and 6 are possible, 4 will always be the result.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPMesh::SetNumVertices

Sets the current level of detail to as close to the specified number of vertices as possible.

HRESULT SetNumVertices(
  DWORD Vertices
);

Parameters

Vertices
[in] Target number of vertices. This value specifies the desired change in the level of detail (LOD).

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the number of vertices is greater than the maximum number of vertices, it is capped at the maximum number of vertices returned by ID3DXPMesh::GetMaxVertices. If the number of vertices is less than the minimum number of vertices, it is capped at the minimum number of vertices returned by ID3DXPMesh::GetMinVertices.

The number of vertices after this call may be off by one because some edge collapse may introduce or remove one face or two. For example, if you try setting the number of faces to an intermediate value such as 5, when 4 and 6 are possible, 4 will always be the result.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPMesh::TrimByFaces

Modifies the minimum and maximum level of detail (LOD) of an ID3DXPMesh object.

HRESULT TrimByFaces(
  DWORD NewFacesMin,
  DWORD NewFacesMax,
  DWORD * rgiFaceRemap,
  DWORD * rgiVertRemap
);

Parameters

NewFacesMin
[in] New minimum number of faces. This parameter must be between current minimum and maximum number of faces.
NewFacesMax
[in] New maximum number of faces. This parameter must be between current minimum and maximum number of faces.
rgiFaceRemap
[out] Returns one DWORD per face that contains face remap information.
rgiVertRemap
[out] Returns one DWORD per vertex that contians vertex remap information.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPMesh::TrimByVertices


ID3DXPMesh::TrimByVertices

Modifies the minimum and maximum level of detail (LOD) of an ID3DXPMesh object.

HRESULT TrimByVertices(
  DWORD NewVerticesMin,
  DWORD NewVerticessMax,
  DWORD * rgiFaceRemap,
  DWORD * rgiVertRemap
);

Parameters

NewVerticesMin
[in] New minimum number of vertices. This parameter must be between current minimum and maximum number of vertices.
NewVerticessMax
[in] New maximum number of vertices. This parameter must be between current minimum and maximum number of vertices.
rgiFaceRemap
[out] Returns one DWORD per face that contains face remap information.
rgiVertRemap
[out] Returns one DWORD per vertex that contains vertex remap information.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPMesh::TrimByFaces


ID3DXPRTBuffer

The ID3DXPRTBuffer interface is used as a data buffer to store vertex and pixel data for use with precomputed radiance transfer (PRT) methods and functions.

ID3DXPRTBuffer Members

Method | Description
ID3DXPRTBuffer::AddBuffer | Adds another buffer to the ID3DXPRTBuffer and stores the results in ID3DXPRTBuffer.
ID3DXPRTBuffer::AttachGH | Associates an ID3DXTextureGutterHelper object with the ID3DXPRTBuffer object.
ID3DXPRTBuffer::EvalGH | Applies stored texture gutter data to an ID3DXPRTBuffer texture buffer.
ID3DXPRTBuffer::ExtractTexture | Extracts coefficient data from a color channel of the buffer for a specified range of coefficients, and adds the data to an IDirect3DTexture9 object.
ID3DXPRTBuffer::ExtractToMesh | Extracts coefficient data from a single-channel buffer and adds the data to an ID3DXMesh object.
ID3DXPRTBuffer::GetHeight | Retrieves the height of the texture, in pixels.
ID3DXPRTBuffer::GetNumChannels | Retrieves the number of color channels used in memory to store samples.
ID3DXPRTBuffer::GetNumCoeffs | Retrieves the number of scalars per color channel used in memory to store samples.
ID3DXPRTBuffer::GetNumSamples | Retrieves the number of vertices (or texels) sampled.
ID3DXPRTBuffer::GetWidth | Retrieves the width of the texture, in pixels.
ID3DXPRTBuffer::IsTexture | Indicates whether the buffer contains a texture.
ID3DXPRTBuffer::LockBuffer | Locks a range of vertex or texel sample data and obtains a pointer to the location in buffer memory.
ID3DXPRTBuffer::ReleaseGH | Unassociates an attached ID3DXTextureGutterHelper object with the ID3DXPRTBuffer object.
ID3DXPRTBuffer::Resize | Changes the number of samples contained in the buffer.
ID3DXPRTBuffer::ScaleBuffer | Multiplies every value in the buffer by a constant value.
ID3DXPRTBuffer::UnlockBuffer | Ends the lifespan of the ID3DXPRTBuffer::LockBuffer pointer returned by ID3DXPRTBuffer::LockBuffer.

Remarks

The ID3DXPRTBuffer interface is obtained by calling the D3DXCreatePRTBuffer or D3DXCreatePRTBufferTex functions.

The LPD3DXPRTBUFFER type is defined as a pointer to the ID3DXPRTBuffer interface.

typedef interface ID3DXPRTBuffer ID3DXPRTBuffer;
typedef interface ID3DXPRTBuffer *LPD3DXPRTBUFFER;

See Also

D3DXCreatePRTBuffer, D3DXCreatePRTBufferTex, ID3DXPRTCompBuffer

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXPRTBuffer::AddBuffer

Adds another buffer to the ID3DXPRTBuffer and stores the results in ID3DXPRTBuffer.

HRESULT AddBuffer(
  LPD3DXPRTBUFFER pBuffer
);

Parameters

pBuffer
[in] Pointer to a buffer that contains members to be added to the respective members of the ID3DXPRTBuffer buffer.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

pBuffer and ID3DXPRTBuffer must have the same number of samples, coefficients, and color channels; the method will fail otherwise.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTBuffer::AttachGH

Associates an ID3DXTextureGutterHelper object with the ID3DXPRTBuffer object.

HRESULT AttachGH(
  LPD3DXTEXTUREGUTTERHELPER pGH
);

Parameters

pGH
[in] Pointer to the ID3DXTextureGutterHelper interface of an object that contains texture gutter data.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

The reference count of the ID3DXTextureGutterHelper object will automatically be incremented by one. Any existing ID3DXTextureGutterHelper pointers will be released.

You must ensure that the number of ID3DXPRTBuffer::AttachGH calls matches the number of ID3DXPRTBuffer::ReleaseGH calls. After calling ID3DXPRTBuffer::ReleaseGH, the pGH pointer returned by ID3DXPRTBuffer::AttachGH should no longer be used.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTBuffer::ReleaseGH


ID3DXPRTBuffer::EvalGH

Applies stored texture gutter data to an ID3DXPRTBuffer texture buffer.

HRESULT EvalGH();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

This method makes an internal call to ID3DXTextureGutterHelper::ApplyGuttersFloat to retrieve and apply texture gutter data.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTBuffer::ExtractTexture

Extracts coefficient data from a color channel of the buffer for a specified range of coefficients, and adds the data to an IDirect3DTexture9 object.

HRESULT ExtractTexture(
  UINT Channel,
  UINT StartCoefficient,
  UINT NumCoefficients,
  LPDIRECT3DTEXTURE9 pTexture
);

Parameters

Channel
[in] Buffer color channel from which to extract texture data.
StartCoefficient
[in] Starting value of the buffer coefficient from which to extract texture data.
NumCoefficients
[in] Number of scalars, beginning at StartCoefficient, from which to extract texture data.
pTexture
[in] Pointer to a IDirect3DTexture9 texture object that will store coefficients.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTBuffer::ExtractToMesh

Extracts coefficient data from a single-channel buffer and adds the data to an ID3DXMesh object.

HRESULT ExtractToMesh(
  UINT NumCoefficients,
  D3DDECLUSAGE Usage,
  UINT UsageIndexStart,
  LPD3DXMESH pScene
);

Parameters

NumCoefficients
[in] Number of coefficients to extract from the buffer. When using spherical harmonic (SH) precomputed radiance transfer (PRT), the number of coefficients should be Order 2. Order must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive.
Usage
[in] Vertex usage descriptions of the mesh. See D3DDECLUSAGE.
UsageIndexStart
[in] Starting index for coefficients to be stored in the mesh.
pScene
[in] Pointer to an ID3DXMesh mesh object that will store coefficients.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTBuffer::GetHeight

Retrieves the height of the texture, in pixels.

UINT GetHeight();

Parameters

None.

Return Values

Returns the height of the texture, in pixels.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTBuffer::GetWidth


ID3DXPRTBuffer::GetNumChannels

Retrieves the number of color channels used in memory to store samples.

UINT GetNumChannels();

Parameters

None.

Return Values

Returns the number of color channels used in memory to store samples. The value generally will be either 1 to represent luminance values, or 3 to represent RGB values.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTBuffer::GetNumCoeffs

Retrieves the number of scalars per color channel used in memory to store samples.

UINT GetNumCoeffs();

Parameters

None.

Return Values

Returns the number of scalars per color channel used in memory to store samples.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTBuffer::GetNumSamples

Retrieves the number of vertices (or texels) sampled.

UINT GetNumSamples();

Parameters

None.

Return Values

Returns the number of vertices (or texels) sampled.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTBuffer::GetWidth

Retrieves the width of the texture, in pixels.

UINT GetWidth();

Parameters

None.

Return Values

Returns the width of the texture, in pixels.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTBuffer::GetHeight


ID3DXPRTBuffer::IsTexture

Indicates whether the buffer contains a texture.

BOOL IsTexture();

Parameters

None.

Return Values

Returns TRUE if the buffer contains a texture; returns FALSE otherwise.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTBuffer::LockBuffer

Locks a range of vertex or texel sample data and obtains a pointer to the location in buffer memory.

HRESULT LockBuffer(
  UINT Start,
  UINT NumSamples,
  FLOAT ** ppData
);

Parameters

Start
[in] Index of the sample of vertex or texel data.
NumSamples
[in] Number of vertices (or texels) sampled.
ppData
[out] Pointer to the location in memory where the Start sample begins. The memory layout of the buffer data is:
float fData[NumberSamples][NumberChannels][NumberCoefficients]

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned:

D3DERR_INVALIDCALL

Remarks

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTBuffer::GetNumChannels, ID3DXPRTBuffer::GetNumCoeffs, ID3DXPRTBuffer::GetNumSamples


ID3DXPRTBuffer::ReleaseGH

Unassociates an attached ID3DXTextureGutterHelper object with the ID3DXPRTBuffer object.

HRESULT ReleaseGH();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method releases the pointer to the ID3DXTextureGutterHelper interface.

You must ensure that the number of ID3DXPRTBuffer::AttachGH calls matches the number of ID3DXPRTBuffer::ReleaseGH calls. After calling ID3DXPRTBuffer::ReleaseGH, the pGH pointer returned by ID3DXPRTBuffer::AttachGH should no longer be used.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTBuffer::AttachGH


ID3DXPRTBuffer::Resize

Changes the number of samples contained in the buffer.

HRESULT Resize(
  UINT NewSize
);

Parameters

NewSize
[in] Number of samples to be contained in the buffer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the following value will be returned, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTBuffer::ScaleBuffer

Multiplies every value in the buffer by a constant value.

HRESULT ScaleBuffer(
  FLOAT Scale
);

Parameters

Scale
[in] Constant value used to scale the buffer. Every value in the buffer is replaced by the product of this value and the original buffer value.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTBuffer::UnlockBuffer

Ends the lifespan of the ppData pointer returned by ID3DXPRTBuffer::LockBuffer.

HRESULT UnlockBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer

The ID3DXPRTCompBuffer interface stores a compressed version of a ID3DXPRTBuffer buffer, for use with principal component analysis (PCA).

ID3DXPRTCompBuffer Members

Method | Description
ID3DXPRTCompBuffer::ExtractBasis | Extracts the mean and principal component analysis (PCA) basis vectors for a given cluster from an ID3DXPRTCompBuffer compressed data buffer.
ID3DXPRTCompBuffer::ExtractClusterIDs | Extracts the per-sample cluster IDs from an ID3DXPRTCompBuffer compressed data buffer.
ID3DXPRTCompBuffer::ExtractPCA | Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer.
ID3DXPRTCompBuffer::ExtractTexture | Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer and adds the data to an IDirect3DTexture9 object.
ID3DXPRTCompBuffer::ExtractToMesh | Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer and adds the data to an ID3DXMesh object.
ID3DXPRTCompBuffer::GetHeight | Retrieves the height of the texture, in pixels.
ID3DXPRTCompBuffer::GetNumChannels | Retrieves the number of color channels used in memory to store samples.
ID3DXPRTCompBuffer::GetNumClusters | Retrieves the number of clusters to use for compression.
ID3DXPRTCompBuffer::GetNumCoeffs | Retrieves the number of scalars per color channel used in memory to store samples.
ID3DXPRTCompBuffer::GetNumPCA | Retrieves the number of principal component analysis (PCA) basis vectors to use in each cluster.
ID3DXPRTCompBuffer::GetNumSamples | Retrieves the number of vertices (or texels) sampled.
ID3DXPRTCompBuffer::GetWidth | Retrieves the width of the texture, in pixels.
ID3DXPRTCompBuffer::IsTexture | Indicates whether the buffer contains a texture.
ID3DXPRTCompBuffer::NormalizeData | Normalizes all principal component analysis (PCA) weights so that they are between -1 and 1. Basis vectors are modified to reflect this normalization.

Remarks

The ID3DXPRTCompBuffer interface is obtained by calling the D3DXCreatePRTCompBuffer function.

The LPD3DXPRTCOMPBUFFER type is defined as a pointer to the ID3DXPRTCompBuffer interface.

typedef interface ID3DXPRTCompBuffer ID3DXPRTCompBuffer;
typedef interface ID3DXPRTCompBuffer *LPD3DXPRTCOMPBUFFER;

See Also

D3DXCreatePRTCompBuffer, ID3DXPRTBuffer

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXPRTCompBuffer::ExtractBasis

Extracts the mean and principal component analysis (PCA) basis vectors for a given cluster from an ID3DXPRTCompBuffer compressed data buffer.

HRESULT ExtractBasis(
  UINT Cluster,
  FLOAT * pClusterBasis
);

Parameters

Cluster
[in] Cluster for which the basis will be extracted.
pClusterBasis
[in, out] Pointer to an array of basis vector data for Cluster. The size of the FLOAT data stored will be: (1 + Number of PCA vectors per cluster) * (Number of coefficients) * (Number of color channels)

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::ExtractClusterIDs

Extracts the per-sample cluster IDs from an ID3DXPRTCompBuffer compressed data buffer.

HRESULT ExtractClusterIDs(
  UINT * pClusterIDs
);

Parameters

pClusterIDs
[in, out] Pointer to the location in memory where IDs are written. The length of memory required is the value returned by ID3DXPRTCompBuffer::GetNumSamples.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::ExtractPCA

Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer.

HRESULT ExtractPCA(
  UINT StartPCA,
  UINT NumExtract,
  FLOAT * pPCACoefficients
);

Parameters

StartPCA
[in] Starting index for PCA projection coefficients to extract from the buffer.
NumExtract
[in] Number of PCA projection coefficients to extract from the buffer.
pPCACoefficients
[in] Pointer to the location where clustered principal component analysis (CPCA) coefficients are written. The size of the data written is (Number of Samples) * (Number of PCA Coefficients).

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::ExtractTexture

Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer and adds the data to an IDirect3DTexture9 object.

HRESULT ExtractTexture(
  UINT StartPCA,
  UINT NumPCA,
  LPDIRECT3DTEXTURE9 pTexture
);

Parameters

StartPCA
[in] Starting value of the buffer coefficient from which to extract texture data.
NumPCA
[in] Number of PCA coefficients to extract from the buffer.
pTexture
[in] Pointer to an IDirect3DTexture9 texture object that will store PCA coefficients.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::ExtractToMesh

Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer and adds the data to an ID3DXMesh object.

HRESULT ExtractToMesh(
  UINT NumPCA,
  D3DDECLUSAGE Usage,
  UINT UsageIndexStart,
  LPD3DXMESH pScene
);

Parameters

NumPCA
[in] Number of PCA coefficients to extract from the buffer.
Usage
[in] Vertex usage descriptions of the mesh. See D3DDECLUSAGE.
UsageIndexStart
[in] Starting index for PCA coefficients to be stored in the mesh.
pScene
[in] Pointer to an ID3DXMesh mesh object that will store PCA coefficients.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::GetHeight

Retrieves the height of the texture, in pixels.

UINT GetHeight();

Parameters

None.

Return Values

Returns the height of the texture, in pixels.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTCompBuffer::GetWidth


ID3DXPRTCompBuffer::GetNumChannels

Retrieves the number of color channels used in memory to store samples.

UINT GetNumChannels();

Parameters

None.

Return Values

Returns the number of color channels used in memory to store samples. The value generally will be either 1 to represent luminance values, or 3 to represent RGB values.

Remarks

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::GetNumClusters

Retrieves the number of clusters to use for compression.

UINT GetNumClusters();

Parameters

None.

Return Values

Returns the number of clusters to use for compression.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::GetNumCoeffs

Retrieves the number of scalars per color channel used in memory to store samples.

UINT GetNumCoeffs();

Parameters

None.

Return Values

Returns the number of scalars per color channel used in memory to store samples.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::GetNumPCA

Retrieves the number of principal component analysis (PCA) basis vectors to use in each cluster.

UINT GetNumPCA();

Parameters

None.

Return Values

Returns the number of principal component analysis (PCA) basis vectors to use in each cluster.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::GetNumSamples

Retrieves the number of vertices (or texels) sampled.

UINT GetNumSamples();

Parameters

None.

Return Values

Returns the number of vertices (or texels) sampled.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::GetWidth

Retrieves the width of the texture, in pixels.

UINT GetWidth();

Parameters

None.

Return Values

Returns the width of the texture, in pixels.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTCompBuffer::GetHeight


ID3DXPRTCompBuffer::IsTexture

Indicates whether the buffer contains a texture.

BOOL IsTexture();

Parameters

None.

Return Values

Returns TRUE if the buffer contains a texture; returns FALSE otherwise.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTCompBuffer::NormalizeData

Normalizes all principal component analysis (PCA) weights so that they are between -1 and 1. Basis vectors are modified to reflect this normalization.

HRESULT NormalizeData();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine

The ID3DXPRTEngine interface is used to compute a precomputed radiance transfer (PRT) simulation. Its methods are typically used offline, to compute per-vertex or per-texel transfer vectors in advance of real-time 3D modeling.

ID3DXPRTEngine Members

Method | Description
ID3DXPRTEngine::ClosestRayIntersects | Uses efficient ray-tracing in precomputed radiance transfer (PRT) simulations to determine whether a ray intersects a mesh. If an intersection is found, the method returns the index of the closest mesh face hit by the ray and the barycentric coordinates of the intersection point.
ID3DXPRTEngine::ComputeBounce | Computes the source radiance resulting from a single bounce of interreflected light. This method can be used for any lit scene, including a spherical harmonic (SH)-based precomputed radiance transfer (PRT) model.
ID3DXPRTEngine::ComputeBounceAdaptive | Computes the source radiance resulting from a single bounce of interreflected light, using adaptive sampling. This method generates new vertices and faces on the mesh to more accurately approximate the precomputed radiance transfer (PRT) signal. This method can be used for any lit scene, including a spherical harmonic (SH)-based PRT model.
ID3DXPRTEngine::ComputeDirectLightingSH | Computes the direct lighting contribution to 3D objects where the source radiance is represented by a spherical harmonic (SH) approximation.
ID3DXPRTEngine::ComputeDirectLightingSHAdaptive | Computes the direct lighting contribution to 3D objects where the source radiance is represented by a spherical harmonic (SH) approximation, using adaptive sampling. This method generates new vertices and faces on the mesh to more accurately approximate the precomputed radiance transfer (PRT) signal.
ID3DXPRTEngine::ComputeDirectLightingSHGPU | Uses the GPU to compute the direct lighting contribution to 3D objects where the source radiance is represented by a spherical harmonic (SH) approximation. Computing the lighting on the GPU will generally be much faster than on the CPU.
ID3DXPRTEngine::ComputeLDPRTCoeffs | Computes locally-deformable precomputed radiance transfer (LDPRT) coefficients relative to per-sample normal vectors to minimize the least-squares error with respect to input ID3DXPRTBuffer data. These coefficients can be used with skinned or transformed normal vectors to model global effects on dynamic objects.
ID3DXPRTEngine::ComputeSS | Computes the source radiance resulting from subsurface scattering, using material properties set by ID3DXPRTEngine::SetMeshMaterials. This method can be used only for materials defined per-vertex in a mesh object.
ID3DXPRTEngine::ComputeSSAdaptive | Computes a transfer vector that maps source radiance to exit radiance resulting from subsurface scattering, using adaptive sampling and material properties set by ID3DXPRTEngine::SetMeshMaterials. The method generates new vertices and faces on the mesh to more accurately approximate the precomputed radiance transfer (PRT) signal. This method can be used only for materials defined per-vertex in a mesh object.
ID3DXPRTEngine::ComputeSurfSamplesBounce | Computes precomputed radiance transfer (PRT) samples for an arbitrary point (and normal vector).
ID3DXPRTEngine::ComputeSurfSamplesDirectSH | Computes, at an arbitrary point not on a mesh, a transfer vector that maps source radiance (represented by a spherical harmonic (SH) approximation) to exit radiance.
ID3DXPRTEngine::ComputeVolumeSamples | Computes a projection of the direct lighting from the previous light bounce into spherical harmonic (SH) basis vectors that represent incident radiance at specified locations.
ID3DXPRTEngine::ComputeVolumeSamplesDirectSH | Computes a projection of distant lighting into spherical harmonic (SH) basis vectors that represent incident radiance at specified locations.
ID3DXPRTEngine::ExtractPerVertexAlbedo | Copies per-vertex albedo values from a mesh.
ID3DXPRTEngine::FreeBounceData | Frees memory used for temporary bounced-light simulation data.
ID3DXPRTEngine::FreeSSData | Frees memory used for temporary subsurface light scattering simulation data.
ID3DXPRTEngine::GetAdaptedMesh | Returns a mesh with modifications resulting from adaptive spatial sampling. The returned mesh contains only positions, normals, and texture coordinates (if defined).
ID3DXPRTEngine::GetNumFaces | Retrieves the number of faces in the mesh, including any new faces added as a result of adaptive spatial sampling.
ID3DXPRTEngine::GetNumVerts | Retrieves the number of vertices in the mesh, including any new vertices added as a result of adaptive spatial sampling.
ID3DXPRTEngine::GetVertexAlbedo | Retrieves albedo values of the mesh vertices.
ID3DXPRTEngine::MultiplyAlbedo | Multiplies each precomputed radiance transfer (PRT) vector by the per-vertex albedo.
ID3DXPRTEngine::ResampleBuffer | Resamples an input ID3DXPRTBuffer buffer and saves it to an output buffer. This method can be used to convert a vertex buffer to a texture buffer and vice-versa. It can also be used to convert single-channel buffers to 3-channel buffers and vice-versa.
ID3DXPRTEngine::RobustMeshRefine | Subdivides faces on a mesh, allowing for conservative adaptive sampling that will not eliminate features on the mesh.
ID3DXPRTEngine::ScaleMeshChunk | Scales all the samples associated with a given submesh. The method is useful for computing subsurface scattering.
ID3DXPRTEngine::SetCallBack | Sets a pointer to an optional callback function that computes the percentage of spherical harmonic (SH) computations completed and gives the caller the option of aborting the simulator.
ID3DXPRTEngine::SetMeshMaterials | Sets mesh material properties in the 3D scene. Use this method to specify subsurface scattering parameters.
ID3DXPRTEngine::SetMinMaxIntersection | Sets the minimum and maximum distances of intersection between 3D objects. These distance values can be used to control the minimum or maximum distance that objects can shadow or reflect light. For example, the method can be used to limit the shadowing of nearby features of a 3D model.
ID3DXPRTEngine::SetPerTexelAlbedo | Sets an albedo value for each texel, overwriting previous albedo values.
ID3DXPRTEngine::SetPerTexelNormal | Sets a normal vector for each texel in a texture object. This method is used to store vertex normal vectors from a mesh (or interpolated vertex normals if pixel-based precomputed radiance transfer (PRT) is being computed).
ID3DXPRTEngine::SetPerVertexAlbedo | Sets an albedo value for each mesh vertex, overwriting previous albedo values.
ID3DXPRTEngine::SetSamplingInfo | Sets sampling properties used by the precomputed radiance transfer (PRT) simulator.
ID3DXPRTEngine::ShadowRayIntersects | Uses efficient ray-tracing in precomputed radiance transfer (PRT) simulations to determine whether a ray intersects a mesh. Typically used to determine whether a given point is in shadow.

Remarks

To convert from RGB to luminance values, the following formula is used:

Luminance = R * 0.2125 + G * 0.7154 + B * 0.0721

The ID3DXPRTEngine interface is obtained by calling the D3DXCreatePRTEngine function.

The LPD3DXPRTENGINE type is defined as a pointer to the ID3DXPRTEngine interface.

typedef interface ID3DXPRTEngine ID3DXPRTEngine;
typedef interface ID3DXPRTEngine *LPD3DXPRTENGINE;

See Also

D3DXCreatePRTEngine, Precomputed Radiance Transfer (Direct3D 9)

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXPRTEngine::ClosestRayIntersects

Uses efficient ray-tracing in precomputed radiance transfer (PRT) simulations to determine whether a ray intersects a mesh. If an intersection is found, the method returns the index of the closest mesh face hit by the ray and the barycentric coordinates of the intersection point.

BOOL ClosestRayIntersects(
  CONST D3DXVECTOR3 * pRayPos,
  CONST D3DXVECTOR3 * pRayDir,
  DWORD * pFaceIndex,
  FLOAT * pU,
  FLOAT * pV,
  FLOAT * pDist
);

Parameters

pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the normalized direction of the ray.
pFaceIndex
[in] Pointer to the index of the current mesh face that is first hit by the given ray, based upon stacking all blocker mesh faces in front of the current mesh.
pU
[out] Pointer to a barycentric hit coordinate, U, for vertex 0 of the triangle.
pV
[out] Pointer to a barycentric hit coordinate, V, for vertex 1 of the triangle.
pDist
[out] Pointer to the distance of the intersection point along the ray.

Return Values

Returns TRUE if the ray intersects the current mesh; otherwise, returns FALSE.

Remarks

Use ID3DXPRTEngine::SetMinMaxIntersection to set minimum and maximum distances of intersection with the ray.

The barycentric coordinate of the third vertex (vertex 2) of the triangle is 1 - ( U + V ).

This method executes slower than ID3DXPRTEngine::ShadowRayIntersects. Use ID3DXPRTEngine::ShadowRayIntersects if the location of the intersection point is not needed.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ShadowRayIntersects, ID3DXPRTEngine::SetMinMaxIntersection


ID3DXPRTEngine::ComputeBounce

Computes the source radiance resulting from a single bounce of interreflected light. This method can be used for any lit scene, including a spherical harmonic (SH)-based precomputed radiance transfer (PRT) model.

HRESULT ComputeBounce(
  LPD3DXPRTBUFFER pDataIn,
  LPD3DXPRTBUFFER pDataOut,
  LPD3DXPRTBUFFER pDataTotal
);

Parameters

pDataIn
[in] Pointer to an input ID3DXPRTBuffer object that represents the 3D object from the previous light bounce. This input buffer must have the proper number of color channels allocated for the simulation.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that models a single bounce of the interreflected light. This output buffer must have the proper number of color channels allocated for the simulation.
pDataTotal
[in, out] Pointer to an optional ID3DXPRTBuffer object that is the running sum of all previous pDataOut outputs. May be NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Use the following calling sequence to model multiple light bounces with direct lighting.

LPD3DXPRTBUFFER pDataA, pDataB, pDataC; // initialization
ID3DXPRTEngine* m_pPRTEngine;

ComputeDirectLightingSH( SHOrder, pDataA );
// The accumulation buffer, pDataC, needs to be
// initialized to the direct lighting result.

pDataC->AddBuffer( pDataA );
hr = m_pPRTEngine->ComputeBounce( pDataA, pDataB, pDataC ); // first bounce
hr = m_pPRTEngine->ComputeBounce( pDataB, pDataA, pDataC ); // second bounce
hr = m_pPRTEngine->ComputeBounce( pDataA, pDataB, pDataC ); // third bounce
hr = m_pPRTEngine->ComputeBounce( pDataB, pDataA, pDataC ); // fourth bounce

Use the following calling sequence to model multiple light bounces with subsurface scattering.

LPD3DXPRTBUFFER pDataA, pDataB, pDataC; // initialization
ID3DXPRTEngine* m_pPRTEngine;
ComputeDirectLightingSH( SHOrder, pDataA );

// *pDataC should be set to zero. The ComputeSS call will add together
// the direct lighting results from pDataA for non-subsurface scattering
// elements and subsurface scattering results for the subsurface scattering
// elements. Perform proper error handling for each call.

hr = m_pPRTEngine->ComputeSS    ( pDataA, pDataB, pDataC );
hr = m_pPRTEngine->ComputeBounce( pDataB, pDataA, NULL   ); // first bounce
hr = m_pPRTEngine->ComputeSS    ( pDataA, pDataB, pDataC );
hr = m_pPRTEngine->ComputeBounce( pDataB, pDataA, NULL   ); // second bounce
hr = m_pPRTEngine->ComputeSS    ( pDataA, pDataB, pDataC );

The output of this method does not include albedo, and only incoming light is integrated in the simulator. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

Call ID3DXPRTEngine::MultiplyAlbedo to multiply each PRT vector by the albedo.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ComputeSS


ID3DXPRTEngine::ComputeBounceAdaptive

Computes the source radiance resulting from a single bounce of interreflected light, using adaptive sampling. This method generates new vertices and faces on the mesh to more accurately approximate the precomputed radiance transfer (PRT) signal. This method can be used for any lit scene, including a spherical harmonic (SH)-based PRT model.

HRESULT ComputeBounceAdaptive(
  LPD3DXPRTBUFFER pDataIn,
  FLOAT AdaptiveThresh,
  FLOAT MinEdgeLength,
  UINT MaxSubdiv,
  LPD3DXPRTBUFFER pDataOut,
  LPD3DXPRTBUFFER pDataTotal
);

Parameters

pDataIn
[in] Pointer to an input ID3DXPRTBuffer object that represents the 3D object from the previous light bounce. This input buffer must have the proper number of color channels allocated for the simulation.
AdaptiveThresh
[in] Threshold on the PRT vector to use for subdividing mesh vertices and faces. If less than 1e-6f, a default value of 1e-6f is specified.
MinEdgeLength
[in] Minimum face edge length that will be generated in adaptive sampling. If the method determines that the value is too small, a model-dependent value is specified. If zero, a default value of 4 is specified.
MaxSubdiv
[in] Maximum level of subdivision of a face that will be used in adaptive sampling.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object. This output buffer must have the proper number of color channels allocated for the simulation.
pDataTotal
[in, out] Pointer to an optional ID3DXPRTBuffer object that keeps a running sum of pDataOut with each light bounce computation. May be NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::RobustMeshRefine


ID3DXPRTEngine::ComputeDirectLightingSH

Computes the direct lighting contribution to 3D objects where the source radiance is represented by a spherical harmonic (SH) approximation.

HRESULT ComputeDirectLightingSH(
  UINT Order,
  LPD3DXPRTBUFFER pDataOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that models the direct lighting contribution with the SH approximation. This buffer must have the proper number of color channels allocated for the simulation.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The output does not include albedo, and only incoming light is integrated in the simulator. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

Call ID3DXPRTEngine::MultiplyAlbedo to multiply each precomputed radiance transfer (PRT) vector by the albedo.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::ComputeDirectLightingSHAdaptive

Computes the direct lighting contribution to 3D objects where the source radiance is represented by a spherical harmonic (SH) approximation, using adaptive sampling. This method generates new vertices and faces on the mesh to more accurately approximate the precomputed radiance transfer (PRT) signal.

HRESULT ComputeDirectLightingSHAdaptive(
  UINT Order,
  FLOAT AdaptiveThresh,
  FLOAT MinEdgeLength,
  UINT MaxSubdiv,
  LPD3DXPRTBUFFER pDataOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
AdaptiveThresh
[in] Threshold on the PRT vector to use for subdividing mesh vertices and faces. If less than 1e-6f, a default value of 1e-6f is specified.
MinEdgeLength
[in] Minimum face edge length that will be generated in adaptive sampling. If the method determines that the value is too small, a model-dependent value is specified. If zero, a default value of 4 is specified.
MaxSubdiv
[in] Maximum level of subdivision of a face that will be used in adaptive sampling.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object. This buffer must have the proper number of color channels allocated for the simulation.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::RobustMeshRefine


ID3DXPRTEngine::ComputeDirectLightingSHGPU

Uses the GPU to compute the direct lighting contribution to 3D objects where the source radiance is represented by a spherical harmonic (SH) approximation. Computing the lighting on the GPU will generally be much faster than on the CPU.

HRESULT ComputeDirectLightingSHGPU(
  LPDIRECT3DDEVICE9 pDevice,
  UINT Flags,
  UINT Order,
  FLOAT ZBias,
  FLOAT ZAngleBias,
  LPD3DXPRTBUFFER pDataOut
);

Parameters

pDevice
[in] Pointer to the IDirect3DDevice9 device object used to run the simulation on the GPU. The device must support ps_2_0 pixel shaders.

Note Callback functions should not use the IDirect3DDevice9 device object used by the GPU simulator.

Flags
[in] GPU simulation parameter that defines the resolution of the shadow z-buffer. Should be set to one of the constant values from D3DXSHGPUSIMOPT. To specifiy higher precision simulation, the D3DXSHGPUSIMOPT_HIGHQUALITY value may be combined with one of the D3DXSHGPUSIMOPT_SHADOWRESxxx values.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
ZBias
[in] Bias in the normal direction.
ZAngleBias
[in] Bias in the normal direction, scaled by one minus the cosine of the angle with the light ray.
pDataOut
[in, out] Pointer to an ID3DXPRTBuffer object. This buffer must have the proper number of color channels allocated for the simulation.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

In this method, the albedo is not multiplied by the light signal, and only incoming light is integrated in the simulator. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

Call ID3DXPRTEngine::MultiplyAlbedo to multiply each precomputed radiance transfer (PRT) vector by the albedo.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::ComputeLDPRTCoeffs

Computes locally-deformable precomputed radiance transfer (LDPRT) coefficients relative to per-sample normal vectors to minimize the least-squares error with respect to input ID3DXPRTBuffer data. These coefficients can be used with skinned or transformed normal vectors to model global effects on dynamic objects.

HRESULT ComputeLDPRTCoeffs(
  LPD3DXPRTBUFFER pDataIn,
  UINT Order,
  D3DXVECTOR3 * pNormOut,
  LPD3DXPRTBUFFER pDataOut
);

Parameters

pDataIn
[in] Pointer to an input ID3DXPRTBuffer spherical harmonic (SH) precomputed radiance transfer (PRT) data object.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pNormOut
[in, out] Optional vector array to be filled with shader-optimal normal vectors for which LDPRT coefficients are optimized. This array must be the same size as the number of samples in pDataIn. If NULL, surface normal vectors are used.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that contains Order zonal harmonic coefficients per color channel per sample.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Solutions for shading normal vectors can optionally be obtained with this method. These normal vectors, along with the LDPRT coefficients, can more accurately represent the PRT signal. In this case, the coefficients represent zonal harmonics oriented in the normal direction.

This method cannot be used with results from ID3DXPRTEngine::ComputeSurfSamplesBounce or ID3DXPRTEngine::ComputeSurfSamplesDirectSH.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::ComputeSS

Computes the source radiance resulting from subsurface scattering, using material properties set by ID3DXPRTEngine::SetMeshMaterials. This method can be used only for materials defined per-vertex in a mesh object.

HRESULT ComputeSS(
  LPD3DXPRTBUFFER pDataIn,
  LPD3DXPRTBUFFER pDataOut,
  LPD3DXPRTBUFFER pDataTotal
);

Parameters

pDataIn
[in] Pointer to an input ID3DXPRTBuffer object that represents the 3D object from the previous light bounce. This input buffer must have the proper number of color channels allocated for the simulation.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that models a single bounce of the subsurface-scattered light. This output buffer must have the proper number of color channels allocated for the simulation.
pDataTotal
[in, out] Pointer to an optional ID3DXPRTBuffer object that is the running sum of all previous pDataOut outputs. May be NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

To model subsurface scattering, call this method for each light bounce after an ID3DXPRTEngine::ComputeDirectLighting method is called.

Use the following calling sequence to model subsurface scattering.

LPD3DXPRTBUFFER pDataA, pDataB, pDataC; // initialization
ID3DXPRTEngine* m_pPRTEngine;

hr = m_pPRTEngine->ComputeDirectLightingSH( SHOrder, pDataA );

// *pDataC should be set to zero. The ComputeSS call will add together the
// direct lighting results from pDataA for non-subsurface scattering elements
// and subsurface scattering results for the subsurface scattering elements.

hr = m_pPRTEngine->ComputeSS( pDataA, pDataB, pDataC );
if ( FAILED( hr ) ) goto Exit;

The output of this method does not include albedo, and only incoming light is integrated in the simulator. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

Call ID3DXPRTEngine::MultiplyAlbedo to multiply each precomputed radiance transfer (PRT) vector by the albedo.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ComputeBounce


ID3DXPRTEngine::ComputeSSAdaptive

Computes a transfer vector that maps source radiance to exit radiance resulting from subsurface scattering, using adaptive sampling and material properties set by ID3DXPRTEngine::SetMeshMaterials. The method generates new vertices and faces on the mesh to more accurately approximate the precomputed radiance transfer (PRT) signal. This method can be used only for materials defined per-vertex in a mesh object.

HRESULT ComputeSSAdaptive(
  LPD3DXPRTBUFFER pDataIn,
  FLOAT AdaptiveThresh,
  FLOAT MinEdgeLength,
  UINT MaxSubdiv,
  LPD3DXPRTBUFFER pDataOut,
  LPD3DXPRTBUFFER pDataTotal
);

Parameters

pDataIn
[in] Pointer to an input ID3DXPRTBuffer object that represents the 3D object from the previous light bounce. This input buffer must have the proper number of color channels allocated for the simulation.
AdaptiveThresh
[in] Threshold on the PRT vector to use for subdividing mesh vertices and faces. If less than 1e-6f, a default value of 1e-6f is specified.
MinEdgeLength
[in] Minimum face edge length that will be generated in adaptive sampling. If the method determines that the value is too small, a model-dependent value is specified.
MaxSubdiv
[in] Maximum level of subdivision of a face that will be used in adaptive sampling. If zero, a default value of 4 is specified.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that models a single bounce of the subsurface-scattered light. This output buffer must have the proper number of color channels allocated for the simulation.
pDataTotal
[in, out] Pointer to an optional ID3DXPRTBuffer object that is the running sum of all previous pDataOut outputs. May be NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

To model subsurface scattering, call this method for each light bounce after an ID3DXPRTEngine::ComputeDirectLightingSHAdaptive method is called.

The output of this method does not include albedo, and only incoming light is integrated in the simulator. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

Call ID3DXPRTEngine::MultiplyAlbedo to multiply each PRT vector by the albedo.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ComputeBounce, ID3DXPRTEngine::ComputeSS


ID3DXPRTEngine::ComputeSurfSamplesBounce

Computes precomputed radiance transfer (PRT) samples for an arbitrary point (and normal vector).

HRESULT ComputeSurfSamplesBounce(
  LPD3DXPRTBUFFER pSurfDataIn,
  UINT NumSamples,
  CONST D3DXVECTOR3 * pSampleLocs,
  CONST D3DXVECTOR3 * pSampleNorms,
  LPD3DXPRTBUFFER pDataOut,
  LPD3DXPRTBUFFER pDataTotal
);

Parameters

pSurfDataIn
[in] Pointer to an input ID3DXPRTBuffer object that represents the source radiance of the 3D object. This input buffer must have the proper number of color channels allocated for the simulation.
NumSamples
[in] Number of sample locations.
pSampleLocs
[in] Position for each sample.
pSampleNorms
[in] Normal vector for each sample location.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that models the direct lighting contribution to the point, using the spherical harmonic (SH) approximation.
pDataTotal
[in, out] Pointer to an optional ID3DXPRTBuffer object that is the running sum of all previous pDataOut outputs. May be NULL.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ComputeSurfSamplesDirectSH


ID3DXPRTEngine::ComputeSurfSamplesDirectSH

Computes, at an arbitrary point not on a mesh, a transfer vector that maps source radiance (represented by a spherical harmonic (SH) approximation) to exit radiance.

HRESULT ComputeSurfSamplesDirectSH(
  UINT SHOrder,
  UINT NumSamples,
  CONST D3DXVECTOR3 * pSampleLocs,
  CONST D3DXVECTOR3 * pSampleNorms,
  LPD3DXPRTBUFFER pDataOut
);

Parameters

SHOrder
[in] Order of the SH approximation to use.
NumSamples
[in] Number of sample locations.
pSampleLocs
[in] Position for each sample.
pSampleNorms
[in] Normal vector for each sample location.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that models the direct lighting contribution to the point, using the SH approximation.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Do not use a texture buffer when calling this method.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ComputeDirectLightingSH, ID3DXPRTEngine::ComputeSurfSamplesBounce


ID3DXPRTEngine::ComputeVolumeSamples

Computes a projection of the direct lighting from the previous light bounce into spherical harmonic (SH) basis vectors that represent incident radiance at specified locations.

HRESULT ComputeVolumeSamples(
  LPD3DXPRTBUFFER pSurfDataIn,
  UINT Order,
  UINT NumVolSamples.xml,
  CONST D3DXVECTOR3 * pSampleLocs,
  LPD3DXPRTBUFFER pDataOut
);

Parameters

pSurfDataIn
[in] Pointer to an input ID3DXPRTBuffer object that represents the 3D object from the previous light bounce.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
NumVolSamples.xml
[in] Number of sample locations.
pSampleLocs
[in] Position for each sample. If pSampleLocs is NULL, ComputeVolumeSamples will compute transfer matrices at every mesh vertex. However, if pSampleLocs is not NULL, you must sample over a sphere (set UseSphere = TRUE and UseCosine = FALSE in ID3DXPRTEngine::SetSamplingInfo); otherwise, ComputeVolumeSamples will return D3DERR_INVALIDCALL.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that projects the direct lighting from the previous light bounce into SH basis vectors. This buffer must have the proper number of color channels allocated for the simulation.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This method computes how the light from the source radiance function is reflected off the surface that represents the scene (pSurfDataIn) and arrives at each point in space specified by pSampleLocs. The SH coefficients represent the mapping, at each pSampleLocs point, of source radiance to transferred incident radiance.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ComputeVolumeSamplesDirectSH


ID3DXPRTEngine::ComputeVolumeSamplesDirectSH

Computes a projection of distant lighting into spherical harmonic (SH) basis vectors that represent incident radiance at specified locations.

HRESULT ComputeVolumeSamplesDirectSH(
  UINT OrderIn,
  UINT OrderOut,
  UINT NumVolSamples.xml,
  CONST D3DXVECTOR3 * pSampleLocs,
  LPD3DXPRTBUFFER pDataOut
);

Parameters

OrderIn
[in] Order of the SH representation of distant lighting. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The degree of the evaluation is OrderIn - 1.
OrderOut
[in] Order of the SH representation of local lighting. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The degree of the evaluation is OrderOut - 1.
NumVolSamples.xml
[in] Number of sample locations.
pSampleLocs
[in] Position for each sample.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that projects the distant lighting into SH basis vectors. This buffer must have the proper number of color channels allocated for the simulation. This method generates OrderIn2 * OrderOut"2 scalars per channel at each sample location.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This method computes how light from a distant source arrives at each point in space specified by pSampleLocs. The SH coefficients represent the mapping, at each pSampleLocs point, of source radiance to transferred incident radiance.

To use this method successfully, you must set sampling over a sphere with UseSphere = TRUE and UseCosine = FALSE in ID3DXPRTEngine::SetSamplingInfo; otherwise, this method will return an error with D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ComputeVolumeSamples


ID3DXPRTEngine::ExtractPerVertexAlbedo

Copies per-vertex albedo values from a mesh.

HRESULT ExtractPerVertexAlbedo(
  LPD3DXMESH pMesh,
  D3DDECLUSAGE Usage,
  UINT NumChanIn
);

Parameters

pMesh
[in] Pointer to the ID3DXMesh mesh object used in D3DXCreatePRTEngine to create the ID3DXPRTEngine object.
Usage
[in] Vertex usage descriptions to copy from the mesh. See D3DDECLUSAGE.
NumChanIn
[in] Number of color channels to copy from the mesh. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::FreeBounceData

Frees memory used for temporary bounced-light simulation data.

HRESULT FreeBounceData();

Parameters

None.

Return Values

The return value is S_OK.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::FreeSSData

Frees memory used for temporary subsurface light scattering simulation data.

HRESULT FreeSSData();

Parameters

None.

Return Values

The return value is D3D_OK.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::GetAdaptedMesh

Returns a mesh with modifications resulting from adaptive spatial sampling. The returned mesh contains only positions, normals, and texture coordinates (if defined).

HRESULT GetAdaptedMesh(
  LPDIRECT3DDEVICE9 pDevice,
  UINT * pFaceRemap,
  UINT * pVertRemap,
  FLOAT * pfVertWeights,
  LPD3DXMESH * ppMesh
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 device that is used to create the output mesh.
pFaceRemap
[in, out] Pointer to the original mesh face that was split to generate the current face.
pVertRemap
[in, out] Pointer to a destination array containing the three original mesh vertices that are the parents of the current vertex.
pfVertWeights
[in, out] Pointer to a destination array containing blending factors for the pVertRemap vertices.
ppMesh
[out] Pointer to the output ID3DXMesh mesh object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

pVertRemap and pfVertWeights can be used to interpolate any per-vertex value over the mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::GetNumFaces

Retrieves the number of faces in the mesh, including any new faces added as a result of adaptive spatial sampling.

UINT GetNumFaces();

Parameters

None.

Return Values

Number of faces in the mesh, including any new faces added as a result of adaptive sampling.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::GetNumVerts

Retrieves the number of vertices in the mesh, including any new vertices added as a result of adaptive spatial sampling.

UINT GetNumVerts();

Parameters

None.

Return Values

Number of vertices in the mesh, including any new vertices added as a result of adaptive sampling.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::GetVertexAlbedo

Retrieves albedo values of the mesh vertices.

HRESULT GetVertexAlbedo(
  D3DXCOLOR * pVertColors,
  UINT NumVerts
);

Parameters

pVertColors
[in, out] Pointer to a destination array of albedo values of the mesh vertices. See D3DXCOLOR.
NumVerts
[in] Number of vertices in the mesh.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::MultiplyAlbedo

Multiplies each precomputed radiance transfer (PRT) vector by the per-vertex albedo.

HRESULT MultiplyAlbedo(
  LPD3DXPRTBUFFER pDataOut
);

Parameters

pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that will contain PRT vectors multiplied by the per-vertex albedo. If this output buffer is a texture object, then care must be taken to store the albedo of the texture at the same resolution as the simulation buffer. You can set the proper resolution on the albedo with D3DXLoadSurfaceFromSurface, applying texture gutter regions if appropriate.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The ID3DXPRTEngine::Computexxx methods compute output buffers in which the light signal has not been multiplied by albedo. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

To include albedo in the rendered-light model, call this method after one of the Computexxx methods.

ID3DXPRTEngine::SetMeshMaterials should be called before calling this method.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ComputeDirectLightingSH


ID3DXPRTEngine::ResampleBuffer

Resamples an input ID3DXPRTBuffer buffer and saves it to an output buffer. This method can be used to convert a vertex buffer to a texture buffer and vice-versa. It can also be used to convert single-channel buffers to 3-channel buffers and vice-versa.

HRESULT ResampleBuffer(
  LPD3DXPRTBUFFER pBufferIn,
  LPD3DXPRTBUFFER pBufferOut
);

Parameters

pBufferIn
[in] Pointer to the input ID3DXPRTBuffer buffer.
pBufferOut
[in, out] Pointer to the output ID3DXPRTBuffer buffer.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::RobustMeshRefine

Subdivides faces on a mesh, allowing for conservative adaptive sampling that will not eliminate features on the mesh.

HRESULT RobustMeshRefine(
  FLOAT MinEdgeLength,
  UINT MaxSubdiv
);

Parameters

MinEdgeLength
[in] Minimum face edge length that will be generated in adaptive sampling. If zero, a reasonable default value will be substituted.
MaxSubdiv
[in] Maximum level of subdivision of a face that will be used in adaptive sampling. If zero, a default value of 5 will be substituted.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ComputeBounceAdaptive, ID3DXPRTEngine::ComputeDirectLightingSHAdaptive


ID3DXPRTEngine::ScaleMeshChunk

Scales all the samples associated with a given submesh. The method is useful for computing subsurface scattering.

HRESULT ScaleMeshChunk(
  UINT uMeshChunk,
  FLOAT fScale,
  LPD3DXPRTBUFFER pDataOut
);

Parameters

uMeshChunk
[in] Location in the mesh at which to start scaling samples.
fScale
[in] Value by which to multiply each vector in the submesh.
pDataOut
[in, out] Pointer to a ID3DXPRTBuffer object to receive rescaled samples in the submesh.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::SetCallBack

Sets a pointer to an optional callback function that computes the percentage of spherical harmonic (SH) computations completed and gives the caller the option of aborting the simulator.

HRESULT SetCallBack(
  LPD3DXSHPRTSIMCB pCB,
  FLOAT Frequency,
  LPVOID lpUserContext
);

Parameters

pCB
[in] Pointer to the LPD3DXSHPRTSIMCB callback function that computes the percentage of SH computations completed. The callback function must be implemented to return S_OK to keep running the simulator. Any other value will abort the simulator.
Frequency
[in] Frequency of callback calls. The inverse of Frequency is approximately the number of times the callback function will be called.
lpUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function.

Return Values

The return value is S_OK.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::SetMeshMaterials

Sets mesh material properties in the 3D scene. Use this method to specify subsurface scattering parameters.

HRESULT SetMeshMaterials(
  CONST D3DXSHMATERIAL ** ppMaterials,
  UINT NumMeshes,
  UINT NumChannels,
  BOOL bSetAlbedo,
  FLOAT fLengthScale
);

Parameters

ppMaterials
[in] Address of a pointer to desired mesh material properties. See D3DXSHMATERIAL.
NumMeshes
[in] Index of the mesh on which to set material properties.
NumChannels
[in] Number of color channels to set in the mesh. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects. If you intend to change this parameter, first set the albedo using another method such as ID3DXPRTEngine::SetPerTexelAlbedo or ID3DXPRTEngine::SetPerVertexAlbedo.
bSetAlbedo
[in] If TRUE, sets the albedo of the mesh to ppMaterials, overwriting all existing texel and vertex albedo values. If FALSE, preserves all existing texel and vertex albedo values set by other methods; NumChannels must match the NumChannels parameter used to create the buffer in D3DXCreatePRTBuffer or D3DXCreatePRTBufferTex.
fLengthScale
[in] Scale of the 3D scene relative to a 1-mm cube. Used for subsurface scattering computations.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::SetMinMaxIntersection

Sets the minimum and maximum distances of intersection between 3D objects. These distance values can be used to control the minimum or maximum distance that objects can shadow or reflect light. For example, the method can be used to limit the shadowing of nearby features of a 3D model.

HRESULT SetMinMaxIntersection(
  FLOAT fMin ,
  FLOAT fMax
);

Parameters

fMin
[in] Minimum intersection distance. Must be positive and less than fMax.
fMax
[in] Maximum intersection distance. If 0.0f, the previous value will be used; otherwise, must be greater than fMin.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This method cannot be used in precomputed radiance transfer (PRT) simulations that run in the GPU. See ID3DXPRTEngine::ComputeDirectLightingSHGPU.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::SetPerTexelAlbedo

Sets an albedo value for each texel, overwriting previous albedo values.

HRESULT SetPerTexelAlbedo(
  LPDIRECT3DTEXTURE9 pAlbedoTexture,
  UINT NumChannels,
  LPD3DXTEXTUREGUTTERHELPER pGH
);

Parameters

pAlbedoTexture
[in] Pointer to an IDirect3DTexture9 texture object in which to store albedo values.
NumChannels
[in] Number of color channels to set. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.
pGH
[in] Optional pointer to an ID3DXTextureGutterHelper object. If not provided, a texture gutter helper object is created and destroyed internally.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORY, D3DERR_WASSTILLDRAWING, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::SetPerTexelNormal

Sets a normal vector for each texel in a texture object. This method is used to store vertex normal vectors from a mesh (or interpolated vertex normals if pixel-based precomputed radiance transfer (PRT) is being computed).

HRESULT SetPerTexelNormal(
  LPDIRECT3DTEXTURE9 pNormalTexture
);

Parameters

pNormalTexture
[in] Pointer to an IDirect3DTexture9 texture object that serves as an object space normal map in which to store normal vectors. The texture must have the same dimensions as ID3DXPRTBuffer and must be able to store signed texture formats.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::SetPerVertexAlbedo

Sets an albedo value for each mesh vertex, overwriting previous albedo values.

HRESULT SetPerVertexAlbedo(
  CONST VOID * pDataIn,
  UINT NumChannels,
  UINT Stride
);

Parameters

pDataIn
[in] Pointer to FLOAT albedo data of the first sample.
NumChannels
[in] Number of color channels to set. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.
Stride
[in] Stride in bytes needed to get to next sample's albedo value. See Width vs. Pitch (Direct3D 9).

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::SetSamplingInfo

Sets sampling properties used by the precomputed radiance transfer (PRT) simulator.

HRESULT SetSamplingInfo(
  UINT NumRays,
  BOOL UseSphere,
  BOOL UseCosine,
  BOOL Adaptive,
  FLOAT AdaptiveThresh
);

Parameters

NumRays
[in] Number of light rays to direct at each sample. Must be greater than zero.
UseSphere
[in] If TRUE, samples will be computed over a full sphere. If FALSE, samples will be computed over a hemisphere.
UseCosine
[in] If TRUE, use a cosine weighting of samples. If both UseCosine and UseSphere are TRUE, the method will fail and an error will be returned.
Adaptive
[in] Must be FALSE. Adaptive sampling is currently not implemented.
AdaptiveThresh
[in] Ignored.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_NOTIMPL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXPRTEngine::ShadowRayIntersects

Uses efficient ray-tracing in precomputed radiance transfer (PRT) simulations to determine whether a ray intersects a mesh. Typically used to determine whether a given point is in shadow.

BOOL ShadowRayIntersects(
  CONST D3DXVECTOR3 * pRayPos,
  CONST D3DXVECTOR3 * pRayDir
);

Parameters

pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the normalized direction of the ray.

Return Values

Returns TRUE if the ray intersects the current mesh; otherwise, returns FALSE.

Remarks

Use ID3DXPRTEngine::SetMinMaxIntersection to set minimum and maximum distances of intersection with the ray.

This method executes faster than ID3DXPRTEngine::ClosestRayIntersects.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPRTEngine::ClosestRayIntersects, ID3DXPRTEngine::SetMinMaxIntersection


ID3DXRenderToEnvMap

The ID3DXRenderToEnvMap interface is used to generalize the process of rendering to environment maps.

ID3DXRenderToEnvMap Members

Method | Description
ID3DXRenderToEnvMap::BeginCube | Initiate the rendering of a cubic environment map.
ID3DXRenderToEnvMap::BeginHemisphere | Initiate the rendering of a hemispheric environment map.
ID3DXRenderToEnvMap::BeginParabolic | Initiate the rendering of a parabolic environment map.
ID3DXRenderToEnvMap::BeginSphere | Initiate the rendering of a spherical environment map.
ID3DXRenderToEnvMap::End | Restore all render targets and, if needed, compose all the rendered faces into the environment map surface.
ID3DXRenderToEnvMap::Face | Initiate the drawing of each face of an environment map.
ID3DXRenderToEnvMap::GetDesc | Retrieves the description of the render surface.
ID3DXRenderToEnvMap::GetDevice | Retrieves the Direct3D device associated with the environment map.
ID3DXRenderToEnvMap::OnLostDevice | Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost, or before resetting a device.
ID3DXRenderToEnvMap::OnResetDevice | Use this method to re-acquire resources and save initial state.

Remarks

An environment map is used to texture-map scene geometry to provide a more sophisticated scene without using complex geometry. This interface supports creating surfaces for the following kinds of geometry: cube, half sphere or hemispheric, parabolic, or sphere.

The ID3DXRenderToEnvMap interface is obtained by calling the D3DXCreateRenderToEnvMap function.

The LPD3DXRenderToEnvMap type is defined as a pointer to the ID3DXRenderToEnvMap interface.

typedef interface ID3DXRenderToEnvMap ID3DXRenderToEnvMap;
typedef interface ID3DXRenderToEnvMap *LPD3DXRenderToEnvMap;

Requirements

Header: Declared in D3dx9core.h.

Library: Use D3dx9.lib.


ID3DXRenderToEnvMap::BeginCube

Initiate the rendering of a cubic environment map.

HRESULT BeginCube(
  LPDIRECT3DCUBETEXTURE9 pCubeTex
);

Parameters

pCubeTex
[in] Pointer to an IDirect3DCubeTexture9 interface that represents the cube texture to which to render.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

See ID3DXRenderToEnvMap::Face to draw each of the 6 faces.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXRenderToEnvMap::End


ID3DXRenderToEnvMap::BeginHemisphere

Initiate the rendering of a hemispheric environment map.

HRESULT BeginHemisphere(
  LPDIRECT3DTEXTURE9 pTexZPos,
  LPDIRECT3DTEXTURE9 pTexZNeg
);

Parameters

pTexZPos
[in] Pointer to an IDirect3DTexture9 interface that represents the positive texture render surface.
pTexZNeg
[in] Pointer to an IDirect3DTexture9 interface that represents the negative texture render surface.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL.

E_FAIL

Remarks

See ID3DXRenderToEnvMap::Face to draw the face.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXRenderToEnvMap::End


ID3DXRenderToEnvMap::BeginParabolic

Initiate the rendering of a parabolic environment map.

HRESULT BeginParabolic(
  LPDIRECT3DTEXTURE9 pTexZPos,
  LPDIRECT3DTEXTURE9 pTexZNeg
);

Parameters

pTexZPos
[in] Pointer to an IDirect3DTexture9 interface that represents the positive render texture.
pTexZNeg
[in] Pointer to an IDirect3DTexture9 interface that represents the negative render texture.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

E_FAIL

Remarks

See ID3DXRenderToEnvMap::Face to draw the faces.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXRenderToEnvMap::End


ID3DXRenderToEnvMap::BeginSphere

Initiate the rendering of a spherical environment map.

HRESULT BeginSphere(
  LPDIRECT3DTEXTURE9 pTex
);

Parameters

pTex
[in] Pointer to an IDirect3DTexture9 interface that represents the texture to which to render.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL.

E_FAIL

Remarks

See ID3DXRenderToEnvMap::Face to draw the face.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXRenderToEnvMap::End


ID3DXRenderToEnvMap::End

Restore all render targets and, if needed, compose all the rendered faces into the environment map surface.

HRESULT End(
  DWORD MipFilter
);

Parameters

MipFilter
[in] A valid combination of one or more D3DX_FILTER flags.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXRenderToEnvMap::Face


ID3DXRenderToEnvMap::Face

Initiate the drawing of each face of an environment map.

HRESULT Face(
  D3DCUBEMAP_FACES Face,
  DWORD MipFilter
);

Parameters

Face
[in] The first face of the environmental cube map. See D3DCUBEMAP_FACES.
MipFilter
[in] A valid combination of one or more D3DX_FILTER flags.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method must be called once for each type of environment map. The only exception is a cubic environment map which requires this method to be called six times, once for each face in D3DCUBEMAP_FACES. For more information, see Environment Mapping (Direct3D 9).

Requirements

Header: Declared in D3dx9core.h.


ID3DXRenderToEnvMap::GetDesc

Retrieves the description of the render surface.

HRESULT GetDesc(
  D3DXRTE_DESC * pDesc
);

Parameters

pDesc
[out] Pointer to a D3DXRTE_DESC structure that describes the rendering surface.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9core.h.


ID3DXRenderToEnvMap::GetDevice

Retrieves the Direct3D device associated with the environment map.

HRESULT GetDevice(
  LPDIRECT3DDEVICE9 * ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface that represents the Direct3D device object associated with the environment map.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL. Calling this method increases the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx9core.h.


ID3DXRenderToEnvMap::OnLostDevice

Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost, or before resetting a device.

HRESULT OnLostDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method should be called whenever the device is lost or before the user calls IDirect3DDevice9::Reset. Even if the device was not actually lost, ID3DXRenderToEnvMap::OnLostDevice is responsible for freeing stateblocks and other resources that may need to be released before resetting the device. As a result, the font object cannot be used again before calling IDirect3DDevice9::Reset and then ID3DXRenderToEnvMap::OnResetDevice.

Requirements

Header: Declared in D3dx9core.h.


ID3DXRenderToEnvMap::OnResetDevice

Use this method to re-acquire resources and save initial state.

HRESULT OnResetDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXRenderToEnvMap::OnResetDevice should be called each time the device is reset (using IDirect3DDevice9::Reset), before any other methods are called. This is a good place to re-acquire video-memory resources and capture state blocks.

Requirements

Header: Declared in D3dx9core.h.


ID3DXRenderToSurface

The ID3DXRenderToSurface interface is used to generalize the process of rendering to surfaces.

ID3DXRenderToSurface Members

Method | Description
ID3DXRenderToSurface::BeginScene | Begins a scene.
ID3DXRenderToSurface::EndScene | Ends a scene.
ID3DXRenderToSurface::GetDesc | Retrieves the parameters of the render surface.
ID3DXRenderToSurface::GetDevice | Retrieves the Direct3D device associated with the render surface.
ID3DXRenderToSurface::OnLostDevice | Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost or before resetting a device.
ID3DXRenderToSurface::OnResetDevice | Use this method to re-acquire resources and save initial state.

Remarks

Surfaces can be used in a variety of ways including render targets, off-screen rendering, or rendering to textures.

A surface can be configured using a separate viewport using the ID3DXRenderToSurface::BeginScene method, to provide a custom render view. If the surface is not a render target, a compatible render target is used, and the result is copied to the surface at the end of the scene.

The ID3DXRenderToSurface interface is obtained by calling the D3DXCreateRenderToSurface function.

The LPD3DXRENDERTOSURFACE type is defined as a pointer to the ID3DXRenderToSurface interface.

typedef interface ID3DXRenderToSurface ID3DXRenderToSurface;
typedef interface ID3DXRenderToSurface *LPD3DXRENDERTOSURFACE;

Requirements

Header: Declared in D3dx9core.h.

Library: Use D3dx9.lib.


ID3DXRenderToSurface::BeginScene

Begins a scene.

HRESULT BeginScene(
  LPDIRECT3DSURFACE9 pSurface,
  CONST D3DVIEWPORT9 * pViewport
);

Parameters

pSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the render surface.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, describing the viewport for the scene.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DERR_OUTOFVIDEOMEMORY D3DXERR_INVALIDDATA E_OUTOFMEMORY

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXRenderToSurface::EndScene


ID3DXRenderToSurface::EndScene

Ends a scene.

HRESULT EndScene(
  DWORD MipFilter
);

Parameters

MipFilter
[in] Filter options, enumerated in D3DX_FILTER.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXRenderToSurface::BeginScene


ID3DXRenderToSurface::GetDesc

Retrieves the parameters of the render surface.

HRESULT GetDesc(
  D3DXRTS_DESC * pParameters
);

Parameters

pParameters
[out] Pointer to a D3DXRTS_DESC structure, describing the parameters of the render surface.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9core.h.


ID3DXRenderToSurface::GetDevice

Retrieves the Direct3D device associated with the render surface.

HRESULT GetDevice(
  LPDIRECT3DDEVICE9 * ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the render surface.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL. Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx9core.h.


ID3DXRenderToSurface::OnLostDevice

Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost or before resetting a device.

HRESULT OnLostDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method should be called whenever the device is lost or before the user calls IDirect3DDevice9::Reset. Even if the device was not actually lost, ID3DXRenderToSurface::OnLostDevice is responsible for freeing stateblocks and other resources that may need to be released before resetting the device. As a result, the font object cannot be used again before calling IDirect3DDevice9::Reset and then ID3DXRenderToSurface::OnResetDevice.

Requirements

Header: Declared in D3dx9core.h.


ID3DXRenderToSurface::OnResetDevice

Use this method to re-acquire resources and save initial state.

HRESULT OnResetDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXRenderToSurface::OnResetDevice should be called each time the device is reset (using IDirect3DDevice9::Reset), before any other methods are called. This is a good place to re-acquire video-memory resources and capture state blocks.

Requirements

Header: Declared in D3dx9core.h.


ID3DXSaveUserData

This interface is implemented by the application to save any additional user data embedded in .x files. An instance of this interface is passed to D3DXSaveMeshHierarchyToFile, and D3DX calls the appropriate method on this interface every time the appropriate data is encountered. For example, for each frame object in the .x file, ID3DXSaveUserData::AddFrameChildData is called and passed the child data.

ID3DXSaveUserData Members

Method | Description
ID3DXSaveUserData::AddFrameChildData | Add child data to the frame.
ID3DXSaveUserData::AddMeshChildData | Add child data to the mesh.
ID3DXSaveUserData::AddTopLevelDataObjectsPost | Add a top level object after the frame hierarchy.
ID3DXSaveUserData::AddTopLevelDataObjectsPre | Add a top level object before the frame hierarchy.
ID3DXSaveUserData::RegisterTemplates | A callback for the user to register a .x file template.
ID3DXSaveUserData::SaveTemplates | A callback for the user to save a .x file template.

Remarks

The LPD3DXSAVEUSERDATA type is defined as a pointer to this interface.

typedef interface ID3DXSaveUserData ID3DXSaveUserData;
typedef interface ID3DXSaveUserData *LPD3DXSAVEUSERDATA;

Requirements

Header: Declared in D3dx9anim.h.

Library: Use D3dx9.lib.


ID3DXSaveUserData::AddFrameChildData

Add child data to the frame.

HRESULT AddFrameChildData(
  CONST D3DXFRAME * pFrame,
  LPD3DXFILESAVEOBJECT pXofSave,
  LPD3DXFileSaveData pXofFrameData
);

Parameters

pFrame
[in] Pointer to a mesh container. See D3DXFRAME.
pXofSave
[in] Pointer to a .x file save object. Use the pointer to call ID3DXFileSaveObject::AddDataObject to add a child data object. Do not save the data with ID3DXFileSaveObject::Save.
pXofFrameData
[in] Pointer to a .x file data node. Use the pointer to call ID3DXFileSaveData::AddDataObject to add a child data object.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Remarks

ID3DXSaveUserData::RegisterTemplates and ID3DXSaveUserData::SaveTemplates provide a mechanism for adding a template to a .x file for saving user data.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXSaveUserData::AddMeshChildData

Add child data to the mesh.

HRESULT AddMeshChildData(
  CONST D3DXMESHCONTAINER * pMeshContainer,
  LPD3DXFILESAVEOBJECT pXofSave,
  LPD3DXFileSaveData pXofMeshData
);

Parameters

pMeshContainer
[in] Pointer to a mesh container. See D3DXMESHCONTAINER.
pXofSave
[in] Pointer to a .x file save object. Use the pointer to call ID3DXFileSaveObject::AddDataObject to add a child data object. Do not save the data with ID3DXFileSaveObject::Save.
pXofMeshData
[in] Pointer to a .x file data node. Use the pointer to call ID3DXFileSaveData::AddDataObject to add a child data object.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXSaveUserData::AddTopLevelDataObjectsPost

Add a top level object after the frame hierarchy.

HRESULT AddTopLevelDataObjectsPost(
  LPD3DXFILESAVEOBJECT pXofSave
);

Parameters

pXofSave
[in] Pointer to a .x file save object. Use this pointer to call IDirectXFileSaveObject::CreateDataObject to create the data object to be saved. Then call IDirectXFileSaveObject::SaveData to save the data.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXSaveUserData::AddTopLevelDataObjectsPre

Add a top level object before the frame hierarchy.

HRESULT AddTopLevelDataObjectsPre(
  LPD3DXFILESAVEOBJECT pXofSave
);

Parameters

pXofSave
[in] Pointer to a .x file save object. Use this pointer to call IDirectXFileSaveObject::CreateDataObject to create the data object to be saved. Then call IDirectXFileSaveObject::SaveData to save the data.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXSaveUserData::RegisterTemplates

A callback for the user to register a .x file template.

HRESULT RegisterTemplates(
  LPD3DXFILE pXFileApi
);

Parameters

pXFileApi
[in] Use this pointer to register user-defined .x file templates. See ID3DXFile. Do not use this parameter to add data objects.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Remarks

ID3DXSaveUserData::RegisterTemplates and ID3DXSaveUserData::SaveTemplates provide a mechanism for adding a template to a .x file for saving user data.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXSaveUserData::SaveTemplates

A callback for the user to save a .x file template.

HRESULT SaveTemplates(
  LPD3DXFILESAVEOBJECT pXofSave
);

Parameters

pXofSave
[in] Pointer to a .x file save object. Do not use this parameter to add data objects. See ID3DXFileSaveObject.

Return Values

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Remarks

ID3DXSaveUserData::RegisterTemplates and ID3DXSaveUserData::SaveTemplates provide a mechanism for adding a template to a .x file for saving user data.

Requirements

Header: Declared in D3dx9anim.h.


ID3DXSkinInfo

Applications use the methods of the ID3DXSkinInfo interface to manipulate bone matrices, which are used to skin vertex data for animation. This interface is no longer strictly tied to ID3DXMesh and can be used to skin any set of vertex data.

ID3DXSkinInfo Members

Method | Description
ID3DXSkinInfo::Clone | Clones a skin info object.
ID3DXSkinInfo::ConvertToBlendedMesh | Takes a mesh and returns a new mesh with per-vertex blend weights and a bone combination table. The table describes which bones affect which subsets of the mesh.
ID3DXSkinInfo::ConvertToIndexedBlendedMesh | Takes a mesh and returns a new mesh with per-vertex blend weights, indices, and a bone combination table. The table describes which bone palettes affect which subsets of the mesh.
ID3DXSkinInfo::FindBoneVertexInfluenceIndex | Retrieves the index of the bone influence affecting a single vertex.
ID3DXSkinInfo::GetBoneInfluence | Gets the vertices and weights that a bone influences.
ID3DXSkinInfo::GetBoneName | Gets the bone name, from the bone index.
ID3DXSkinInfo::GetBoneOffsetMatrix | Gets the bone offset matrix.
ID3DXSkinInfo::GetBoneVertexInfluence | Retrieves the blend factor and vertex affected by a specified bone influence.
ID3DXSkinInfo::GetDeclaration | Gets the vertex declaration.
ID3DXSkinInfo::GetFVF | Gets the fixed function vertex value.
ID3DXSkinInfo::GetMaxFaceInfluences | Gets the maximum face influences in a triangle mesh with the specified index buffer.
ID3DXSkinInfo::GetMaxVertexInfluences | Gets the maximum number of influences for any vertex in the mesh.
ID3DXSkinInfo::GetMinBoneInfluence | Gets the minimum bone influence. Influence values smaller than this are ignored.
ID3DXSkinInfo::GetNumBoneInfluences | Gets the number of influences for a bone.
ID3DXSkinInfo::GetNumBones | Gets the number of bones.
ID3DXSkinInfo::Remap | Updates bone influence information to match vertices after they are reordered. This method should be called if the target vertex buffer has been reordered externally.
ID3DXSkinInfo::SetBoneInfluence | Sets the influence value for a bone.
ID3DXSkinInfo::SetBoneName | Sets the bone name.
ID3DXSkinInfo::SetBoneOffsetMatrix | Sets the bone offset matrix.
ID3DXSkinInfo::SetBoneVertexInfluence | Sets an influence value of a bone on a single vertex.
ID3DXSkinInfo::SetDeclaration | Sets the vertex declaration.
ID3DXSkinInfo::SetFVF | Sets the flexible vertex format (FVF) type.
ID3DXSkinInfo::SetMinBoneInfluence | Sets the minimum bone influence. Influence values smaller than this are ignored.
ID3DXSkinInfo::UpdateSkinnedMesh | Applies software skinning to the target vertices based on the current matrices.

Remarks

Create a ID3DXSkinInfo interface with D3DXCreateSkinInfo, D3DXCreateSkinInfoFromBlendedMesh, or D3DXCreateSkinInfoFVF.

The LPD3DXSKININFO type is defined as a pointer to the ID3DXSkinInfo interface.

typedef struct ID3DXSkinInfo *LPD3DXSKININFO;

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXSkinInfo::Clone

Clones a skin info object.

HRESULT Clone(
  LPD3DXSKININFO * ppSkinInfo
);

Parameters

ppSkinInfo
[in, out] Address of a pointer to an ID3DXSkinInfo object, which will contain the cloned object if the method is successful.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSkinInfo::ConvertToBlendedMesh

Takes a mesh and returns a new mesh with per-vertex blend weights and a bone combination table. The table describes which bones affect which subsets of the mesh.

HRESULT ConvertToBlendedMesh(
  LPD3DXMESH pMesh,
  DWORD Options,
  CONST DWORD * pAdjacencyIn,
  LPDWORD pAdjacencyOut,
  DWORD * pFaceRemap,
  LPD3DXBUFFER * ppVertexRemap,
  DWORD * pMaxVertexInfl,
  DWORD * pNumBoneCombinations,
  LPD3DXBUFFER * ppBoneCombinationTable,
  LPD3DXMESH * ppMesh
);

Parameters

pMesh
[in] Input mesh. See ID3DXMesh.
Options
[in] Currently unused.
pAdjacencyIn
[in] Input mesh adjacency information.
pAdjacencyOut
[in] Output mesh adjacency information.
pFaceRemap
[out] An array of DWORDs, one per face, that identifies the original mesh face that corresponds to each face in the blended mesh. If the value supplied for this argument is NULL, face remap data is not returned.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, which contains a DWORD for each vertex that specifies how the new vertices map to the old vertices. This remap is useful if you need to alter external data based on the new vertex mapping. This parameter is optional; NULL may be used.
pMaxVertexInfl
[out] Pointer to a DWORD that will contain the maximum number of bone influences required per vertex for this skinning method.
pNumBoneCombinations
[out] Pointer to the number of bones in the bone combination table.
ppBoneCombinationTable
[out] Pointer to the bone combination table. The data is organized in a D3DXBONECOMBINATION structure.
ppMesh
[out] Pointer to the new mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each element in the remap array specifies the previous index for that position. For example, if a vertex was in position 3 but has been remapped to position 5, then the fifth element of pVertexRemap will contain 3.

This method does not run on hardware that does not support fixed-function vertex blending.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSkinInfo::ConvertToIndexedBlendedMesh

Takes a mesh and returns a new mesh with per-vertex blend weights, indices, and a bone combination table. The table describes which bone palettes affect which subsets of the mesh.

HRESULT ConvertToIndexedBlendedMesh(
  LPD3DXMESH pMesh,
  DWORD Options,
  DWORD paletteSize,
  CONST DWORD * pAdjacencyIn,
  LPDWORD pAdjacencyOut,
  DWORD * pFaceRemap,
  LPD3DXBUFFER * ppVertexRemap,
  DWORD * pMaxVertexInfl,
  DWORD * pNumBoneCombinations,
  LPD3DXBUFFER * ppBoneCombinationTable,
  LPD3DXMESH * ppMesh
);

Parameters

pMesh
[in] The input mesh. See ID3DXMesh.
Options
[in] Currently unused.
paletteSize
[in] Number of bone matrices available for matrix palette skinning.
pAdjacencyIn
[in] Input mesh adjacency information.
pAdjacencyOut
[in] Output mesh adjacency information.
pFaceRemap
[out] An array of DWORDs, one per face, that identifies the original mesh face that corresponds to each face in the blended mesh. If the value supplied for this argument is NULL, face remap data is not returned.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, which contains a DWORD for each vertex that specifies how the new vertices map to the old vertices. This remap is useful if you need to alter external data based on the new vertex mapping. This parameter is optional; NULL may be used.
pMaxVertexInfl
[out] Pointer to a DWORD that will contain the maximum number of bone influences required per vertex for this skinning method.
pNumBoneCombinations
[out] Pointer to the number of bones in the bone combination table.
ppBoneCombinationTable
[out] Pointer to the bone combination table. The data is organized in a D3DXBONECOMBINATION structure.
ppMesh
[out] Pointer to the new mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each element in the remap arrays specifies the previous index for that position. For example, if a vertex was in position 3 but has been remapped to position 5, then the fifth element of pVertexRemap will contain 3.

This method does not run on hardware that does not support fixed-function vertex blending.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSkinInfo::FindBoneVertexInfluenceIndex

Retrieves the index of the bone influence affecting a single vertex.

HRESULT FindBoneVertexInfluenceIndex(
  DWORD boneNum,
  DWORD vertexNum,
  DWORD * pInfluenceIndex
);

Parameters

boneNum
[in] Index of the bone. Must be between 0 and the number of bones.
vertexNum
[in] Index of the vertex for which the bone influence is to be found. Must be between 0 and the number of vertices in the mesh.
pInfluenceIndex
[in, out] Pointer to the index of the bone influence that affects vertexNum.

Return Values

If the method succeeds, the return value is S_OK. If the specified bone does not influence the given vertex, S_FALSE is returned. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::GetBoneVertexInfluence, ID3DXSkinInfo::SetBoneVertexInfluence, ID3DXSkinInfo::GetBoneInfluence


ID3DXSkinInfo::GetBoneInfluence

Gets the vertices and weights that a bone influences.

HRESULT GetBoneInfluence(
  DWORD Bone,
  DWORD * vertices,
  FLOAT * weights
);

Parameters

Bone
[in] Bone number.
vertices
[in, out] Get the array of vertices influenced by a bone.
weights
[in, out] Get the array of weights influenced by a bone.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Use ID3DXSkinInfo::GetNumBoneInfluences to find out how many vertices the bone influences.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::SetBoneInfluence


ID3DXSkinInfo::GetBoneName

Gets the bone name, from the bone index.

LPCSTR GetBoneName(
  DWORD Bone
);

Parameters

Bone
[in] Bone number.

Return Values

Returns the bone name. Do not free this string.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::SetBoneName, ID3DXSkinInfo::GetNumBones


ID3DXSkinInfo::GetBoneOffsetMatrix

Gets the bone offset matrix.

LPD3DXMATRIX GetBoneOffsetMatrix(
  DWORD Bone
);

Parameters

Bone
[in] Bone number.

Return Values

Returns a pointer to the bone offset matrix. Do not free this pointer.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::SetBoneOffsetMatrix, ID3DXSkinInfo::GetNumBones


ID3DXSkinInfo::GetBoneVertexInfluence

Retrieves the blend factor and vertex affected by a specified bone influence.

HRESULT GetBoneVertexInfluence(
  DWORD boneNum,
  DWORD influenceNum,
  FLOAT * pWeight,
  DWORD * pVertexNum
);

Parameters

boneNum
[in] Index of the bone. Must be between 0 and the number of bones.
influenceNum
[in] Index of the influence array of the specified bone.
pWeight
[in, out] Pointer to the blend factor influenced by influenceNum.
pVertexNum
[in, out] Pointer to the vertex influenced by influenceNum.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::SetBoneVertexInfluence, ID3DXSkinInfo::FindBoneVertexInfluenceIndex, ID3DXSkinInfo::GetBoneInfluence


ID3DXSkinInfo::GetDeclaration

Gets the vertex declaration.

HRESULT GetDeclaration(
  D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::SetDeclaration


ID3DXSkinInfo::GetFVF

Gets the fixed function vertex value.

DWORD GetFVF();

Parameters

None.

Return Values

Returns the flexible vertex format (FVF) codes.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::SetFVF


ID3DXSkinInfo::GetMaxFaceInfluences

Gets the maximum face influences in a triangle mesh with the specified index buffer.

HRESULT GetMaxFaceInfluences(
  LPDIRECT3DINDEXBUFFER9 pIB,
  DWORD NumFaces,
  DWORD * maxFaceInfluences
);

Parameters

pIB
[in] Pointer to the index buffer that contains the mesh index data.
NumFaces
[in] Number of faces in the mesh.
maxFaceInfluences
[in] Pointer to the maximum face influences.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSkinInfo::GetMaxVertexInfluences

Gets the maximum number of influences for any vertex in the mesh.

HRESULT GetMaxVertexInfluences(
  DWORD * maxVertexInfluences
);

Parameters

maxVertexInfluences
[in] Pointer to the maximum vertex influence.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSkinInfo::GetMinBoneInfluence

Gets the minimum bone influence. Influence values smaller than this are ignored.

FLOAT GetMinBoneInfluence();

Parameters

None.

Return Values

Returns the minimum bone influence value.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::SetMinBoneInfluence


ID3DXSkinInfo::GetNumBoneInfluences

Gets the number of influences for a bone.

DWORD GetNumBoneInfluences(
  DWORD bone
);

Parameters

bone
[in] Bone number.

Return Values

Returns the number of influences for a bone.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSkinInfo::GetNumBones

Gets the number of bones.

DWORD GetNumBones();

Parameters

None.

Return Values

Returns the number of bones.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSkinInfo::Remap

Updates bone influence information to match vertices after they are reordered. This method should be called if the target vertex buffer has been reordered externally.

HRESULT Remap(
  DWORD NumVertices,
  DWORD * pVertexRemap
);

Parameters

NumVertices
[in] Number of vertices to remap.
pVertexRemap
[in] Array of DWORDS whose length is specified by NumVertices.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each element in pVertexRemap specifies the previous vertex index for that position. For example, if a vertex was in position 3 but has been remapped to position 5, then the fifth element of pVertexRemap should contain 3. The vertex remap array returned by ID3DXMesh::Optimize can be used.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSkinInfo::SetBoneInfluence

Sets the influence value for a bone.

HRESULT SetBoneInfluence(
  DWORD Bone,
  DWORD numInfluences,
  CONST DWORD * vertices,
  CONST FLOAT * weights
);

Parameters

Bone
[in] Bone number.
numInfluences
[in] Number of influences.
vertices
[in] The array of vertices influenced by a bone.
weights
[in] The array of weights influenced by a bone.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::GetBoneInfluence, ID3DXSkinInfo::GetNumBoneInfluences


ID3DXSkinInfo::SetBoneName

Sets the bone name.

HRESULT SetBoneName(
  DWORD Bone,
  LPCSTR pName
);

Parameters

Bone
[in] Bone number
pName
[in] Bone name

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Bone names are returned by D3DXLoadMeshFromXof.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::GetBoneName


ID3DXSkinInfo::SetBoneOffsetMatrix

Sets the bone offset matrix.

HRESULT SetBoneOffsetMatrix(
  DWORD Bone,
  CONST D3DXMATRIX * pBoneTransform
);

Parameters

Bone
[in] Bone number.
pBoneTransform
[in] Pointer to the bone offset matrix.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Bone names are returned by D3DXLoadMeshFromXof.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::GetBoneOffsetMatrix


ID3DXSkinInfo::SetBoneVertexInfluence

Sets an influence value of a bone on a single vertex.

HRESULT SetBoneVertexInfluence(
  DWORD boneNum,
  DWORD influenceNum,
  FLOAT weight
);

Parameters

boneNum
[in] Index of the bone. Must be between 0 and the number of bones.
influenceNum
[in] Index of the influence array of the specified bone.
weight
[in] Blend factor of the specified bone influence.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::GetBoneVertexInfluence, ID3DXSkinInfo::FindBoneVertexInfluenceIndex, ID3DXSkinInfo::GetBoneInfluence


ID3DXSkinInfo::SetDeclaration

Sets the vertex declaration.

HRESULT SetDeclaration(
  CONST D3DVERTEXELEMENT9 * pDeclaration
);

Parameters

pDeclaration
[in] Pointer to an array of D3DVERTEXELEMENT9 elements.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::GetDeclaration


ID3DXSkinInfo::SetFVF

Sets the flexible vertex format (FVF) type.

HRESULT SetFVF(
  DWORD FVF
);

Parameters

FVF
[in] Flexible vertex format. See D3DFVF.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSkinInfo::SetMinBoneInfluence

Sets the minimum bone influence. Influence values smaller than this are ignored.

HRESULT SetMinBoneInfluence(
  FLOAT MinInfl
);

Parameters

MinInfl
[in] Minimum influence value. Influence values smaller than this are ignored.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::GetMinBoneInfluence


ID3DXSkinInfo::UpdateSkinnedMesh

Applies software skinning to the target vertices based on the current matrices.

HRESULT UpdateSkinnedMesh(
  CONST D3DXMATRIX * pBoneTransforms,
  CONST D3DXMATRIX * pBoneInvTransposeTransforms,
  LPCVOID pVerticesSrc,
  PVOID pVerticesDst
);

Parameters

pBoneTransforms
[in] Bone transform matrix.
pBoneInvTransposeTransforms
[in] Inverse transpose of the bone transform matrix.
pVerticesSrc
[in] Pointer to the buffer containing the source vertices.
pVerticesDst
[in] Pointer to the buffer containing the destination vertices.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When used to skin vertices with two position elements, this method skins the second position element with the inverse of the bone instead of the bone itself.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSPMesh

Applications use the methods of the ID3DXSPMesh interface to manipulate simplification mesh objects. A simplification mesh is used to simplify a given mesh to a lower number of faces.

ID3DXSPMesh Members

Method | Description
ID3DXSPMesh::CloneMesh | Clones a mesh using a declarator.
ID3DXSPMesh::CloneMeshFVF | Clones a mesh using a flexible vertex format (FVF) code.
ID3DXSPMesh::ClonePMesh | Clones a progressive mesh using a declarator.
ID3DXSPMesh::ClonePMeshFVF | Clones a progressive mesh using a flexible vertex format (FVF) code.
ID3DXSPMesh::GetDeclaration | Retrieves a declaration describing the vertices in the mesh.
ID3DXSPMesh::GetDevice | Retrieves the device object associated with the simplification mesh.
ID3DXSPMesh::GetFVF | Retrieves the flexible vertex format (FVF) of the vertices in the simplification mesh.
ID3DXSPMesh::GetMaxFaces | Retrieves the maximum number of faces that the simplification mesh supports.
ID3DXSPMesh::GetMaxVertices | Retrieves the maximum number of vertices that the simplification mesh supports.
ID3DXSPMesh::GetNumFaces | Retrieves the number of faces in the simplification mesh.
ID3DXSPMesh::GetNumVertices | Retrieves the number of vertices in the simplification mesh.
ID3DXSPMesh::GetOptions | Retrieves the mesh options enabled for this simplification mesh at creation time.
ID3DXSPMesh::GetVertexAttributeWeights | Retrieves the per-vertex attribute weights used to create the ID3DXSPMesh object.
ID3DXSPMesh::GetVertexWeights | Retrieves the per-vertex weights used to create the ID3DXSPMesh object.
ID3DXSPMesh::ReduceFaces | Reduces the number of faces in a simplification mesh.
ID3DXSPMesh::ReduceVertices | Reduces the number of vertices in a simplification mesh.

Remarks

The ID3DXSPMesh interface is obtained by calling the D3DXCreateSPMesh function.

The LPD3DXSPMESH> type is defined as a pointer to the ID3DXSPMesh interface.

typedef struct ID3DXSPMesh *LPD3DXSPMESH;

See Also

Mesh Functions

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXSPMesh::CloneMesh

Clones a mesh using a declarator.

HRESULT CloneMesh(
  DWORD Options,
  CONST D3DVERTEXELEMENT9 * pDeclaration,
  LPDIRECT3DDEVICE9 pDevice,
  DWORD * pAdjacencyOut,
  DWORD * pVertexRemapOut,
  LPD3DXMESH * ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, specifying the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face, specifying the three neighbors for each face in the source mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSPMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXSPMesh::CloneMeshFVF

Clones a mesh using a flexible vertex format (FVF) code.

HRESULT CloneMeshFVF(
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE9 pD3DDevice,
  DWORD * pAdjacencyOut,
  DWORD * pVertexRemapOut,
  LPD3DXMESH * ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, specifying the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face, specifying the three neighbors for each face in the source mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

CloneMeshFVF can be used to convert a mesh from one FVF to another.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSPMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXSPMesh::ClonePMesh

Clones a progressive mesh using a declarator.

HRESULT ClonePMesh(
  DWORD Options,
  CONST D3DVERTEXELEMENT9 * pDeclaration,
  LPDIRECT3DDEVICE9 pD3DDevice,
  DWORD * pVertexRemapOut,
  FLOAT * pErrorsByFace,
  LPD3DXPMESH * ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh. The following flags are defined.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements describing the vertex format for the returned mesh. This parameter must map directly to an flexible vertex format (FVF).
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
pErrorsByFace
[out] Pointer to an array containing error values.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DXERR_CANNOTATTRSORT

E_OUTOFMEMORY

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSPMesh::ClonePMeshFVF

Clones a progressive mesh using a flexible vertex format (FVF) code.

HRESULT ClonePMeshFVF(
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE9 pD3DDevice,
  DWORD * pVertexRemapOut,
  FLOAT * pErrorsByFace,
  LPD3DXPMESH * ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, specifying the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
pErrorsByFace
[out] Pointer to an array containing error values.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DXERR_CANNOTATTRSORT

E_OUTOFMEMORY

Remarks

ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSPMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXSPMesh::GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

HRESULT GetDeclaration(
  D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSPMesh::GetFVF


ID3DXSPMesh::GetDevice

Retrieves the device object associated with the simplification mesh.

HRESULT GetDevice(
  LPDIRECT3DDEVICE9 * ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the simplification mesh.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL. Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSPMesh::GetFVF

Retrieves the flexible vertex format (FVF) of the vertices in the simplification mesh.

DWORD GetFVF();

Parameters

None.

Return Values

Returns an FVF that describes the vertex format of the vertices in the simplification mesh.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSPMesh::GetDeclaration


ID3DXSPMesh::GetMaxFaces

Retrieves the maximum number of faces that the simplification mesh supports.

DWORD GetMaxFaces();

Parameters

None.

Return Values

Returns the maximum number of faces in the original mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSPMesh::GetMaxVertices

Retrieves the maximum number of vertices that the simplification mesh supports.

DWORD GetMaxVertices();

Parameters

None.

Return Values

Returns the maximum number of vertices in the original mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSPMesh::GetNumFaces

Retrieves the number of faces in the simplification mesh.

DWORD GetNumFaces();

Parameters

None.

Return Values

Returns the number of faces in the simplification mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSPMesh::GetNumVertices

Retrieves the number of vertices in the simplification mesh.

DWORD GetNumVertices();

Parameters

None.

Return Values

Returns the number of vertices in the simplification mesh.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSPMesh::GetOptions

Retrieves the mesh options enabled for this simplification mesh at creation time.

DWORD GetOptions();

Parameters

None.

Return Values

Returns a combination of one or more flags from the D3DXMESH enumeration, indicating the options enabled for this mesh at creation time.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSPMesh::GetVertexAttributeWeights

Retrieves the per-vertex attribute weights used to create the ID3DXSPMesh object.

HRESULT GetVertexAttributeWeights(
  LPD3DXATTRIBUTEWEIGHTS pVertexAttributeWeights
);

Parameters

pVertexAttributeWeights
[out] Array of vertex attribute weights. See D3DXATTRIBUTEWEIGHTS.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXCreateSPMesh


ID3DXSPMesh::GetVertexWeights

Retrieves the per-vertex weights used to create the ID3DXSPMesh object.

HRESULT GetVertexWeights(
  FLOAT * pVertexWeights
);

Parameters

pVertexWeights
[in, out] Array of floats that will be filled with vertex weights. Each float contains one vertex. The array should be large enough to handle the maximum number of vertices in the original ID3DXMesh (which was used to create the simplification mesh).

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXCreateSPMesh


ID3DXSPMesh::ReduceFaces

Reduces the number of faces in a simplification mesh.

HRESULT ReduceFaces(
  DWORD Faces
);

Parameters

Faces
[in] Number of faces to which to reduce the primitive count.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method performs edge collapses to reduce the number of primitives to the value specified in Faces. It is not always possible to reduce a mesh to the requested value due to certain restrictions.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSPMesh::ReduceVertices

Reduces the number of vertices in a simplification mesh.

HRESULT ReduceVertices(
  DWORD Vertices
);

Parameters

Vertices
[in] Number of vertices to which to reduce the primitive count.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method performs edge collapses to reduce the number of primitives to the value specified in Vertices. It is not always possible to reduce a mesh to the requested value due to certain restrictions.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXSprite

The ID3DXSprite interface provides a set of methods that simplify the process of drawing sprites using Microsoft Direct3D.

ID3DXSprite Members

Method | Description
ID3DXSprite::Begin | Prepares a device for drawing sprites.
ID3DXSprite::Draw | Adds a sprite to the list of batched sprites.
ID3DXSprite::End | Calls ID3DXSprite::Flush and restores the device state to how it was before ID3DXSprite::Begin was called.
ID3DXSprite::Flush | Forces all batched sprites to be submitted to the device. Device states remain as they were after the last call to ID3DXSprite::Begin. The list of batched sprites is then cleared.
ID3DXSprite::GetDevice | Retrieves the device associated with the sprite object.
ID3DXSprite::GetTransform | Gets the sprite transform.
ID3DXSprite::OnLostDevice | Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost or before resetting a device.
ID3DXSprite::OnResetDevice | Use this method to re-acquire resources and save initial state.
ID3DXSprite::SetTransform | Sets the sprite transform.
ID3DXSprite::SetWorldViewLH | Sets the left-handed world-view transform for a sprite. A call to this method is required before billboarding or sorting sprites.
ID3DXSprite::SetWorldViewRH | Sets the right-handed world-view transform for a sprite. A call to this method is required before billboarding or sorting sprites.

Remarks

The ID3DXSprite interface is obtained by calling the D3DXCreateSprite function.

The application typically first calls ID3DXSprite::Begin, which allows control over the device render state, alpha blending, and sprite transformation and sorting. Then for each sprite to be displayed, call ID3DXSprite::Draw. ID3DXSprite::Draw can be called repeatedly to store any number of sprites. To display the batched sprites to the device, call ID3DXSprite::End or ID3DXSprite::Flush.

The LPD3DXSPRITE type is defined as a pointer to the ID3DXSprite interface.

typedef interface ID3DXSprite ID3DXSprite;
typedef interface ID3DXSprite *LPD3DXSPRITE;

Requirements

Header: Declared in D3dx9core.h.

Library: Use D3dx9.lib.


ID3DXSprite::Begin

Prepares a device for drawing sprites.

HRESULT Begin(
  DWORD Flags
);

Parameters

Flags
[in] Combination of zero or more flags that describe sprite rendering options. For this method, the valid flags are:
  • D3DXSPRITE_ALPHABLEND
  • D3DXSprite__BILLBOARD
  • D3DXSPRITE_DONOTMODIFY_RENDERSTATE
  • D3DXSPRITE_DONOTSAVESTATE
  • D3DXSPRITE_OBJECTSPACE
  • D3DXSprite__SORT_DEPTH_BACKTOFRONT
  • D3DXSprite__SORT_DEPTH_FRONTTOBACK
  • D3DXSprite__SORT_TEXTURE
For a description of the flags and for information on how to control device state capture and device view transforms, see D3DXSPRITE.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

This method must be called from inside a IDirect3DDevice9::BeginScene . . . IDirect3DDevice9::EndScene sequence. ID3DXSprite::Begin cannot be used as a substitute for either IDirect3DDevice9::BeginScene or ID3DXRenderToSurface::BeginScene.

This method will set the following states on the device.

Render States:

Type (D3DRENDERSTATETYPE) | Value
D3DRS_ALPHABLENDENABLE | TRUE
D3DRS_ALPHAFUNC | D3DCMP_GREATER
D3DRS_ALPHAREF | 0x00
D3DRS_ALPHATESTENABLE | AlphaCmpCaps
D3DRS_BLENDOP | D3DBLENDOP_ADD
D3DRS_CLIPPING | TRUE
D3DRS_CLIPPLANEENABLE | FALSE
D3DRS_COLORWRITEENABLE | D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED
D3DRS_CULLMODE | D3DCULL_NONE
D3DRS_DESTBLEND | D3DBLEND_INVSRCALPHA
D3DRS_DIFFUSEMATERIALSOURCE | D3DMCS_COLOR1
D3DRS_ENABLEADAPTIVETESSELLATION | FALSE
D3DRS_FILLMODE | D3DFILL_SOLID
D3DRS_FOGENABLE | FALSE
D3DRS_INDEXEDVERTEXBLENDENABLE | FALSE
D3DRS_LIGHTING | FALSE
D3DRS_RANGEFOGENABLE | FALSE
D3DRS_SEPARATEALPHABLENDENABLE | FALSE
D3DRS_SHADEMODE | D3DSHADE_GOURAUD
D3DRS_SPECULARENABLE | FALSE
D3DRS_SRCBLEND | D3DBLEND_SRCALPHA
D3DRS_SRGBWRITEENABLE | FALSE
D3DRS_STENCILENABLE | FALSE
D3DRS_VERTEXBLEND | FALSE
D3DRS_WRAP0 | 0

Texture Stage States:

Stage Identifier | Type (D3DTEXTURESTAGESTATETYPE) | Value
0 | D3DTSS_ALPHAARG1 | D3DTA_TEXTURE
0 | D3DTSS_ALPHAARG2 | D3DTA_DIFFUSE
0 | D3DTSS_ALPHAOP | D3DTOP_MODULATE
0 | D3DTSS_COLORARG1 | D3DTA_TEXTURE
0 | D3DTSS_COLORARG2 | D3DTA_DIFFUSE
0 | D3DTSS_COLOROP | D3DTOP_MODULATE
0 | D3DTSS_TEXCOORDINDEX | 0
0 | D3DTSS_TEXTURETRANSFORMFLAGS | D3DTTFF_DISABLE
1 | D3DTSS_ALPHAOP | D3DTOP_DISABLE
1 | D3DTSS_COLOROP | D3DTOP_DISABLE

Sampler States:

Sampler Stage Index | Type (D3DSAMPLERSTATETYPE) | Value
0 | D3DSAMP_ADDRESSU | D3DTADDRESS_CLAMP
0 | D3DSAMP_ADDRESSV | D3DTADDRESS_CLAMP
0 | D3DSAMP_MAGFILTER | D3DTEXF_ANISOTROPIC if TextureFilterCaps includes D3DPTFILTERCAPS_MAGFANISOTROPIC; otherwise D3DTEXF_LINEAR
0 | D3DSAMP_MAXMIPLEVEL | 0
0 | D3DSAMP_MAXANISOTROPY | MaxAnisotropy
0 | D3DSAMP_MINFILTER | D3DTEXF_ANISOTROPIC if TextureFilterCaps includes D3DPTFILTERCAPS_MINFANISOTROPIC; otherwise D3DTEXF_LINEAR
0 | D3DSAMP_MIPFILTER | D3DTEXF_LINEAR if TextureFilterCaps includes D3DPTFILTERCAPS_MIPFLINEAR; otherwise D3DTEXF_POINT
0 | D3DSAMP_MIPMAPLODBIAS | 0
0 | D3DSAMP_SRGBTEXTURE | 0

Note This method disables N-patches.

Requirements

Header: Declared in D3dx9core.h.

See Also

D3DXSPRITE


ID3DXSprite::Draw

Adds a sprite to the list of batched sprites.

HRESULT Draw(
  LPDIRECT3DTEXTURE9 pTexture,
  CONST RECT * pSrcRect,
  CONST D3DXVECTOR3 * pCenter,
  CONST D3DXVECTOR3 * pPosition,
  D3DCOLOR Color
);

Parameters

pTexture
[in] Pointer to an IDirect3DTexture9 interface that represents the sprite texture.
pSrcRect
[in] Pointer to a RECT structure that indicates the portion of the source texture to use for the sprite. If this parameter is NULL, then the entire source image is used for the sprite.
pCenter
[in] Pointer to a D3DXVECTOR3 vector that identifies the center of the sprite. If this argument is NULL, the point (0,0,0) is used, which is the upper-left corner.
pPosition
[in] Pointer to a D3DXVECTOR3 vector that identifies the position of the sprite. If this argument is NULL, the point (0,0,0) is used, which is the upper-left corner.
Color
[in] D3DCOLOR type. The color and alpha channels are modulated by this value. A value of 0xFFFFFFFF maintains the original source color and alpha data. Use the D3DCOLOR_RGBA macro to help generate this color.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

To scale, rotate, or translate a sprite, call ID3DXSprite::SetTransform with a matrix that contains the scale, rotate, and translate (SRT) values, before calling ID3DXSprite::Draw. For information about setting SRT values in a matrix, see Matrix Transforms.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXSprite::GetTransform


ID3DXSprite::End

Calls ID3DXSprite::Flush and restores the device state to how it was before ID3DXSprite::Begin was called.

HRESULT End();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

ID3DXSprite::End cannot be used as a substitute for either IDirect3DDevice9::EndScene or ID3DXRenderToSurface::EndScene.

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXSprite::Begin


ID3DXSprite::Flush

Forces all batched sprites to be submitted to the device. Device states remain as they were after the last call to ID3DXSprite::Begin. The list of batched sprites is then cleared.

HRESULT Flush();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3dx9core.h.

See Also

ID3DXSprite::End


ID3DXSprite::GetDevice

Retrieves the device associated with the sprite object.

HRESULT GetDevice(
  LPDIRECT3DDEVICE9 * ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the sprite object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface.

Requirements

Header: Declared in D3dx9core.h.


ID3DXSprite::GetTransform

Gets the sprite transform.

HRESULT GetTransform(
  D3DXMATRIX * pTransform
);

Parameters

pTransform
[in] Pointer to a D3DXMATRIX that contains a transform of the sprite from the original world space.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3dx9core.h.


ID3DXSprite::OnLostDevice

Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost or before resetting a device.

HRESULT OnLostDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method should be called whenever the device is lost or before the user calls IDirect3DDevice9::Reset. Even if the device was not actually lost, ID3DXSprite::OnLostDevice is responsible for freeing stateblocks and other resources that may need to be released before resetting the device. As a result, the font object cannot be used again before calling IDirect3DDevice9::Reset and then ID3DXSprite::OnResetDevice.

Requirements

Header: Declared in D3dx9core.h.


ID3DXSprite::OnResetDevice

Use this method to re-acquire resources and save initial state.

HRESULT OnResetDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXSprite::OnResetDevice should be called each time the device is reset (using IDirect3DDevice9::Reset), before any other methods are called. This is a good place to re-acquire video-memory resources and capture state blocks.

Requirements

Header: Declared in D3dx9core.h.


ID3DXSprite::SetTransform

Sets the sprite transform.

HRESULT SetTransform(
  CONST D3DXMATRIX * pTransform
);

Parameters

pTransform
[in] Pointer to a D3DXMATRIX that contains a transform of the sprite from the original world space. Use this transform to scale, rotate, or transform the sprite.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3dx9core.h.

See Also

Transforms (Direct3D 9)


ID3DXSprite::SetWorldViewLH

Sets the left-handed world-view transform for a sprite. A call to this method is required before billboarding or sorting sprites.

HRESULT SetWorldViewLH(
  CONST D3DXMATRIX * pWorld,
  CONST D3DXMATRIX * pView
);

Parameters

pWorld
[in] Pointer to a D3DXMATRIX that contains a world transform. If NULL, the identity matrix is used for the world transform.
pView
[in] Pointer to a D3DXMATRIX that contains a view transform. If NULL, the identity matrix is used for the view transform.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

A call to this method (or to ID3DXSprite::SetWorldViewRH) is required if the sprite will be rendered with the D3DXSprite__BILLBOARD, D3DXSprite__SORT_DEPTH_FRONTTOBACK, or D3DXSprite__SORT_DEPTH_BACKTOFRONT flag value in ID3DXSprite::Begin.

Requirements

Header: Declared in D3dx9core.h.


ID3DXSprite::SetWorldViewRH

Sets the right-handed world-view transform for a sprite. A call to this method is required before billboarding or sorting sprites.

HRESULT SetWorldViewRH(
  CONST D3DXMATRIX * pWorld,
  CONST D3DXMATRIX * pView
);

Parameters

pWorld
[in] Pointer to a D3DXMATRIX that contains a world transform. If NULL, the identity matrix is used for the world transform.
pView
[in] Pointer to a D3DXMATRIX that contains a view transform. If NULL, the identity matrix is used for the view transform.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

A call to this method (or to ID3DXSprite::SetWorldViewLH) is required if the sprite will be rendered with the D3DXSprite__BILLBOARD, D3DXSprite__SORT_DEPTH_FRONTTOBACK, or D3DXSprite__SORT_DEPTH_BACKTOFRONT flag value in ID3DXSprite::Begin.

Requirements

Header: Declared in D3dx9core.h.


ID3DXTextureGutterHelper

The ID3DXTextureGutterHelper interface is used to build and manage gutter regions in a texture. Gutter regions separate textures and allow for bilinear interpolation to avoid rendering artifacts at texture boundaries.

The Get... methods provide access to the data structures used by the Apply... methods.

ID3DXTextureGutterHelper Members

Method | Description
ID3DXTextureGutterHelper::ApplyGuttersFloat | Applies gutters to a FLOAT texture buffer.
ID3DXTextureGutterHelper::ApplyGuttersPRT | Applies gutters to an ID3DXPRTBuffer buffer object.
ID3DXTextureGutterHelper::ApplyGuttersTex | Applies gutters to an IDirect3DTexture9 texture object.
ID3DXTextureGutterHelper::GetBaryMap | Retrieves texel barycentric coordinates.
ID3DXTextureGutterHelper::GetFaceMap | Retrieves the index of the mesh face to which each texel belongs.
ID3DXTextureGutterHelper::GetGutterMap | Receives a texel class value that indicates texel class according to each texel's location.
ID3DXTextureGutterHelper::GetHeight | Retrieves the height of the texture, in pixels.
ID3DXTextureGutterHelper::GetTexelMap | Retrieves the (u, v) texture coordinates of each texel.
ID3DXTextureGutterHelper::GetWidth | Retrieves the width of the texture, in pixels.
ID3DXTextureGutterHelper::ResampleTex | Resamples a texture into this gutterhelper's parameterization.
ID3DXTextureGutterHelper::SetBaryMap | Sets texel barycentric coordinates.
ID3DXTextureGutterHelper::SetFaceMap | Sets the index of the mesh face to which each texel belongs.
ID3DXTextureGutterHelper::SetGutterMap | Sets a texel class value that indicates texel class according to each texel's location.
ID3DXTextureGutterHelper::SetTexelMap | Sets the (u, v) texture coordinates of each texel.

Remarks

Note When used with precomputed radiance transfer (PRT), this interface requires a unique parameterization of the model. Every texel must correspond to a single point on the surface of the model and vice-versa. If the model includes multiple textures, it must be split into separate pieces that each contain one gutter helper object per texture.

This interface can be used to generate a map in texture space in which each texel is in one of four classes.

Texel Class | Texel Location
0 | Invalid point; texel will not be used.
1 | Inside triangle.
2 | Inside gutter.
4 | Inside gutter; texel will be evaluated as a full sample in the ID3DXTextureGutterHelper::ApplyGuttersFloat, ID3DXTextureGutterHelper::ApplyGuttersTex, or ID3DXTextureGutterHelper::ApplyGuttersPRT methods.

For classes 1 and 2, a texel is stored with the face it belongs to, along with barycentric coordinates of the first two vertices of that face. Gutter vertices are assigned to the closest edge in texture space.

There is no texel class 3.

The ID3DXTextureGutterHelper interface is obtained by calling the D3DXCreateTextureGutterHelper function.

The LPD3DXTEXTUREGUTTERHELPER type is defined as a pointer to the ID3DXTextureGutterHelper interface.

typedef interface ID3DXTextureGutterHelper ID3DXTextureGutterHelper;
typedef interface ID3DXTextureGutterHelper *LPD3DXTEXTUREGUTTERHELPER;

Requirements

Header: Declared in D3DX9Mesh.h.

Library: Use D3dx9.lib.


ID3DXTextureGutterHelper::ApplyGuttersFloat

Applies gutters to a FLOAT texture buffer.

HRESULT ApplyGuttersFloat(
  FLOAT * pDataIn,
  UINT * NumCoeffs,
  UINT * Width,
  UINT * Height
);

Parameters

pDataIn
[in] Pointer to a buffer of FLOAT texture data.
NumCoeffs
[in] Number of scalars per color channel used in memory to store samples. Each texel contains NumCoeffs FLOAT values.
Width
[in] Width of the texture, in pixels, obtained from ID3DXTextureGutterHelper::GetWidth.
Height
[in] Height of the texture, in pixels, obtained from ID3DXTextureGutterHelper::GetHeight.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

Class 2 texels are generated by resampling class 1 and 4 texels.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureGutterHelper::ApplyGuttersPRT

Applies gutters to an ID3DXPRTBuffer buffer object.

HRESULT ApplyGuttersPRT(
  LPD3DXPRTBUFFER pBuffer
);

Parameters

pBuffer
[in] Pointer to an ID3DXPRTBuffer buffer object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

Class 2 texels are generated by resampling class 1 and 4 texels.

The width and height of the texture must be the same as those returned by ID3DXTextureGutterHelper::GetWidth and ID3DXTextureGutterHelper::GetHeight.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureGutterHelper::ApplyGuttersTex

Applies gutters to an IDirect3DTexture9 texture object.

HRESULT ApplyGuttersTex(
  LPDIRECT3DTEXTURE9 pTexture
);

Parameters

pTexture
[in] Pointer to a IDirect3DTexture9 texture object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_NOTAVAILABLE, D3DERR_OUTOFVIDEOMEMORY, D3DERR_WASSTILLDRAWING, E_OUTOFMEMORY.

Remarks

Class 2 texels are generated by resampling class 1 and 4 texels.

The width and height of the texture must be the same as those returned by ID3DXTextureGutterHelper::GetWidth and ID3DXTextureGutterHelper::GetHeight.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureGutterHelper::GetBaryMap

Retrieves texel barycentric coordinates.

HRESULT GetBaryMap(
  D3DXVECTOR2 * pBaryData
);

Parameters

pBaryData
[in, out] Pointer to a D3DXVECTOR2 structure that contains the first two barycentric coordinates of each texel.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

The third barycentric coordinate is given by:

    1 - ( pBaryData.x + pBaryData.y )

Barycentric coordinates are always specified with respect to the triangle returned by ID3DXTextureGutterHelper::GetFaceMap.

The barycentric coordinates returned by this method are valid only for valid (non-class 0) texels. ID3DXTextureGutterHelper::GetGutterMap will return nonzero values for valid texels.

Class 2 texels are mapped to the nearest point on the triangle in texel space.

The application must allocate and manage pBaryData.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureGutterHelper::GetFaceMap

Retrieves the index of the mesh face to which each texel belongs.

HRESULT GetFaceMap(
  UINT * pFaceData
);

Parameters

pFaceData
[in] Pointer to the index of the mesh face to which each texel belongs.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

The mesh face data returned by this method is valid only for valid (non-class 0) texels. ID3DXTextureGutterHelper::GetGutterMap will return nonzero values for valid (non-class 0) texels.

For class 2 texels, this method retrieves the closest face.

The application must allocate and manage pFaceData.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureGutterHelper::GetGutterMap

Receives a texel class value that indicates texel class according to each texel's location.

HRESULT GetGutterMap(
  BYTE * pGutterData
);

Parameters

pGutterData
[in, out] Pointer to the texel class. Possible texel classes are as follows. There is no texel class 3.
Texel Class | Texel Location
0 | Invalid point; texel will not be used.
1 | Inside triangle.
2 | Inside gutter.
4 | Inside gutter; texel will be evaluated as a full sample in the ID3DXTextureGutterHelper::ApplyGuttersFloat, ID3DXTextureGutterHelper::ApplyGuttersTex, or ID3DXTextureGutterHelper::ApplyGuttersPRT methods.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

The application must allocate and manage pGutterData, with size given by:

texture width * texture height * sizeof(BYTE)

Texture width and height are returned by ID3DXTextureGutterHelper::GetWidth and ID3DXTextureGutterHelper::GetHeight.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureGutterHelper::GetHeight

Retrieves the height of the texture, in pixels.

UINT GetHeight();

Parameters

None.

Return Values

Returns the height of the texture, in pixels.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXTextureGutterHelper::GetWidth


ID3DXTextureGutterHelper::GetTexelMap

Retrieves the (u, v) texture coordinates of each texel.

HRESULT GetTexelMap(
  D3DXVECTOR2 * pTexelData
);

Parameters

pTexelData
[out] Pointer to the location in pixel (u, v) texture coordinates where each texel is located.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

For class 2 and 4 texels, the returned (u, v) texture coordinates correspond to the closest point on the closest triangle.

The application must allocate and manage pTexelData.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureGutterHelper::GetWidth

Retrieves the width of the texture, in pixels.

UINT GetWidth();

Parameters

None.

Return Values

Returns the width of the texture, in pixels.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXTextureGutterHelper::GetHeight


ID3DXTextureGutterHelper::ResampleTex

Resamples a texture into this gutterhelper's parameterization.

HRESULT ResampleTex(
  LPDIRECT3DTEXTURE9 pTextureIn,
  LPD3DXMESH pMeshIn,
  D3DDECLUSAGE Usage,
  UINT UsageIndex,
  LPDIRECT3DTEXTURE9 pTextureOut
);

Parameters

pTextureIn
[in] Texture that corresponds to the original parameterization in pMeshIn. This texture will be used to create pTextureOut.
pMeshIn
[in] Mesh containing the original and new parameterizations. It is required to store the new parameterization in D3DDECLUSAGE_TEXCOORD index 0.
Usage
[in] Vertex data usage (used in combination with UsageIndex) which identifies the component of the vertex declaration that contains the original parameterization in pMeshIn. See D3DDECLUSAGE.
UsageIndex
[in] Zero-based index (used in combination with Usage), which identifies the component of the vertex declaration that contains the original parameterization in pMeshIn. The combination of D3DDECLUSAGE_TEXCOORD and index 0 is required for the new parameterization; any other usage/index combination may be used.
pTextureOut
[out] Resampled texture.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

A parameterization in the case of this function is a set of texture coordinates that maps the triangles of a mesh to the triangles on a texture. The new parameterization is the set of texture coordinates contained in the gutter helper interface, and the original parameterization is the set of texture coordinates contained within the input mesh.

It is assumed that texture coordinates are between 0 and 1, inclusive, and the new parameterization must be declared in the vertex declaration as texture coordinate index 0. The original texture and the resampled texture must have the same width and height.

For example, to prepare for resampling a texture:

  • Create the original texture interface (pOriginalTex below) using a function like D3DXCreateTextureFromFile.
  • Create the new texture interface for the resampled texture (pResampledTex below). The size of this texture must match the size (width and height) of the gutter helper texture.
  • Call D3DXCreateTextureGutterHelper to obtain the new parameterization as shown here:
// Given:
// pMesh points to a mesh that contains the original and new texture coordinates
ID3DXTextureGutterHelper * pGutterHelper;

// Mesh vertex declaration
D3DVERTEXELEMENT9 decl[] = {
    {0,  0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
    {0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0},
    // contains new set of texcoords
    {0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
    // contains original set of texcoords
    {0, 32, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1},
    D3DDECL_END()
};

// Create a gutter helper with the new parameterization
hr = D3DXCreateTextureGutterHelper(width, height, pMesh, 1, &pGutterHelper);

// Resample the texture
hr = pGutterHelper->ResampleTex(pOriginalTex, pMesh, D3DDECLUSAGE_TEXCOORD,
           1, pResampledTex);

// Release the gutter helper interface when done with it

One common scenario might be to use UVAtlas to create a texture atlas and then use ResampleTex to resample the texture into the new parameterization. For more information about atlases, see Using UVAtlas (Direct3D 9).

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXUVAtlasCreate


ID3DXTextureGutterHelper::SetBaryMap

Sets texel barycentric coordinates.

HRESULT SetBaryMap(
  D3DXVECTOR2 * pBaryData
);

Parameters

pBaryData
[in] Pointer to a D3DXVECTOR2 structure that contains the first two barycentric coordinates of each texel.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

The third barycentric coordinate is given by:

1 - ( pBaryData.x + pBaryData.y )

The barycentric coordinates input to this method are valid only for valid (non-class 0) texels. ID3DXTextureGutterHelper::GetGutterMap will return non-zero values for valid texels.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureGutterHelper::SetFaceMap

Sets the index of the mesh face to which each texel belongs.

HRESULT SetFaceMap(
  UINT * pFaceData
);

Parameters

pFaceData
[in] Pointer to the index of the mesh face to which each texel belongs.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Remarks

The mesh face data input to this method is valid only for valid (non-class 0) texels. ID3DXTextureGutterHelper::GetGutterMap will return non-zero values for valid texels.

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureGutterHelper::SetGutterMap

Sets a texel class value that indicates texel class according to each texel's location.

HRESULT SetGutterMap(
  BYTE * pGutterData
);

Parameters

pGutterData
[in] Pointer to the texel class. Possible texel classes are as follows. There is no texel class 3.
Texel Class | Texel Location
0 | Invalid point; texel will not be used.
1 | Inside triangle.
2 | Inside gutter.
4 | Inside gutter; texel will be evaluated as a full sample in the ID3DXTextureGutterHelper::ApplyGuttersFloat, ID3DXTextureGutterHelper::ApplyGuttersTex, or ID3DXTextureGutterHelper::ApplyGuttersPRT methods.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureGutterHelper::SetTexelMap

Sets the (u, v) texture coordinates of each texel.

HRESULT SetTexelMap(
  D3DXVECTOR2 * pTexelData
);

Parameters

pTexelData
[in] Pointer to the location in pixel (u, v) texture coordinates where each texel is located.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned.

D3DERR_INVALIDCALL

Requirements

Header: Declared in D3DX9Mesh.h.


ID3DXTextureShader

The ID3DXTextureShader interface.

ID3DXTextureShader Members

Method | Description
ID3DXTextureShader::GetConstant | Gets a constant by looking up its index.
ID3DXTextureShader::GetConstantBuffer | Get a pointer to the constant table.
ID3DXTextureShader::GetConstantByName | Gets a constant by looking up its name.
ID3DXTextureShader::GetConstantDesc | Gets a pointer to the array of constants in the constant table.
ID3DXTextureShader::GetConstantElement | Get a constant from the constant table.
ID3DXTextureShader::GetDesc | Gets a description of the constant table.
ID3DXTextureShader::GetFunction | Gets a pointer the the function DWORD stream.
ID3DXTextureShader::SetBool | Sets a BOOL value.
ID3DXTextureShader::SetBoolArray | Sets an array of BOOL values.
ID3DXTextureShader::SetDefaults | Sets the constants to the default values declared in the shader.
ID3DXTextureShader::SetFloat | Sets a floating-point number.
ID3DXTextureShader::SetFloatArray | Sets an array of floating-point numbers.
ID3DXTextureShader::SetInt | Sets an integer value.
ID3DXTextureShader::SetIntArray | Sets an array of integers.
ID3DXTextureShader::SetMatrix | Sets a non-transposed matrix.
ID3DXTextureShader::SetMatrixArray | Sets an array of non-transposed matrices.
ID3DXTextureShader::SetMatrixPointerArray | Sets an array of pointers to non-transposed matrices.
ID3DXTextureShader::SetMatrixTranspose | Sets a transposed matrix.
ID3DXTextureShader::SetMatrixTransposeArray | Sets an array of transposed matrices.
ID3DXTextureShader::SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
ID3DXTextureShader::SetValue | Sets the constant table with the data in the buffer.
ID3DXTextureShader::SetVector | Sets a 4D vector.
ID3DXTextureShader::SetVectorArray | Sets an array of 4D vectors.

Remarks

The ID3DXTextureShader interface is obtained by calling the D3DXCreateTextureShader function.

The ID3DXTextureShader interface, like all COM interfaces, inherits the IUnknown interface.

The LPD3DXTEXTURESHADER type is defined as a pointer to the ID3DXTextureShader interface.

typedef interface ID3DXTextureShader *LPD3DXTEXTURESHADER;

Requirements

Header: Declared in D3DX9Shader.h.

Library: Use D3dx9.lib.


ID3DXTextureShader::GetConstant

Gets a constant by looking up its index.

D3DXHANDLE GetConstant(
  D3DXHANDLE hConstant,
  UINT Index
);

Parameters

hConstant
[in] A handle to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
Index
[in] Zero-based index of the constant.

Return Values

Returns a unique identifier to the constant.

Remarks

To get a constant from an array of constants, use ID3DXTextureShader::GetConstantElement.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::GetConstantBuffer

Get a pointer to the constant table.

HRESULT GetConstantBuffer(
  LPD3DXBUFFER * ppConstantBuffer
);

Parameters

ppConstantBuffer
[out] Pointer to an ID3DXBuffer interface, which contains the constants.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::GetConstantByName

Gets a constant by looking up its name.

D3DXHANDLE GetConstantByName(
  D3DXHANDLE hConstant,
  LPCSTR pName
);

Parameters

hConstant
[in] A handle to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
pName
[in] A string containing the name of the constant.

Return Values

Returns a unique identifier to the constant.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::GetConstantDesc

Gets a pointer to the array of constants in the constant table.

HRESULT GetConstantDesc(
  D3DXHANDLE hConstant,
  D3DXCONSTANT_DESC * pDesc,
  UINT * pCount
);

Parameters

hConstant
[in] Unique identifier to a constant. See D3DXHANDLE.
pDesc
[in, out] Returns a pointer to an array of descriptions. See D3DXCONSTANT_DESC.
pCount
[in, out] The input supplied must be the maximum size of the array. The output is the number of elements that are filled in the array when the function returns.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

Samplers can appear more than once in a constant table, therefore, this method can return an array of descriptions each with a different register index.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXTextureShader::GetDesc


ID3DXTextureShader::GetConstantElement

Get a constant from the constant table.

D3DXHANDLE GetConstantElement(
  D3DXHANDLE hConstant,
  UINT Index
);

Parameters

hConstant
[in] A handle to the array of constants. This value may not be NULL.
Index
[in] Zero-based index of the element in the constant table.

Return Values

Returns a unique identifier to the constant.

Remarks

To get a constant that is not part of an array, use ID3DXTextureShader::GetConstant or ID3DXTextureShader::GetConstantByName.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::GetDesc

Gets a description of the constant table.

HRESULT GetDesc(
  D3DXCONSTANTTABLE_DESC * pDesc
);

Parameters

pDesc
[in] The attributes of the constant table. See D3DXCONSTANTTABLE_DESC.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::GetFunction

Gets a pointer the the function DWORD stream.

HRESULT GetFunction(
  LPD3DXBUFFER * ppFunction
);

Parameters

ppFunction
[in] A pointer to the function DWORD stream. See ID3DXBuffer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetBool

Sets a BOOL value.

HRESULT SetBool(
  D3DXHANDLE hConstant,
  BOOL b
);

Parameters

hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
b
[in] BOOL value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetBoolArray

Sets an array of BOOL values.

HRESULT SetBoolArray(
  D3DXHANDLE hConstant,
  CONST BOOL* pB,
  UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pB
[in] Array of BOOL values.
Count
[in] Number of BOOL values in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetDefaults

Sets the constants to the default values declared in the shader.

HRESULT SetDefaults();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetFloat

Sets a floating-point number.

HRESULT SetFloat(
  D3DXHANDLE hConstant,
  FLOAT f
);

Parameters

hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
f
[in] Floating-point number.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetFloatArray

Sets an array of floating-point numbers.

HRESULT SetFloatArray(
  D3DXHANDLE hConstant,
  CONST FLOAT* pf,
  UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pf
[in] Array of floating-point numbers.
Count
[in] Number of floating-point values in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetInt

Sets an integer value.

HRESULT SetInt(
  D3DXHANDLE hConstant,
  INT n
);

Parameters

hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
n
[in] Integer value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetIntArray

Sets an array of integers.

HRESULT SetIntArray(
  D3DXHANDLE hConstant,
  CONST INT* pn,
  UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetMatrix

Sets a non-transposed matrix.

HRESULT SetMatrix(
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX* pMatrix
);

Parameters

hConstant
[in] Unique identifier to the matrix of constants. See D3DXHANDLE.
pMatrix
[in] Pointer to a non-transposed matrix. See D3DXMATRIX.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data; that is, each vector is contained in a row.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetMatrixArray

Sets an array of non-transposed matrices.

HRESULT SetMatrixArray(
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX* pMatrix,
  UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of constant matrices. See D3DXHANDLE.
pMatrix
[in] Array of non-transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data; that is, each vector is contained in a row.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetMatrixPointerArray

Sets an array of pointers to non-transposed matrices.

HRESULT SetMatrixPointerArray(
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX ** ppMatrix,
  UINT Count
);

Parameters

hConstant
[in] Unique identifier to an array of constant matrices. See D3DXHANDLE.
ppMatrix
[in] Array of pointers to non-transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data; that is, each vector is contained in a row.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetMatrixTranspose

Sets a transposed matrix.

HRESULT SetMatrixTranspose(
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX* pMatrix
);

Parameters

hConstant
[in] Unique identifier to the matrix of constants. See D3DXHANDLE.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetMatrixTransposeArray

Sets an array of transposed matrices.

HRESULT SetMatrixTransposeArray(
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX* pMatrix,
  UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of matrix constants. See D3DXHANDLE.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetMatrixTransposePointerArray

Sets an array of pointers to transposed matrices.

HRESULT SetMatrixTransposePointerArray(
  D3DXHANDLE hConstant,
  CONST D3DXMATRIX** ppMatrix,
  UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of matrix constants. See D3DXHANDLE.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetValue

Sets the constant table with the data in the buffer.

HRESULT SetValue(
  D3DXHANDLE hConstant,
  LPCVOID pData,
  UINT Bytes
);

Parameters

hConstant
[in] Unique identifier to a constant. See D3DXHANDLE.
pData
[in] A pointer to a buffer containing the constant data.
Bytes
[in] Size of the buffer, in bytes.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetVector

Sets a 4D vector.

HRESULT SetVector(
  D3DXHANDLE hConstant,
  CONST D3DXVECTOR4* pVector
);

Parameters

hConstant
[in] Unique identifier to the vector constant. See D3DXHANDLE.
pVector
[in] Pointer to a 4D vector. See D3DXVECTOR4.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXTextureShader::SetVectorArray

Sets an array of 4D vectors.

HRESULT SetVectorArray(
  D3DXHANDLE hConstant,
  CONST D3DXVECTOR4* pVector,
  UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of vector constants. See D3DXHANDLE.
pVector
[in] Array of 4D vectors. See D3DXVECTOR4.
Count
[in] Number of vectors in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


D3DX Functions

This section contains reference information for the functions that you need to implement when you work with the D3DX utility library. The following functions are implemented.

  • Animation Functions
  • General Purpose Functions
  • Math Functions
  • Mesh Functions
  • UVAtlas Functions
  • Precomputed Radiance Transfer Functions
  • Shader Functions
  • Shape Drawing Functions
  • Texturing Functions


Animation Functions

D3DX supplies the following animation functions.

  • D3DXCreateAnimationController
  • D3DXCreateCompressedAnimationSet
  • D3DXCreateKeyframedAnimationSet
  • D3DXFRAMEAppendChild
  • D3DXFRAMECalculateBoundingSphere
  • D3DXFRAMEDestroy
  • D3DXFRAMEFind
  • D3DXFRAMENumNamedMatrices
  • D3DXFRAMERegisterNamedMatrices
  • D3DXLoadMeshHierarchyFromX
  • D3DXLoadMeshHierarchyFromXInMemory
  • D3DXSaveMeshHierarchyToFile


D3DXCreateAnimationController

Creates an animation controller object.

HRESULT D3DXCreateAnimationController(
  UINT MaxNumAnimationOutputs,
  UINT MaxNumAnimationSets,
  UINT MaxNumTracks,
  UINT MaxNumEvents,
  LPD3DXANIMATIONCONTROLLER* ppAnimController
);

Parameters

MaxNumAnimationOutputs
[in] Maximum number of animation outputs the controller can support.
MaxNumAnimationSets
[in] Maximum number of animation sets that can be mixed.
MaxNumTracks
[in] Maximum number of animation sets that can be mixed simultaneously.
MaxNumEvents
[in] Maximum number of outstanding events that the controller will support.
ppAnimController
[out, retval] Pointer to the animation controller object created. See ID3DXAnimationController.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

An animation controller controls an animation mixer. The controller adds methods to modify blending parameters over time to enable smooth transitions.

Requirements

Header: Declared in D3dx9anim.h.


D3DXCreateCompressedAnimationSet

Creates a ID3DXCompressedAnimationSet key framed animation set interface that stores key frame data in a compressed format.

HRESULT D3DXCreateCompressedAnimationSet(
  LPCSTR pName,
  DOUBLE TicksPerSecond,
  D3DXPLAYBACK_TYPE Playback,
  LPD3DXBUFFER pCompressedData,
  UINT NumCallbackKeys,
  CONST LPD3DXKEY_CALLBACK * pCallKeys,
  LPD3DXCOMPRESSEDANIMATIONSET * ppAnimationSet
);

Parameters

pName
[in] Pointer to the name of the animation set.
TicksPerSecond
[in] Number of key frame ticks that elapse per second.
Playback
[in] Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.
pCompressedData
[in] Pointer to the ID3DXBuffer buffer that stores the animation set as compressed data.
NumCallbackKeys
[in] Number of callback keys.
pCallKeys
[in] Pointer to a D3DXKEY_CALLBACK structure that stores user callback data.
ppAnimationSet
[out] Address of a pointer to the ID3DXCompressedAnimationSet interface that stores key framed animation set data in a compressed format.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


D3DXCreateKeyframedAnimationSet

Creates a ID3DXKeyframedAnimationSet key framed animation set interface.

HRESULT D3DXCreateKeyframedAnimationSet(
  LPCSTR pName,
  DOUBLE TicksPerSecond,
  D3DXPLAYBACK_TYPE Playback,
  UINT NumAnimations,
  UINT NumCallbackKeys,
  CONST LPD3DXKEY_CALLBACK * pCallKeys,
  LPD3DXKEYFRAMEDANIMATIONSET * ppAnimationSet
);

Parameters

pName
[in] Pointer to the name of the animation set.
TicksPerSecond
[in] Number of key frame ticks that elapse per second.
Playback
[in] Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.
NumAnimations
[in] Number of scale, rotate, and translate (SRT) animation sets.
NumCallbackKeys
[in] Number of callback keys.
pCallKeys
[in] Pointer to a D3DXKEY_CALLBACK structure that stores user callback data.
ppAnimationSet
[out] Address of a pointer to the ID3DXKeyframedAnimationSet key framed animation set interface.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


D3DXFRAMEAppendChild

Adds a child frame to a frame.

HRESULT D3DXFRAMEAppendChild(
  LPD3DXFRAME pFrameParent,
  CONST D3DXFRAME * pFrameChild
);

Parameters

pFrameParent
[in] Pointer to the parent node.
pFrameChild
[in] Pointer to the child node.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


D3DXFRAMECalculateBoundingSphere

Computes the bounding sphere of all the meshes in the frame hierarchy.

HRESULT D3DXFRAMECalculateBoundingSphere(
  CONST D3DXFRAME * pFrameRoot,
  LPD3DXVECTOR3 pObjectCenter,
  FLOAT * pObjectRadius
);

Parameters

pFrameRoot
[in] Pointer to the root node.
pObjectCenter
[out] Returns the center of the bounding sphere.
pObjectRadius
[out] Returns the radius of the bounding sphere.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


D3DXFRAMEDestroy

Destroys the subtree of frames under the root, including the root.

HRESULT D3DXFRAMEDestroy(
  LPD3DXFRAME pFrameRoot,
  LPD3DXALLOCATEHIERARCHY pAlloc
);

Parameters

pFrameRoot
[in] Pointer to the root node.
pAlloc
[in] Allocation interface used to deallocate nodes of the frame hierarchy.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


D3DXFRAMEFind

Finds the child frame of a root frame.

LPD3DXFRAME D3DXFRAMEFind(
  CONST D3DXFRAME * pFrameRoot,
  LPCSTR Name
);

Parameters

pFrameRoot
[in] Pointer to the root frame. See D3DXFRAME.
Name
[in] Name of the child frame to find.

Return Values

Returns the child frame if it is found, or NULL otherwise. See D3DXFRAME.

Requirements

Header: Declared in D3dx9anim.h.


D3DXFRAMENumNamedMatrices

Counts number of frames in a subtree that have non-null names.

UINT D3DXFRAMENumNamedMatrices(
  CONST D3DXFRAME * pFrameRoot
);

Parameters

pFrameRoot
[in] Pointer to the root node of the subtree.

Return Values

Returns the frame count.

Requirements

Header: Declared in D3dx9anim.h.


D3DXFRAMERegisterNamedMatrices

Given a frame hierarchy, registers all the named matrices in the animation mixer.

HRESULT D3DXFRAMERegisterNamedMatrices(
  LPD3DXFRAME pFrameRoot,
  LPD3DXANIMATIONCONTROLLER pAnimController
);

Parameters

pFrameRoot
[in] The top level node in the frame hierarchy.
pAnimController
[in] Pointer to the animation controller object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9anim.h.


D3DXLoadMeshHierarchyFromX

Loads the first frame hierarchy from a .x file.

HRESULT D3DXLoadMeshHierarchyFromX(
  LPCSTR Filename,
  DWORD MeshOptions,
  LPDIRECT3DDEVICE9 pDevice,
  LPD3DXALLOCATEHIERARCHY pAlloc,
  LPD3DXLOADUSERDATA pUserDataLoader,
  LPD3DXFRAME* ppFrameHierarchy,
  LPD3DXANIMATIONCONTROLLER* ppAnimController
);

Parameters

Filename
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
MeshOptions
[in] Combination of one or more flags from the D3DXMESH enumeration that specify creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
pAlloc
[in] Pointer to an ID3DXAllocateHierarchy interface.
pUserDataLoader
[in] Application provided interface that allows loading of user data. See ID3DXLoadUserData.
ppFrameHierarchy
[out, retval] Returns a pointer to the loaded frame hierarchy. See D3DXFRAME.
ppAnimController
[out, retval] Returns a pointer to the animation controller corresponding to animation in the .x file. This is created with default tracks and events. See ID3DXAnimationController.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadMeshHierarchyFromXW. Otherwise, the function call resolves to D3DXLoadMeshHierarchyFromXA.

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

D3DXLoadMeshHierarchyFromX loads the animation data and frame hierarchy from a .x file. It scans the .x file and builds a frame hierarchy and animation controller according to the ID3DXAllocateHierarchy-derived object passed to it through pAlloc. Loading the data requires several steps as follows:

  1. Derive ID3DXAllocateHierarchy, implementing each method. This controls how frames and meshes are allocated and freed.
  2. Derive ID3DXLoadUserData, implementing each method. If your .x file has no embedded user-defined data, or if you do not need it, you can skip this part.
  3. Create an object of your ID3DXAllocateHierarchy class, and optionally of your LoadUserData class. You do not need to call any methods of these objects yourself.
  4. Call D3DXLoadMeshHierarchyFromX, passing in your ID3DXAllocateHierarchy object and your ID3DXLoadUserData object (or NULL) to create the frame hierarchy and animation controller. All the animation sets and frames are automatically registered to the animation controller.

During the load, ID3DXAllocateHierarchy::CreateFrame and ID3DXLoadUserData::LoadFrameChildData are called back on each frame to control loading and allocation of the frame. The application defines these methods to control how frames are stored. ID3DXAllocateHierarchy::CreateMeshContainer and ID3DXLoadUserData::LoadMeshChildData are called back on each mesh object to control loading and allocation of mesh objects. ID3DXLoadUserData::LoadTopLevelData is called back for each top level object that doesn't get loaded by the other methods.

To free this data, call ID3DXAnimationController::Release to free the animation sets, and D3DXFRAMEDestroy, passing in the root node of the frame hierarchy and an object of your derived ID3DXAllocateHierarchy class. ID3DXAllocateHierarchy::DestroyFrame and ID3DXAllocateHierarchy::DestroyMeshContainer will each be called for every frame and mesh object in the frame hierarchy. Your implementation of ID3DXAllocateHierarchy::DestroyFrame should release everything allocated by ID3DXAllocateHierarchy::CreateFrame, and likewise for the mesh container methods.

Requirements

Header: Declared in D3dx9anim.h.


D3DXLoadMeshHierarchyFromXInMemory

Loads the first frame hierarchy from a .x file.

HRESULT D3DXLoadMeshHierarchyFromXInMemory(
  LPCVOID pMemory,
  DWORD SizeOfMemory,
  DWORD MeshOptions,
  LPDIRECT3DDEVICE9 pDevice,
  LPD3DXALLOCATEHIERARCHY pAlloc,
  LPD3DXLOADUSERDATA pUserDataLoader,
  LPD3DXFRAME * ppFrameHeirarchy,
  LPD3DXANIMATIONCONTROLLER * ppAnimController
);

Parameters

pMemory
[in] ] Pointer to a buffer that contains the mesh hierarchy.
SizeOfMemory
[in] Size of the pMemory buffer, in bytes.
MeshOptions
[in] Combination of one or more flags from the D3DXMESH enumeration that specify creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
pAlloc
[in] Pointer to an ID3DXAllocateHierarchy interface.
pUserDataLoader
[in] Application provided interface that allows loading of user data. See ID3DXLoadUserData.
ppFrameHeirarchy
[out, retval] Returns a pointer to the loaded frame heirarchy. See D3DXFRAME.
ppAnimController
[out, retval] Returns a pointer to the animation controller corresponding to animation in the .x file. This is created with default tracks and events. See ID3DXAnimationController.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

Requirements

Header: Declared in D3dx9anim.h.


D3DXSaveMeshHierarchyToFile

Creates a .x file and saves the mesh hierarchy and corresponding animations in it.

HRESULT D3DXSaveMeshHierarchyToFile(
  LPCSTR pFilename,
  DWORD XFormat,
  CONST D3DXFRAME * pFrameRoot,
  LPD3DXANIMATIONCONTROLLER pAnimController,
  LPD3DXSAVEUSERDATA pUserDataSaver
);

Parameters

pFilename
[in] Pointer to a string that specifies the name of the .x file identifying the saved mesh. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
XFormat
[in] Format of the .x file (text or binary, compressed or not). See D3DXF_FILEFORMAT. D3DXF_FILEFORMAT_COMPRESSED can be combined (using a logical OR) with either the D3DXF_FILEFORMAT_BINARY or D3DXF_FILEFORMAT_TEXT flags to reduce the output file size.
pFrameRoot
[in] Root node of the hierarchy to be saved. See D3DXFRAME.
pAnimController
[in] Animation controller that has animation sets to be stored. See ID3DXAnimationController.
pUserDataSaver
[in] Application-provided interface that allows saving of user data. See ID3DXSaveUserData.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be:

D3DERR_INVALIDCALL

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveMeshHierarchyToFileW. Otherwise, the function call resolves to D3DXSaveMeshHierarchyToFileA.

This function does not save compressed animation sets.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

X File Reference


General Purpose Functions

D3DX supplies the following general purpose functions:

  • D3DXCheckVersion
  • D3DXCreateBuffer
  • D3DXCreateFont
  • D3DXCreateFontIndirect
  • D3DXCreateLine
  • D3DXCreateRenderToEnvMap
  • D3DXCreateRenderToSurface
  • D3DXCreateSprite
  • D3DXGetDriverLevel


D3DXCheckVersion

Verify that the version of D3DX you compiled with is the version that you are running.

BOOL D3DXCheckVersion(
  UINT D3DSDKVersion,
  UINT D3DXSDKVersion
);

Parameters

D3DSDKVersion
[in] Use D3D_SDK_VERSION. See remarks.
D3DXSDKVersion
[in] Use D3DX_SDK_VERSION. See remarks.

Return Values

Returns TRUE if the version of D3DX you compiled against is the version you are running with; otherwise, FALSE is returned.

Remarks

Use this function during the initialization of your application like this:

HRESULT CD3DXMyApplication::Initialize(HINSTANCE hInstance,
  LPCSTR szWindowName, LPCSTR szClassName, UINT uWidth, UINT uHeight)
{
    HRESULT hr;

    if (!D3DXCheckVersion(D3D_SDK_VERSION, D3DX_SDK_VERSION))
        return E_FAIL;

    ...
}

Use Direct3DCreate9 to verify that the correct runtime is installed.

Requirements

Header: Declared in D3dx9core.h.


D3DXCreateBuffer

Creates a buffer object.

HRESULT D3DXCreateBuffer(
  DWORD NumBytes,
  LPD3DXBUFFER * ppBuffer
);

Parameters

NumBytes
[in] Size of the buffer to create, in bytes.
ppBuffer
[out] Address of a pointer to an ID3DXBuffer interface, representing the created buffer object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXCreateFont

Creates a font object for a device and font.

HRESULT D3DXCreateFont(
  LPDIRECT3DDEVICE9 pDevice,
  INT Height,
  UINT Width,
  UINT Weight,
  UINT MipLevels,
  BOOL Italic,
  DWORD CharSet,
  DWORD OutputPrecision,
  DWORD Quality,
  DWORD PitchAndFamily,
  LPCTSTR pFacename,
  LPD3DXFONT * ppFont
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the font object.
Height
[in] The height of the characters in logical units.
Width
[in] The width of the characters in logical units.
Weight
[in] Typeface weight. One example is bold.
MipLevels
[in] The number of mipmap levels.
Italic
[in] True for italic font, false otherwise.
CharSet
[in] The character set of the font.
OutputPrecision
[in] Specifies how Windows should attempt to match the desired font sizes and characteristics with actual fonts. Use OUT_TT_ONLY_PRECIS for instance, to ensure that you always get a TrueType font.
Quality
[in] Specifies how Windows should match the desired font with a real font. It applies to raster fonts only and should not affect TrueType fonts.
PitchAndFamily
[in] Pitch and family index.
pFacename
[in] String containing the typeface name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppFont
[out] Returns a pointer to an ID3DXFont interface, representing the created font object.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The creation of an ID3DXFont object requires that the device supports 32-bit color.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateFontW. Otherwise, the function call resolves to D3DXCreateFontA because ANSI strings are being used.

If you want more information about font parameters, see The Logical Font.

Requirements

Header: Declared in D3dx9core.h.


D3DXCreateFontIndirect

Creates a font object indirectly for both a device and a font.

HRESULT D3DXCreateFontIndirect(
  LPDIRECT3DDEVICE9 pDevice,
  CONST D3DXFONT_DESC * pDesc,
  LPD3DXFONT * ppFont
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the font object.
pDesc
[in] Pointer to a D3DXFONT_DESC structure, describing the attributes of the font object to create. If the compiler settings require Unicode, the data type D3DXFONT_DESC resolves to D3DXFONT_DESCW; otherwise, the data type resolves to D3DXFONT_DESCA. See Remarks.
ppFont
[out] Returns a pointer to an ID3DXFont interface, representing the created font object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateFontIndirectW. Otherwise, the function call resolves to D3DXCreateFontIndirectA because ANSI strings are being used.

Requirements

Header: Declared in D3dx9core.h.


D3DXCreateLine

Uses a left-handed coordinate system to create a line.

HRESULT D3DXCreateLine(
  LPDIRECT3DDEVICE9 pDevice,
  LPD3DXLINE* ppLine
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created box mesh.
ppLine
[out] Pointer to an ID3DXLine interface.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL Flexible Vertex Format (FVF).

Requirements

Header: Declared in D3dx9core.h.


D3DXCreateRenderToEnvMap

Creates a render environment map.

HRESULT D3DXCreateRenderToEnvMap(
  LPDIRECT3DDEVICE9 pDevice,
  UINT Size,
  UINT MipLevels,
  D3DFORMAT Format,
  BOOL DepthStencil,
  D3DFORMAT DepthStencilFormat,
  LPD3DXRENDERTOENVMAP * ppRenderToEnvMap
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, which is the device to associate with the render surface.
Size
[in] Size of the render surface.
MipLevels
[in] The number of mipmap levels.
Format
[in] Member of the D3DFORMAT enumerated type that describes the pixel format of the environment map.
DepthStencil
[in] If TRUE, the render surface supports a depth-stencil surface. Otherwise, this member is set to FALSE.
DepthStencilFormat
[in] If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type that describes the depth-stencil format of the environment map.
ppRenderToEnvMap
[out, retval] Address of a pointer to an ID3DXRenderToEnvMap interface that represents the created render environment map.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9core.h.


D3DXCreateRenderToSurface

Creates a render surface.

HRESULT D3DXCreateRenderToSurface(
  LPDIRECT3DDEVICE9 pDevice,
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  BOOL DepthStencil,
  D3DFORMAT DepthStencilFormat,
  LPD3DXRENDERTOSURFACE * ppRenderToSurface
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the render surface.
Width
[in] Width of the render surface, in pixels.
Height
[in] Height of the render surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the pixel format of the render surface.
DepthStencil
[in] If TRUE, the render surface supports a depth-stencil surface. Otherwise, this member is set to FALSE. This function will create a new depth buffer.
DepthStencilFormat
[in] If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type, describing the depth-stencil format of the render surface.
ppRenderToSurface
[out, retval] Address of a pointer to an ID3DXRenderToSurface interface, representing the created render surface.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9core.h.


D3DXCreateSprite

Creates a sprite object which is associated with a particular device. Sprite objects are used to draw 2D images to the screen.

HRESULT D3DXCreateSprite(
  LPDIRECT3DDEVICE9 pDevice,
  LPD3DXSPRITE * ppSprite
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the sprite.
ppSprite
[out] Address of a pointer to an ID3DXSprite interface. This interface allows the user to access sprite functions.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This interface can be used to draw two dimensional images in screen space of the associated device.

Requirements

Header: Declared in D3dx9core.h.


D3DXDebugMute

Turns on or off all D3DX debug output.

BOOL D3DXDebugMute(
  BOOL Mute
);

Parameters

Mute
[in] If TRUE, debugger output is halted; if FALSE, debug output is enabled.

Return Values

Returns the previous value of Mute.

Requirements

Header: Declared in D3dx9core.h.


D3DXGetDriverLevel

Returns the driver level.

UINT D3DXGetDriverLevel(
  LPDIRECT3DDEVICE9 pDevice
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device.

Return Values

The driver level. See remarks.

Remarks

This method returns the driver version, which is one of the following:

  • 700 - Direct3D 7 level driver
  • 800 - Direct3D 8 level driver
  • 900 - Direct3D 9 level driver

Requirements

Header: Declared in D3dx9core.h.


Math Functions

The math library provided by the D3DX utility library supplies functions to compute 3D mathematical operations. Each of the functions can take the same object as the passed [in] and returned [out] parameters. Also, out parameters are typically returned as return values, so that the output of one math function can be used as a parameter for another math function.

Many of the functions are implemented in d3dx9math.inl.

The 3D math application functions can be organized into the following groups.

Functions

  • D3DXColorAdd
  • D3DXColorAdjustContrast
  • D3DXColorAdjustSaturation
  • D3DXColorLerp
  • D3DXColorModulate
  • D3DXColorNegative
  • D3DXColorScale
  • D3DXColorSubtract
  • D3DXCreateMatrixStack
  • D3DXFloat16To32Array
  • D3DXFloat32To16Array
  • D3DXFresnelTerm
  • D3DXMatrixAffineTransformation
  • D3DXMatrixAffineTransformation2D
  • D3DXMatrixDecompose
  • D3DXMatrixDeterminant
  • D3DXMatrixIdentity
  • D3DXMatrixInverse
  • D3DXMatrixIsIdentity
  • D3DXMatrixLookAtLH
  • D3DXMatrixLookAtRH
  • D3DXMatrixMultiply
  • D3DXMatrixMultiplyTranspose
  • D3DXMatrixOrthoLH
  • D3DXMatrixOrthoOffCenterLH
  • D3DXMatrixOrthoOffCenterRH
  • D3DXMatrixOrthoRH
  • D3DXMatrixPerspectiveFovLH
  • D3DXMatrixPerspectiveFovRH
  • D3DXMatrixPerspectiveLH
  • D3DXMatrixPerspectiveOffCenterLH
  • D3DXMatrixPerspectiveOffCenterRH
  • D3DXMatrixPerspectiveRH
  • D3DXMatrixReflect
  • D3DXMatrixRotationAxis
  • D3DXMatrixRotationQuaternion
  • D3DXMatrixRotationX
  • D3DXMatrixRotationY
  • D3DXMatrixRotationYawPitchRoll
  • D3DXMatrixRotationZ
  • D3DXMatrixScaling
  • D3DXMatrixShadow
  • D3DXMatrixTransformation
  • D3DXMatrixTransformation2D
  • D3DXMatrixTranslation
  • D3DXMatrixTranspose
  • D3DXPlaneDot
  • D3DXPlaneDotCoord
  • D3DXPlaneDotNormal
  • D3DXPlaneFromPointNormal
  • D3DXPlaneFromPoints
  • D3DXPlaneIntersectLine
  • D3DXPlaneNormalize
  • D3DXPlaneScale
  • D3DXPlaneTransform
  • D3DXPlaneTransformArray
  • D3DXQuaternionBaryCentric
  • D3DXQuaternionConjugate
  • D3DXQuaternionDot
  • D3DXQuaternionExp
  • D3DXQuaternionIdentity
  • D3DXQuaternionInverse
  • D3DXQuaternionIsIdentity
  • D3DXQuaternionLength
  • D3DXQuaternionLengthSq
  • D3DXQuaternionLn
  • D3DXQuaternionMultiply
  • D3DXQuaternionNormalize
  • D3DXQuaternionRotationAxis
  • D3DXQuaternionRotationMatrix
  • D3DXQuaternionRotationYawPitchRoll
  • D3DXQuaternionSlerp
  • D3DXQuaternionSquad
  • D3DXQuaternionSquadSetup
  • D3DXQuaternionToAxisAngle
  • D3DXSHAdd
  • D3DXSHDot
  • D3DXSHEvalConeLight
  • D3DXSHEvalDirection
  • D3DXSHEvalDirectionalLight
  • D3DXSHEvalHemisphereLight
  • D3DXSHEvalSphericalLight
  • D3DXSHProjectCubeMap
  • D3DXSHRotate
  • D3DXSHRotateZ
  • D3DXSHScale
  • D3DXVec2Add
  • D3DXVec2BaryCentric
  • D3DXVec2CatmullRom
  • D3DXVec2CCW
  • D3DXVec2Dot
  • D3DXVec2Hermite
  • D3DXVec2Length
  • D3DXVec2LengthSq
  • D3DXVec2Lerp
  • D3DXVec2Maximize
  • D3DXVec2Minimize
  • D3DXVec2Normalize
  • D3DXVec2Scale
  • D3DXVec2Subtract
  • D3DXVec2Transform
  • D3DXVec2TransformArray
  • D3DXVec2TransformCoord
  • D3DXVec2TransformCoordArray
  • D3DXVec2TransformNormal
  • D3DXVec2TransformNormalArray
  • D3DXVec3Add
  • D3DXVec3BaryCentric
  • D3DXVec3CatmullRom
  • D3DXVec3Cross
  • D3DXVec3Dot
  • D3DXVec3Hermite
  • D3DXVec3Length
  • D3DXVec3LengthSq
  • D3DXVec3Lerp
  • D3DXVec3Maximize
  • D3DXVec3Minimize
  • D3DXVec3Normalize
  • D3DXVec3Project
  • D3DXVec3ProjectArray
  • D3DXVec3Scale
  • D3DXVec3Subtract
  • D3DXVec3Transform
  • D3DXVec3TransformArray
  • D3DXVec3TransformCoord
  • D3DXVec3TransformCoordArray
  • D3DXVec3TransformNormal
  • D3DXVec3TransformNormalArray
  • D3DXVec3Unproject
  • D3DXVec3UnprojectArray
  • D3DXVec4Add
  • D3DXVec4BaryCentric
  • D3DXVec4CatmullRom
  • D3DXVec4Cross
  • D3DXVec4Dot
  • D3DXVec4Hermite
  • D3DXVec4Length
  • D3DXVec4LengthSq
  • D3DXVec4Lerp
  • D3DXVec4Maximize
  • D3DXVec4Minimize
  • D3DXVec4Normalize
  • D3DXVec4Scale
  • D3DXVec4Subtract
  • D3DXVec4Transform
  • D3DXVec4TransformArray


D3DXColorAdd

Adds two color values together to create a new color value.

D3DXCOLOR * D3DXColorAdd(
  D3DXCOLOR * pOut,
  CONST D3DXCOLOR * pC1,
  CONST D3DXCOLOR * pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the sum of two color values.

Remarks

The return value for this function is the same value returned in pOut. In this way, the D3DXColorAdd function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXColorModulate, D3DXColorSubtract


D3DXColorAdjustContrast

Adjusts the contrast value of a color.

D3DXCOLOR * D3DXColorAdjustContrast(
  D3DXCOLOR * pOut,
  CONST D3DXCOLOR * pC,
  FLOAT c
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
c
[in] Contrast value. This parameter linearly interpolates between fifty percent gray and the color, pC. There are not limits on the value of c. If this parameter is zero, then the returned color is fifty percent gray. If this parameter is 1, then the returned color is the original color.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the result of the contrast adjustment.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between fifty percent gray and a specified contrast value, as shown in the following example.

pOut->r = 0.5f + c * (pC->r - 0.5f);

If c is greater than 0 and less than 1, the contrast is decreased. If c is greater than 1, the contrast is increased.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXColorAdjustSaturation


D3DXColorAdjustSaturation

Adjusts the saturation value of a color.

D3DXCOLOR * D3DXColorAdjustSaturation(
  D3DXCOLOR * pOut,
  CONST D3DXCOLOR * pC,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Saturation value. This parameter linearly interpolates between the color converted to grayscale and the original color, pC. There are no limits on the value of s. If s is 0, the returned color is the grayscale color. If s is 1, the returned color is the original color.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the result of the saturation adjustment.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between an unsaturated color and a color, as shown in the following example.

    // Approximate values for each component's contribution to luminance.
    // Based upon the NTSC standard described in ITU-R Recommendation BT.709.
    FLOAT grey = pC->r * 0.2125f + pC->g * 0.7154f + pC->b * 0.0721f;

    pOut->r = grey + s * (pC->r - grey);

If s is greater than 0 and less than 1, the saturation is decreased. If s is greater than 1, the saturation is increased.

The grayscale color is computed as:

r = g = b = 0.2125*r + 0.7154*g + 0.0721*b

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXColorAdjustContrast


D3DXColorLerp

Uses linear interpolation to create a color value.

D3DXCOLOR * D3DXColorLerp(
  D3DXCOLOR * pOut,
  CONST D3DXCOLOR * pC1,
  CONST D3DXCOLOR * pC2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Parameter that linearly interpolates between the colors, pC1 and pC2, treating them both as 4D vectors. There are no limits on the value of s.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the result of the linear interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorLerp function can be used as a parameter for another function.

This function interpolates the red, green, blue, and alpha components of a D3DXCOLOR structure between two colors, as shown in the following example.

pOut->r = pC1->r + s * (pC2->r - pC1->r);

If you are linearly interpolating between the colors A and B, and s is 0, the resulting color is A. If s is 1, the resulting color is color B.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXColorModulate, D3DXColorNegative, D3DXColorScale


D3DXColorModulate

Blends two colors.

D3DXCOLOR * D3DXColorModulate(
  D3DXCOLOR * pOut,
  CONST D3DXCOLOR * pC1,
  CONST D3DXCOLOR * pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the result of the blending operation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorModulate function can be used as a parameter for another function.

This function blends together two colors by multiplying matching color components, as shown in the following example.

pOut->r = pC1->r * pC2->r;

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXColorLerp, D3DXColorNegative, D3DXColorScale


D3DXColorNegative

Creates the negative color value of a color value.

D3DXCOLOR * D3DXColorNegative(
  D3DXCOLOR * pOut,
  CONST D3DXCOLOR * pC
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the negative color value of the color value.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorNegative function can be used as a parameter for another function.

This function returns the negative color value by subtracting 1.0 from the color components of the D3DXCOLOR structure, as shown in the following example.

pOut->r = 1.0f - pC->r;

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorScale


D3DXColorScale

Scales a color value.

D3DXCOLOR * D3DXColorScale(
  D3DXCOLOR * pOut,
  CONST D3DXCOLOR * pC,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Scale factor. It scales the color, treating it like a 4D vector. There are no limits on the value of s. If s is 1, the resulting color is the original color.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the scaled color value.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorScale function can be used as a parameter for another function.

This function computes the scaled color value by multiplying the color components of the D3DXCOLOR structure by the specified scale factor, as shown in the following example.

pOut->r = pC->r * s;

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorNegative


D3DXColorSubtract

Subtracts two color values to create a new color value.

D3DXCOLOR * D3DXColorSubtract(
  D3DXCOLOR * pOut,
  CONST D3DXCOLOR * pC1,
  CONST D3DXCOLOR * pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the difference between two color values.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorSubtract function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXColorAdd


D3DXCreateMatrixStack

Creates an instance of the ID3DXMATRIXStack interface.

HRESULT D3DXCreateMatrixStack(
  DWORD Flags,
  LPD3DXMATRIXSTACK * ppStack
);

Parameters

Flags
[in] Not implemented. Specify zero.
ppStack
[out] Address of a pointer filled with an ID3DXMATRIXStack interface pointer if the function succeeds.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx9math.h.


D3DXFloat16To32Array

Converts an array of 16-bit floats to 32-bit floats.

FLOAT * D3DXFloat16To32Array(
  FLOAT * pOut,
  CONST D3DXFLOAT16 * pIn,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the array of 32-bit floats.
pIn
[in] Pointer to an array of 16-bit floats.
n
[in] Number of elements in the array.

Return Values

Pointer to an array of 32-bit floats.

Requirements

Header: Declared in D3dx9math.h.


D3DXFloat32To16Array

Converts an array of 32-bit floats to 16-bit floats.

D3DXFLOAT16 * D3DXFloat32To16Array(
  D3DXFLOAT16* pOut,
  CONST FLOAT* pIn,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the array of 16-bit floats.
pIn
[in] Pointer to an array of 32-bit floats.
n
[in] The number of elements in the array.

Return Values

Pointer to an array of 16-bit floats.

Requirements

Header: Declared in D3dx9math.h.


D3DXFresnelTerm

Calculate the Fresnel term.

FLOAT D3DXFresnelTerm(
  FLOAT CosTheta,
  FLOAT RefractionIndex
);

Parameters

CosTheta
[in] The value must be between 0 and 1.
RefractionIndex
[in] The refraction index of a material. The value must be greater than 1.

Return Values

This function returns the Fresnel term for unpolarized light. CosTheta is the cosine of the incident angle.

Remarks

To find the Fresnel term (F):

If A is angle of incidence and B is the angle of refraction, then

F = 0.5 * [tan2(A - B) / tan2(A + B) + sin2(A - B) / sin2(A + B)]
  = 0.5 * sin2(A - B) / sin2(A + B) * [cos2(A + B) / cos2(A - B) + 1]

Let r   = sina(A) / sin(B)      (the relative refractive index)
Let c   = cos(A)
Let g   = (r2 + c2 - 1)1/2

Then, expanding using the trig identities and simplifying, you get:

F = 0.5 * (g + c)2 / (g - c)2 * ([c(g + c) - 1]2 / [c(g - c) + 1]2 + 1)

Requirements

Header: Declared in D3dx9math.h.


D3DXMatrixAffineTransformation

Builds a 3D affine transformation matrix. NULL arguments are treated as identity transformations.

D3DXMATRIX * D3DXMatrixAffineTransformation(
  D3DXMATRIX * pOut,
  FLOAT Scaling,
  CONST D3DXVECTOR3 * pRotationCenter,
  CONST D3DXQUATERNION * pRotation,
  CONST D3DXVECTOR3 * pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Scaling
[in] Scaling factor.
pRotationCenter
[in] Pointer to a D3DXVECTOR3 structure, a point identifying the center of rotation. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
pRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the rotation. If this argument is NULL, an identity Mr matrix is applied to the formula in Remarks.
pTranslation
[in] Pointer to a D3DXVECTOR3 structure representing the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Values

Pointer to a D3DXMATRIX structure that is an affine transformation matrix.

Remarks

This function calculates the affine transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = Ms * (Mrc)-1 * Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Ms = scaling matrix (Scaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (pRotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixAffineTransformation function can be used as a parameter for another function.

For 2D affine transformations, use D3DXMatrixAffineTransformation2D.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixTransformation, Transforms (Direct3D 9)


D3DXMatrixAffineTransformation2D

Builds a 2D affine transformation matrix in the xy plane. NULL arguments are treated as identity transformations.

D3DXMATRIX * D3DXMatrixAffineTransformation2D(
  D3DXMATRIX * pOut,
  FLOAT Scaling,
  CONST D3DXVECTOR2 * pRotationCenter,
  FLOAT Rotation,
  CONST D3DXVECTOR2 * pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Scaling
[in] Scaling factor.
pRotationCenter
[in] Pointer to a D3DXVECTOR2 structure, a point identifying the center of rotation. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
Rotation
[in] The angle of rotation.
pTranslation
[in] Pointer to a D3DXVECTOR2 structure, representing the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Values

Pointer to a D3DXMATRIX structure that is an affine transformation matrix.

Remarks

This function calculates the affine transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = Ms * (Mrc)-1 * Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Ms = scaling matrix (Scaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (Rotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixAffineTransformation2D function can be used as a parameter for another function.

For 3D affine transformations, use D3DXMatrixAffineTransformation.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixTransformation2D, Transforms (Direct3D 9)


D3DXMatrixDecompose

Breaks down a general 3D transformation matrix into its scalar, rotational, and translational components.

HRESULT D3DXMatrixDecompose(
  D3DXVECTOR3 * pOutScale,
  D3DXQUATERNION * pOutRotation,
  D3DXVECTOR3 * pOutTranslation,
  CONST D3DXMATRIX * pM
);

Parameters

pOutScale
[in, out] Pointer to the output D3DXVECTOR3 that contains scaling factors applied along the x, y, and z-axes.
pOutRotation
[in, out] Pointer to the D3DXQUATERNION structure that describes the rotation.
pOutTranslation
[in, out] Pointer to the D3DXVECTOR3 vector that describes the translation.
pM
[in] Pointer to an input D3DXMATRIX matrix to decompose.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9math.h.


D3DXMatrixDeterminant

Returns the determinant of a matrix.

FLOAT D3DXMatrixDeterminant(
  CONST D3DXMATRIX * pM
);

Parameters

pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Returns the determinant of the matrix.

Requirements

Header: Declared in D3dx9math.h.


D3DXMatrixIdentity

Creates an identity matrix.

D3DXMATRIX * D3DXMatrixIdentity(
  D3DXMATRIX * pOut
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.

Return Values

Pointer to a D3DXMATRIX structure that is the identity matrix.

Remarks

The identity matrix is a matrix in which all coefficients are 0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4 x4 matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixIdentity function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixIsIdentity


D3DXMatrixInverse

Calculates the inverse of a matrix.

D3DXMATRIX * D3DXMatrixInverse(
  D3DXMATRIX * pOut,
  FLOAT * pDeterminant,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pDeterminant
[in, out] Pointer to a FLOAT value containing the determinant of the matrix. If the determinant is not needed, set this parameter to NULL.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXMATRIX structure that is the inverse of the matrix. If matrix inversion fails, NULL is returned.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixInverse function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXMatrixIsIdentity

Determines if a matrix is an identity matrix.

BOOL D3DXMatrixIsIdentity(
  CONST D3DXMATRIX * pM
);

Parameters

pM
[in] Pointer to the D3DXMATRIX structure that will be tested for identity.

Return Values

If the matrix is an identity matrix, this function returns TRUE. Otherwise, this function returns FALSE.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixIdentity


D3DXMatrixLookAtLH

Builds a left-handed, look-at matrix.

D3DXMATRIX * D3DXMatrixLookAtLH(
  D3DXMATRIX * pOut,
  CONST D3DXVECTOR3 * pEye,
  CONST D3DXVECTOR3 * pAt,
  CONST D3DXVECTOR3 * pUp
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
[in] Pointer to the D3DXVECTOR3 structure that defines the eye point. This value is used in translation.
pAt
[in] Pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
[in] Pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Values

Pointer to a D3DXMATRIX structure that is a left-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

zaxis = normal(At - Eye)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, eye)  -dot(yaxis, eye)  -dot(zaxis, eye)  l

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixLookAtRH


D3DXMatrixLookAtRH

Builds a right-handed, look-at matrix.

D3DXMATRIX * D3DXMatrixLookAtRH(
  D3DXMATRIX * pOut,
  CONST D3DXVECTOR3 * pEye,
  CONST D3DXVECTOR3 * pAt,
  CONST D3DXVECTOR3 * pUp
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
[in] Pointer to the D3DXVECTOR3 structure that defines the eye point. This value is used in translation.
pAt
[in] Pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
[in] Pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Values

Pointer to a D3DXMATRIX structure that is a right-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

zaxis = normal(Eye - At)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, eye)  -dot(yaxis, eye)  -dot(zaxis, eye)  l

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixLookAtLH


D3DXMatrixMultiply

Determines the product of two matrices.

D3DXMATRIX * D3DXMatrixMultiply(
  D3DXMATRIX * pOut,
  CONST D3DXMATRIX * pM1,
  CONST D3DXMATRIX * pM2
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM1
[in] Pointer to a source D3DXMATRIX structure.
pM2
[in] Pointer to a source D3DXMATRIX structure.

Return Values

Pointer to a D3DXMATRIX structure that is the product of two matrices.

Remarks

The result represents the transformation M1 followed by the transformation M2 (Out = M1 * M2).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixMultiply function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionMultiply


D3DXMatrixMultiplyTranspose

Calculates the transposed product of two matrices.

D3DXMATRIX * D3DXMatrixMultiplyTranspose(
  D3DXMATRIX* pOut,
  CONST D3DXMATRIX* pM1,
  CONST D3DXMATRIX* pM2
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM1
[in] Pointer to a source D3DXMATRIX structure.
pM2
[in] Pointer to a source D3DXMATRIX structure.

Return Values

Pointer to a D3DXMATRIX structure that is the product of two matrices.

Remarks

The result is the transposed of the product of two transformation matrices, Out = T(M1*M2).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixMultiplyTranspose function can be used as a parameter for another function.

This function is useful to set matrices as constants for vertex and pixel shaders.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixMultiply, D3DXQuaternionMultiply


D3DXMatrixOrthoLH

Builds a left-handed orthographic projection matrix.

D3DXMATRIX * D3DXMatrixOrthoLH(
  D3DXMATRIX * pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the resulting D3DXMATRIX.
w
[in] Width of the view volume.
h
[in] Height of the view volume.
zn
[in] Minimum z-value of the view volume which is referred to as z-near.
zf
[in] Maximum z-value of the view volume which is referred to as z-far.

Return Values

Pointer to the resulting D3DXMATRIX.

Remarks

All the parameters of the D3DXMatrixOrthoLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/w  0    0           0
0    2/h  0           0
0    0    1/(zf-zn)   0
0    0   -zn/(zf-zn)  1

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoOffCenterRH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoOffCenterLH

Builds a customized, left-handed orthographic projection matrix.

D3DXMATRIX * D3DXMatrixOrthoOffCenterLH(
  D3DXMATRIX * pOut,
  FLOAT l,
  FLOAT r,
  FLOAT b,
  FLOAT t,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the resulting D3DXMATRIX.
l
[in] Minimum x-value of view volume.
r
[in] Maximum x-value of view volume.
b
[in] Minimum y-value of view volume.
t
[in] Maximum y-value of view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to the resulting D3DXMATRIX.

Remarks

The D3DXMatrixOrthoLH function is a special case of the D3DXMatrixOrthoOffCenterLH function. To create the same projection using D3DXMatrixOrthoOffCenterLH, use the following values:

    l = -w/2,

    r = w/2,

    b = -h/2, and

    t = h/2.

All the parameters of the D3DXMatrixOrthoOffCenterLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/(r-l)      0            0           0
0            2/(t-b)      0           0
0            0            1/(zf-zn)   0
(l+r)/(l-r)  (t+b)/(b-t)  zn/(zn-zf)  l

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterRH


D3DXMatrixOrthoOffCenterRH

Builds a customized, right-handed orthographic projection matrix.

D3DXMATRIX * D3DXMatrixOrthoOffCenterRH(
  D3DXMATRIX * pOut,
  FLOAT l,
  FLOAT r,
  FLOAT b,
  FLOAT t,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the resulting D3DXMATRIX.
l
[in] Minimum x-value of view volume.
r
[in] Maximum x-value of view volume.
b
[in] Minimum y-value of view volume.
t
[in] Maximum y-value of view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to the resulting D3DXMATRIX.

Remarks

The D3DXMatrixOrthoRH function is a special case of the D3DXMatrixOrthoOffCenterRH function. To create the same projection using D3DXMatrixOrthoOffCenterRH, use the following values:

    l = -w/2,

    r = w/2,

    b = -h/2, and

    t = h/2.

All the parameters of the D3DXMatrixOrthoOffCenterRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/(r-l)      0            0           0
0            2/(t-b)      0           0
0            0            1/(zn-zf)   0
(l+r)/(l-r)  (t+b)/(b-t)  zn/(zn-zf)  l

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoRH

Builds a right-handed orthographic projection matrix.

D3DXMATRIX * D3DXMatrixOrthoRH(
  D3DXMATRIX * pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the resulting D3DXMATRIX.
w
[in] Width of the view volume.
h
[in] Height of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to the resulting D3DXMATRIX.

Remarks

All the parameters of the D3DXMatrixOrthoRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/w  0    0           0
0    2/h  0           0
0    0    1/(zn-zf)   0
0    0    zn/(zn-zf)  l

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterRH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixPerspectiveFovLH

Builds a left-handed perspective projection matrix based on a field of view.

D3DXMATRIX * D3DXMatrixPerspectiveFovLH(
  D3DXMATRIX * pOut,
  FLOAT fovy,
  FLOAT Aspect,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
fovy
[in] Field of view in the y direction, in radians.
Aspect
[in] Aspect ratio, defined as view space width divided by height.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovLH function can be used as a parameter for another function.

This function computes the returned matrix as shown:

xScale     0          0               0
0        yScale       0               0
0          0       zf/(zf-zn)         1
0          0       -zn*zf/(zf-zn)     0
where:
yScale = cot(fovY/2)

xScale = yScale / aspect ratio

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveFovRH

Builds a right-handed perspective projection matrix based on a field of view.

D3DXMATRIX * D3DXMatrixPerspectiveFovRH(
  D3DXMATRIX * pOut,
  FLOAT fovy,
  FLOAT Aspect,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
fovy
[in] Field of view in the y direction, in radians.
Aspect
[in] Aspect ratio, defined as view space width divided by height.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovRH function can be used as a parameter for another function.

This function computes the returned matrix as shown.

xScale     0          0              0
0        yScale       0              0
0        0        zf/(zn-zf)        -1
0        0        zn*zf/(zn-zf)      0
where:
yScale = cot(fovY/2)

xScale = yScale / aspect ratio

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveLH

Builds a left-handed perspective projection matrix

D3DXMATRIX * D3DXMatrixPerspectiveLH(
  D3DXMATRIX * pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view volume at the near view-plane.
h
[in] Height of the view volume at the near view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/w  0       0              0
0       2*zn/h  0              0
0       0       zf/(zf-zn)     1
0       0       zn*zf/(zn-zf)  0

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveOffCenterLH

Builds a customized, left-handed perspective projection matrix.

D3DXMATRIX * D3DXMatrixPerspectiveOffCenterLH(
  D3DXMATRIX * pOut,
  FLOAT l,
  FLOAT r,
  FLOAT b,
  FLOAT t,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of the view volume.
r
[in] Maximum x-value of the view volume.
b
[in] Minimum y-value of the view volume.
t
[in] Maximum y-value of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to a D3DXMATRIX structure that is a customized, left-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/(r-l)   0            0              0
0            2*zn/(t-b)   0              0
(l+r)/(l-r)  (t+b)/(b-t)  zf/(zf-zn)     1
0            0            zn*zf/(zn-zf)  0

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH


D3DXMatrixPerspectiveOffCenterRH

Builds a customized, right-handed perspective projection matrix.

D3DXMATRIX * D3DXMatrixPerspectiveOffCenterRH(
  D3DXMATRIX * pOut,
  FLOAT l,
  FLOAT r,
  FLOAT b,
  FLOAT t,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of the view volume.
r
[in] Maximum x-value of the view volume.
b
[in] Minimum y-value of the view volume.
t
[in] Maximum y-value of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to a D3DXMATRIX structure that is a customized, right-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/(r-l)   0            0                0
0            2*zn/(t-b)   0                0
(l+r)/(r-l)  (t+b)/(t-b)  zf/(zn-zf)      -1
0            0            zn*zf/(zn-zf)    0

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveRH

Builds a right-handed perspective projection matrix.

D3DXMATRIX * D3DXMatrixPerspectiveRH(
  D3DXMATRIX * pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view volume at the near view-plane.
h
[in] Height of the view volume at the near view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/w  0       0              0
0       2*zn/h  0              0
0       0       zf/(zn-zf)    -1
0       0       zn*zf/(zn-zf)  0

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixReflect

Builds a matrix that reflects the coordinate system about a plane.

D3DXMATRIX * D3DXMatrixReflect(
  D3DXMATRIX * pOut,
  CONST D3DXPLANE * pPlane
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pPlane
[in] Pointer to the source D3DXPLANE structure.

Return Values

Pointer to a D3DXMATRIX structure that reflects the coordinate system about the source plane.

Remarks

This function normalizes the plane equation before it creates the reflected matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixReflect function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

P = normalize(Plane);

-2 * P.a * P.a + 1  -2 * P.b * P.a      -2 * P.c * P.a        0
-2 * P.a * P.b      -2 * P.b * P.b + 1  -2 * P.c * P.b        0
-2 * P.a * P.c      -2 * P.b * P.c      -2 * P.c * P.c + 1    0
-2 * P.a * P.d      -2 * P.b * P.d      -2 * P.c * P.d        l

Requirements

Header: Declared in D3dx9math.h.


D3DXMatrixRotationAxis

Builds a matrix that rotates around an arbitrary axis.

D3DXMATRIX * D3DXMatrixRotationAxis(
  D3DXMATRIX * pOut,
  CONST D3DXVECTOR3 * pV,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pV
[in] Pointer to the arbitrary axis. See D3DXVECTOR3.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationAxis function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationQuaternion

Builds a rotation matrix from a quaternion.

D3DXMATRIX * D3DXMatrixRotationQuaternion(
  D3DXMATRIX * pOut,
  CONST D3DXQUATERNION * pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXMATRIX structure built from the source quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationQuaternion function can be used as a parameter for another function.

For information about how to calculate quaternion values from a direction vector ( x, y, z ) and an angle of rotation, see D3DXQUATERNION.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationX

Builds a matrix that rotates around the x-axis.

D3DXMATRIX * D3DXMatrixRotationX(
  D3DXMATRIX * pOut,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the x-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationX function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationY

Builds a matrix that rotates around the y-axis.

D3DXMATRIX * D3DXMatrixRotationY(
  D3DXMATRIX * pOut,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the y-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationY function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationYawPitchRoll

Builds a matrix with a specified yaw, pitch, and roll.

D3DXMATRIX * D3DXMatrixRotationYawPitchRoll(
  D3DXMATRIX * pOut,
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Yaw
[in] Yaw around the y-axis, in radians.
Pitch
[in] Pitch around the x-axis, in radians.
Roll
[in] Roll around the z-axis, in radians.

Return Values

Pointer to a D3DXMATRIX structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationYawPitchRoll function can be used as a parameter for another function.

The order of transformations is roll first, then pitch, then yaw. Relative to the object's local coordinate axis, this is equivalent to rotation around the z-axis, followed by rotation around the x-axis, followed by rotation around the y-axis.

Roll, pitch, yaw diagram

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ


D3DXMatrixRotationZ

Builds a matrix that rotates around the z-axis.

D3DXMATRIX * D3DXMatrixRotationZ(
  D3DXMATRIX * pOut,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when viewed from the rotation axis (positive side) toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the z-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationZ function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll


D3DXMatrixScaling

Builds a matrix that scales along the x-axis, the y-axis, and the z-axis.

D3DXMATRIX * D3DXMatrixScaling(
  D3DXMATRIX * pOut,
  FLOAT sx,
  FLOAT sy,
  FLOAT sz
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
sx
[in] Scaling factor that is applied along the x-axis.
sy
[in] Scaling factor that is applied along the y-axis.
sz
[in] Scaling factor that is applied along the z-axis.

Return Values

Pointer to the scaling transformation D3DXMATRIX.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixScaling function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXMatrixShadow

Builds a matrix that flattens geometry into a plane.

D3DXMATRIX * D3DXMatrixShadow(
  D3DXMATRIX * pOut,
  CONST D3DXVECTOR4 * pLight,
  CONST D3DXPLANE * pPlane
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pLight
[in] Pointer to a D3DXVECTOR4 structure describing the light's position.
pPlane
[in] Pointer to the source D3DXPLANE structure.

Return Values

Pointer to a D3DXMATRIX structure that flattens geometry into a plane.

Remarks

The D3DXMatrixShadow function flattens geometry into a plane, as if casting a shadow from a light.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixShadow function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

P = normalize(Plane);
L = Light;
d = dot(P, L)

P.a * L.x + d  P.a * L.y      P.a * L.z      P.a * L.w
P.b * L.x      P.b * L.y + d  P.b * L.z      P.b * L.w
P.c * L.x      P.c * L.y      P.c * L.z + d  P.c * L.w
P.d * L.x      P.d * L.y      P.d * L.z      P.d * L.w + d

If the light's w-component is 0, the ray from the origin to the light represents a directional light. If it is 1, the light is a point light.

Requirements

Header: Declared in D3dx9math.h.


D3DXMatrixTransformation

Builds a transformation matrix. NULL arguments are treated as identity transformations.

D3DXMATRIX * D3DXMatrixTransformation(
  D3DXMATRIX * pOut,
  CONST D3DXVECTOR3 * pScalingCenter,
  CONST D3DXQUATERNION * pScalingRotation,
  CONST D3DXVECTOR3 * pScaling,
  CONST D3DXVECTOR3 * pRotationCenter,
  CONST D3DXQUATERNION * pRotation,
  CONST D3DXVECTOR3 * pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pScalingCenter
[in] Pointer to a D3DXVECTOR3 structure, identifying the scaling center point. If this argument is NULL, an identity Msc matrix is applied to the formula in Remarks.
pScalingRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the scaling rotation. If this argument is NULL, an identity Msr matrix is applied to the formula in Remarks.
pScaling
[in] Pointer to a D3DXVECTOR3 structure, the scaling vector. If this argument is NULL, an identity Ms matrix is applied to the formula in Remarks.
pRotationCenter
[in] Pointer to a D3DXVECTOR3 structure, a point that identifies the center of rotation. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
pRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the rotation. If this argument is NULL, an identity Mr matrix is applied to the formula in Remarks.
pTranslation
[in] Pointer to a D3DXVECTOR3 structure, representing the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Values

Pointer to a D3DXMATRIX structure that is the transformation matrix.

Remarks

This function calculates the transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = (Msc)-1 * (Msr)-1* Ms * Msr * Msc * (Mrc)-1* Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Msc = scaling center matrix (pScalingCenter)

Msr = scaling rotation matrix (pScalingRotation)

Ms = scaling matrix (pScaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (pRotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTransformation function can be used as a parameter for another function.

For 2D transformations, use D3DXMatrixTransformation2D.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixAffineTransformation, Transforms (Direct3D 9)


D3DXMatrixTransformation2D

Builds a 2D transformation matrix that represents transformations in the xy plane. NULL arguments are treated as identity transformations.

D3DXMATRIX * D3DXMatrixTransformation2D(
  D3DXMATRIX * pOut,
  CONST D3DXVECTOR2 * pScalingCenter,
  FLOAT pScalingRotation,
  CONST D3DXVECTOR2 * pScaling,
  CONST D3DXVECTOR2 * pRotationCenter,
  FLOAT Rotation,
  CONST D3DXVECTOR2 * pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that contains the result of the transformations.
pScalingCenter
[in] Pointer to a D3DXVECTOR2 structure, a point identifying the scaling center. If this argument is NULL, an identity Msc matrix is applied to the formula in Remarks.
pScalingRotation
[in] The scaling rotation factor.
pScaling
[in] Pointer to a D3DXVECTOR2 structure, a point identifying the scale. If this argument is NULL, an identity Ms matrix is applied to the formula in Remarks.
pRotationCenter
[in] Pointer to a D3DXVECTOR2 structure, a point identifying the rotation center. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
Rotation
[in] The angle of rotation in radians.
pTranslation
[in] Pointer to a D3DXVECTOR2 structure, identifying the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Values

Pointer to a D3DXMATRIX structure that contains the transformation matrix.

Remarks

This function calculates the transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = (Msc)-1* (Msr)-1* Ms * Msr * Msc * (Mrc)-1* Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Msc = scaling center matrix (pScalingCenter)

Msr = scaling rotation matrix (pScalingRotation)

Ms = scaling matrix (pScaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (Rotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTransformation2D function can be used as a parameter for another function.

For 3D transformations, use D3DXMatrixTransformation.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixAffineTransformation2D, Transforms (Direct3D 9)


D3DXMatrixTranslation

Builds a matrix using the specified offsets.

D3DXMATRIX * D3DXMatrixTranslation(
  D3DXMATRIX * pOut,
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
x
[in] X-coordinate offset.
y
[in] Y-coordinate offset.
z
[in] Z-coordinate offset.

Return Values

Pointer to a D3DXMATRIX structure that contains a translated transformation matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMATRIXTranslation can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXMatrixTranspose

Returns the matrix transpose of a matrix.

D3DXMATRIX * D3DXMatrixTranspose(
  D3DXMATRIX * pOut,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to the D3DXMATRIX structure that is the matrix transpose of the matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTranspose function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXPlaneDot

Computes the dot product of a plane and a 4D vector.

FLOAT D3DXPlaneDot(
  CONST D3DXPLANE * pP,
  CONST D3DXVECTOR4 * pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a D3DXVECTOR4 structure.

Return Values

The dot product of the plane and 4D vector.

Remarks

Given a plane (a, b, c, d) and a 4D vector (x, y, z, w) the return value of this function is a*x + b*y + c*z + d*w. The D3DXPlaneDot function is useful for determining the plane's relationship with a homogeneous coordinate. For example, this function could be used to determine if a particular coordinate is on a particular plane, or on which side of a particular plane a particular coordinate lies.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXPlaneDotCoord, D3DXPlaneDotNormal


D3DXPlaneDotCoord

Computes the dot product of a plane and a 3D vector. The w parameter of the vector is assumed to be 1.

FLOAT D3DXPlaneDotCoord(
  CONST D3DXPLANE * pP,
  CONST D3DXVECTOR3 * pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

The dot product of the plane and 3D vector.

Remarks

Given a plane (a, b, c, d) and a 3D vector (x, y, z) the return value of this function is a*x + b*y + c*z + d*1. The D3DXPlaneDotCoord function is useful for determining the plane's relationship with a coordinate in 3D space.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXPlaneDot, D3DXPlaneDotNormal


D3DXPlaneDotNormal

Computes the dot product of a plane and a 3D vector. The w parameter of the vector is assumed to be 0.

FLOAT D3DXPlaneDotNormal(
  CONST D3DXPLANE * pP,
  CONST D3DXVECTOR3 * pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

The dot product of the plane and 3D vector.

Remarks

Given a plane (a, b, c, d) and a 3D vector (x, y, z) the return value of this function is a*x + b*y + c*z + d*0. The D3DXPlaneDotNormal function is useful for calculating the angle between the normal of the plane, and another normal.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXPlaneDot, D3DXPlaneDotCoord


D3DXPlaneFromPointNormal

Constructs a plane from a point and a normal.

D3DXPLANE * D3DXPlaneFromPointNormal(
  D3DXPLANE * pOut,
  CONST D3DXVECTOR3 * pPoint,
  CONST D3DXVECTOR3 * pNormal
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pPoint
[in] Pointer to a D3DXVECTOR3 structure, defining the point used to construct the plane.
pNormal
[in] Pointer to a D3DXVECTOR3 structure, defining the normal used to construct the plane.

Return Values

Pointer to the D3DXPLANE structure constructed from the point and the normal.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPointNormal function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXPlaneFromPoints


D3DXPlaneFromPoints

Constructs a plane from three points.

D3DXPLANE * D3DXPlaneFromPoints(
  D3DXPLANE * pOut,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2,
  CONST D3DXVECTOR3 * pV3
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pV1
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.
pV2
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.
pV3
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.

Return Values

Pointer to the D3DXPLANE structure constructed from the given points.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPoints function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXPlaneFromPointNormal


D3DXPlaneIntersectLine

Finds the intersection between a plane and a line.

D3DXVECTOR3 * D3DXPlaneIntersectLine(
  D3DXVECTOR3 * pOut,
  CONST D3DXPLANE * pP,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2
);

Parameters

pOut
[in, out] Pointer to a D3DXVECTOR3 structure, identifying the intersection between the specified plane and line.
pP
[in] Pointer to the source D3DXPLANE structure.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, defining a line starting point.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, defining a line ending point.

Return Values

Pointer to a D3DXVECTOR3 structure that is the intersection between the specified plane and line.

Remarks

If the line is parallel to the plane, NULL is returned.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneIntersectLine function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXPlaneNormalize

Normalizes the plane coefficients so that the plane normal has unit length.

D3DXPLANE * D3DXPlaneNormalize(
  D3DXPLANE * pOut,
  CONST D3DXPLANE * pP
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pP
[in] Pointer to the source D3DXPLANE structure.

Return Values

Pointer to a D3DXPLANE structure that represents the normal of the plane.

Remarks

This function normalizes a plane so that |a,b,c| == 1.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXPlaneScale

Scale the plane with the given scaling factor.

D3DXPLANE * D3DXPlaneScale(
  D3DXPLANE * pOut,
  CONST D3DXPLANE * pP,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pP
[in] Pointer to the source D3DXPLANE structure.
s
[in] Scale factor.

Return Values

Pointer to a D3DXPLANE structure that represents the scaled plane.

Remarks

The return value for this function is the same value returned in the pOut parameter. Therefore, this function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXPlaneTransform

Transforms a plane by a matrix. The input matrix is the inverse transpose of the actual transformation.

D3DXPLANE * D3DXPlaneTransform(
  D3DXPLANE * pOut,
  CONST D3DXPLANE * pP,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that contains the resulting transformed plane. See example.
pP
[in] Pointer to the input D3DXPLANE structure, which contains the plane that will be transformed. The vector (a,b,c) that describes the plane must be normalized before this function is called. See example.
pM
[in] Pointer to the source D3DXMATRIX structure, which contains the transformation values. This matrix must contain the inverse transpose of the transformation values.

Return Values

Pointer to a D3DXPLANE structure, representing the transformed plane. This is the same value returned in the pOut parameter so that this function can be used as a parameter for another function.

Remarks

Examples

This example transforms a plane by applying a non-uniform scale.

D3DXPLANE   planeNew;
D3DXPLANE   plane(0,1,1,0);
D3DXPlaneNormalize(&plane, &plane);

D3DXMATRIX  matrix;
D3DXMatrixScaling(&matrix, 1.0f,2.0f,3.0f);
D3DXMatrixInverse(&matrix, NULL, &matrix);
D3DXMatrixTranspose(&matrix, &matrix);
D3DXPlaneTransform(&planeNew, &plane, &matrix);

A plane is described by ax + by + cz + dw = 0. The first plane is created with (a,b,c,d) = (0,1,1,0), which is a plane described by y + z = 0. After scaling, the new plane contains (a,b,c,d) = (0, 0.353f, 0.235f, 0), which shows the new plane to be described by 0.353y + 0.235z = 0.

The parameter pM contains the inverse transpose of the transformation matrix. The inverse transpose is required by this method so that the normal vector of the transformed plane can be correctly transformed as well.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXPlaneNormalize, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ, D3DXMatrixInverse, D3DXMatrixTranspose


D3DXPlaneTransformArray

Transforms an array of planes by a matrix. The vectors that describe each plane must be normalized.

D3DXPLANE * D3DXPlaneTransformArray(
  D3DXPLANE * pOut,
  UINT OutStride,
  CONST D3DXPLANE* pP,
  UINT PStride,
  CONST D3DXMATRIX* pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that contains the resulting transformed plane. See Example.
OutStride
[out] The stride of each transformed plane.
pP
[in] Pointer to the input D3DXPLANE structure, which contains the array of planes to transform. The vector (a,b,c) that describes the plane must be normalized before this function is called. See Example.
PStride
[in] The stride of each non-transformed plane.
pM
[in] Pointer to the source D3DXMATRIX structure, which contains the inverse transpose of the transformation values.
n
[in] The number of planes to transform.

Return Values

Pointer to a D3DXPLANE structure, representing the transformed plane. This is the same value returned in the pOut parameter so that this function can be used as a parameter for another function.

Remarks

This example transforms one plane by applying a non-uniform scale.

#define ARRAYSIZE 4
D3DXPLANE planeNew[ARRAYSIZE];
D3DXPLANE plane[ARRAYSIZE];

for(int i = 0; i < ARRAYSIZE; i++)
{
    plane = D3DXPLANE( 0.0f, 1.0f, 1.0f, 0.0f );
    D3DXPlaneNormalize( &plane[i], &plane[i] );
}

D3DXMATRIX  matrix;
D3DXMatrixScaling( &matrix, 1.0f, 2.0f, 3.0f );
D3DXMatrixInverse( &matrix, NULL, &matrix );
D3DXMatrixTranspose( &matrix, &matrix );
D3DXPlaneTransformArray( &planeNew, sizeof (D3DXPLANE), &plane,
                         sizeof (D3DXPLANE), &matrix, ARRAYSIZE );

A plane is described by ax + by + cz + dw = 0. The first plane is created with (a,b,c,d) = (0,1,1,0), which is a plane described by y + z = 0. After scaling, the new plane contains (a,b,c,d) = (0, 0.353f, 0.235f, 0), which shows the new plane to be described by 0.353y + 0.235z = 0.

The parameter pM, contains the inverse transpose of the transformation matrix. The inverse transpose is required by this method so that the normal vector of the transformed plane can be correctly transformed as well.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXPlaneNormalize, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ, D3DXMatrixInverse, D3DXMatrixTranspose


D3DXQuaternionBaryCentric

Returns a quaternion in barycentric coordinates.

D3DXQUATERNION * D3DXQuaternionBaryCentric(
  D3DXQUATERNION * pOut,
  CONST D3DXQUATERNION * pQ1,
  CONST D3DXQUATERNION * pQ2,
  CONST D3DXQUATERNION * pQ3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
pQ3
[in] Pointer to a source D3DXQUATERNION structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXQUATERNION structure in Barycentric coordinates.

Remarks

To compute the barycentric coordinates, the D3DXQuaternionBaryCentric function implements the following series of spherical linear interpolation operations:

Slerp(Slerp(Q1, Q2, f+g), Slerp(Q1, Q3, f+g), g/(f+g))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionBaryCentric function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3dx9math.h.


D3DXQuaternionConjugate

Returns the conjugate of a quaternion.

D3DXQUATERNION * D3DXQuaternionConjugate(
  D3DXQUATERNION * pOut,
  CONST D3DXQUATERNION * pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the conjugate of the quaternion.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionConjugate function will return the quaternion (-x, -y, -z, w).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionConjugate function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionInverse


D3DXQuaternionDot

Returns the dot product of two quaternions.

FLOAT D3DXQuaternionDot(
  CONST D3DXQUATERNION * pQ1,
  CONST D3DXQUATERNION * pQ2
);

Parameters

pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.

Return Values

The dot product of two quaternions.

Remarks

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.


D3DXQuaternionExp

Calculates the exponential.

D3DXQUATERNION * D3DXQuaternionExp(
  D3DXQUATERNION * pOut,
  CONST D3DXQUATERNION * pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the exponential.

Remarks

This method converts a pure quaternion to a unit quaternion. D3DXQuaternionExp expects a pure quaternion, where w is ignored in the calculation (w == 0).

Given a pure quaternion defined by:
q = (0, theta * v);

This method calculates the exponential result.
exp(Q) = (cos(theta), sin(theta) * v)

where v is the vector portion of a quaternion.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionExp function can be used as a parameter for another function.

The D3DXQuaternionSquadSetup method can also be used to set up the control points of a quaternion.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionLn, D3DXQuaternionSquad


D3DXQuaternionIdentity

Returns the identity quaternion.

D3DXQUATERNION * D3DXQuaternionIdentity(
  D3DXQUATERNION * pOut
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.

Return Values

Pointer to the D3DXQUATERNION structure that is the identity quaternion.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionIdentity function will return the quaternion (0, 0, 0, 1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionIdentity function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionIsIdentity


D3DXQuaternionInverse

Conjugates and renormalizes a quaternion.

D3DXQUATERNION * D3DXQuaternionInverse(
  D3DXQUATERNION * pOut,
  CONST D3DXQUATERNION * pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the inverse quaternion of the quaternion.

Remarks

A unit quaternion, is defined by:
Q == (cos(theta), sin(theta) * v) where |v| = 1
The natural logarithm of Q is, ln(Q) = (0, theta * v)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionInverse function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionConjugate, D3DXQuaternionNormalize


D3DXQuaternionIsIdentity

Determines if a quaternion is an identity quaternion.

BOOL D3DXQuaternionIsIdentity(
  CONST D3DXQUATERNION * pQ
);

Parameters

pQ
[in] Pointer to the D3DXQUATERNION structure that will be tested for identity.

Return Values

If the quaternion is an identity quaternion, this function returns TRUE. Otherwise, this function returns FALSE.

Remarks

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionIdentity


D3DXQuaternionLength

Returns the length of a quaternion.

FLOAT D3DXQuaternionLength(
  CONST D3DXQUATERNION * pQ
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

The quaternion's length.

Remarks

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionLengthSq


D3DXQuaternionLengthSq

Returns the square of the length of a quaternion.

FLOAT D3DXQuaternionLengthSq(
  CONST D3DXQUATERNION * pQ
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

The quaternion's squared length.

Remarks

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionLength


D3DXQuaternionLn

Calculates the natural logarithm.

D3DXQUATERNION * D3DXQuaternionLn(
  D3DXQUATERNION * pOut,
  CONST D3DXQUATERNION * pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the natural logarithm.

Remarks

The D3DXQuaternionLn function works only for unit quaternions.

A unit quaternion, is defined by:
Q == (cos(theta), sin(theta) * v) where |v| = 1
The natural logarithm of Q is, ln(Q) = (0, theta * v)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionLn function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionExp, D3DXQuaternionSquad


D3DXQuaternionMultiply

Multiplies two quaternions.

D3DXQUATERNION * D3DXQuaternionMultiply(
  D3DXQUATERNION * pOut,
  CONST D3DXQUATERNION * pQ1,
  CONST D3DXQUATERNION * pQ2
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the product of two quaternions.

Remarks

The result represents the rotation Q1 followed by the rotation Q2 (Out = Q1 * Q2). This is done so that D3DXQuaternionMultiply maintain the same semantics as D3DXMatrixMultiply because unit quaternions can be considered as another way to represent rotation matrices.

Transformations are concatenated in the same order for both the D3DXQuaternionMultiply and D3DXMatrixMultiply functions. For example, assuming mX and mY represent the same rotations as qX and qY, both m and q will represent the same rotations.

D3DXMatrixMultiply(&m, &mX, &mY);
D3DXQuaternionMultiply(&q, &qX, &qY);

The multiplication of quaternions is not commutative.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionMultiply function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXMatrixMultiply


D3DXQuaternionNormalize

Computes a unit length quaternion.

D3DXQUATERNION * D3DXQuaternionNormalize(
  D3DXQUATERNION * pOut,
  CONST D3DXQUATERNION * pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the normal of the quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionNormalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionInverse


D3DXQuaternionRotationAxis

Rotates a quaternion about an arbitrary axis.

D3DXQUATERNION * D3DXQuaternionRotationAxis(
  D3DXQUATERNION * pOut,
  CONST D3DXVECTOR3 * pV,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pV
[in] Pointer to the D3DXVECTOR3 structure that identifies the axis about which to rotate the quaternion.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXQUATERNION structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationAxis function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionRotationMatrix, D3DXQuaternionRotationYawPitchRoll


D3DXQuaternionRotationMatrix

Builds a quaternion from a rotation matrix.

D3DXQUATERNION * D3DXQuaternionRotationMatrix(
  D3DXQUATERNION * pOut,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to the D3DXQUATERNION structure built from a rotation matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationMatrix function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationYawPitchRoll


D3DXQuaternionRotationYawPitchRoll

Builds a quaternion with the given yaw, pitch, and roll.

D3DXQUATERNION * D3DXQuaternionRotationYawPitchRoll(
  D3DXQUATERNION * pOut,
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
Yaw
[in] Yaw around the y-axis, in radians.
Pitch
[in] Pitch around the x-axis, in radians.
Roll
[in] Roll around the z-axis, in radians.

Return Values

Pointer to a D3DXQUATERNION structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationYawPitchRoll function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationMatrix


D3DXQuaternionSlerp

Interpolates between two quaternions, using spherical linear interpolation.

D3DXQUATERNION * D3DXQuaternionSlerp(
  D3DXQUATERNION * pOut,
  CONST D3DXQUATERNION * pQ1,
  CONST D3DXQUATERNION * pQ2,
  FLOAT t
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
t
[in] Parameter that indicates how far to interpolate between the quaternions.

Return Values

Pointer to a D3DXQUATERNION structure that is the result of the interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSlerp function can be used as a parameter for another function.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.


D3DXQuaternionSquad

Interpolates between quaternions, using spherical quadrangle interpolation.

D3DXQUATERNION * D3DXQuaternionSquad(
  D3DXQUATERNION * pOut,
  CONST D3DXQUATERNION * pQ1,
  CONST D3DXQUATERNION * pA,
  CONST D3DXQUATERNION * pB,
  CONST D3DXQUATERNION * pC,
  FLOAT t
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pA
[in] Pointer to a source D3DXQUATERNION structure.
pB
[in] Pointer to a source D3DXQUATERNION structure.
pC
[in] Pointer to a source D3DXQUATERNION structure.
t
[in] Parameter that indicates how far to interpolate between the quaternions.

Return Values

Pointer to a D3DXQUATERNION structure that is the result of the spherical quadrangle interpolation.

Remarks

This function uses the following sequence of spherical linear interpolation operations:

Slerp(Slerp(pQ1, pC, t), Slerp(pA, pB, t), 2t(1 - t))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSquad function can be used as a parameter for another function.

For an example of interpolating between quaternions, see SkinnedMesh Sample.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionExp, D3DXQuaternionLn, D3DXQuaternionSquadSetup


D3DXQuaternionSquadSetup

Sets up control points for spherical quadrangle interpolation.

void D3DXQuaternionSquadSetup(
  D3DXQUATERNION * pAOut,
  D3DXQUATERNION * pBOut,
  D3DXQUATERNION * pCOut,
  CONST D3DXQUATERNION * pQ0,
  CONST D3DXQUATERNION * pQ1,
  CONST D3DXQUATERNION * pQ2,
  CONST D3DXQUATERNION * pQ3
);

Parameters

pAOut
[out] Pointer to AOut.
pBOut
[out] Pointer to BOut.
pCOut
[out] Pointer to COut.
pQ0
[in] Pointer to the input control point, Q0.
pQ1
[in] Pointer to the input control point, Q1.
pQ2
[in] Pointer to the input control point, Q2.
pQ3
[in] Pointer to the input control point, Q3.

Return Values

None.

Remarks

This function takes four control points, which are supplied to the inputs pQ0, pQ1, pQ2, and pQ3. The function then alters these values to find a curve that flows along the shortest path. The values of q0, q2, and q3 are calculated as shown below.

q0 = |Q0 + Q1| < |Q0 - Q1| ? -Q0 : Q0
q2 = |Q1 + Q2| < |Q1 - Q2| ? -Q2 : Q2
q3 = |Q2 + Q3| < |Q2 - Q3| ? -Q3 : Q3

Having calculated the new Q values, the values for AOut, BOut, and COut are calculated as follows:

AOut = q1 * e[-0.25 *( Ln[Exp(q1)*q2] + Ln[Exp(q1)*q0] ) ]

BOut = q2 * e[-0.25 *( Ln[Exp(q2)*q3] + Ln[Exp(q2)*q1] ) ]

COut = q2

Note Ln is the API method D3DXQuaternionLn and Exp is the API method D3DXQuaternionExp.

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Examples

The following example shows how to use a set of quaternion keys (Q0, Q1, Q2, Q3) to compute the inner quadrangle points (A, B, C). This ensures that the tangents are continuous across adjacent segments.

      A     B
Q0    Q1    Q2    Q3

The following code example demonstrates how you can interpolate between Q1 and Q2.

// Rotation about the z-axis
D3DXQUATERNION Q0 = D3DXQUATERNION(0,  0, 0.707f, -.707f);
D3DXQUATERNION Q1 = D3DXQUATERNION(0,  0, 0.000f, 1.000f);
D3DXQUATERNION Q2 = D3DXQUATERNION(0,  0, 0.707f, 0.707f);
D3DXQUATERNION Q3 = D3DXQUATERNION(0,  0, 1.000f, 0.000f);
D3DXQUATERNION A, B, C, Qt;
FLOAT time = 0.5f;

D3DXQuaternionSquadSetup(&A, &B, &C, &Q0, &Q1, &Q2, &Q3);
D3DXQuaternionSquad(&Qt, &Q1, &A, &B, &C, time);

Note

  • C is +/- Q2 depending on the result of the function.
  • Qt is the result of the function.

The result is a rotation of 45 degrees around the z-axis for time = 0.5.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXQuaternionSquad


D3DXQuaternionToAxisAngle

Computes a quaternion's axis and angle of rotation.

void D3DXQuaternionToAxisAngle(
  CONST D3DXQUATERNION * pQ,
  D3DXVECTOR3 * pAxis,
  FLOAT * pAngle
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.
pAxis
[in, out] This function returns a pointer to a D3DXVECTOR3 structure that identifies the quaternion's axis of rotation.
pAngle
[in, out] This function returns a pointer to a FLOAT value that identifies the quaternion's angle of rotation in radians.

Return Values

No return value.

Remarks

Use D3DXQuaternionNormalize for any quaternion input that is not already normalized.

Requirements

Header: Declared in D3dx9math.h.


D3DXSHAdd

Adds two spherical harmonic (SH) vectors; in other words, pOut[i] = pA[i] + pB[i].

FLOAT * D3DXSHAdd(
  FLOAT * pOut,
  UINT Order,
  CONST FLOAT * pA,
  CONST FLOAT * pB
);

Parameters

pOut
[out] Pointer to SH output coefficients. The evaluation generates Order2 coefficients. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pA
[in] Pointer to the first SH vector.
pB
[in] Pointer to the second SH vector.

Return Values

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXSHDot

Computes the dot product of two spherical harmonic (SH) vectors.

FLOAT D3DXSHDot(
  UINT Order,
  CONST FLOAT * pA,
  CONST FLOAT * pB
);

Parameters

Order
[in] Order of the spherical harmonic (SH) evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pA
[in] Pointer to the first SH vector.
pB
[in] Pointer to the second SH vector.

Return Values

SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXSHEvalConeLight

Evaluates a light that is a cone of constant intensity and returns spectral spherical harmonic (SH) data.

HRESULT D3DXSHEvalConeLight(
  UINT Order,
  CONST D3DXVECTOR3 * pDir,
  FLOAT Radius,
  FLOAT RIntensity,
  FLOAT GIntensity,
  FLOAT BIntensity,
  FLOAT* pROut,
  FLOAT* pGOut,
  FLOAT* pBOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] Pointer to the (x, y, z) hemisphere axis direction vector in which to evaluate the SH basis functions. See Remarks.
Radius
[in] Radius of cone in radians.
RIntensity
[in] The red intensity of the light.
GIntensity
[in] The green intensity of the light.
BIntensity
[in] The blue intensity of the light.
pROut
[out] Pointer to the output SH vector for the red component.
pGOut
[out] Pointer to the output SH vector for the green component.
pBOut
[out] Pointer to the output SH vector for the blue component.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

Evaluates a light that is a cone of constant intensity and returns spectral SH data. The output vector is computed so that if the intensity ratio R/G/B is equal to 1, the exit radiance of a point directly under the light (oriented in the cone direction on a diffuse object with an albedo of 1) would be 1.0. This will compute three spectral samples; pROut will be returned, while pGOut and pBOut may be returned.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXSHEvalDirection

Evaluates the spherical harmonic (SH) basis functions from an input direction vector.

FLOAT * D3DXSHEvalDirection(
  FLOAT * pOut,
  UINT Order,
  CONST D3DXVECTOR3 * pDir
);

Parameters

pOut
[out] Pointer to Spherical harmonic (SH) output coefficients. The evaluation generates Order2 coefficients. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] (x, y, z) direction vector in which to evaluate the SH basis functions. Must be normalized. See Remarks.

Return Values

Pointer to SH output coefficients. See Remarks.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXSHEvalDirectionalLight

Evaluates a directional light And returns spectral spherical harmonic (SH) data.

HRESULT D3DXSHEvalDirectionalLight(
  UINT Order,
  CONST D3DXVECTOR3 * pDir,
  FLOAT Radius,
  FLOAT RIntensity,
  FLOAT GIntensity,
  FLOAT BIntensity,
  FLOAT * pROut,
  FLOAT * pGOut,
  FLOAT * pBOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] Pointer to the (x, y, z) hemisphere axis direction vector in which to evaluate the SH basis functions. See Remarks.
Radius
[in] Radius of the spherical light source.
RIntensity
[in] The red intensity of the light.
GIntensity
[in] The green intensity of the light.
BIntensity
[in] The blue intensity of the light.
pROut
[out] Pointer to the output SH vector for the red component.
pGOut
[out] Optional pointer to the output SH vector for the green component.
pBOut
[out] Optional pointer to the output SH vector for the blue component.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

The output vector is computed so that if the intensity ratio R/G/B is equal to 1, the resulting exit radiance of a point directly under the light on a diffuse object with an albedo of 1 would be 1.0. This will compute three spectral samples; pROut will be returned, while pGOut and pBOut may be returned.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXSHEvalHemisphereLight

Evaluates a light that is a linear interpolation between two colors over the sphere.

HRESULT D3DXSHEvalHemisphereLight(
  UINT Order,
  CONST D3DXVECTOR3 * pDir,
  D3DXCOLOR Top,
  D3DXCOLOR Bottom,
  FLOAT * pROut,
  FLOAT * pGOut,
  FLOAT * pBOut
);

Parameters

Order
[in] Order of the spherical harmonic (SH) evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] Pointer to the (x, y, z) hemisphere axis direction vector in which to evaluate the SH basis functions. See Remarks.
Top
[in] The sky color.
Bottom
[in] The ground color.
pROut
[in] Pointer to the output SH vector for the red component.
pGOut
[in] Pointer to the output SH vector for the green component.
pBOut
[in] Pointer to the output SH vector for the blue component.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

The interpolation is done linearly between the two points, not over the surface of the sphere (that is, if the axis was (0,0,1) it is linear in Z, not in the azimuthal angle). The resulting spherical lighting function is normalized so that a point on a perfectly diffuse surface with no shadowing and a normal pointed in the direction pDir would result in exit radiance with a value of 1 (if the top color was white and the bottom color was black). This is a very simple model where Top represents the intensity of the "sky" and Bottom represents the intensity of the "ground."

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXSHEvalSphericalLight

Evaluates a spherical light and returns spectral spherical harmonic (SH) data.

HRESULT D3DXSHEvalSphericalLight(
  UINT Order,
  CONST D3DXVECTOR3 * pPos,
  FLOAT Radius,
  FLOAT RIntensity,
  FLOAT GIntensity,
  FLOAT BIntensity,
  FLOAT * pROut,
  FLOAT * pGOut,
  FLOAT * pBOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pPos
[in] Pointer to the light position.
Radius
[in] Radius of spherical light source.
RIntensity
[in] The red intensity of the light.
GIntensity
[in] The green intensity of the light.
BIntensity
[in] The blue intensity of the light.
pROut
[out] Pointer to the output SH vector for the red component.
pGOut
[out] Pointer to the output SH vector for the green component.
pBOut
[out] Pointer to the output SH vector for the blue component.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

Evaluates a spherical light and returns spectral SH data. There is no normalization of the intensity of the light like there is for directional lights, so care has to be taken when specifying the intensities. This will compute three spectral samples; pROut will be returned, while pGOut and pBOut may be returned.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXSHMultiply2

Computes the product of two functions represented using SH (f and g).

FLOAT * D3DXSHMultiply2(
  FLOAT *pOut,
  CONST FLOAT *pF,
  CONST FLOAT *pG
);

Parameters

pOut
[in] Pointer to the output SH coefficients - basis function Ylm is stored at l*l + m+l.
pF
[in] Input SH coeffs for first function.
pG
[in] Second set of input SH coeffs.

Return Values

Pointer to SH output coefficients.

Remarks

The order is a number between 2 and 6 inclusive. So this page actually documents several functions: D3DXSHMultiply2, D3DXSHMultiply3, ... D3DXSHMultiply6.

Computes the product of two functions represented using SH (f and g), where pOut[i] = int(y_i(s) * f(s) * g(s)), where y_i(s) is the ith SH basis function, f(s) and g(s) are SH functions (sum_i(y_i(s)*c_i)). The order O determines the lengths of the arrays, where there should always be O^2 coefficients. In general the product of two SH functions of order O generates an SH function of order 2*O - 1, but the results are truncated. This means that the product commutes (f*g == g*f) but doesn't associate (f*(g*h) != (f*g)*h.

See Also

Math Functions


D3DXSHProjectCubeMap

Projects a function represented on a cube map into spherical harmonics (SH).

HRESULT D3DXSHProjectCubeMap(
  UINT Order,
  LPDIRECT3DCUBETEXTURE9 pCubeMap,
  FLOAT  * pROut,
  FLOAT * pGOut,
  FLOAT * pBOut
);

Parameters

Order
[in] Order of the spherical harmonic (SH) evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pCubeMap
[in] Pointer to a source cube texture. See IDirect3DCubeTexture9.
pROut
[in] Pointer to the output SH vector for the red component.
pGOut
[in] Pointer to the output SH vector for the green component.
pBOut
[in] Pointer to the output SH vector for the blue component.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXSHRotate

Rotates the spherical harmonic (SH) vector by the given matrix.

FLOAT * D3DXSHRotate(
  FLOAT * pOut,
  UINT Order,
  CONST D3DXMATRIX * pMatrix,
  CONST FLOAT * pIn
);

Parameters

pOut
[out] Pointer to Spherical harmonic (SH) output coefficients. The evaluation generates Order2 coefficients. This pointer should not alias with pIn. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pMatrix
[in] Pointer to the rotation matrix. The rotation sub-matrix must be orthogonal, with a unit determinant.
pIn
[in] Pointer to rotated SH coefficients.

Return Values

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXSHRotateZ

Rotates the spherical harmonic (SH) vector in the z-axis by the given angle.

FLOAT * D3DXSHRotateZ(
  FLOAT * pOut,
  UINT Order,
  FLOAT Angle,
  CONST FLOAT * pIn
);

Parameters

pOut
[out] Pointer to Spherical harmonic (SH) output coefficients. The evaluation generates Order2 coefficients. This pointer should not alias with pIn. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
Angle
[in] Rotation angle in radians. The rotation is performed around the z-axis.
pIn
[in] Pointer to rotated SH coefficients.

Return Values

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXSHScale

Scales a spherical harmonic (SH) vector; in other words, pOut[i] = pA[i]*Scale.

FLOAT * D3DXSHScale(
  FLOAT * pOut,
  UINT Order,
  CONST FLOAT * pIn,
  CONST FLOAT * Scale
);

Parameters

pOut
[out] Pointer to Spherical harmonic (SH) output coefficients. The evaluation generates Order2 coefficients. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pIn
[in] Pointer to the SH vector to scale.
Scale
[in] Pointer to the scale value.

Return Values

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Requirements

Header: Declared in D3dx9math.h.

See Also

Precomputed Radiance Transfer (Direct3D 9)


D3DXVec2Add

Adds two 2D vectors.

D3DXVECTOR2 * D3DXVec2Add(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV1,
  CONST D3DXVECTOR2 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the sum of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Add function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2Subtract, D3DXVec2Scale


D3DXVec2BaryCentric

Returns a point in Barycentric coordinates, using the specified 2D vectors.

D3DXVECTOR2 * D3DXVec2BaryCentric(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV1,
  CONST D3DXVECTOR2 * pV2,
  CONST D3DXVECTOR2 * pV3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[out, retval] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.
pV3
[in] Pointer to a source D3DXVECTOR2 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR2 structure in Barycentric coordinates.

Remarks

The D3DXVec2BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result, and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 &, & g>=0 &, & 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 &, & g>=0 &, & 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 &, & g==0 &, & 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 &, & g>=0 &, & 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2BaryCentric function can be used as a parameter for another function.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec2CatmullRom

Performs a Catmull-Rom interpolation, using the specified 2D vectors.

D3DXVECTOR2 * D3DXVec2CatmullRom(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV0,
  CONST D3DXVECTOR2 * pV1,
  CONST D3DXVECTOR2 * pV2,
  CONST D3DXVECTOR2 * pV3,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV0
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV1
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR2 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where:

v1 is the contents of pV0.

v2 is the contents of pV1.

p3 is the contents of pV2.

p4 is the contents of pV3.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s)(p3 - p1) / 2 + (s3 - s2)(p4 - p2)/2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 + (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3CatmullRom, D3DXVec4CatmullRom


D3DXVec2CCW

Returns the z-component by taking the cross product of two 2D vectors.

FLOAT D3DXVec2CCW(
  CONST D3DXVECTOR2 * pV1,
  CONST D3DXVECTOR2 * pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

The z-component.

Remarks

This function determines the z-component by determining the cross-product based on the following formula: ((x1,y1,0) cross (x2,y2,0)). Or as shown in the following example.

pV1->x * pV2->y - pV1->y * pV2->x

If the value of the z-component is positive, the vector V2 is counterclockwise from the vector V1. This information is useful for back-face culling.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2Dot


D3DXVec2Dot

Determines the dot product of two 2D vectors.

FLOAT D3DXVec2Dot(
  CONST D3DXVECTOR2 * pV1,
  CONST D3DXVECTOR2 * pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

The dot product.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2CCW


D3DXVec2Hermite

Performs a Hermite spline interpolation, using the specified 2D vectors.

D3DXVECTOR2 * D3DXVec2Hermite(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV1,
  CONST D3DXVECTOR2 * pT1,
  CONST D3DXVECTOR2 * pV2,
  CONST D3DXVECTOR2 * pT2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR2 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR2 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR2 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec2Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t-1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Hermite function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec2Length

Returns the length of a 2D vector.

FLOAT D3DXVec2Length(
  CONST D3DXVECTOR2 * pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Values

The vector's length.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2LengthSq


D3DXVec2LengthSq

Returns the square of the length of a 2D vector.

FLOAT D3DXVec2LengthSq(
  CONST D3DXVECTOR2 * pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Values

The vector's squared length.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2Length


D3DXVec2Lerp

Performs a linear interpolation between two 2D vectors.

D3DXVECTOR2 * D3DXVec2Lerp(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV1,
  CONST D3DXVECTOR2 * pV2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Values

Pointer to a D3DXVECTOR2 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Lerp function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec2Maximize

Returns a 2D vector that is made up of the largest components of two 2D vectors.

D3DXVECTOR2 * D3DXVec2Maximize(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV1,
  CONST D3DXVECTOR2 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Maximize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2Minimize


D3DXVec2Minimize

Returns a 2D vector that is made up of the smallest components of two 2D vectors.

D3DXVECTOR2 * D3DXVec2Minimize(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV1,
  CONST D3DXVECTOR2 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Minimize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2Maximize


D3DXVec2Normalize

Returns the normalized version of a 2D vector.

D3DXVECTOR2 * D3DXVec2Normalize(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the normalized version of the vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Normalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec2Scale

Scales a 2D vector.

D3DXVECTOR2 * D3DXVec2Scale(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
s
[in] Scaling value.

Return Values

Pointer to a D3DXVECTOR2 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Scale function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2Add, D3DXVec2Subtract


D3DXVec2Subtract

Subtracts two 2D vectors.

D3DXVECTOR2 * D3DXVec2Subtract(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV1,
  CONST D3DXVECTOR2 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Subtract function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2Add, D3DXVec2Scale


D3DXVec2Transform

Transforms a 2D vector by a given matrix.

D3DXVECTOR4 * D3DXVec2Transform(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR2 * pV,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the vector pV (x, y, 0, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2TransformCoord, D3DXVec2TransformNormal


D3DXVec2TransformArray

Transforms an array (x, y, 0, 1) by a given matrix.

D3DXVECTOR4 * D3DXVec2TransformArray(
  D3DXVECTOR4 * pOut,
  UINT OutStride,
  CONST D3DXVECTOR2 * pV,
  UINT VStride,
  CONST D3DXMATRIX * pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed array.

Remarks

This function transforms the array pV (x, y, 0, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2TransformCoord, D3DXVec2TransformNormal


D3DXVec2TransformCoord

Transforms a 2D vector by a given matrix, projecting the result back into w = 1.

D3DXVECTOR2 * D3DXVec2TransformCoord(
  D3DXVECTOR2 * pOut,
  CONST D3DXVECTOR2 * pV,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, 0, 1), by the matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformCoord function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2Transform, D3DXVec2TransformNormal


D3DXVec2TransformCoordArray

Transforms an array (x, y, 0, 1) by a given matrix, and projects the result back into w = 1.

D3DXVECTOR2 * D3DXVec2TransformCoordArray(
  D3DXVECTOR2* pOut,
  UINT OutStride,
  CONST D3DXVECTOR2 * pV,
  UINT VStride,
  CONST D3DXMATRIX * pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR4 transformed array.

Remarks

This function transforms the array pV (x, y, 0, 1) by the matrix pM, projecting the result back into w = 1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformCoordArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec2TransformNormal

Transforms the 2D vector normal by the given matrix.

D3DXVECTOR2 * D3DXVec2TransformNormal(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2 * pV,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector (pV->x, pV->y, 0, 0) by the matrix pointed to by pM.

If you want to transform a normal, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a point.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformNormal function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2Transform, D3DXVec2TransformCoord


D3DXVec2TransformNormalArray

Transforms an array (x, y, 0, 0) by a given matrix.

D3DXVECTOR2 * D3DXVec2TransformNormalArray(
  D3DXVECTOR2* pOut,
  UINT OutStride,
  CONST D3DXVECTOR2* pV,
  UINT VStride,
  CONST D3DXMATRIX* pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR2 structure that is the transformed array.

Remarks

This function transforms the vector (pV->x, pV->y, 0, 0) by the matrix pointed to by pM.

If you want to transform a normal, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a point.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformNormalArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec3Add

Adds two 3D vectors.

D3DXVECTOR3 * D3DXVec3Add(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the sum of the two 3D vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Add function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Subtract, D3DXVec3Scale


D3DXVec3BaryCentric

Returns a point in Barycentric coordinates, using the specified 3D vectors.

D3DXVECTOR3 * D3DXVec3BaryCentric(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2,
  CONST D3DXVECTOR3 * pV3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[out, retval] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.
pV3
[in] Pointer to a source D3DXVECTOR3 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR3 structure in Barycentric coordinates.

Remarks

The D3DXVec3BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 &, & g>=0 &, & 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 &, & g>=0 &, & 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 &, & g==0 &, & 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 &, & g>=0 &, & 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3BaryCentric function can be used as a parameter for another function.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec3CatmullRom

Performs a Catmull-Rom interpolation, using the specified 3D vectors.

D3DXVECTOR3 * D3DXVec3CatmullRom(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV0,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2,
  CONST D3DXVECTOR3 * pV3,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV0
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR3 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where:

v1 is the contents of pV0.

v2 is the contents of pV1.

p3 is the contents of pV2.

p4 is the contents of pV3.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s)(p3 - p1) / 2 + (s3 - s2)(p4 - p2) / 2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 + (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2CatmullRom, D3DXVec4CatmullRom


D3DXVec3Cross

Determines the cross-product of two 3D vectors.

D3DXVECTOR3 * D3DXVec3Cross(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the cross product of two 3D vectors.

Remarks

This function determines the cross-product with the following code.

D3DXVECTOR3 v;

v.x = pV1->y * pV2->z - pV1->z * pV2->y;
v.y = pV1->z * pV2->x - pV1->x * pV2->z;
v.z = pV1->x * pV2->y - pV1->y * pV2->x;

*pOut = v;

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Cross function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Dot


D3DXVec3Dot

Determines the dot-product of two 3D vectors.

FLOAT D3DXVec3Dot(
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

The dot-product.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Cross


D3DXVec3Hermite

Performs a Hermite spline interpolation, using the specified 3D vectors.

D3DXVECTOR3 * D3DXVec3Hermite(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pT1,
  CONST D3DXVECTOR3 * pV2,
  CONST D3DXVECTOR3 * pT2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR3 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR3 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR3 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec3Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Hermite function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec3Length

Returns the length of a 3D vector.

FLOAT D3DXVec3Length(
  CONST D3DXVECTOR3 * pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Values

The vector's length.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3LengthSq


D3DXVec3LengthSq

Returns the square of the length of a 3D vector.

FLOAT D3DXVec3LengthSq(
  CONST D3DXVECTOR3 * pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Values

The vector's squared length.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Length


D3DXVec3Lerp

Performs a linear interpolation between two 3D vectors.

D3DXVECTOR3 * D3DXVec3Lerp(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Values

Pointer to a D3DXVECTOR3 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Lerp function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec3Maximize

Returns a 3D vector that is made up of the largest components of two 3D vectors.

D3DXVECTOR3 * D3DXVec3Maximize(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Maximize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Minimize


D3DXVec3Minimize

Returns a 3D vector that is made up of the smallest components of two 3D vectors.

D3DXVECTOR3 * D3DXVec3Minimize(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Minimize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Maximize


D3DXVec3Normalize

Returns the normalized version of a 3D vector.

D3DXVECTOR3 * D3DXVec3Normalize(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the normalized version of the specified vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Normalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec3Project

Projects a 3D vector from object space into screen space.

D3DXVECTOR3 * D3DXVec3Project(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV,
  CONST D3DVIEWPORT9 * pViewport,
  CONST D3DXMATRIX * pProjection,
  CONST D3DXMATRIX * pView,
  CONST D3DXMATRIX * pWorld
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.

Return Values

Pointer to a D3DXVECTOR3 structure that is the vector projected from object space to screen space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Project function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Unproject


D3DXVec3ProjectArray

Projects an array (x, y, z, 0) from object space into screen space.

D3DXVECTOR3 * D3DXVec3ProjectArray(
  D3DXVECTOR3 * pOut,
  UINT OutStride,
  CONST D3DXVECTOR3 * pV,
  UINT VStride,
  CONST D3DVIEWPORT9 * pViewport,
  CONST D3DXMATRIX * pProjection,
  CONST D3DXMATRIX * pView,
  CONST D3DXMATRIX * pWorld,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
VStride
[in] Stride between vectors in the input data stream.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR3 structure that is the array projected from object space to screen space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3ProjectArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Unproject


D3DXVec3Scale

Scales a 3D vector.

D3DXVECTOR3 * D3DXVec3Scale(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
s
[in] Scaling value.

Return Values

Pointer to a D3DXVECTOR3 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Scale function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Add, D3DXVec3Subtract


D3DXVec3Subtract

Subtracts two 3D vectors.

D3DXVECTOR3 * D3DXVec3Subtract(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV1,
  CONST D3DXVECTOR3 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Subtract function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Add, D3DXVec3Scale


D3DXVec3Transform

Transforms vector (x, y, z, 1) by a given matrix.

D3DXVECTOR4 * D3DXVec3Transform(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR3 * pV,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec3TransformArray

Transforms an array (x, y, z, 1) by a given matrix.

D3DXVECTOR4 * D3DXVec3TransformArray(
  D3DXVECTOR4 * pOut,
  UINT OutStride,
  CONST D3DXVECTOR3* pV,
  UINT VStride,
  CONST D3DXMATRIX* pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR4 transformed array.

Remarks

This function transforms the array pV (x, y, z, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec3TransformCoord

Transforms a 3D vector by a given matrix, projecting the result back into w = 1.

D3DXVECTOR3 * D3DXVec3TransformCoord(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformCoord function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Transform, D3DXVec3TransformNormal


D3DXVec3TransformCoordArray

Transforms an array (x, y, z, 1) by a given matrix, and projects the result back into w = 1.

D3DXVECTOR3 * D3DXVec3TransformCoordArray(
  D3DXVECTOR3* pOut,
  UINT OutStride,
  CONST D3DXVECTOR3* pV,
  UINT VStride,
  CONST D3DXMATRIX* pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR3 structure that is the transformed array.

Remarks

This function transforms the array pV (x, y, z, 1) by the matrix pM, projecting the result back into w = 1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformCoord function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec3TransformNormal

Transforms the 3D vector normal by the given matrix.

D3DXVECTOR3 * D3DXVec3TransformNormal(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector (pV->x, pV->y, pV->z, 0) by the matrix pointed to by pM.

If you want to transform a normal, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a point.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformNormal function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec3TransformNormalArray

Transforms an array (x, y, z, 0) by a given matrix.

D3DXVECTOR3 * D3DXVec3TransformNormalArray(
  D3DXVECTOR3* pOut,
  UINT OutStride,
  CONST D3DXVECTOR3* pV,
  UINT VStride,
  CONST D3DXMATRIX* pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR3 array that is the transformed array.

Remarks

This function transforms the vector (pV->x, pV->y, pV->z, 0) by the matrix pointed to by pM.

If you want to transform a normal, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a point.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformNormalArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec3Unproject

Projects a vector from screen space into object space.

D3DXVECTOR3 * D3DXVec3Unproject(
  D3DXVECTOR3 * pOut,
  CONST D3DXVECTOR3 * pV,
  CONST D3DVIEWPORT9 * pViewport,
  CONST D3DXMATRIX * pProjection,
  CONST D3DXMATRIX * pView,
  CONST D3DXMATRIX * pWorld
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.

Return Values

Pointer to a D3DXVECTOR3 structure that is the vector projected from screen space to object space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Unproject function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Project


D3DXVec3UnprojectArray

Projects an array (x, y, z, 0) from screen space into object space.

D3DXVECTOR3 * D3DXVec3UnprojectArray(
  D3DXVECTOR3 * pOut,
  UINT OutStride,
  CONST D3DXVECTOR3 * pV,
  UINT VStride,
  CONST D3DVIEWPORT9 * pViewport,
  CONST D3DXMATRIX * pProjection,
  CONST D3DXMATRIX * pView,
  CONST D3DXMATRIX * pWorld,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
VStride
[in] Stride between vectors in the input data stream.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR3 structure that is the array projected from screen space to object space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Unproject function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Project


D3DXVec4Add

Adds two 4D vectors.

D3DXVECTOR4 * D3DXVec4Add(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV1,
  CONST D3DXVECTOR4 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the sum of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Add function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec4Subtract, D3DXVec4Scale


D3DXVec4BaryCentric

Returns a point in Barycentric coordinates, using the specified 4D vectors.

D3DXVECTOR4 * D3DXVec4BaryCentric(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV1,
  CONST D3DXVECTOR4 * pV2,
  CONST D3DXVECTOR4 * pV3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[out, retval] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
pV3
[in] Pointer to a source D3DXVECTOR4 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR4 structure in Barycentric coordinates.

Remarks

The D3DXVec4BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 &, & g>=0 &, & 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 &, & g>=0 &, & 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 &, & g==0 &, & 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 &, & g>=0 &, & 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4BaryCentric function can be used as a parameter for another function.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec4CatmullRom

Performs a Catmull-Rom interpolation, using the specified 4D vectors.

D3DXVECTOR4 * D3DXVec4CatmullRom(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV0,
  CONST D3DXVECTOR4 * pV1,
  CONST D3DXVECTOR4 * pV2,
  CONST D3DXVECTOR4 * pV3,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV0
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV1
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR4 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where:

v1 is the contents of pV0.

v2 in the contents of pV1.

p3 is the contents of pV2.

p4 is the contents of pV3.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s)(p3 - p1) / 2 + (s3 - s2)(p4 - p2) / 2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 + (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec2CatmullRom, D3DXVec3CatmullRom


D3DXVec4Cross

Determines the cross-product in four dimensions.

D3DXVECTOR4 * D3DXVec4Cross(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV1,
  CONST D3DXVECTOR4 * pV2,
  CONST D3DXVECTOR4 * pV3
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
pV3
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the cross product.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Cross function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec4Dot


D3DXVec4Dot

Determines the dot product of two 4D vectors.

FLOAT D3DXVec4Dot(
  CONST D3DXVECTOR4 * pV1,
  CONST D3DXVECTOR4 * pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

The dot product.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec4Cross


D3DXVec4Hermite

Performs a Hermite spline interpolation, using the specified 4D vectors.

D3DXVECTOR4 * D3DXVec4Hermite(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV1,
  CONST D3DXVECTOR4 * pT1,
  CONST D3DXVECTOR4 * pV2,
  CONST D3DXVECTOR4 * pT2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR4 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR4 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR4 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec4Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t-1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Hermite function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec4Length

Returns the length of a 4D vector.

FLOAT D3DXVec4Length(
  CONST D3DXVECTOR4 * pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Values

The vector's length.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec4LengthSq


D3DXVec4LengthSq

Returns the square of the length of a 4D vector.

FLOAT D3DXVec4LengthSq(
  CONST D3DXVECTOR4 * pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Values

The vector's squared length.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec4Length


D3DXVec4Lerp

Performs a linear interpolation between two 4D vectors.

D3DXVECTOR4 * D3DXVec4Lerp(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV1,
  CONST D3DXVECTOR4 * pV2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Values

Pointer to a D3DXVECTOR4 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Lerp function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec4Maximize

Returns a 4D vector that is made up of the largest components of two 4D vectors.

D3DXVECTOR4 * D3DXVec4Maximize(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV1,
  CONST D3DXVECTOR4 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Maximize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec4Minimize


D3DXVec4Minimize

Returns a 4D vector that is made up of the smallest components of two 4D vectors.

D3DXVECTOR4 * D3DXVec4Minimize(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV1,
  CONST D3DXVECTOR4 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Minimize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec4Maximize


D3DXVec4Normalize

Returns the normalized version of a 4D vector.

D3DXVECTOR4 * D3DXVec4Normalize(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the normalized version of the vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Normalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec4Scale

Scales a 4D vector.

D3DXVECTOR4 * D3DXVec4Scale(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.
s
[in] Scaling value.

Return Values

Pointer to the D3DXVECTOR4 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Scale function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec4Add, D3DXVec4Subtract


D3DXVec4Subtract

Subtracts two 4D vectors.

D3DXVECTOR4 * D3DXVec4Subtract(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV1,
  CONST D3DXVECTOR4 * pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Subtract function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXVec3Add, D3DXVec3Scale


D3DXVec4Transform

Transforms a 4D vector by a given matrix.

D3DXVECTOR4 * D3DXVec4Transform(
  D3DXVECTOR4 * pOut,
  CONST D3DXVECTOR4 * pV,
  CONST D3DXMATRIX * pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed 4D vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


D3DXVec4TransformArray

Transforms an array (x, y, 0, 1) by a given matrix.

D3DXVECTOR4 * D3DXVec4TransformArray(
  D3DXVECTOR4 * pOut,
  UINT OutStride,
  CONST D3DXVECTOR4* pV,
  UINT VStride,
  CONST D3DXMATRIX* pM,
  UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR4 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed array.

Remarks

This function transforms the array pV (x, y, 0, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4TransformArray function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx9math.h.


Mesh Functions

D3DX supplies the following mesh functions.

  • D3DXBoxBoundProbe
  • D3DXCleanMesh
  • D3DXComputeBoundingBox
  • D3DXComputeBoundingSphere
  • D3DXComputeNormals
  • D3DXComputeTangent
  • D3DXComputeTangentFrame
  • D3DXComputeTangentFrameEx
  • D3DXConcatenateMeshes
  • D3DXConvertMeshSubsetToSingleStrip
  • D3DXConvertMeshSubsetToStrips
  • D3DXCreateMesh
  • D3DXCreateMeshFVF
  • D3DXCreateNPatchMesh
  • D3DXCreatePatchMesh
  • D3DXCreatePMeshFromStream
  • D3DXCreateSkinInfo
  • D3DXCreateSkinInfoFromBlendedMesh
  • D3DXCreateSkinInfoFVF
  • D3DXCreateSPMesh
  • D3DXDeclaratorFromFVF
  • D3DXFVFFromDeclarator
  • D3DXGenerateOutputDecl
  • D3DXGeneratePMesh
  • D3DXGetDeclLength
  • D3DXGetDeclVertexSize
  • D3DXGetFVFVertexSize
  • D3DXIntersect
  • D3DXIntersectSubset
  • D3DXIntersectTri
  • D3DXLoadMeshFromX
  • D3DXLoadMeshFromXInMemory
  • D3DXLoadMeshFromXof
  • D3DXLoadMeshFromXResource
  • D3DXLoadPatchMeshFromXof
  • D3DXLoadSkinMeshFromXof
  • D3DXOptimizeFaces
  • D3DXOptimizeVertices
  • D3DXRectPatchSize
  • D3DXSaveMeshToX
  • D3DXSimplifyMesh
  • D3DXSphereBoundProbe
  • D3DXSplitMesh
  • D3DXTessellateNPatches
  • D3DXTessellateRectPatch
  • D3DXTessellateTriPatch
  • D3DXTriPatchSize
  • D3DXValidMesh
  • D3DXValidPatchMesh
  • D3DXWeldVertices

See Also

D3DXCreateTextureGutterHelper


D3DXBoxBoundProbe

Determines whether a ray intersects the volume of a box's bounding box.

BOOL D3DXBoxBoundProbe(
  CONST D3DXVECTOR3 * pMin,
  CONST D3DXVECTOR3 * pMax,
  CONST D3DXVECTOR3 * pRayPosition,
  CONST D3DXVECTOR3 * pRayDirection
);

Parameters

pMin
[in] Pointer to a D3DXVECTOR3 structure, describing the lower-left corner of the bounding box. See Remarks.
pMax
[in] Pointer to a D3DXVECTOR3 structure, describing the upper-right corner of the bounding box. See Remarks.
pRayPosition
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDirection
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray. This vector should not be (0,0,0) but does not need to be normalized.

Return Values

Returns TRUE if the ray intersects the volume of the box's bounding box. Otherwise, returns FALSE.

Remarks

D3DXBoxBoundProbe determines if the ray intersects the volume of the box's bounding box, not just the surface of the box.

The values passed to D3DXBoxBoundProbe are xmin, xmax, ymin, ymax, zmin, and zmax. Thus, the following defines the corners of the bounding box.

xmax, ymax, zmax
xmax, ymax, zmin
xmax, ymin, zmax
xmax, ymin, zmin
xmin, ymax, zmax
xmin, ymax, zmin
xmin, ymin, zmax
xmin, ymin, zmin

The depth of the bounding box in the z direction is zmax - zmin, in the y direction is ymax - ymin, and in the x direction is xmax - xmin. For example, with the following minimum and maximum vectors, min (-1, -1, -1) and max (1, 1, 1), the bounding box is defined in the following manner.

 1,  1,  1
 1,  1, -1
 1, -1,  1
 1, -1, -1
-1,  1,  1
-1,  1, -1
-1, -1,  1
-1, -1, -l

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXComputeBoundingBox


D3DXCleanMesh

Cleans a mesh, preparing it for simplification.

HRESULT D3DXCleanMesh(
  D3DXCLEANTYPE CleanType,
  LPD3DXMESH pMeshIn,
  CONST DWORD * pAdjacencyIn,
  LPD3DXMESH * ppMeshOut,
  DWORD * pAdjacencyOut,
  LPD3DXBUFFER * ppErrorsAndWarnings
);

Parameters

CleanType
[in] Vertex operations to perform in preparation for mesh cleaning. See D3DXCLEANTYPE.
pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to be cleaned.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be cleaned.
ppMeshOut
[out] Address of a pointer to an ID3DXMesh interface, representing the returned cleaned mesh. The same mesh is returned that was passed in if no cleaning was necessary.
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the output mesh.
ppErrorsAndWarnings
[out] Returns a buffer containing a string of errors and warnings, which explain the problems found in the mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This function cleans a mesh using the cleaning method and options specified in the CleanType parameter. See the D3DXCLEANTYPE enumeration for a description of the available options.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXComputeBoundingBox

Computes a coordinate-axis oriented bounding box.

HRESULT D3DXComputeBoundingBox(
  CONST D3DXVECTOR3 * pFirstPosition,
  DWORD NumVertices,
  DWORD dwStride,
  D3DXVECTOR3 * pMin,
  D3DXVECTOR3 * pMax
);

Parameters

pFirstPosition
[in] Pointer to the first position.
NumVertices
[in] Number of vertices.
dwStride
[in] Count or number of bytes between vertices.
pMin
[out] Pointer to a D3DXVECTOR3 structure, describing the returned lower-left corner of the bounding box. See Remarks.
pMax
[out] Pointer to a D3DXVECTOR3 structure, describing the returned upper-right corner of the bounding box. See Remarks.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

Remarks

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXComputeBoundingSphere

Computes a bounding sphere for the mesh.

HRESULT D3DXComputeBoundingSphere(
  CONST D3DXVECTOR3 * pFirstPosition,
  DWORD NumVertices,
  DWORD dwStride,
  D3DXVECTOR3 * pCenter,
  FLOAT * pRadius
);

Parameters

pFirstPosition
[in] Pointer to first position.
NumVertices
[in] Number of vertices.
dwStride
[in] Number of bytes between position vectors. Use ID3DXBaseMesh::GetNumBytesPerVertex, D3DXGetFVFVertexSize, or D3DXGetDeclVertexSize to get the vertex stride.
pCenter
[out] D3DXVECTOR3 structure, defining the coordinate center of the returned bounding sphere.
pRadius
[out] Radius of the returned bounding sphere.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXComputeNormals

Computes unit normals for each vertex in a mesh. Provided to support legacy applications. Use D3DXComputeTangentFrameEx for better results.

HRESULT D3DXComputeNormals(
  LPD3DXBASEMESH pMesh,
  CONST DWORD * pAdjacency
);

Parameters

pMesh
[in, out] Pointer to an ID3DXBaseMesh interface, representing the normalized mesh object. This function may not take an ID3DXPMesh progressive mesh as input.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created progressive mesh. This parameter is optional and should be set to NULL if it is unused.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The input mesh must have the D3DFVF_NORMAL flag specified in its flexible vertex format (FVF).

A normal for a vertex is generated by averaging the normals of all faces that share that vertex.

If adjacency is provided, replicated vertices are ignored and "smoothed" over. If adjacency is not provided, replicated vertices will have normals averaged in from only the faces explicitly referencing them.

This function simply calls D3DXComputeTangentFrameEx with the following input parameters:

D3DXComputeTangentFrameEx( pMesh,
                           D3DX_DEFAULT,
                           0,
                           D3DX_DEFAULT,
                           0,
                           D3DX_DEFAULT,
                           0,
                           D3DDECLUSAGE_NORMAL,
                           0,
                           D3DXTANGENT_GENERATE_IN_PLACE | D3DXTANGENT_CALCULATE_NORMALS,
                           pAdjacency,
                           -1.01f,
                           -0.01f,
                           -1.01f,
                           NULL,
                           NULL);

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXComputeTangent

Computes the tangent vectors for the texture coordinates given in the texture stage. Provided to support legacy applications. Use D3DXComputeTangentFrameEx for better results.

HRESULT D3DXComputeTangent(
  LPD3DXMESH Mesh,
  DWORD TexStageIndex,
  DWORD TangentIndex,
  DWORD BinormIndex,
  DWORD Wrap,
  CONST DWORD * pAdjacency
);

Parameters

Mesh
[in] Pointer to an ID3DXMesh interface that represent the input mesh. This function may not take an ID3DXPMesh progressive mesh as input.
TexStageIndex
[in] Index that represents the texture stage.
TangentIndex
[in] Index that provides the usage index for the tangent data. The vertex declaration implies the usage; this index modifies the usage with the usage index. For more information about a vertex declaration, see Vertex Declaration (Direct3D 9).
BinormIndex
[in] Index that provides the usage index for the binormal data. The vertex declaration implies the usage; this index modifies the usage with the usage index. For more information about a vertex declaration, see Vertex Declaration (Direct3D 9).
Wrap
[in] Set this value to 0 for no wrapping, or to 1 for wrapping in the U and V directions.
pAdjacency
[in] Pointer to an array of three DWORDs per face to be filled with adjacent face indices. The number of bytes in this array must be at least ((3 * ID3DXBaseMesh::GetNumFaces) * sizeof(DWORD)).

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

If the mesh vertex declaration specifies tangent or binormal fields, D3DXComputeTangent will update any user-supplied tangent or binormal data. Alternatively, set TangentIndex to D3DX_DEFAULT to not update the user-supplied tangent data, or set BinormIndex to D3DX_DEFAULT to not update the user-supplied binormal data. TexStageIndex cannot be set to D3DX_DEFAULT.

D3DXComputeTangent depends on the mesh vertex declaration containing either the binormal field (BinormIndex), the tangent field (TangentIndex), or both. If both are missing, this function will fail.

This function simply calls D3DXComputeTangentFrameEx with the following input parameters:

D3DXComputeTangentFrameEx( Mesh,
                           D3DDECLUSAGE_TEXCOORD,
                           TexStageIndex,
                           ( BinormIndex == D3DX_DEFAULT ) ?
                               D3DX_DEFAULT : D3DDECLUSAGE_BINORMAL,
                               // provides backward function compatibility
                           BinormIndex,
                           ( TangentIndex == D3DX_DEFAULT ) ?
                               D3DX_DEFAULT : D3DDECLUSAGE_TANGENT,
                           TangentIndex,
                           D3DX_DEFAULT, // do not store normals
                           0,
                           ( Wrap ? D3DXTANGENT_WRAP_UV : 0 )
                               | D3DXTANGENT_GENERATE_IN_PLACE
                               | D3DXTANGENT_ORTHOGONALIZE_FROM_U,
                           pAdjacency,
                           -1.01f,
                           -0.01f,
                           -1.01f,
                           NULL,
                           NULL);

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXComputeTangentFrame

Compute tangent, binormal, and normal vectors for a mesh.

HRESULT D3DXComputeTangentFrame(
  ID3DXMesh * pMesh,
  DWORD dwOptions
);

Parameters

pMesh
[in] Pointer to an input ID3DXMesh mesh object.
dwOptions

Combination of one or more D3DXTANGENT flags.

[in] Use NULL to specify the following options:
  • Weight the normal vector length by the angle, in radians, subtended by the two edges leaving the vertex.
  • Compute orthogonal Cartesian coordinates from the UV texture coordinates.
  • Textures are not wrapped in either U or V directions
  • Partial derivatives with respect to texture coordinates are normalized.
  • Vertices are ordered in a counterclockwise direction around each triangle.
  • Use per-vertex normal vectors already present in the input mesh.
  • The results will be stored in the original input mesh. The function will fail if new vertices need to be created.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

This function simply calls D3DXComputeTangentFrameEx with the following input parameters:

D3DXComputeTangentFrameEx(pMesh, D3DDECLUSAGE_TEXCOORD, 0,
      D3DDECLUSAGE_BINORMAL, 0, D3DDECLUSAGE_TANGENT, 0,
      D3DDECLUSAGE_NORMAL, 0,
      dwOptions | D3DXTANGENT_GENERATE_IN_PLACE,
      NULL, 0.01f, 0.25f, 0.01f, NULL, NULL);

Singularities are handled as required by grouping edges and splitting vertices. If any vertices need to be split, the function will fail. The computed normal vector at each vertex is always normalized to have unit length.

The most robust solution for computing orthogonal Cartesian coordinates is to not set flags D3DXTANGENT_ORTHOGONALIZE_FROM_U and D3DXTANGENT_ORTHOGONALIZE_FROM_V, so that orthogonal coordinates are computed from both UV texture coordinates. However, in this case, if either U or V is zero, then the function will compute orthogonal coordinates using D3DXTANGENT_ORTHOGONALIZE_FROM_V or D3DXTANGENT_ORTHOGONALIZE_FROM_U respectively.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXComputeTangentFrameEx, D3DXTANGENT


D3DXComputeTangentFrameEx

Performs tangent frame computations on a mesh. Tangent, binormal, and optionally normal vectors are generated. Singularities are handled as required by grouping edges and splitting vertices.

HRESULT D3DXComputeTangentFrameEx(
  ID3DXMesh * pMesh,
  DWORD dwTextureInSemantic,
  DWORD dwTextureInIndex,
  DWORD dwUPartialOutSemantic,
  DWORD dwUPartialOutIndex,
  DWORD dwVPartialOutSemantic,
  DWORD dwVPartialOutIndex,
  DWORD dwNormalOutSemantic,
  DWORD dwNormalOutIndex,
  DWORD dwOptions,
  CONST DWORD * pdwAdjacency,
  FLOAT fPartialEdgeThreshold,
  FLOAT fSingularPointThreshold,
  FLOAT fNormalEdgeThreshold,
  ID3DXMesh ** ppMeshOut,
  ID3DXBuffer ** ppVertexMapping
);

Parameters

pMesh
[in] Pointer to an input ID3DXMesh mesh object.
dwTextureInSemantic
[in] Specifies the texture coordinate input semantic. If D3DX_DEFAULT, the function assumes that there are no texture coordinates, and the function will fail unless normal vector calculation is specified.
dwTextureInIndex
[in] If a mesh has multiple texture coordinates, specifies the texture coordinate to use for the tangent frame computations. If zero, the mesh has only a single texture coordinate.
dwUPartialOutSemantic
[in] Specifies the output semantic for the type, typically D3DDECLUSAGE_TANGENT, that describes where the partial derivative with respect to the U texture coordinate will be stored. If D3DX_DEFAULT, then this partial derivative will not be stored.
dwUPartialOutIndex
[in] Specifies the semantic index at which to store the partial derivative with respect to the U texture coordinate.
dwVPartialOutSemantic
[in] Specifies the D3DDECLUSAGE type, typically D3DDECLUSAGE_BINORMAL, that describes where the partial derivative with respect to the V texture coordinate will be stored. If D3DX_DEFAULT, then this partial derivative will not be stored.
dwVPartialOutIndex
[in] Specifies the semantic index at which to store the partial derivative with respect to the V texture coordinate.
dwNormalOutSemantic
[in] Specifies the output normal semantic, typically D3DDECLUSAGE_NORMAL, that describes where the normal vector at each vertex will be stored. If D3DX_DEFAULT, then this normal vector will not be stored.
dwNormalOutIndex
[in] Specifies the semantic index at which to store the normal vector at each vertex.
dwOptions

Combination of one or more D3DXTANGENT flags that specify tangent frame computation options. If NULL, the following options will be specified:
Description | D3DXTANGENT Flag Value
Weight the normal vector length by the angle, in radians, subtended by the two edges leaving the vertex. | & !( D3DXTANGENT_WEIGHT_BY_AREA | D3DXTANGENT_WEIGHT_EQUAL )
Compute orthogonal Cartesian coordinates from texture coordinates (u, v). See Remarks. | & !( D3DXTANGENT_ORTHOGONALIZE_FROM_U | D3DXTANGENT_ORTHOGONALIZE_FROM_V )
Textures are not wrapped in either u or v directions | & !( D3DXTANGENT_WRAP_UV )
Partial derivatives with respect to texture coordinates are normalized. | & !( D3DXTANGENT_DONT_NORMALIZE_PARTIALS )
Vertices are ordered in a counterclockwise direction around each triangle. | & !( D3DXTANGENT_WIND_CW )
Use per-vertex normal vectors already present in the input mesh. | & !( D3DXTANGENT_CALCULATE_NORMALS )

[in] If D3DXTANGENT_GENERATE_IN_PLACE is not set, the input mesh is cloned. The original mesh must therefore have sufficient space to store the computed normal vector and partial derivative data.

pdwAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).
fPartialEdgeThreshold
[in] Specifies the maximum cosine of the angle at which two partial derivatives are deemed to be incompatible with each other. If the dot product of the direction of the two partial derivatives in adjacent triangles is less than or equal to this threshold, then the vertices shared between these triangles will be split.
fSingularPointThreshold
[in] Specifies the maximum magnitude of a partial derivative at which a vertex will be deemed singular. As multiple triangles are incident on a point that have nearby tangent frames, but altogether cancel each other out (such as at the top of a sphere), the magnitude of the partial derivative will decrease. If the magnitude is less than or equal to this threshold, then the vertex will be split for every triangle that contains it.
fNormalEdgeThreshold
[in] Similar to fPartialEdgeThreshold, specifies the maximum cosine of the angle between two normals that is a threshold beyond which vertices shared between triangles will be split. If the dot product of the two normals is less than the threshold, the shared vertices will be split, forming a hard edge between neighboring triangles. If the dot product is more than the threshold, neighboring triangles will have their normals interpolated.
ppMeshOut
[out] Address of a pointer to an output ID3DXMesh mesh object that receives the computed tangent, binormal, and normal vector data.
ppVertexMapping
[out] Address of a pointer to an output ID3DXBuffer buffer object that receives a mapping of new vertices computed by this method to the original vertices. The buffer is an array of DWORDs, with the array size defined as the number of vertices in ppMeshOut.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

A simplified version of this function is available as D3DXComputeTangentFrame.

The computed normal vector at each vertex is always normalized to have unit length.

The most robust solution for computing orthogonal Cartesian coordinates is to not set flags D3DXTANGENT_ORTHOGONALIZE_FROM_U and D3DXTANGENT_ORTHOGONALIZE_FROM_V, so that orthogonal coordinates are computed from both texture coordinates u and v. However, in this case, if either u or v is zero, then the function will compute orthogonal coordinates using D3DXTANGENT_ORTHOGONALIZE_FROM_V or D3DXTANGENT_ORTHOGONALIZE_FROM_U, respectively.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXComputeTangentFrame


D3DXConcatenateMeshes

Concatenates a group of meshes into one common mesh. This method can optionally apply a matrix transformation to each input mesh and its texture coordinates.

HRESULT D3DXConcatenateMeshes(
  LPD3DXMESH * ppMeshes,
  UINT NumMeshes,
  DWORD Options,
  CONST D3DXMATRIX * pGeomXForms,
  CONST D3DXMATRIX * pTextureXForms,
  CONST D3DVERTEXELEMENT9 * pDecl,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LPD3DXMESH * ppMeshOut
);

Parameters

ppMeshes
[in] Array of input mesh pointers (see ID3DXMesh). The number of elements in the array is NumMeshes.
NumMeshes
[in] Number of input meshes to concatenate.
Options
[in] Mesh creation options; this is a combination of one or more D3DXMESH flags. The mesh creation options are equivalent to the options parameter required by D3DXCreateMesh.
pGeomXForms
[in] Optional array of geometry transforms. The number of elements in the array is NumMeshes; each element is a transformation matrix (see D3DXMATRIX). May be NULL.
pTextureXForms
[in] Optional array of texture transforms. The number of elements in the array is NumMeshes; each element is a transformation matrix (see D3DXMATRIX). This parameter may be NULL.
pDecl
[in] Optional pointer to a vertex declaration (see D3DVERTEXELEMENT9). This parameter may be NULL.
pD3DDevice
[in] Pointer to a IDirect3DDevice9 device that is used to create the new mesh.
ppMeshOut
[out] Address of a pointer to the mesh created (see ID3DXMesh).

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of these: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

If no vertex declaration is given as part of the Options mesh creation parameter, the method will generate a union of all of the vertex declarations of the submeshes, promoting channels and types if necessary. The method will create an attribute table from attribute tables of the input meshes. To ensure creation of an attribute table, call ID3DXMesh::Optimize with Flags set to D3DXMESHOPT_COMPACT and D3DXMESHOPT_ATTRSORT (see D3DXMESHOPT).

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXConvertMeshSubsetToSingleStrip

Converts the specified mesh subset into a single triangle strip.

HRESULT D3DXConvertMeshSubsetToSingleStrip(
  LPD3DXBASEMESH MeshIn,
  DWORD AttribId,
  DWORD IBOptions,
  LPDIRECT3DINDEXBUFFER9 * ppIndexBuffer,
  DWORD * pNumIndices
);

Parameters

MeshIn
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to convert to a strip.
AttribId
[in] Attribute ID of the mesh subset to convert to strips.
IBOptions
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying options for creating the index buffer. Cannot be D3DXMESH_32BIT. The index buffer will be created with 32-bit or 16-bit indices, depending on the format of the index buffer of the mesh specified by the MeshIn parameter.
ppIndexBuffer
[out] Pointer to an IDirect3DIndexBuffer9 interface, representing the index buffer containing the strip.
pNumIndices
[out] Number of indices in the buffer returned in the ppIndexBuffer parameter.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Before running this function, call ID3DXMesh::Optimize or D3DXOptimizeFaces, with the D3DXMESHOPT_ATTRSORT flag set.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXConvertMeshSubsetToStrips

Convert the specified mesh subset into a series of strips.

HRESULT D3DXConvertMeshSubsetToStrips(
  LPD3DXBASEMESH MeshIn,
  DWORD AttribId,
  DWORD IBOptions,
  LPDIRECT3DINDEXBUFFER9 * ppIndexBuffer,
  DWORD * pNumIndices,
  LPD3DXBUFFER * ppStripLengths,
  DWORD * pNumStrips
);

Parameters

MeshIn
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to convert to a strip.
AttribId
[in] Attribute ID of the mesh subset to convert to strips.
IBOptions
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying options for creating the index buffer. Cannot be D3DXMESH_32BIT. The index buffer will be created with 32-bit or 16-bit indices depending on the format of the index buffer of the mesh specified by the MeshIn parameter.
ppIndexBuffer
[out] Pointer to an IDirect3DIndexBuffer9 interface, representing index buffer containing the strip.
pNumIndices
[out] Number of indices in the buffer returned in the ppIndexBuffer parameter.
ppStripLengths
[out] Buffer containing an array of one DWORD per strip, which specifies the number of triangles in the that strip.
pNumStrips
[out] Number of individual strips in the index buffer and corresponding strip length array.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Before running this function, call ID3DXMesh::Optimize or D3DXOptimizeFaces, with the D3DXMESHOPT_ATTRSORT flag set.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXCreateMesh

Creates a mesh object using a declarator.

HRESULT D3DXCreateMesh(
  DWORD NumFaces,
  DWORD NumVertices,
  DWORD Options,
  CONST LPD3DVERTEXELEMENT9 * pDeclaration,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LPD3DXMESH * ppMesh
);

Parameters

NumFaces
[in] Number of faces for the mesh. The valid range for this number is greater than 0, and one less than the maximum DWORD (typically 65534), because the last index is reserved.
NumVertices
[in] Number of vertices for the mesh. This parameter must be greater than 0.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying options for the mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, describing the vertex format for the returned mesh. This parameter must map directly to a flexible vertex format (FVF).
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object to be associated with the mesh.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the created mesh object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXDeclaratorFromFVF


D3DXCreateMeshFVF

Creates a mesh object using a flexible vertex format (FVF) code.

HRESULT D3DXCreateMeshFVF(
  DWORD NumFaces,
  DWORD NumVertices,
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LPD3DXMESH * ppMesh
);

Parameters

NumFaces
[in] Number of faces for the mesh. The valid range for this number is greater than 0, and one less than the max DWORD value, typically 232 - 1, because the last index is reserved.
NumVertices
[in] Number of vertices for the mesh. This parameter must be greater than 0.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of D3DFVF that describes the vertex format for the returned mesh. This function does not support D3DFVF_XYZRHW.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object to be associated with the mesh.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the created mesh object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXFVFFromDeclarator


D3DXCreateNPatchMesh

Creates an N-patch mesh from a triangle mesh.

HRESULT D3DXCreateNPatchMesh(
  LPD3DXMESH pMeshSysMem,
  LPD3DXPATCHMESH * pPatchMesh
);

Parameters

pMeshSysMem
[in] Address of a pointer to an ID3DXMesh interface that represents the triangle mesh object.
pPatchMesh
[in, out] Address of a pointer to an ID3DXPatchMesh interface that represents the created patch mesh object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXCreatePatchMesh

Creates a mesh from a control-patch mesh.

HRESULT D3DXCreatePatchMesh(
  CONST D3DXPATCHINFO * pInfo,
  DWORD dwNumPatches,
  DWORD dwNumVertices,
  DWORD dwOptions,
  CONST D3DVERTEXELEMENT9 * pDecl,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LPD3DXPATCHMESH * pPatchMesh
);

Parameters

pInfo
[in] Patch information structure. For more information, see D3DXPATCHINFO.
dwNumPatches
[in] Number of patches.
dwNumVertices
[in] Number of control vertices in the patch.
dwOptions
[in] Unused. Reserved for later use.
pDecl
[in] Array of D3DVERTEXELEMENT9 elements, describing the vertex format for the returned mesh.
pD3DDevice
[in] Pointer the device that creates the patch mesh. See IDirect3DDevice9.
pPatchMesh
[out] Pointer to the ID3DXPatchMesh object that is created.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This method takes an input patch mesh and converts it to a tessellated mesh. Patch meshes use 16-bit index buffers. Therefore, indices to ID3DXPatchMesh::LockIndexBuffer are 16 bits.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXPATCHINFO


D3DXCreatePMeshFromStream

Creates a progressive mesh from a stream object.

HRESULT D3DXCreatePMeshFromStream(
  IStream * pStream,
  DWORD Options,
  LPDIRECT3DDEVICE9 pDevice,
  LPD3DXBUFFER * ppMaterials,
  LPD3DXBUFFER * ppEffectInstances,
  DWORD * pNumMaterials,
  LPD3DXPMESH * ppPMesh
);

Parameters

pStream
[in] Pointer to an IStream interface, representing the stream object from which to create the progressive mesh. The data in this stream was generated with the ID3DXPMesh::Save method.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object to be associated with the progressive mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the stream object.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppPMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the created progressive mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DXERR_INVALIDDATA E_OUTOFMEMORY

Remarks

For more information about the IStream interface, see the Platform SDK.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXPMesh::Save


D3DXCreateSkinInfo

Creates an empty skin mesh object using a declarator.

HRESULT D3DXCreateSkinInfo(
  DWORD NumVertices,
  CONST D3DVERTEXELEMENT9 * pDeclaration,
  DWORD NumBones,
  LPD3DXSKININFO * ppSkinInfo
);

Parameters

NumVertices
[in] Number of vertices for the skin mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, describing the vertex format for the returned mesh.
NumBones
[in] Number of bones for the skin mesh.
ppSkinInfo
[out, retval] Address of a pointer to an ID3DXSkinInfo interface, representing the created skin mesh object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: E_OUTOFMEMORY.

Remarks

Use ID3DXSkinInfo::SetBoneInfluence to populate the empty skin mesh object returned by this method.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::SetBoneInfluence


D3DXCreateSkinInfoFromBlendedMesh

Creates a skin mesh from another mesh.

HRESULT D3DXCreateSkinInfoFromBlendedMesh(
  LPD3DXBASEMESH pMesh,
  DWORD NumBones,
  CONST D3DXBONECOMBINATION * pBoneCombinationTable,
  LPD3DXSKININFO * ppSkinInfo
);

Parameters

pMesh
[in] Pointer to an ID3DXBaseMesh object, the mesh from which to create the skin mesh.
NumBones
[in] The length of the array attached to the BoneId. See D3DXBONECOMBINATION.
pBoneCombinationTable
[in] Pointer to an array of bone combinations. See D3DXBONECOMBINATION.
ppSkinInfo
[out, retval] Address of a pointer to an ID3DXSkinInfo interface representing the created skin mesh object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following: E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXCreateSkinInfoFVF

Creates an empty skin mesh object using a flexible vertex format (FVF) code.

HRESULT D3DXCreateSkinInfoFVF(
  DWORD NumVertices,
  DWORD FVF,
  DWORD NumBones,
  LPD3DXSKININFO * ppSkinInfo
);

Parameters

NumVertices
[in] Number of vertices for the skin mesh.
FVF
[in] Combination of D3DFVF that describes the vertex format for the returned skin mesh.
NumBones
[in] Number of bones for the skin mesh.
ppSkinInfo
[out, retval] Address of a pointer to an ID3DXSkinInfo interface, representing the created skin information object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Use ID3DXSkinInfo::SetBoneInfluence to populate the empty skin mesh object returned by this method.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

ID3DXSkinInfo::SetBoneInfluence


D3DXCreateSPMesh

Creates a simplification mesh.

HRESULT D3DXCreateSPMesh(
  LPD3DXMESH pMesh,
  CONST DWORD * pAdjacency,
  CONST D3DXATTRIBUTEWEIGHTS * pVertexAttributeWeights,
  CONST FLOAT * pVertexWeights,
  LPD3DXSPMESH * ppSMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the mesh to simplify.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created simplification mesh.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0. Note that the higher the vertex weight for a given vertex, the less likely it is to be simplified away.
ppSMesh
[out] Address of a pointer to an ID3DXSPMesh interface, representing the created simplification mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DXERR_CANNOTATTRSORT, D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

A simplification mesh is used to simplify a mesh to a lower number of triangles and faces.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;
AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXDeclaratorFromFVF

Returns a declarator from a flexible vertex format (FVF) code.

HRESULT D3DXDeclaratorFromFVF(
  DWORD FVF,
  D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

FVF
[in] Combination of D3DFVF that describes the FVF from which to generate the returned declarator array.
Declaration
[in, out] An array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DXERR_INVALIDMESH.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXFVFFromDeclarator


D3DXFVFFromDeclarator

Returns a flexible vertex format (FVF) code from a declarator.

HRESULT D3DXFVFFromDeclarator(
  CONST LPD3DVERTEXELEMENT9 * pDeclaration,
  DWORD * pFVF
);

Parameters

pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, describing the FVF code.
pFVF
[out] Pointer to a DWORD value, representing the returned combination of D3DFVF that describes the vertex format returned from the declarator.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: D3DERR_INVALIDCALL.

Remarks

This function will fail for any declarator that does not map directly to an FVF.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXDeclaratorFromFVF


D3DXGenerateOutputDecl

Generates an output vertex declaration from the input declaration. The output declaration is intended for use by the mesh tessellation functions.

HRESULT D3DXGenerateOutputDecl(
  D3DVERTEXELEMENT9 * pOutput,
  CONST D3DVERTEXELEMENT9 * pInput
);

Parameters

pOutput
[out] Pointer to the output vertex declaration. See D3DVERTEXELEMENT9.
pInput
[in] Pointer to the input vertex declaration. See D3DVERTEXELEMENT9.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXGeneratePMesh

Generates a progressive mesh.

HRESULT D3DXGeneratePMesh(
  LPD3DXMESH pMesh,
  CONST DWORD * pAdjacency,
  CONST D3DXATTRIBUTEWEIGHTS * pVertexAttributeWeights,
  CONST FLOAT * pVertexWeights,
  DWORD MinValue,
  DWORD Options,
  LPD3DXPMESH * ppPMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created progressive mesh.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0. Note that the higher the vertex weight for a given vertex, the less likely it is to be simplified away.
MinValue
[in] Number of vertices or faces, depending on the flag set in the Options parameter, by which to simplify the source mesh.
Options
[in] Specifies simplification options for the mesh. One flag from the D3DXMESHSIMP enumeration can be set.
ppPMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the created progressive mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DXERR_CANNOTATTRSORT, D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This function generates a mesh where the level of detail (LOD) can be adjusted from the current value to the MinValue.

If the simplification process cannot reduce the mesh to MinValue, the call still succeeds because MinValue is a desired minimum, not an absolute minimum.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;

AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXGetDeclLength

Returns the number of elements in the vertex declaration.

UINT D3DXGetDeclLength(
  CONST D3DVERTEXELEMENT9 * pDecl
);

Parameters

pDecl
[in] A pointer to the vertex declaration. See D3DVERTEXELEMENT9.

Return Values

The number of elements in the vertex declaration.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXGetDeclVertexSize

Returns the size of a vertex from the vertex declaration.

UINT D3DXGetDeclVertexSize(
  CONST D3DVERTEXELEMENT9 * pDecl,
  DWORD Stream
);

Parameters

pDecl
[in] A pointer to the vertex declaration. See D3DVERTEXELEMENT9.
Stream
[in] The zero-based stream index.

Return Values

The vertex declaration size, in bytes.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXGetFVFVertexSize

Returns the size of a vertex for a flexible vertex format (FVF).

UINT D3DXGetFVFVertexSize(
  DWORD FVF
);

Parameters

FVF
[in] FVF to be queried. A combination of D3DFVF.

Return Values

The FVF vertex size, in bytes.

Requirements

Header: Declared in D3dx9core.h.


D3DXIntersect

Determines if a ray intersects with a mesh.

HRESULT D3DXIntersect(
  LPD3DXBASEMESH pMesh,
  CONST D3DXVECTOR3 * pRayPos,
  CONST D3DXVECTOR3 * pRayDir,
  BOOL * pHit,
  DWORD * pFaceIndex,
  FLOAT * pU,
  FLOAT * pV,
  FLOAT * pDist,
  LPD3DXBUFFER * ppAllHits,
  DWORD * pCountOfHits
);

Parameters

pMesh
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to be tested.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pHit
[out] Pointer to a BOOL. If the ray intersects a triangular face on the mesh, this value will be set to TRUE. Otherwise, this value is set to FALSE.
pFaceIndex
[out] Pointer to an index value of the face closest to the ray origin, if pHit is TRUE.
pU
[out] Pointer to a barycentric hit coordinate, U.
pV
[out] Pointer to a barycentric hit coordinate, V.
pDist
[out] Pointer to a ray intersection parameter distance.
ppAllHits
[out] Pointer to an ID3DXBuffer object, containing an array of D3DXINTERSECTINFO structures.
pCountOfHits
[out] Pointer to a DWORD that contains the number of entries in the ppAllHits array.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be: E_OUTOFMEMORY.

Remarks

The D3DXIntersect function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2 - V1) + V(V3 - V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result, and the parameter V controls how much V3 gets weighted into the result. Lastly, the value of [1 - (U + V)] controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXIntersectSubset

Intersects the specified ray with the given mesh subset. This provides similar functionality to D3DXIntersect.

HRESULT D3DXIntersectSubset(
  LPD3DXBASEMESH pMesh,
  DWORD AttribId,
  CONST D3DXVECTOR3 * pRayPos,
  CONST D3DXVECTOR3 * pRayDir,
  BOOL * pHit,
  DWORD * pFaceIndex,
  FLOAT * pU,
  FLOAT * pV,
  FLOAT * pDist,
  LPD3DXBUFFER * ppAllHits,
  DWORD * pCountOfHits
);

Parameters

pMesh
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to be tested. The mesh must be attribute sorted.
AttribId
[in] Attribute identifier of the subset to intersect with.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pHit
[out] Pointer to a BOOL. If the ray intersects a triangular face on the mesh, this value will be set to TRUE. Otherwise, this value is set to FALSE.
pFaceIndex
[out] Pointer to an index value of the face closest to the ray origin, if pHit is TRUE.
pU
[out] Pointer to a barycentric hit coordinate, U.
pV
[out] Pointer to a barycentric hit coordinate, V.
pDist
[out] Pointer to a ray intersection parameter distance.
ppAllHits
[out] Array of D3DXINTERSECTINFO structures, representing all hits, not just closest hits.
pCountOfHits
[out] Number of elements in the array returned from ppAllHits.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following value: E_OUTOFMEMORY.

Remarks

The D3DXIntersectSubset function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2 - V1) + V(V3 - V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result and the parameter V controls how much V3 gets weighted into the result. Lastly, the value of [1 - (U + V)] controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXIntersectTri

Computes the intersection of a ray and a triangle.

BOOL D3DXIntersectTri(
  CONST D3DXVECTOR3 * p0,
  CONST D3DXVECTOR3 * p1,
  CONST D3DXVECTOR3 * p2,
  CONST D3DXVECTOR3 * pRayPos,
  CONST D3DXVECTOR3 * pRayDir,
  FLOAT * pU,
  FLOAT * pV,
  FLOAT * pDist
);

Parameters

p0
[in] Pointer to a D3DXVECTOR3 structure, describing the first triangle vertex position.
p1
[in] Pointer to a D3DXVECTOR3 structure, describing the second triangle vertex position.
p2
[in] Pointer to a D3DXVECTOR3 structure, describing the third triangle vertex position.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pU
[out] Barycentric hit coordinates, U.
pV
[out] Barycentric hit coordinates, V.
pDist
[out] Ray-intersection parameter distance.

Return Values

Returns TRUE if the ray intersects the area of the triangle. Otherwise, returns FALSE.

Remarks

The D3DXIntersect function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2 - V1) + V(V3 - V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result, and the parameter V controls how much V3 gets weighted into the result. Lastly, the value of [1 - (U + V)] controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXLoadMeshFromX

Loads a mesh from a DirectX .x file.

HRESULT D3DXLoadMeshFromX(
  LPCTSTR pFilename,
  DWORD Options,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LPD3DXBUFFER * ppAdjacency,
  LPD3DXBUFFER * ppMaterials,
  LPD3DXBUFFER * ppEffectInstances,
  DWORD * pNumMaterials,
  LPD3DXMESH * ppMesh
);

Parameters

pFilename
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, which specifies creation options for the mesh.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Pointer to a buffer that contains adjacency data. The adjacency data contains an array of three DWORDs per face that specify the three neighbors for each face in the mesh. For more information about accessing the buffer, see ID3DXBuffer.
ppMaterials
[out] Pointer to a buffer containing materials data. The buffer contains an array of D3DXMATERIAL structures, containing information from the DirectX file. For more information about accessing the buffer, see ID3DXBuffer.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadMeshFromXW. Otherwise, the function call resolves to D3DXLoadMeshFromXA because ANSI strings are being used.

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXLoadMeshFromXInMemory

Loads a mesh from memory.

HRESULT D3DXLoadMeshFromXInMemory(
  LPCVOID Memory,
  DWORD SizeOfMemory,
  DWORD Options,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LPD3DXBUFFER * ppAdjacency,
  LPD3DXBUFFER * ppMaterials,
  LPD3DXBUFFER * ppEffectInstances,
  DWORD * pNumMaterials,
  LPD3DXMESH * ppMesh
);

Parameters

Memory
[in] Pointer to the memory buffer which contains the mesh data.
SizeOfMemory
[in] Size of the file in memory, in bytes.
Options
[out] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the DirectX file.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXLoadMeshFromXof

Loads a mesh from an ID3DXFileData object.

HRESULT D3DXLoadMeshFromXof(
  LPD3DXFILEDATA pxofMesh,
  DWORD Options,
  LPDIRECT3DDEVICE9 pDevice,
  LPD3DXBUFFER * ppAdjacency,
  LPD3DXBUFFER * ppMaterials,
  LPD3DXBUFFER * ppEffectInstances,
  DWORD * pNumMaterials,
  LPD3DXMESH * ppMesh
);

Parameters

pxofMesh
[in] Pointer to an ID3DXFileData interface, representing the file data object to load.
Options
[out] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Pointer to a buffer that contains adjacency data. The adjacency data contains an array of three DWORDs per face that specify the three neighbors for each face in the mesh. For more information about accessing the buffer, see ID3DXBuffer.
ppMaterials
[in, out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of D3DXMATERIAL structures.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[in, out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DXERR_INVALIDDATA E_OUTOFMEMORY

Remarks

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXLoadMeshFromXResource

Loads a mesh from a resource.

HRESULT D3DXLoadMeshFromXResource(
  HMODULE Module,
  LPCSTR Name,
  LPCSTR Type,
  DWORD Options,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LPD3DXBUFFER * ppAdjacency,
  LPD3DXBUFFER * ppMaterials,
  LPD3DXBUFFER * ppEffectInstances,
  DWORD * pNumMaterials,
  LPD3DXMESH * ppMesh
);

Parameters

Module
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process. See remarks.
Name
[in] Pointer to a string that specifies the resource to create the mesh from. See remarks.
Type
[in] Pointer to a string that specifies the resource type. See remarks.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration that specify creation options for the mesh.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the DirectX file.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

See Find Resource to find out more about the Module, Name and Type parameters.

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXLoadPatchMeshFromXof

Loads a patch mesh from an ID3DXFileData object.

HRESULT D3DXLoadPatchMeshFromXof(
  LPD3DXFILEDATA pxofMesh,
  DWORD Options,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LPD3DXBUFFER * ppMaterials,
  LPD3DXBUFFER * ppEffectInstances,
  PDWORD pNumMaterials,
  LPD3DXPATCHMESH* ppMesh
);

Parameters

pxofMesh
[in] Pointer to an ID3DXFileData interface, representing the file data object to load.
Options
[in] Combination of one or more D3DXMESH flags, specifying creation options for the mesh.
pD3DDevice
[in] Pointer to the device that the mesh is created from.
ppMaterials
[out] Array of materials contained in the mesh. Each material is indexed by an ID3DXBuffer interface.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer that contains the number of materials in the mesh.
ppMesh
[out, retval] Address of a pointer to an ID3DXPatchMesh interface, representing the loaded mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXLoadSkinMeshFromXof

Loads a skin mesh from a DirectX .x file data object.

HRESULT D3DXLoadSkinMeshFromXof(
  LPD3DXFILEDATA pxofMesh,
  DWORD Options,
  LPDIRECT3DDEVICE9 pD3DDevice,
  LPD3DXBUFFER * ppAdjacency,
  LPD3DXBUFFER * ppMaterials,
  LPD3DXBUFFER * ppEffectInstances,
  DWORD * pMatOut,
  LPD3DXSKININFO * ppSkinInfo,
  LPD3DXMESH * ppMesh
);

Parameters

pxofMesh
[in] Pointer to an ID3DXFileData interface, representing the file data object to load.
Options
[in] Combination of one or more flags, from the D3DXMESH enumeration, specifying creation options for the mesh.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of D3DXMATERIAL structures.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pMatOut
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppSkinInfo
[out] Address of a pointer to an ID3DXSkinInfo interface, which represents the skinning information.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, which represents the loaded mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DXERR_INVALIDDATA E_OUTOFMEMORY

Remarks

This method takes a pointer to an internal object in the .x file, enabling you to load the frame hierarchy.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXOptimizeFaces

Generates an optimized face remapping for a triangle list.

HRESULT D3DXOptimizeFaces(
  LPCVOID pIndices,
  UINT NumFaces,
  UINT NumVertices,
  BOOL Indices32Bit,
  DWORD * pFaceRemap
);

Parameters

pIndices
[in] Pointer to triangle list indices to use for ordering vertices.
NumFaces
[in] Number of faces in the triangle list. For 16-bit meshes, this is limited to 2^16 - 1 (65535) or fewer faces.
NumVertices
[in] Number of vertices referenced by the triangle list.
Indices32Bit
[in] Flag indicating index type: TRUE if indices are 32-bit (more than 65535 indices), FALSE if indices are 16-bit (65535 or fewer indices).
pFaceRemap
[in, out] Pointer to the original mesh face that was split to generate the current face.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This function's optimization procedure is functionally equivalent to calling ID3DXMesh::Optimize with the D3DXMESHOPT_DEVICEINDEPENDENT flag, but this function makes more efficient use of vertex caches.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXOptimizeVertices

Generates an optimized vertex remapping for a triangle list. This function is commonly used after applying the face remapping generated by D3DXOptimizeFaces.

HRESULT D3DXOptimizeVertices(
  LPCVOID pIndices,
  UINT NumFaces,
  UINT NumVertices,
  BOOL Indices32Bit,
  DWORD * pVertexRemap
);

Parameters

pIndices
[in] Pointer to triangle list indices to use for ordering vertices.
NumFaces
[in] Number of faces in the triangle list.
NumVertices
[in] Number of vertices referenced by the triangle list.
Indices32Bit
[in] Flag indicating index type: TRUE if indices are 32-bit (more than 65535 vertices), FALSE if indices are 16-bit (65535 or fewer vertices).
pVertexRemap
[in, out] Pointer to a destination buffer that will contain the new index for each vertex. The value stored in pVertexRemap for a given element is the source vertex location in the new vertex ordering.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

By default, a mesh uses 16 bit indices when it is created unless the application specifies otherwise. To check whether an existing mesh uses 16-bit or 32-bit indices, call ID3DXBaseMesh::GetOptions and check for the D3DXMESH_32BIT flag.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXRectPatchSize

Gets the size of the rectangle patch.

HRESULT D3DXRectPatchSize(
  CONST FLOAT * pfNumSegs,
  DWORD * pdwTriangles,
  DWORD * pwdVertices
);

Parameters

pfNumSegs
[in] Number of segments per edge to tessellate.
pdwTriangles
[out] Pointer to a DWORD that contains the number of triangles in the patch.
pwdVertices
[out] Pointer to a DWORD that contains the number of vertices in the patch.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXTessellateRectPatch


D3DXSaveMeshToX

Saves a mesh to a .x file.

HRESULT D3DXSaveMeshToX(
  LPCTSTR pFilename,
  LPD3DXMESH pMesh,
  CONST DWORD * pAdjacency,
  CONST D3DXMATERIAL * pMaterials,
  CONST D3DXEFFECTINSTANCE * pEffectInstances,
  DWORD NumMaterials,
  DWORD Format
);

Parameters

pFilename
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pMesh
[in] Pointer to an ID3DXMesh interface, representing the mesh to save to a .x file.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. This parameter may be NULL.
pMaterials
[in] Pointer to an array of D3DXMATERIAL structures, containing material information to be saved in the .x file.
pEffectInstances
[in] Pointer to an array of effect instances, one per attribute group in the mesh. This parameter may be NULL. An effect instance is a particular instance of state information used to initialize an effect. For more information, see D3DXEFFECTINSTANCE.
NumMaterials
[in] Number of D3DXMATERIAL structures in the pMaterials array.
Format
[in] A combination of file format and save options when saving an .x file. See D3DX X File Constants.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveMeshToXW. Otherwise, the function call resolves to D3DXSaveMeshToXA because ANSI strings are being used.

The default file format is binary; however, if a file is specified as both a binary and a text file, it will be saved as a text file. Regardless of the file format, you may also use the compressed format to reduce the file size.

The following is a typical code example of how to use this function.

ID3DXMesh*    m_pMesh;           // Mesh object to be saved to a .x file
D3DXMATERIAL* m_pMaterials;      // Array of material structs in the mesh
DWORD         m_dwNumMaterials;  // Number of material structs in the mesh

DWORD dwFormat = D3DXF_FILEFORMAT_BINARY;  // Binary-format .x file (default)
// DWORD dwFormat = D3DXF_FILEFORMAT_TEXT; // Text-format .x file

// Load mesh into m_pMesh and determine values of m_pMaterials and
// m_dwNumMaterials with calls to D3DXLoadMeshxxx or other D3DX functions

// ...

D3DXSaveMeshToX(
    L"outputxfilename.x",
    m_pMesh,
    NULL,
    m_pMaterials,
    NULL,
    m_dwNumMaterials,
    dwFormat );

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXSimplifyMesh

Generates a simplified mesh using the provided weights that come as close as possible to the given MinValue.

HRESULT D3DXSimplifyMesh(
  LPD3DXMESH pMesh,
  CONST DWORD * pAdjacency,
  CONST D3DXATTRIBUTEWEIGHTS * pVertexAttributeWeights,
  CONST FLOAT * pVertexWeights,
  DWORD MinValue,
  DWORD Options,
  LPD3DXMESH * ppMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be simplified.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0.
MinValue
[in] Number of vertices or faces, depending on the flag set in the Options parameter, by which to simplify the source mesh.
Options
[in] Specifies simplification options for the mesh. One of the flags in D3DXMESHSIMP can be set.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the returned simplification mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

This function generates a mesh that has MinValue vertices or faces.

If the simplification process cannot reduce the mesh to MinValue, the call still succeeds because MinValue is a desired minimum, not an absolute minimum.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;

AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXSphereBoundProbe

Determines if a ray intersects the volume of a sphere's bounding box.

BOOL D3DXSphereBoundProbe(
  CONST D3DXVECTOR3 * pCenter,
  FLOAT Radius,
  CONST D3DXVECTOR3 * pRayPosition,
  CONST D3DXVECTOR3 * pRayDirection
);

Parameters

pCenter
[in] Pointer to a D3DXVECTOR3 structure, specifying the center coordinate of the sphere.
Radius
[in] Radius of the sphere.
pRayPosition
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDirection
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray. This vector should not be (0,0,0) but does not need to be normalized.

Return Values

Returns TRUE if the ray intersects the volume of the sphere's bounding box. Otherwise, returns FALSE.

Remarks

D3DXSphereBoundProbe determines if the ray intersects the volume of the sphere's bounding box, not just the surface of the sphere.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXSplitMesh

Splits a mesh into meshes smaller than the specified size.

void D3DXSplitMesh(
  LPD3DXMESH pMeshIn,
  CONST DWORD * pAdjacencyIn,
  CONST DWORD MaxSize,
  CONST DWORD Options,
  DWORD * pMeshesOut,
  LPD3DXBUFFER * ppMeshArrayOut,
  LPD3DXBUFFER * ppAdjacencyArrayOut,
  LPD3DXBUFFER * ppFaceRemapArrayOut,
  LPD3DXBUFFER * ppVertRemapArrayOut
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be simplified.
MaxSize
[in] Maximum number of vertices in the resulting mesh.
Options
[in] Option flags for the new meshes.
pMeshesOut
[out, retval] Number of meshes returned.
ppMeshArrayOut
[out, retval] Buffer containing an array of ID3DXMesh interfaces for the new meshes. For a source mesh split into n meshes, ppMeshArrayOut is an array of n ID3DXMesh pointers.
ppAdjacencyArrayOut
[out, retval] Buffer containing an array of adjacency arrays (DWORDs) for the new meshes. See ID3DXBuffer. This parameter is optional.
ppFaceRemapArrayOut
[out, retval] Buffer containing an array of face remap arrays (DWORDs) for the new meshes. See ID3DXBuffer. This parameter is optional.
ppVertRemapArrayOut
[out, retval] Buffer containing an array of vertex remap arrays for the new meshes. See ID3DXBuffer. This parameter is optional.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

A common use of this function is to split a mesh with 32-bit indices (more than 65535 vertices) into more than one mesh, each of which has 16-bit indices.

The adjacency, vertex remap and face remap arrays are arrays are DWORDs where each array contains n DWORD pointers, followed by the DWORD data referenced by the pointers. For example, to obtain the face remap information for face 3 in mesh 2, the following code could be used, assuming the face remap data was returned in a variable named ppFaceRemapArrayOut.

const DWORD **face_remaps =
    static_cast<DWORD **>(ppFaceRemapArrayOut->GetBufferPointer());
const DWORD remap = face_remaps[2][3];

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXTessellateNPatches

Tessellates the given mesh using the N-patch tessellation scheme.

HRESULT D3DXTessellateNPatches(
  LPD3DXMESH pMeshIn,
  CONST CONST DWORD * pAdjacencyIn,
  FLOAT NumSegs,
  BOOL QuadraticInterpNormals,
  LPD3DXMESH * ppMeshOut,
  LPD3DXBUFFER * ppAdjacencyOut
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to tessellate.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. This parameter may be NULL.
NumSegs
[in] Number of segments per edge to tessellate.
QuadraticInterpNormals
[in] Set to TRUE to use quadratic interpolation for normals; set to FALSE for linear interpolation.
ppMeshOut
[out] Address of a pointer to an ID3DXMesh interface, representing the returned tessellated mesh.
ppAdjacencyOut
[out] Address of a pointer to an ID3DXBuffer interface. If the value of this parameter is not set to NULL>, this buffer will contain an array of three DWORDs per face that specify the three neighbors for each face in the output mesh. This parameter may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

This function tessellates by using the N-patch algorithm.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXTessellateRectPatch

Tessellates a rectangular higher-order surface patch into a triangle mesh.

HRESULT D3DXTessellateRectPatch(
  LPDIRECT3DVERTEXBUFFER9 pVB,
  CONST FLOAT * pNumSegs,
  CONST D3DVERTEXELEMENT9 * pInDecl,
  CONST D3DRECTPATCH_INFO * pRectPatchInfo,
  LPD3DXMESH pMesh
);

Parameters

pVB
[in] Vertex buffer containing the patch data.
pNumSegs
[in] Pointer to an array of four floating-point values that identify the number of segments into which each edge of the rectangle patch should be divided when tessellated. See D3DRECTPATCH_INFO.
pInDecl
[in] Vertex declaration structure that defines the vertex data. See D3DVERTEXELEMENT9.
pRectPatchInfo
[in] Describes a rectangular patch. See D3DRECTPATCH_INFO.
pMesh
[in, out] Pointer to the created mesh. See ID3DXMesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Use D3DXRectPatchSize to get the number of output vertices and indices that the tessellation function needs.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXTessellateTriPatch


D3DXTessellateTriPatch

Tessellates a triangular higher-order surface patch into a triangle mesh.

HRESULT D3DXTessellateTriPatch(
  LPDIRECT3DVERTEXBUFFER9 pVB,
  CONST FLOAT * pNumSegs,
  CONST D3DVERTEXELEMENT9 * pInDecl,
  CONST D3TRIPATCH_INFO * pTriPatchInfo,
  LPD3DXMESH pMesh
);

Parameters

pVB
[in] Vertex buffer containing the patch data.
pNumSegs
[in] Pointer to an array of three floating-point values that identify the number of segments into which each edge of the triangle patch should be divided when tessellated. See D3DTRIPATCH_INFO.
pInDecl
[in] Vertex declaration structure that defines the vertex data. See D3DVERTEXELEMENT9.
pTriPatchInfo
[in] Describes a triangle patch. See D3DTRIPATCH_INFO.
pMesh
[in, out] Pointer to the created mesh. See ID3DXMesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Use D3DXTriPatchSize to get the number of output vertices and indices that the tessellation function needs.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXTessellateRectPatch


D3DXTriPatchSize

Gets the size of the triangle patch.

HRESULT D3DXTriPatchSize(
  CONST LOAT * pfNumSegs,
  DWORD * pdwTriangles,
  DWORD * pdwVertices
);

Parameters

pfNumSegs
[in] Number of segments per edge to tessellate.
pdwTriangles
[out] Pointer to a DWORD that contains the number of triangles in the patch.
pdwVertices
[out] Pointer to a DWORD that contains the number of vertices in the triangle patch.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXTessellateTriPatch


D3DXValidMesh

Validates a mesh.

HRESULT D3DXValidMesh(
  LPD3DXMESH pMeshIn,
  CONST DWORD * pAdjacency,
  LPD3DXBUFFER * ppErrorsAndWarnings
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to be tested.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be tested.
ppErrorsAndWarnings
[out] Returns a buffer containing a string of errors and warnings, which explain the problems found in the mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DXERR_INVALIDMESH, D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This method validates the mesh by checking for invalid indices. Error information is available from the debugger output.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXValidPatchMesh

Validates a patch mesh, returning the number of degenerate vertices and patches.

HRESULT D3DXValidPatchMesh(
  LPD3DXPATCHMESH  pMeshIn,
  DWORD * pNumDegenerateVertices,
  DWORD * pNumDegeneratePatches,
  LPD3DXBUFFER * ppErrorsAndWarnings
);

Parameters

pMeshIn
[in] Pointer to an ID3DXPatchMesh interface, representing the patch mesh to be tested.
pNumDegenerateVertices
[out] Returns the number of degenerate vertices in the patch mesh.
pNumDegeneratePatches
[out] Returns the number of degenerate patches in the patch mesh.
ppErrorsAndWarnings
[out] Returns a pointer to a buffer containing a string of errors and warnings that explain the problems found in the patch mesh.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This method validates the mesh by checking for invalid indices. Error information is available from the debugger output.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXWeldVertices

Welds together replicated vertices that have equal attributes. This method uses specified epsilon values for equality comparisons.

HRESULT D3DXWeldVertices(
  LPD3DXMESH pMesh,
  DWORD Flags,
  CONST D3DXWeldEpsilons * pEpsilons,
  CONST DWORD * pAdjacencyIn,
  DWORD * pAdjacencyOut,
  DWORD * pFaceRemap,
  LPD3DXBUFFER * ppVertexRemap
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh object, the mesh from which to weld vertices.
Flags
[in] Combination of one or more flags from D3DXWeldEpsilonsFLAGS.
pEpsilons
[in] Pointer to a D3DXWeldEpsilons structure, specifying the epsilon values to be used for this method. Use NULL to initialize all structure members to a default value of 1.0e-6f.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. If the edge has no adjacent faces, the value is 0xffffffff. If this parameter is set to NULL, ID3DXBaseMesh::GenerateAdjacency will be called to create logical adjacency information.
pAdjacencyOut
[in, out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the optimized mesh. If the edge has no adjacent faces, the value is 0xffffffff.
pFaceRemap
[out] An array of DWORDs, one per face, that identifies the original mesh face that corresponds to each face in the welded mesh.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, which contains a DWORD for each vertex that specifies how the new vertices map to the old vertices. This remap is useful if you need to alter external data based on the new vertex mapping.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

This function uses supplied adjacency information to determine the points that are replicated. Vertices are merged based on an epsilon comparison. Vertices with equal position must already have been calculated and represented by point-representative data.

This function combines logically-welded vertices that have similar components, such as normals or texture coordinates within pEpsilons.

The following example code calls this function with welding enabled. Vertices are compared using epsilon values for normal vector and vertex position. A pointer is returned to a face remapping array (pFaceRemap).

TCHAR            strMediaPath[512];       // X-file path
LPD3DXBUFFER     pAdjacencyBuffer = NULL; // adjacency data buffer
LPD3DXBUFFER     pD3DXMtrlBuffer  = NULL; // material buffer
LPD3DXMESH       pMesh            = NULL; // mesh object
DWORD            m_dwNumMaterials;        // number of materials
D3DXWELDEPSILONS Epsilons;                // structure with epsilon values
DWORD            *pFaceRemap[65536];      // face remapping array
DWORD            i;                       // internal variable

    // Load the mesh from the specified file
    hr = D3DXLoadMeshFromX ( strMediaPath,
                         D3DXMESH_MANAGED,
                         m_pd3dDevice,
                         &pAdjacencyBuffer,
                         &pD3DXMtrlBuffer,
                         NULL,
                         &m_dwNumMaterials,
                         &pMesh ) )

    if( FAILED( hr ) )
      goto End;              // Go to error handling

    // Set epsilon values
    Epsilons.Normal = 0.001;
    Epsilons.Position = 0.1;

    // Weld the vertices
    for( i=0; i < 65536; i++ )
    {
        pFaceRemap[i] = 0;
    }

    hr = D3DXWeldVertices ( pMesh,
                            D3DXWELDEPSILONS_WELDPARTIALMATCHES,
                            &Epsilons,
                            (DWORD*)pAdjacencyBuffer->GetBufferPointer(),
                            (DWORD*)pAdjacencyBuffer->GetBufferPointer(),
                            (DWORD*)pFaceRemap,
                            NULL )

    if( FAILED( hr ) )
      goto End;              // Go to error handling

Requirements

Header: Declared in D3DX9Mesh.h.


Precomputed Radiance Transfer Functions

D3DX supplies the following precomputed radiance transfer (PRT) functions:

  • D3DXCreatePRTBuffer
  • D3DXCreatePRTBufferTex
  • D3DXCreatePRTCompBuffer
  • D3DXCreatePRTEngine
  • D3DXCreateTextureGutterHelper
  • D3DXLoadPRTBufferFromFile
  • D3DXLoadPRTCompBufferFromFile
  • D3DXSavePRTBufferToFile
  • D3DXSavePRTCompBufferToFile
  • D3DXSHPRTCompSplitMeshSC
  • D3DXSHPRTCompSuperCluster

For more information about using PRT, see Precomputed Radiance Transfer (Direct3D 9).

The D3DXSHxxx functions are also used for PRT spherical harmonic (SH) operations.

See Also

D3DXConcatenateMeshes


D3DXCreatePRTBuffer

Creates a precomputed radiance transfer (PRT) buffer that can be compressed or filled by a simulator. This function should be used to create per-vertex or volume buffers.

HRESULT D3DXCreatePRTBuffer(
  UINT NumSamples,
  UINT NumCoeffs,
  UINT NumChannels,
  LPD3DXPRTBUFFER * ppBuffer
);

Parameters

NumSamples
[in] Number of vertices (or texels) sampled.
NumCoeffs
[in] Number of coefficients per sample location. When using spherical harmonic (SH) PRT, the number of coefficients should be Order2, where Order is the order of the SH evaluation. Order must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The degree of the evaluation is Order - 1.
NumChannels
[in] Number of color channels to set in the mesh. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.
ppBuffer
[in, out] Address of a pointer to the created ID3DXPRTBuffer object.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of these: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

When the buffer is created, all values are initialized to zero.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXCreatePRTBufferTex


D3DXCreatePRTBufferTex

Creates a precomputed radiance transfer (PRT) buffer that can be compressed or filled by a simulator. This function should be used to create per-pixel buffers.

HRESULT D3DXCreatePRTBufferTex(
  UINT Width,
  UINT Height,
  UINT NumCoeffs,
  UINT NumChannels,
  LPD3DXPRTBUFFER * ppBuffer
);

Parameters

Width
[in] Width of the texture, in pixels.
Height
[in] Height of the texture, in pixels.
NumCoeffs
[in] Number of coefficients per sample location. When using spherical harmonic (SH) PRT, the number of coefficients should be Order2, where Order is the order of the SH evaluation. Order must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The degree of the evaluation is Order - 1.
NumChannels
[in] Number of color channels to set in the mesh. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.
ppBuffer
[in, out] Address of a pointer to the created ID3DXPRTBuffer object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

When the buffer is created, all values are initialized to zero.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXCreatePRTBuffer


D3DXCreatePRTCompBuffer

Creates a compressed precomputed radiance transfer (PRT) buffer from an uncompressed ID3DXPRTBuffer object. This function should be used with per-vertex or volume buffers.

HRESULT D3DXCreatePRTCompBuffer(
  D3DXSHCOMPRESSQUALITYTYPE Quality,
  UINT NumClusters,
  UINT NumPCA,
  LPD3DXSHPRTSIMCB pCB,
  LPVOID lpUserContext,
  LPD3DXPRTBUFFER pBuffer,
  LPD3DXPRTCOMPBUFFER * ppBuffer
);

Parameters

Quality
[in] Quality of spherical harmonic (SH) compression. See D3DXSHCOMPRESSQUALITYTYPE.
NumClusters
[in] Number of clusters to use for compression.
NumPCA
[in] Number of principal component analysis (PCA) basis vectors to use in each cluster.
pCB
[in] Optional pointer to the LPD3DXSHPRTSIMCB callback function that is used to compute the percentage of PRT compression computations completed. The callback function must be implemented to return S_OK to keep running the compression routine. Any other value will halt compression. May be NULL.
lpUserContext
[in] Optional pointer to a user-defined value passed to the LPD3DXSHPRTSIMCB callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function. May be NULL.
pBuffer
[in] Address of a pointer to the uncompressed ID3DXPRTBuffer object that will be compressed.
ppBuffer
[in, out] Address of a pointer to the output ID3DXPRTCompBuffer object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXCreatePRTBuffer, D3DXCreatePRTBufferTex


D3DXCreatePRTEngine

Creates an ID3DXPRTEngine object that can efficiently generate precomputed radiance transfer (PRT) simulations of a 3D scene.

HRESULT D3DXCreatePRTEngine(
  LPD3DXMESH pMesh,
  DWORD * pAdjacency,
  BOOL ExtractUVs,
  LPD3DXMESH pBlockerMesh,
  LPD3DXPRTENGINE ppEngine
);

Parameters

pMesh
[in] Pointer to an input ID3DXMesh mesh object that models the 3D scene. This mesh must have an attribute table in which vertices are in a unique attribute.
pAdjacency
[in] Optional pointer to an array of three DWORDs per face to be filled with adjacent face indices. The number of bytes in this array must be at least ((3 * ID3DXBaseMesh::GetNumFaces) * sizeof(DWORD)). May be NULL.
ExtractUVs
[in] If TRUE, textures will be used to store albedos or PRT vectors.
pBlockerMesh
[in] Pointer to an optional ID3DXMesh mesh object that blocks the 3D scene. May be NULL.
ppEngine
[in, out] Pointer to an output ID3DXPRTEngine object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Use D3DXConcatenateMeshes to combine multiple meshes into a single mesh interface.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXCreateTextureGutterHelper

Creates an ID3DXTextureGutterHelper object from an input mesh and texture data.

HRESULT D3DXCreateTextureGutterHelper(
  UINT Width,
  UINT Height,
  LPD3DXMESH pMesh,
  FLOAT GutterSize,
  LPD3DXTEXTUREGUTTERHELPER * ppBuffer
);

Parameters

Width
[in] Width of the texture, in pixels.
Height
[in] Height of the texture, in pixels.
pMesh
[in] Pointer to an input ID3DXMesh mesh object.
GutterSize
[in] Number of texels by which to over-sample the texture and create the gutter region. Must be at least 1.
ppBuffer
[in, out] Pointer to an ID3DXTextureGutterHelper object to be created.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of these: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

Use D3DXConcatenateMeshes to transform a scene to new coordinates.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXLoadPRTBufferFromFile

Loads into memory a precomputed radiance transfer (PRT) buffer that was saved to disk.

HRESULT D3DXLoadPRTBufferFromFile(
  LPCSTR pFileName,
  LPD3DXPRTBUFFER * ppBuffer
);

Parameters

pFileName
[in] Name of the file from which to load the buffer data.
ppBuffer
[in, out] Address of a pointer to the output ID3DXPRTBuffer object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadPRTBufferFromFileW. Otherwise, the function call resolves to D3DXLoadPRTBufferFromFileA.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXLoadPRTCompBufferFromFile

Loads into memory a compressed precomputed radiance transfer (PRT) buffer that was saved to disk.

HRESULT D3DXLoadPRTCompBufferFromFile(
  LPCSTR pFileName,
  LPD3DXPRTCOMPBUFFER * ppBuffer
);

Parameters

pFileName
[in] Name of the file from which to load the compressed buffer data.
ppBuffer
[in, out] Address of a pointer to the output ID3DXPRTCompBuffer object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadPRTCompBufferFromFileW. Otherwise, the function call resolves to D3DXLoadPRTCompBufferFromFileA.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXSavePRTBufferToFile

Saves a precomputed radiance transfer (PRT) buffer to disk.

HRESULT D3DXSavePRTBufferToFile(
  LPCSTR pFileName,
  LPD3DXPRTBUFFER pBuffer
);

Parameters

pFileName
[in] Name of the file to which the buffer is to be saved.
pBuffer
[in] Address of a pointer to the input ID3DXPRTBuffer object.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSavePRTBufferToFileW. Otherwise, the function call resolves to D3DXSavePRTBufferToFileA.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXSavePRTCompBufferToFile

Saves a compressed precomputed radiance transfer (PRT) buffer to disk.

HRESULT D3DXSavePRTCompBufferToFile(
  LPCSTR pFileName,
  LPD3DXPRTCOMPBUFFER pBuffer
);

Parameters

pFileName
[in] Name of the file to which the compressed buffer is to be saved.
pBuffer
[in] Address of a pointer to the input ID3DXPRTCompBuffer object.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSavePRTCompBufferToFileW. Otherwise, the function call resolves to D3DXSavePRTCompBufferToFileA.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXSHPRTCompSplitMeshSC

Used with compressed results of the vertex version of the precomputed radiance transfer (PRT) simulator. After D3DXSHPRTCompSuperCluster has been called, this function can be used to split the mesh into a group of faces/vertices per super cluster. Each super cluster contains all of the faces that contain any vertex classified in one of its clusters. All of the vertices connected to this set of faces are also included with the returned array ppVertStatus indicating whether or not the vertex belongs to the super cluster.

HRESULT D3DXSHPRTCompSplitMeshSC(
  UINT * pClusterIDs,
  UINT NumVertices,
  UINT NumCs,
  UINT * pSClusterIDs,
  UINT NumSCs,
  LPVOID pInputIB,
  BOOL InputIBIs32Bit,
  UINT NumFaces,
  LPD3DXBUFFER * ppIBData,
  UINT * pIBDataLength,
  BOOL OutputIBIs32Bit,
  LPD3DXBUFFER * ppFaceRemap,
  LPD3DXBUFFER * ppVertData,
  UINT * pVertDataLength,
  UINT * pSCClusterList,
  D3DXSHPRTSPLITMESHCLUSTERDATA* pSCData
);

Parameters

pClusterIDs
[in] uNumVerts cluster IDs (extracted from a compressed buffer.)
NumVertices
[in] Number of vertices in original mesh.
NumCs
[in] Number of clusters (input parameter to compression.)
pSClusterIDs
[in] Array of size uNumC that will contain super cluster IDs.
NumSCs
[in] Number of super clusters allocated in D3DXSHPRTCompSuperCluster.
pInputIB
[in] Raw index buffer for mesh. The format depends on InputIBIs32Bit.
InputIBIs32Bit
[in] If TRUE, the index buffer is set to 32 bit; otherwise, 16 bit.
NumFaces
[in] Number of faces in the original mesh (pInputIB is 3 times this length.)
ppIBData
[in, out] Raw index buffer that will contain the resulting split faces. Format determined by bIBIs32Bit. Allocated by function.
pIBDataLength
[in, out] Length of ppIBData, assigned in function.
OutputIBIs32Bit
[in, out] If TRUE, allocates an unsigned integer array; otherwise, allocates an unsigned short array.
ppFaceRemap
[in, out] Mapping of each face in ppIBData to original faces. Length is *pIBDataLength/3.
ppVertData
[in, out] New vertex data structure. Size of pVertDataLength.
pVertDataLength
[in, out] Number of new vertices in split mesh. Assigned in function.
pSCClusterList
[in, out] Array of length uNumC which pSCData indexes into (Cluster* fields) for each supercluster, contains clusters sorted by supercluster.
pSCData
[in, out] Structure per super cluster. Contains indices into ppIBData, pSCClusterList, and ppVertData.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXSHPRTCompSuperCluster

Used with compressed results of the vertex version of the precomputed radiance transfer (PRT) simulator. Generates "superclusters," which are groups of clusters that can be drawn in the same draw call. A greedy algorithm that minimizes overdraw is used to group the clusters.

HRESULT D3DXSHPRTCompSuperCluster(
  UINT * pClusterIDs,
  LPD3DXMESH pScene,
  UINT MaxNumClusters,
  UINT NumClusters,
  UINT * pSClusterIDs,
  UINT * pNumSCs
);

Parameters

pClusterIDs
[in] Pointer to a NumVerts cluster IDs (extracted from a compressed buffer.)
pScene
[in] Pointer to a mesh that represents composite scene passed to the simulator. See ID3DXMesh.
MaxNumClusters
[in] Maximum number of clusters allocated per super cluster.
NumClusters
[in] Number of clusters computed in the simulator.
pSClusterIDs
[in, out] Pointer to an array of length NumClusters. Contains the index of the super cluster to which the corresponding cluster was assigned.
pNumSCs
[in, out] Number of super clusters allocated.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Mesh.h.


Shader Functions

D3DX supplies the following shader functions.

  • D3DXAssembleShader
  • D3DXAssembleShaderFromFile
  • D3DXAssembleShaderFromResource
  • D3DXCompileShader
  • D3DXCompileShaderFromFile
  • D3DXCompileShaderFromResource
  • D3DXCreateFragmentLinker
  • D3DXCreateTextureShader
  • D3DXDisassembleShader
  • D3DXFindShaderComment
  • D3DXGatherFragments
  • D3DXGatherFragmentsFromFile
  • D3DXGatherFragmentsFromResource
  • D3DXGetPixelShaderProfile
  • D3DXGetShaderConstantTable
  • D3DXGetShaderSize
  • D3DXGetShaderVersion
  • D3DXGetShaderInputSemantics
  • D3DXGetShaderOutputSemantics
  • D3DXGetShaderSamplers
  • D3DXGetVertexShaderProfile
  • D3DXPreprocessShader
  • D3DXPreprocessShaderFromFile
  • D3DXPreprocessShaderFromResource


D3DXAssembleShader

Assemble a shader.

HRESULT D3DXAssembleShader(
  LPCSTR pSrcData,
  UINT SrcDataLen,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXBUFFER* ppShader,
  LPD3DXBUFFER * ppErrorMsgs
);

Parameters

pSrcData
[in] Pointer to a memory buffer that contains the shader data.
SrcDataLen
[in] Length of the effect data, in bytes.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXAssembleShaderFromFile, D3DXAssembleShaderFromResource


D3DXAssembleShaderFromFile

Assemble a shader.

HRESULT D3DXAssembleShaderFromFile(
  LPCTSTR pSrcFile,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXBUFFER* ppShader,
  LPD3DXBUFFER * ppErrorMsgs
);

Parameters

pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXAssembleShaderFromFileW. Otherwise, the function call resolves to D3DXAssembleShaderFromFileA because ANSI strings are being used.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXAssembleShaderFromResource

Assemble a shader.

HRESULT D3DXAssembleShaderFromResource(
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXBUFFER* ppShader,
  LPD3DXBUFFER * ppErrorMsgs
);

Parameters

hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXAssembleShaderFromResourceW. Otherwise, the function call resolves to D3DXAssembleShaderFromResourceA because ANSI strings are being used.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCompileShader

Compile a shader file.

HRESULT D3DXCompileShader(
  LPCSTR pSrcData,
  UINT srcDataLen,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  LPCSTR pFunctionName,
  LPCSTR pProfile,
  DWORD Flags,
  LPD3DXBUFFER* ppShader,
  LPD3DXBUFFER* ppErrorMsgs,
  LPD3DXCONSTANTTABLE * ppConstantTable
);

Parameters

pSrcData
[in] Pointer to a string that contains the shader.
srcDataLen
[in] Length of the data in bytes.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
pFunctionName
[in] Pointer to a string that contains the name of the shader entry point function where execution begins.
pProfile
[in] Pointer to a shader profile which determines the shader instruction set. See D3DXGetVertexShaderProfile or D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.
ppConstantTable
[out] Returns an ID3DXConstantTable interface, which can be used to access shader constants. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXCompileShaderFromFile, D3DXCompileShaderFromResource


D3DXCompileShaderFromFile

Compile a shader file.

HRESULT D3DXCompileShaderFromFile(
  LPCSTR pSrcFile,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  LPCSTR pFunctionName,
  LPCSTR pProfile,
  DWORD Flags,
  LPD3DXBUFFER* ppShader,
  LPD3DXBUFFER * ppErrorMsgs,
  LPD3DXCONSTANTTABLE * ppConstantTable
);

Parameters

pSrcFile
[in] Pointer to a string that specifies the filename.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
pFunctionName
[in] Pointer to the shader entry point function where execution begins.
pProfile
[in] Pointer to a shader profile which determines the shader instruction set. See D3DXGetVertexShaderProfile or D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.
ppConstantTable
[out] Returns an ID3DXConstantTable interface, which can be used to access shader constants. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCompileShaderFromResource

Compile a shader file.

HRESULT D3DXCompileShaderFromResource(
  HMODULE hSrcModule,
  LPCSTR pSrcResource,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  LPCSTR pFunctionName,
  LPCSTR pProfile,
  DWORD Flags,
  LPD3DXBUFFER* ppShader,
  LPD3DXBUFFER * ppErrorMsgs,
  LPD3DXCONSTANTTABLE * ppConstantTable
);

Parameters

hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to a string that specifies the resource name.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file, or will error when compiled from a resource or memory.
pFunctionName
[in] Pointer to the shader entry point function where execution begins.
pProfile
[in] Pointer to a shader profile which determines the shader instruction set. See D3DXGetVertexShaderProfile or D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.
ppConstantTable
[out] Returns an ID3DXConstantTable interface, which can be used to access shader constants. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXCompileShader, D3DXCompileShaderFromFile


D3DXCreateFragmentLinker

Create a fragment linker. This can be used to link one or more shader fragments together.

HRESULT D3DXCreateFragmentLinker(
  LPDIRECT3DDEVICE9 pDevice,
  UINT ShaderCacheSize,
  LPD3DXFRAGMENTLINKER * ppFragmentLinker
);

Parameters

pDevice
[in] Pointer to the current device. See IDirect3DDevice9.
ShaderCacheSize
[in] Shader cache size in bytes. This can be used for optimization.
ppFragmentLinker
[out] Returns a pointer to the new fragment linker interface. See ID3DXFragmentLinker.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

Here is an example taken from the FragmentLinker Sample that creates a fragment linker:

ID3DXFragmentLinker* g_pFragmentLinker = NULL;
IDirect3DDevice9*    pd3dDevice        = NULL;

    // Initialize the device before using it
    ...

    // Create the fragment linker interface
    D3DXCreateFragmentLinker( pd3dDevice, 0, &g_pFragmentLinker );

Requirements

Header: Declared in D3DX9Shader.h.


D3DXCreateTextureShader

Creates a texture shader object from the compiled shader.

HRESULT D3DXCreateTextureShader(
  CONST DWORD * pFunction,
  LPD3DXTEXTURESHADER * ppTextureShader
);

Parameters

pFunction
[in] Pointer to the function DWORD stream.
ppTextureShader
[out] Returns an ID3DXTextureShader object which can be used to procedurally fill the contents of a texture using the D3DXFillTextureTX functions.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXDisassembleShader

Disassemble a shader.

HRESULT D3DXDisassembleShader(
  CONST DWORD * pShader,
  BOOL EnableColorCode,
  LPCSTR pComments,
  LPD3DXBUFFER * ppDisassembly
);

Parameters

pShader
[in] Pointer to a memory buffer that contains the shader data.
EnableColorCode
[in] Enable color code to make it easier to read the disassembly.
pComments
[in] An optional NULL-terminated comment string. This value may be NULL.
ppDisassembly
[out] Returns a buffer containing the disassembled shader. See ID3DXBuffer.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXFindShaderComment

Searches through a shader for a particular comment. The comment is identified by a four-character code (FOURCC) in the first DWORD of the comment.

HRESULT D3DXFindShaderComment(
  CONST DWORD* pFunction,
  DWORD FourCC,
  LPCVOID* ppData,
  UINT* pSizeInBytes
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
FourCC
[in] FOURCC code that identifies the comment block. See FourCC Formats.
ppData
[in] Returns a pointer to the comment data (not including the comment token and FOURCC code). This value can be NULL.
pSizeInBytes
[out] Returns the size of the comment data in bytes. This value can be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the comment is not found, and no other error has occurred, S_FALSE is returned.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXGatherFragments

Gathers shader fragments into a buffer to be passed to the fragment linker.

HRESULT D3DXGatherFragments(
  LPCSTR pSrcData,
  UINT SrcDataLen,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXBUFFER* ppShader,
  LPD3DXBUFFER * ppErrorMsgs
);

Parameters

pSrcData
[in] Pointer to a ANSI string that contains the shader code.
SrcDataLen
[in] Length of the shader code, in bytes.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppShader
[in, out] Returns a buffer containing the created shader fragments, as well as any embedded debug info.
ppErrorMsgs
[in, out] Returns a buffer containing a listing of errors and warnings that were encountered during the creation of shader fragments. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DXERR_INVALIDDATA E_OUTOFMEMORY

Remarks

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXCreateFragmentLinker, Writing HLSL Shaders (Direct3D 9)


D3DXGatherFragmentsFromFile

Gathers shader fragments into a buffer to be passed to the fragment linker.

HRESULT D3DXGatherFragmentsFromFile(
  LPCTSTR pSrcFile,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXBUFFER* ppShader,
  LPD3DXBUFFER * ppErrorMsgs
);

Parameters

pSrcFile
[in] Pointer to the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppShader
[in, out] Returns a buffer containing the created shader fragments, as well as any embedded debug info.
ppErrorMsgs
[in, out] Returns a buffer containing a listing of errors and warnings that were encountered during the creation of shader fragments. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXGatherFragmentsFromFileW. Otherwise, the function call resolves to D3DXGatherFragmentsFromFileA because ANSI strings are being used.

To compile a fragment within an effect call D3DXGatherFragmentsFromFile as shown here:

DWORD         g_dwShaderFlags; // Shader compilation/linking flags
LPD3DXBUFFER  g_pCompiledFragments = NULL;

    // Compile the fragments to a buffer. The fragments must be linked together to form
    // a shader before they can be used for rendering.
    V_RETURN( D3DXGatherFragmentsFromFile( L"FragmentLinker.fx", NULL,
                      NULL, g_dwShaderFlags, &g_pCompiledFragments, NULL ) );

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXCreateFragmentLinker, Writing HLSL Shaders (Direct3D 9)


D3DXGatherFragmentsFromResource

Gather shader fragments into a buffer to be passed to the fragment linker.

HRESULT D3DXGatherFragmentsFromResource(
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXBUFFER* ppShader,
  LPD3DXBUFFER * ppErrorMsgs
);

Parameters

hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppShader
[in, out] Returns a buffer containing the created shader fragments, as well as any embedded debug info.
ppErrorMsgs
[in, out] Returns a buffer containing a listing of errors and warnings that were encountered during the creation of shader fragments. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXGatherFragmentsFromResourceW. Otherwise, the function call resolves to D3DXGatherFragmentsFromResourceA because ANSI strings are being used.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXCreateFragmentLinker, Writing HLSL Shaders (Direct3D 9)


D3DXGetPixelShaderProfile

Returns the name of the highest high-level shader language (HLSL) profile supported by a given device.

LPCSTR D3DXGetPixelShaderProfile(
  LPDIRECT3DDEVICE9 pDevice
);

Parameters

pDevice
[in] Pointer to the device. See IDirect3DDevice9.

Return Values

The HLSL profile name.

If the device does not support pixel shaders then the function returns NULL.

Remarks

A shader profile specifies the assembly shader version to use and the capabilities available to the HLSL compiler when compiling a shader. The following table lists the pixel shader profiles that are supported.

Shader Profile | Description
ps_1_1 | Compile to ps_1_1 version.
ps_1_2 | Compile to ps_1_2 version.
ps_1_3 | Compile to ps_1_3 version.
ps_1_4 | Compile to ps_1_4 version.
ps_2_0 | Compile to ps_2_0 version.
ps_2_a Same as the ps_2_0 profile, with the following additional capabilities available for the compiler to target:
  • Number of Temporary Registers (r#) is greater than or equal to 22.
  • Arbitrary source swizzle.
  • Gradient instructions: dsx, dsy.
  • Predication.
  • No dependent texture read limit.
  • No limit for the number of texture instructions.
ps_2_b Same as the ps_2_0 profile, with the following additional capabilities available for the compiler to target:
  • Number of Temporary Registers (r#) is greater than or equal to 32.
  • No limit for the number of texture instructions.
ps_3_0 | Compile to ps_3_0 version.

For more information about the differences between shader versions, see Pixel Shader Differences.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXGetShaderConstantTable

Gets the shader constant table embedded inside shader.

HRESULT D3DXGetShaderConstantTable(
  CONST DWORD* pFunction,
  LPD3DXCONSTANTTABLE*  ppConstantTable
);

Parameters

pFunction
[in] Pointer to the function DWORD stream.
ppConstantTable
[out, retval] Returns the constant table interface that manages the constant table. See ID3DXConstantTable.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DXERR_INVALIDDATA E_OUTOFMEMORY

Remarks

A constant table is generated by D3DXCompileShader and embedded in the body of the shader.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXGetShaderInputSemantics

Gets the semantics for the shader inputs. Use this method to determine the input vertex format.

HRESULT D3DXGetShaderInputSemantics(
  CONST DWORD* pFunction,
  D3DXSEMANTIC* pSemantics,
  UINT* pCount
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
pSemantics
[in] Pointer to an array of D3DXSEMANTIC structures. The function will fill this array with the semantics for each input element referenced by the shader. This array is assumed to contain at least MAXD3DDECLLENGTH elements. However, calling D3DXGetShaderInputSemantics with pSemantics = NULL will return the number of elements needed for pCount.
pCount
[out] Returns the number of elements in pSemantics.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

Use D3DXGetShaderInputSemantics to return a list of input semantics required by the shader. This is the way to find out what the input vertex format is for a high-level shader language (HLSL) shader. If the shader has additional inputs that your vertex declaration is missing, you could create an extra vertex stream that has a stride of 0 that has the missing components with default values. For instance, this technique could be used to provide default vertex color for models that do not specify it.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXGetShaderOutputSemantics

Get the semantics for all shader output elements.

HRESULT D3DXGetShaderOutputSemantics(
  CONST DWORD* pFunction,
  D3DXSEMANTIC* pSemantics,
  UINT* pCount
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
pSemantics
[in] Pointer to an array of D3DXSEMANTIC structures. The function will fill this array with the semantics for each output element referenced by the shader. This array is assumed to contain at least MAXD3DDECLLENGTH elements. However, calling D3DXGetShaderOutputSemantics with pSemantics = NULL will return the number of elements needed for pCount.
pCount
[out] Returns the number of elements in pSemantics.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXGetShaderSamplers

Get the sampler names referenced in a shader.

HRESULT D3DXGetShaderSamplers(
  CONST DWORD* pFunction,
  LPCSTR* pSamplers,
  UINT* pCount
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
pSamplers
[in, out] Pointer to an array of LPCSTRs. The function will fill this array with pointers to the sampler names contained within pFunction. The maximum array size is the maximum number of sampler registers (16 for vs_3_0 and ps_3_0).

To find the number of samplers used, check pCount after calling D3DXGetShaderSamplers with pSamplers = NULL.

pCount
[out] Returns the number of samplers referenced by the shader.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXGetShaderSize

Returns the size of the shader byte code, in bytes.

UINT D3DXGetShaderSize(
  CONST DWORD * pFunction
);

Parameters

pFunction
[in] Pointer to the function DWORD stream.

Return Values

Returns the size of the shader byte code, in bytes.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXGetShaderVersion

Returns the shader version of the compiled shader.

DWORD D3DXGetShaderVersion(
  CONST DWORD* pFunction
);

Parameters

pFunction
[in] Pointer to the function DWORD stream.

Return Values

Returns the shader version of the given shader, or zero if the shader function is NULL.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXGetVertexShaderProfile

Returns the name of the highest high-level shader language (HLSL) profile supported by a given device.

LPCSTR D3DXGetVertexShaderProfile(
  LPDIRECT3DDEVICE9 pDevice
);

Parameters

pDevice
[in] Pointer to the device. See IDirect3DDevice9.

Return Values

The HLSL profile name.

If the device does not support vertex shaders then the function returns NULL.

Remarks

A shader profile specifies the assembly shader version to use and the capabilities available to the HLSL compiler when compiling a shader. The following table lists the vertex shader profiles that are supported.

Shader Profile | Description
vs_1_1 | Compile to vs_1_1 version.
vs_2_0 | Compile to vs_2_0 version.
vs_2_a Same as the vs_2_0 profile, with the following additional capabilities available for the compiler to target:
  • Number of Temporary Registers (r#) is greater than or equal to 13.
  • Dynamic flow control instruction.
  • Predication.
vs_3_0 | Compile to vs_3_0 version.

For more information about the differences between shader versions, see Vertex Shader Differences.

Requirements

Header: Declared in D3DX9Shader.h.


D3DXPreprocessShader

Preprocesses a shader without performing compilation. This resolves all #defines and #includes, providing a self-contained shader for subsequent compilation.

HRESULT D3DXPreprocessShader(
  LPCSTR pSrcData,
  UINT SrcDataSize,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  LPD3DXBUFFER* ppShaderText,
  LPD3DXBUFFER* ppErrorMsgs
);

Parameters

pSrcData
[in] Pointer to a string that contains the shader.
SrcDataSize
[in] Length of the data in bytes.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
ppShaderText
[out] Returns a buffer containing a single large string that represents the resulting formatted token stream.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXPreprocessShaderFromFile, D3DXPreprocessShaderFromResource


D3DXPreprocessShaderFromFile

Preprocesses a shader file without performing compilation. This resolves all #defines and #includes, providing a self-contained shader for subsequent compilation.

HRESULT D3DXPreprocessShaderFromFile(
  LPCSTR pSrcFile,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  LPD3DXBUFFER* ppShaderText,
  LPD3DXBUFFER* ppErrorMsgs
);

Parameters

pSrcFile
[in] Pointer to a string that specifies the filename of the shader.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
ppShaderText
[out] Returns a buffer containing a single large string that represents the resulting formatted token stream.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXPreprocessShader, D3DXPreprocessShaderFromResource


D3DXPreprocessShaderFromResource

Preprocesses a shader resource without performing compilation. This resolves all #defines and #includes, providing a self-contained shader for subsequent compilation.

HRESULT D3DXPreprocessShaderFromResource(
  HMODULE hSrcModule,
  LPCSTR pSrcResource,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  LPD3DXBUFFER* ppShaderText,
  LPD3DXBUFFER* ppErrorMsgs
);

Parameters

hSrcModule
[in] Handle to the module that holds the shader resource. If this value is NULL, the current module will be used.
pSrcResource
[in] String that represents the name of the resource in the module.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
ppShaderText
[out] Returns a buffer containing a single large string that represents the resulting formatted token stream.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXPreprocessShaderFromFile, D3DXPreprocessShader


Shape Drawing Functions

D3DX supplies the following shape-drawing functions.

  • D3DXCreateBox
  • D3DXCreateCylinder
  • D3DXCreatePolygon
  • D3DXCreateSphere
  • D3DXCreateTeapot
  • D3DXCreateText
  • D3DXCreateTorus

All shapes are returned as mesh objects.

These functions can be used in either a left-handed or right-handed coordinate system.


D3DXCreateBox

Uses a left-handed coordinate system to create a mesh containing an axis-aligned box.

HRESULT D3DXCreateBox(
  LPDIRECT3DDEVICE9 pDevice,
  FLOAT Width,
  FLOAT Height,
  FLOAT Depth,
  LPD3DXMESH * ppMesh,
  LPD3DXBUFFER * ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created box mesh.
Width
[in] Width of the box, along the x-axis.
Height
[in] Height of the box, along the y-axis.
Depth
[in] Depth of the box, along the z-axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The created box is centered at the origin.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Requirements

Header: Declared in D3dx9shape.h.


D3DXCreateCylinder

Uses a left-handed coordinate system to create a mesh containing a cylinder.

HRESULT D3DXCreateCylinder(
  LPDIRECT3DDEVICE9 pDevice,
  FLOAT Radius1,
  FLOAT Radius2,
  FLOAT Length,
  UINT Slices,
  UINT Stacks,
  LPD3DXMESH * ppMesh,
  LPD3DXBUFFER * ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created cylinder mesh.
Radius1
[in] Radius at the negative Z end. Value should be greater than or equal to 0.0f.
Radius2
[in] Radius at the positive Z end. Value should be greater than or equal to 0.0f.
Length
[in] Length of the cylinder along the z-axis.
Slices
[in] Number of slices about the main axis.
Stacks
[in] Number of stacks along the main axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The created cylinder is centered at the origin, and its axis is aligned with the z-axis.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Requirements

Header: Declared in D3dx9shape.h.


D3DXCreatePolygon

Uses a left-handed coordinate system to create a mesh containing an n-sided polygon.

HRESULT D3DXCreatePolygon(
  LPDIRECT3DDEVICE9 pDevice,
  FLOAT Length,
  UINT Sides,
  LPD3DXMESH * ppMesh,
  LPD3DXBUFFER * ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created polygon mesh.
Length
[in] Length of each side.
Sides
[in] Number of sides for the polygon. Value must be greater than or equal to 3.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The created polygon is centered at the origin.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Requirements

Header: Declared in D3dx9shape.h.


D3DXCreateSphere

Uses a left-handed coordinate system to create a mesh containing a sphere.

HRESULT D3DXCreateSphere(
  LPDIRECT3DDEVICE9 pDevice,
  FLOAT Radius,
  UINT Slices,
  UINT Stacks,
  LPD3DXMESH * ppMesh,
  LPD3DXBUFFER * ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created sphere mesh.
Radius
[in] Radius of the sphere. This value should be greater than or equal to 0.0f.
Slices
[in] Number of slices about the main axis.
Stacks
[in] Number of stacks along the main axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The created sphere is centered at the origin, and its axis is aligned with the z-axis.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Requirements

Header: Declared in D3dx9shape.h.


D3DXCreateTeapot

Uses a left-handed coordinate system to create a mesh containing a teapot.

HRESULT D3DXCreateTeapot(
  LPDIRECT3DDEVICE9 pDevice,
  LPD3DXMESH * ppMesh,
  LPD3DXBUFFER * ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created teapot mesh.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Requirements

Header: Declared in D3dx9shape.h.


D3DXCreateText

Creates a mesh containing the specified text, using the font associated with the device context.

HRESULT D3DXCreateText(
  LPDIRECT3DDEVICE9 pDevice,
  HDC hDC,
  LPCTSTR pText,
  FLOAT Deviation,
  FLOAT Extrusion,
  LPD3DXMESH * ppMesh,
  LPD3DXBUFFER * ppAdjacency,
  LPGLYPHMETRICSFLOAT pGlyphMetrics
);

Parameters

pDevice
[in] Pointer to the device that created the mesh.
hDC
[in] Device context, containing the font for output. The font selected by the device context must be a TrueType font.
pText
[in] Pointer to a string that specifies the text to generate. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Deviation
[in] Maximum chordal deviation from TrueType font outlines.
Extrusion
[in] Amount to extrude text in the negative z-direction.
ppMesh
[out] Pointer to the returned mesh.
ppAdjacency
[out] Pointer to a buffer containing adjacency information. May be NULL.
pGlyphMetrics
[out] Pointer to an array of GLYPHMETRICSFLOAT structures that contain the glyph metric data. Each element contains information about the position and orientation of the corresponding glyph in the string. The number of elements in the array should be equal to the number of characters in the string. Note that the origin in each structure is not relative to the entire string, but rather is relative to that character cell. To compute the entire bounding box, add the increment for each glyph while traversing the string. If you are not concerned with the glyph sizes, set this parameter to NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextW. Otherwise, the function call resolves to D3DXCreateTextA because ANSI strings are being used.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Requirements

Header: Declared in D3dx9shape.h.


D3DXCreateTorus

Uses a left-handed coordinate system to create a mesh containing a torus.

HRESULT D3DXCreateTorus(
  LPDIRECT3DDEVICE9 pDevice,
  FLOAT InnerRadius,
  FLOAT OuterRadius,
  UINT Sides,
  UINT Rings,
  LPD3DXMESH * ppMesh,
  LPD3DXBUFFER * ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created torus mesh.
InnerRadius
[in] Inner-radius of the torus. Value should be greater than or equal to 0.0f.
OuterRadius
[in] Outer-radius of the torus. Value should be greater than or equal to 0.0f.
Sides
[in] Number of sides in a cross-section. Value must be greater than or equal to 3.
Rings
[in] Number of rings making up the torus. Value must be greater than or equal to 3.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The created torus is centered at the origin, and its axis is aligned with the z-axis. The inner radius of the torus is the radius of the cross-section (the minor radius), and the outer radius of the torus is the radius of the central hole.

This function returns a mesh that can be used later for drawing or manipulation by the application.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Requirements

Header: Declared in D3dx9shape.h.


Texturing Functions

D3DX supplies the following texturing functions.

  • D3DXCheckCubeTextureRequirements
  • D3DXCheckTextureRequirements
  • D3DXCheckVolumeTextureRequirements
  • D3DXComputeNormalMap
  • D3DXCreateCubeTexture
  • D3DXCreateCubeTextureFromFile
  • D3DXCreateCubeTextureFromFileEx
  • D3DXCreateCubeTextureFromFileInMemory
  • D3DXCreateCubeTextureFromFileInMemoryEx
  • D3DXCreateCubeTextureFromResource
  • D3DXCreateCubeTextureFromResourceEx
  • D3DXCreateTexture
  • D3DXCreateTextureFromFile
  • D3DXCreateTextureFromFileEx
  • D3DXCreateTextureFromFileInMemory
  • D3DXCreateTextureFromFileInMemoryEx
  • D3DXCreateTextureFromResource
  • D3DXCreateTextureFromResourceEx
  • D3DXCreateVolumeTexture
  • D3DXCreateVolumeTextureFromFile
  • D3DXCreateVolumeTextureFromFileEx
  • D3DXCreateVolumeTextureFromFileInMemory
  • D3DXCreateVolumeTextureFromFileInMemoryEx
  • D3DXCreateVolumeTextureFromResource
  • D3DXCreateVolumeTextureFromResourceEx
  • D3DXFillCubeTexture
  • D3DXFillCubeTextureTX
  • D3DXFillTexture
  • D3DXFillTextureTX
  • D3DXFillVolumeTexture
  • D3DXFillVolumeTextureTX
  • D3DXFilterTexture
  • D3DXGetImageInfoFromFile
  • D3DXGetImageInfoFromFileInMemory
  • D3DXGetImageInfoFromResource
  • D3DXLoadSurfaceFromFile
  • D3DXLoadSurfaceFromFileInMemory
  • D3DXLoadSurfaceFromMemory
  • D3DXLoadSurfaceFromResource
  • D3DXLoadSurfaceFromSurface
  • D3DXLoadVolumeFromFile
  • D3DXLoadVolumeFromFileInMemory
  • D3DXLoadVolumeFromMemory
  • D3DXLoadVolumeFromResource
  • D3DXLoadVolumeFromVolume
  • D3DXSaveSurfaceToFile
  • D3DXSaveSurfaceToFileInMemory
  • D3DXSaveTextureToFile
  • D3DXSaveTextureToFileInMemory
  • D3DXSaveVolumeToFile
  • D3DXSaveVolumeToFileInMemory

See Also

D3DXCreateTextureGutterHelper


D3DXCheckCubeTextureRequirements

Checks cube-texture-creation parameters.

HRESULT D3DXCheckCubeTextureRequirements(
  LPDIRECT3DDEVICE9 pDevice,
  UINT * pSize,
  UINT * pNumMipLevels,
  DWORD Usage,
  D3DFORMAT * pFormat,
  D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSize
[in, out] Pointer to the requested width and height in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to the number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL.

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

Requirements

Header: Declared in D3dx9tex.h.


D3DXCheckTextureRequirements

Checks texture-creation parameters.

HRESULT D3DXCheckTextureRequirements(
  LPDIRECT3DDEVICE9 pDevice,
  UINT * pWidth,
  UINT * pHeight,
  UINT * pNumMipLevels,
  DWORD Usage,
  D3DFORMAT * pFormat,
  D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pWidth
[in, out] Pointer to the requested width in pixels, or NULL. Returns the corrected size.
pHeight
[in, out] Pointer to the requested height in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DERR_NOTAVAILABLE

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

This function uses the following heuristics when comparing the requested requirements against available formats:

  • Do not choose a format that has fewer channels.
  • Avoid FOURCC And 24-bit formats unless explicitly requested.
  • Try not to add new channels.
  • Try not to change the number of bits per channel.
  • Try to avoid converting between types of formats. For instance, avoid converting an ARGB format to a depth format.

Requirements

Header: Declared in D3dx9tex.h.


D3DXCheckVolumeTextureRequirements

Checks volume-texture-creation parameters.

HRESULT D3DXCheckVolumeTextureRequirements(
  LPDIRECT3DDEVICE9 pDevice,
  UINT * pWidth,
  UINT * pHeight,
  UINT * pDepth,
  UINT * pNumMipLevels,
  DWORD Usage,
  D3DFORMAT * pFormat,
  D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
pWidth
[in, out] Pointer to the requested width in pixels, or NULL. Returns the corrected size.
pHeight
[in, out] Pointer to the requested height in pixels, or NULL. Returns the corrected size.
pDepth
[in, out] Pointer to the requested depth in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to the number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] Currently not used, set to 0.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL.

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Requirements

Header: Declared in D3dx9tex.h.


D3DXComputeNormalMap

Converts a height map into a normal map. The (x,y,z) components of each normal are mapped to the (r,g,b) channels of the output texture.

HRESULT D3DXComputeNormalMap(
  LPDIRECT3DTEXTURE9 pTexture,
  LPDIRECT3DTEXTURE9 pSrcTexture,
  CONST PALETTEENTRY * pSrcPalette,
  DWORD Flags,
  DWORD Channel,
  FLOAT Amplitude
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DTexture9 interface, representing the destination texture.
pSrcTexture
[in, retval] Pointer to an IDirect3DTexture9 interface, representing the source height-map texture.
pSrcPalette
[in] Pointer to a PALETTEENTRY type that contains the source palette of 256 colors or NULL.
Flags
[in] One or more D3DX_NORMALMAP flags that control generation of normal maps.
Channel
[in] One D3DX_CHANNEL flag specifying the source of height information.
Amplitude
[in] Constant value multiplier that increases (or decreases) the values in the normal map. Higher values usually make bumps more visible, lower values usually make bumps less visible.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following value: D3DERR_INVALIDCALL.

Remarks

This method computes the normal by using the central difference with a kernel size of 3x3. The central differencing denominator used is 2.0. RGB channels in the destination contain biased (x,y,z) components of the normal.

Requirements

Header: Declared in D3dx9tex.h.


D3DXCreateCubeTexture

Creates an empty cube texture, adjusting the calling parameters as needed.

HRESULT D3DXCreateCubeTexture(
  LPDIRECT3DDEVICE9 pDevice,
  UINT Size,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  LPDIRECT3DCUBETEXTURE9 * ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_NOTAVAILABLE, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces.

Internally, D3DXCreateCubeTexture uses D3DXCheckCubeTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateCubeTexture will often succeed where calls to IDirect3DDevice9::CreateCubeTexture would fail.

Requirements

Header: Declared in D3dx9tex.h.

See Also

Texturing Functions


D3DXCreateCubeTextureFromFile

Creates a cube texture from a file.

HRESULT D3DXCreateCubeTextureFromFile(
  LPDIRECT3DDEVICE9 pDevice,
  LPCTSTR pSrcFile,
  LPDIRECT3DCUBETEXTURE9 * ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL.

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromFileW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromFileA because ANSI strings are being used.

The function is equivalent to D3DXCreateCubeTextureFromFileEx(pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppCubeTexture).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Filtering is automatically applied to a texture created using this method. The filtering is equivalent to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER in D3DX_FILTER.

D3DXCreateCubeTextureFromFile uses the DirectDraw surface (DDS) file format. The DirectX Texture Editor (Dxtex.exe) enables you to generate a cube map from other file formats and save it in the DDS file format.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateCubeTextureFromFileEx, Texturing Functions


D3DXCreateCubeTextureFromFileEx

Creates a cube texture from a file. This is a more advanced function than D3DXCreateCubeTextureFromFile.

HRESULT D3DXCreateCubeTextureFromFileEx(
  LPDIRECT3DDEVICE9 pDevice,
  LPCTSTR pSrcFile,
  UINT Size,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo,
  PALETTEENTRY * pPalette,
  LPDIRECT3DCUBETEXTURE9 * ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8. If this value is 0 or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER constants, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER constants controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX. In addition, use bits 27-31 to specify the number of mip levels to be skipped (from the top of the mipmap chain) when a .dds texture is loaded into memory; this allows you to skip up to 32 levels.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromFileExW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromFileExA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

D3DXCreateCubeTextureFromFileEx uses the DirectDraw surface (DDS) file format. The DirectX Texture Editor (Dxtex.exe) enables you to generate a cube map from other file formats and save it in the DDS file format.

When skipping mipmap levels while loading a .dds file, use the D3DX_SKIP_DDS_MIP_LEVELS macro to generate the MipFilter value. This macro takes the number of levels to skip and the filter type and returns the filter value, which would then be passed into the MipFilter parameter.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateCubeTextureFromFile, Texturing Functions


D3DXCreateCubeTextureFromFileInMemory

Creates a cube texture from a file in memory.

HRESULT D3DXCreateCubeTextureFromFileInMemory(
  LPDIRECT3DDEVICE9 pDevice,
  LPCVOID pSrcData,
  UINT SrcDataSize,
  LPDIRECT3DCUBETEXTURE9 * ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcData
[in] Pointer to the file in memory from which to create the cubemap. See Remarks.
SrcDataSize
[in] Size of the file in memory, in bytes.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

The function is equivalent to D3DXCreateCubeTextureFromFileInMemoryEx(pDevice, pSrcData, SrcDataSize, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppCubeTexture).

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

This method is designed to be used for loading image files stored as RT_RCDATA, which is an application-defined resource (raw data). Otherwise this method will fail.

Filtering is automatically applied to a texture created using this method. The filtering is equivalent to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER in D3DX_FILTER.

D3DXCreateCubeTextureFromFileInMemory uses the DirectDraw surface (DDS) file format. The DirectX Texture Editor (Dxtex.exe) enables you to generate a cube map from other file formats and save it in the DDS file format.

Requirements

Header: Declared in D3dx9tex.h.

See Also

Texturing Functions


D3DXCreateCubeTextureFromFileInMemoryEx

Creates a cube texture from a file in memory. This is a more advanced function than D3DXCreateCubeTextureFromFileInMemory.

HRESULT D3DXCreateCubeTextureFromFileInMemoryEx(
  LPDIRECT3DDEVICE9 pDevice,
  LPCVOID pSrcData,
  UINT SrcDataSize,
  UINT Size,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo,
  PALETTEENTRY * pPalette,
  LPDIRECT3DCUBETEXTURE9 * ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcData
[in] Pointer to the file in memory from which to create the cube texture. See Remarks.
SrcDataSize
[in] Size of the file in memory, in bytes.
Size
[in] Width (or height) in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX. In addition, use bits 27-31 to specify the number of mip levels to be skipped (from the top of the mipmap chain) when a .dds texture is loaded into memory; this allows you to skip up to 32 levels.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget .

This method is designed to be used for loading image files stored as RT_RCDATA, which is an application-defined resource (raw data). Otherwise this method will fail.

For details on PALETTEENTRY, see the Platform SDK. Note that as of DirectX 8.0, the peFlags member of the PALETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXCreateCubeTextureFromFileInMemoryEx uses the DirectDraw surface (DDS) file format. The DirectX Texture Editor (Dxtex.exe) enables you to generate a cube map from other file formats and save it in the DDS file format

When skipping mipmap levels while loading a .dds file, use the D3DX_SKIP_DDS_MIP_LEVELS macro to generate the MipFilter value. This macro takes the number of levels to skip and the filter type and returns the filter value, which would then be passed into the MipFilter parameter.

Requirements

Header: Declared in D3dx9tex.h.

See Also

Texturing Functions


D3DXCreateCubeTextureFromResource

Creates a cube texture from a resource.

HRESULT D3DXCreateCubeTextureFromResource(
  LPDIRECT3DDEVICE9 pDevice,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  LPDIRECT3DCUBETEXTURE9 * ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL.

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromResourceW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromResourceA because ANSI strings are being used.

The function is equivalent to D3DXCreateCubeTextureFromResourceEx(pDevice, hSrcModule, pSrcResource, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppCubeTexture).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Filtering is automatically applied to a texture created using this method. The filtering is equivalent to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER in D3DX_FILTER.

D3DXCreateCubeTextureFromResource uses the DirectDraw surface (DDS) file format. The DirectX Texture Editor (Dxtex.exe) enables you to generate a cube map from other file formats and save it in the DDS file format.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateCubeTextureFromResourceEx, Texturing Functions


D3DXCreateCubeTextureFromResourceEx

Creates a cube texture from a resource specified by a string. This is a more advanced function than D3DXCreateCubeTextureFromResource.

HRESULT D3DXCreateCubeTextureFromResourceEx(
  LPDIRECT3DDEVICE9 pDevice,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  UINT Size,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo,
  PALETTEENTRY * pPalette,
  LPDIRECT3DCUBETEXTURE9 * ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8. If this value is 0 or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in or NULL.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromResourceExW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromResourceExA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

D3DXCreateCubeTextureFromResourceEx uses the DirectDraw surface (DDS) file format. The DirectX Texture Editor (Dxtex.exe) enables you to generate a cube map from other file formats and save it in the DDS file format.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateCubeTextureFromResource, Texturing Functions


D3DXCreateTexture

Creates an empty texture, adjusting the calling parameters as needed.

HRESULT D3DXCreateTexture(
  LPDIRECT3DDEVICE9 pDevice,
  UINT Width,
  UINT Height,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  LPDIRECT3DTEXTURE9 * ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
Width
[in] Width in pixels. If this value is 0, a value of 1 is used. See Remarks.
Height
[in] Height in pixels. If this value is 0, a value of 1 is used. See Remarks.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target by calling the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture may be of a different format from that specified, if the device does not support the requested format. Applications should check the format of the returned texture to see if it matches the format requested.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DERR_NOTAVAILABLE, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

Remarks

Internally, D3DXCreateTexture uses D3DXCheckTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateTexture will often succeed where calls to IDirect3DDevice9::CreateTexture would fail.

If both Height and Width are set to D3DX_DEFAULT, a value of 256 is used for both parameters. If either Height or Width is set to D3DX_DEFAULT And the other parameter is set to a numeric value, the texture will be square with both the height and width equal to the numeric value.

Requirements

Header: Declared in D3dx9tex.h.

See Also

Texturing Functions


D3DXCreateTextureFromFile

Creates a texture from a file.

HRESULT D3DXCreateTextureFromFile(
  LPDIRECT3DDEVICE9 pDevice,
  LPCTSTR pSrcFile,
  LPDIRECT3DTEXTURE9 * ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromFileW. Otherwise, the function call resolves to D3DXCreateTextureFromFileA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

The function is equivalent to D3DXCreateTextureFromFileEx(pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppTexture).

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, the images need to be loaded manually.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Filtering is automatically applied to a texture created using this method. The filtering is equivalent to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER in D3DX_FILTER.

For the best performance when using D3DXCreateTextureFromFile:

  1. Doing image scaling and format conversion at load time can be slow. Store images in the format and resolution they will be used. If the target hardware requires power of two dimensions, create and store images using power of two dimensions.
  2. Consider using DirectDraw surface (DDS) files. Because DDS files can be used to represent any Direct3D 9 texture format, they are very easy for D3DX to read. Also, they can store mipmaps, so any mipmap-generation algorithms can be used to author the images.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateTextureFromFileEx, Texturing Functions


D3DXCreateTextureFromFileEx

Creates a texture from a file. This is a more advanced function than D3DXCreateTextureFromFile.

HRESULT D3DXCreateTextureFromFileEx(
  LPDIRECT3DDEVICE9 pDevice,
  LPCTSTR pSrcFile,
  UINT Width,
  UINT Height,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo,
  PALETTEENTRY * pPalette,
  LPDIRECT3DTEXTURE9 * ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file and rounded up to a power of two. If the device supports non-power of 2 textures and D3DX_DEFAULT_NONPOW2 is specified, the size will not be rounded.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file and rounded up to a power of two. If the device supports non-power of 2 textures and D3DX_DEFAULT_NONPOW2 is sepcified, the size will not be rounded.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created. If D3DX_FROM_FILE, the size will be taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. See Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER constants controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER constants controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX. In addition, use bits 27-31 to specify the number of mip levels to be skipped (from the top of the mipmap chain) when a .dds texture is loaded into memory; this allows you to skip up to 32 levels.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the color key. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromFileExW. Otherwise, the function call resolves to D3DXCreateTextureFromFileExA because ANSI strings are being used.

Use D3DXCheckTextureRequirements to determine if your device can support the texture given the current state.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Mipmapped textures automatically have each level filled with the loaded texture. When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

For the best performance when using D3DXCreateTextureFromFileEx:

  1. Doing image scaling and format conversion at load time can be slow. Store images in the format and resolution they will be used. If the target hardware requires power of 2 dimensions, then create and store images using power of 2 dimensions.
  2. For mipmap image creation at load time, filter using D3DX_FILTER_BOX. A box filter is much faster than other filter types such as D3DX_FILTER_TRIANGLE.
  3. Consider using DDS files. Since DDS files can be used to represent any Direct3D 9 texture format, they are very easy for D3DX to read. Also, they can store mipmaps, so any mipmap-generation algorithms can be used to author the images.

When skipping mipmap levels while loading a .dds file, use the D3DX_SKIP_DDS_MIP_LEVELS macro to generate the MipFilter value. This macro takes the number of levels to skip and the filter type and returns the filter value, which would then be passed into the MipFilter parameter.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateTextureFromFile, Texturing Functions


D3DXCreateTextureFromFileInMemory

Creates a texture from a file in memory.

HRESULT D3DXCreateTextureFromFileInMemory(
  LPDIRECT3DDEVICE9 pDevice,
  LPCVOID pSrcData,
  UINT SrcDataSize,
  LPDIRECT3DTEXTURE9 * ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the texture.
SrcDataSize
[in] Size in bytes of the file in memory.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_NOTAVAILABLE, D3DERR_OUTOFVIDEOMEMORY, D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The function is equivalent to D3DXCreateTextureFromFileInMemoryEx(pDevice, pSrcData, SrcDataSize, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppTexture).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Filtering is automatically applied to a texture created using this method. The filtering is equivalent to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER in D3DX_FILTER.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateTextureFromFileInMemoryEx, Texturing Functions


D3DXCreateTextureFromFileInMemoryEx

Creates a texture from a file in memory. This is a more advanced function than D3DXCreateTextureFromFileInMemory.

HRESULT D3DXCreateTextureFromFileInMemoryEx(
  LPDIRECT3DDEVICE9 pDevice,
  LPCVOID pSrcData,
  UINT SrcDataSize,
  UINT Width,
  UINT Height,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo,
  PALETTEENTRY * pPalette,
  LPDIRECT3DTEXTURE9 * ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the texture.
SrcDataSize
[in] Size of the file in memory, in bytes.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] Combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER. Each valid filter must contain one of the flags in D3DX_FILTER.
MipFilter
[in] Combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX. Each valid filter must contain one of the flags in D3DX_FILTER. In addition, use bits 27-31 to specify the number of mip levels to be skipped (from the top of the mipmap chain) when a .dds texture is loaded into memory; this allows you to skip up to 32 levels.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_NOTAVAILABLE, D3DERR_OUTOFVIDEOMEMORY, D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

For details about PALETTEENTRY, see the Platform SDK. Note that as of DirectX 8.0, the peFlags member of the PALETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

When skipping mipmap levels while loading a .dds file, use the D3DX_SKIP_DDS_MIP_LEVELS macro to generate the MipFilter value. This macro takes the number of levels to skip and the filter type and returns the filter value, which would then be passed into the MipFilter parameter.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateTextureFromFileInMemory, Texturing Functions


D3DXCreateTextureFromResource

Creates a texture from a resource.

HRESULT D3DXCreateTextureFromResource(
  LPDIRECT3DDEVICE9 pDevice,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  LPDIRECT3DTEXTURE9 * ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromResourceW. Otherwise, the function call resolves to D3DXCreateTextureFromResourceA because ANSI strings are being used.

The function is equivalent to D3DXCreateTextureFromResourceEx(pDevice, hSrcModule, pSrcResource, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppTexture).

The resource being loaded must be of type RT_BITMAP or RT_RCDATA. Resource type RT_RCDATA is used to load formats other than bitmaps (such as .tga, .jpg, and .dds).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Filtering is automatically applied to a texture created using this method. The filtering is equivalent to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER in D3DX_FILTER.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateTextureFromResourceEx, Texturing Functions


D3DXCreateTextureFromResourceEx

Creates a texture from a resource. This is a more advanced function than D3DXCreateTextureFromResource.

HRESULT D3DXCreateTextureFromResourceEx(
  LPDIRECT3DDEVICE9 pDevice,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  UINT Width,
  UINT Height,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo,
  PALETTEENTRY * pPalette,
  LPDIRECT3DTEXTURE9 * ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Performance Optimizations (Direct3D 9)Using Dynamic Textures.
Format
[in] A member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in or NULL.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromResourceExW. Otherwise, the function call resolves to D3DXCreateTextureFromResourceExA because ANSI strings are being used.

The resource being loaded must be of type RT_BITMAP or RT_RCDATA. Resource type RT_RCDATA is used to load formats other than bitmaps (such as .tga, .jpg, and .dds).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateTextureFromResource, Texturing Functions


D3DXCreateVolumeTexture

Creates an empty volume texture, adjusting the calling parameters as needed.

HRESULT D3DXCreateVolumeTexture(
  LPDIRECT3DDEVICE9 pDevice,
  UINT Width,
  UINT Height,
  UINT Depth,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  LPDIRECT3DVOLUMETEXTURE9 * ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
Width
[in] Width in pixels. This value must be nonzero. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Height
[in] Height in pixels. This value must be nonzero. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Depth
[in] Depth in pixels. This value must be nonzero. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_DYNAMIC. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the volume texture. The returned volume texture might have a different format from that specified by Format. Applications should check the format of the returned volume texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created volume texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DERR_INVALIDCALLE_OUTOFMEMORY

Remarks

Internally, D3DXCreateVolumeTexture uses D3DXCheckVolumeTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateVolumeTexture will often succeed where calls to IDirect3DDevice9::CreateVolumeTexture would fail.

Requirements

Header: Declared in D3dx9tex.h.

See Also

Texturing Functions


D3DXCreateVolumeTextureFromFile

Creates a volume texture from a file.

HRESULT D3DXCreateVolumeTextureFromFile(
  LPDIRECT3DDEVICE9 pDevice,
  LPCTSTR pSrcFile,
  LPDIRECT3DVOLUMETEXTURE9 * ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
pSrcFile
[in] Pointer to a string that specifies the file name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromFileW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromFileA because ANSI strings are being used.

The function is equivalent to D3DXCreateVolumeTextureFromFileEx(pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppVolumeTexture).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Filtering is automatically applied to a texture created using this method. The filtering is equivalent to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER in D3DX_FILTER.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texturing Functions


D3DXCreateVolumeTextureFromFileEx

Creates a volume texture from a file.

HRESULT D3DXCreateVolumeTextureFromFileEx(
  LPDIRECT3DDEVICE9 pDevice,
  LPCTSTR pSrcFile,
  UINT Width,
  UINT Height,
  UINT Depth,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo,
  PALETTEENTRY * pPalette,
  LPDIRECT3DVOLUMETEXTURE9 * ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Depth
[in] Depth, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX. In addition, use bits 27-31 to specify the number of mip levels to be skipped (from the top of the mipmap chain) when a .dds texture is loaded into memory; this allows you to skip up to 32 levels.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromFileExW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromFileExA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Mipmapped textures automatically have each level filled with the loaded volume texture. When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

When skipping mipmap levels while loading a .dds file, use the D3DX_SKIP_DDS_MIP_LEVELS macro to generate the MipFilter value. This macro takes the number of levels to skip and the filter type and returns the filter value, which would then be passed into the MipFilter parameter.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texturing Functions


D3DXCreateVolumeTextureFromFileInMemory

Creates a volume texture from a file in memory.

HRESULT D3DXCreateVolumeTextureFromFileInMemory(
  LPDIRECT3DDEVICE9 pDevice,
  LPCVOID pSrcFile,
  UINT SrcData,
  LPDIRECT3DVOLUMETEXTURE9 ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
pSrcFile
[in] Pointer to the file in memory from which to create the volume texture.
SrcData
[in] Size of the file in memory, in bytes.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

The function is equivalent to D3DXCreateVolumeTextureFromFileInMemoryEx(pDevice, pSrcFile, SrcData, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppVolumeTexture).

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Filtering is automatically applied to a texture created using this method. The filtering is equivalent to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER in D3DX_FILTER.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texturing Functions


D3DXCreateVolumeTextureFromFileInMemoryEx

Creates a volume texture from a file. This is a more advanced function than D3DXCreateVolumeTextureFromFileInMemory.

HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx(
  LPDIRECT3DDEVICE9 pDevice,
  LPCVOID pSrcData,
  UINT SrcDataSize,
  UINT Width,
  UINT Height,
  UINT Depth,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo,
  PALETTEENTRY * pPalette,
  LPDIRECT3DVOLUMETEXTURE9 * ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the volume texture.
SrcDataSize
[in] Size of the file in memory, in bytes.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Depth
[in] Depth, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX. In addition, use bits 27-31 to specify the number of mip levels to be skipped (from the top of the mipmap chain) when a .dds texture is loaded into memory; this allows you to skip up to 32 levels.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

When skipping mipmap levels while loading a .dds file, use the D3DX_SKIP_DDS_MIP_LEVELS macro to generate the MipFilter value. This macro takes the number of levels to skip and the filter type and returns the filter value, which would then be passed into the MipFilter parameter.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texturing Functions


D3DXCreateVolumeTextureFromResource

Creates a volume texture from a resource.

HRESULT D3DXCreateVolumeTextureFromResource(
  LPDIRECT3DDEVICE9 pDevice,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  LPDIRECT3DVOLUMETEXTURE9 * ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromResourceW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromResourceA because ANSI strings are being used.

The function is equivalent to D3DXCreateVolumeTextureFromResourceEx(pDevice, hSrcModule, pSrcResource, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppVolumeTexture).

The resource being loaded must be an application-defined resource (RT_RCDATA).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Filtering is automatically applied to a texture created using this method. The filtering is equivalent to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER in D3DX_FILTER.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResourceEx, Texturing Functions


D3DXCreateVolumeTextureFromResourceEx

Creates a volume texture from a resource specified by a string. This is a more advanced function than D3DXCreateVolumeTextureFromResource.

HRESULT D3DXCreateVolumeTextureFromResourceEx(
  LPDIRECT3DDEVICE9 pDevice,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  UINT Width,
  UINT Height,
  UINT Depth,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo,
  PALETTEENTRY * pPalette,
  LPDIRECT3DVOLUMETEXTURE9 * ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Depth
[in] Depth, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DERR_INVALIDCALLD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromResourceExW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromResourceExA because ANSI strings are being used.

The resource being loaded must be an application-defined resource (RT_RCDATA).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, Texturing Functions


D3DXFillCubeTexture

Uses a user-provided function to fill each texel of each mip level of a given cube texture.

HRESULT D3DXFillCubeTexture(
  LPDIRECT3DCUBETEXTURE9 pTexture,
  LPD3DXFILL3D pFunction,
  LPVOID pData
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DCubeTexture9 interface, representing the filled texture.
pFunction
[in] Pointer to a user-provided evaluator function, which will be used to compute the value of each texel. The function follows the prototype of LPD3DXFILL3D.
pData
[in] Pointer to an arbitrary block of user-defined data. This pointer will be passed to the function provided in pFunction.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL.

Remarks

Here is an example that creates a function called ColorCubeFill, which relies on D3DXFillCubeTexture.

// Define a function that matches the prototype of LPD3DXFILL3D
VOID WINAPI ColorCubeFill (D3DXVECTOR4* pOut, const D3DXVECTOR3* pTexCoord,
const D3DXVECTOR3* pTexelSize, LPVOID pData)
{
    *pOut = D3DXVECTOR4(pTexCoord->x, pTexCoord->y, pTexCoord->z, 0.0f);
}

// Fill the texture using D3DXFillCubeTexture
if (FAILED (hr = D3DXFillCubeTexture (m_pTexture, ColorCubeFill, NULL)))
{
    return hr;
}

Requirements

Header: Declared in D3dx9tex.h.


D3DXFillCubeTextureTX

Uses a compiled high-level shader language (HLSL) function to fill each texel of each mipmap level of a texture.

HRESULT D3DXFillCubeTextureTX(
  LPDIRECT3DCUBETEXTURE9 pTexture,
  LPD3DXTEXTURESHADER pTextureShader
);

Parameters

pTexture
[in] Pointer to an IDirect3DCubeTexture9 object, representing the texture to be filled.
pTextureShader
[in] Pointer to a ID3DXTextureShader texture shader object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL.

Remarks

The texture target must be an HLSL function that takes contains the following semantics:

  • One input parameter must use a POSITION semantic.
  • One input parameter must use a PSIZE semantic.
  • The function must return a parameter that uses the COLOR semantic.

The input parameters can be in any order. For an example, see D3DXFillTextureTX

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXFillVolumeTextureTX


D3DXFillTexture

Uses a user-provided function to fill each texel of each mip level of a given texture.

HRESULT D3DXFillTexture(
  LPDIRECT3DTEXTURE9 pTexture,
  LPD3DXFILL2D pFunction,
  LPVOID pData
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DTexture9 interface, representing the filled texture.
pFunction
[in] Pointer to a user-provided evaluator function, which will be used to compute the value of each texel. The function follows the prototype of LPD3DXFILL2D.
pData
[in] Pointer to an arbitrary block of user-defined data. This pointer will be passed to the function provided in pFunction.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL.

Remarks

Here is an example that creates a function called ColorFill, which relies on D3DXFillTexture.

// Define a function that matches the prototype of LPD3DXFILL3D
VOID WINAPI ColorFill (D3DXVECTOR4* pOut, const D3DXVECTOR2* pTexCoord,
const D3DXVECTOR2* pTexelSize, LPVOID pData)
{
    *pOut = D3DXVECTOR4(pTexCoord->x, pTexCoord->y, 0.0f, 0.0f);
}

// Fill the texture using D3DXFillTexture
if (FAILED (hr = D3DXFillTexture (m_pTexture, ColorFill, NULL)))
{
    return hr;
}

Requirements

Header: Declared in D3dx9tex.h.


D3DXFillTextureTX

Uses a compiled high-level shader language (HLSL) function to fill each texel of each mipmap level of a texture.

HRESULT D3DXFillTextureTX(
  LPDIRECT3DTEXTURE9 pTexture,
  LPD3DXTEXTURESHADER pTextureShader
);

Parameters

pTexture
[in, out] Pointer to an IDirect3DTexture9 object, representing the texture to be filled.
pTextureShader
[in] Pointer to a ID3DXTextureShader texture shader object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL.

Remarks

The texture target must be an HLSL function that takes contains the following semantics:

  • One input parameter must use a POSITION semantic.
  • One input parameter must use a PSIZE semantic.
  • The function must return a parameter that uses the COLOR semantic.

The following is an example of such an HLSL function:

float4 TextureGradientFill(
  float2 vTexCoord : POSITION,
  float2 vTexelSize : PSIZE) : COLOR
  {
    float r,g, b, xSq,ySq, a;
    xSq = 2.f*vTexCoord.x-1.f; xSq *= xSq;
    ySq = 2.f*vTexCoord.y-1.f; ySq *= ySq;
    a = sqrt(xSq+ySq);
    if (a > 1.0f) {
        a = 1.0f-(a-1.0f);
    }
    else if (a < 0.2f) {
        a = 0.2f;
    }
    r = 1-vTexCoord.x;
    g = 1-vTexCoord.y;
    b = vTexCoord.x;
    return float4(r, g, b, a);

  };

Note that the input parameters can be in any order, but both input semantics must be represented.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXFillCubeTextureTX, D3DXFillVolumeTextureTX


D3DXFillVolumeTexture

Uses a user-provided function to fill each texel of each mip level of a given volume texture.

HRESULT D3DXFillVolumeTexture(
  LPDIRECT3DVOLUMETEXTURE9 pTexture,
  LPD3DXFILL3D pFunction,
  LPVOID pData
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DVolumeTexture9 interface, representing the filled texture.
pFunction
[in] Pointer to a user-provided evaluator function, which will be used to compute the value of each texel. The function follows the prototype of LPD3DXFILL3D.
pData
[in] Pointer to an arbitrary block of user-defined data. This pointer will be passed to the function provided in pFunction.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL.

Remarks

If the volume is non-dynamic (because usage is set to 0 when it is created), and located in video memory (the memory pool set to D3DPOOL_DEFAULT), D3DXFillVolumeTexture will fail because the volume cannot be locked.

This example creates a function called ColorVolumeFill, which relies on D3DXFillVolumeTexture.

// Define a function that matches the prototype of LPD3DXFILL3D
VOID WINAPI ColorVolumeFill (D3DXVECTOR4* pOut, const D3DXVECTOR3* pTexCoord,
const D3DXVECTOR3* pTexelSize, LPVOID pData)
{
   *pOut = D3DXVECTOR4(pTexCoord->x, pTexCoord->y, pTexCoord->z, 0.0f);
}

// Fill volume texture
if (FAILED (hr = D3DXFillVolumeTexture (m_pTexture, ColorVolumeFill, NULL)))
{
       return hr;
}

Requirements

Header: Declared in D3dx9tex.h.


D3DXFillVolumeTextureTX

Uses a compiled high-level shader language (HLSL) function to fill each texel of each mipmap level of a texture.

HRESULT D3DXFillVolumeTextureTX(
  LPDIRECT3DVOLUMETEXTURE9 pTexture,
  LPD3DXTEXTURESHADER pTextureShader
);

Parameters

pTexture
[in] Pointer to an IDirect3DVolumeTexture9 object, representing the texture to be filled.
pTextureShader
[in] Pointer to a ID3DXTextureShader texture shader object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following:D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL.

Remarks

The texture target must be an HLSL function that takes contains the following semantics:

  • One input parameter must use a POSITION semantic.
  • One input parameter must use a PSIZE semantic.
  • The function must return a parameter that uses the COLOR semantic.

The input parameters can be in any order. For an example, see D3DXFillTextureTX

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXFillTextureTX, D3DXFillCubeTextureTX


D3DXFilterTexture

Filters mipmap levels of a texture.

HRESULT D3DXFilterTexture(
  LPDIRECT3DBASETEXTURE9 pBaseTexture,
  CONST PALETTEENTRY * pPalette,
  UINT SrcLevel,
  DWORD MipFilter
);

Parameters

pBaseTexture
[in] Pointer to an IDirect3DBaseTexture9 interface that represents the texture object to filter.
pPalette
[out] Pointer to a PALETTEENTRY structure that represents a 256-color palette to fill in, or NULL for nonpalletized formats. If a palette is not specified, the default Direct3D palette (an all opaque white palette) is provided. See Remarks.
SrcLevel
[in] Level whose image is used to generate the subsequent levels. Specifying D3DX_DEFAULT for this parameter is equivalent to specifying 0.
MipFilter
[in] Combination of one or more D3DX_FILTER controlling how the mipmap is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX if the texture size is a power of two, and D3DX_FILTER_BOX | D3DX_FILTER_DITHER otherwise.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

A filter is recursively applied to each texture level to generate the next texture level.

Writing to a non-level-zero surface of the texture will not cause the dirty rectangle to be updated. If D3DXFilterTexture is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the texture.

Textures created in the default pool (D3DPOOL_DEFAULT) cannot be used with D3DXFilterTexture (unless created with D3DUSAGE_DYNAMIC) because a lock operation is needed on the object. Note that locks are prohibited on textures in the default pool (unless they are dynamic).

For details on PALETTEENTRY, see the Platform SDK. Note that as of DirectX 8.0, the peFlags member of the PALETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

There is only one texture filtering function, but two macros that call this method.

#define D3DXFilterCubeTexture D3DXFilterTexture
#define D3DXFilterVolumeTexture D3DXFilterTexture

Requirements

Header: Declared in D3dx9tex.h.


D3DXGetImageInfoFromFile

Retrieves information about a given image file.

HRESULT D3DXGetImageInfoFromFile(
  LPCSTR pSrcFile,
  D3DXIMAGE_INFO * pSrcInfo
);

Parameters

pSrcFile
[in] File name of image to retrieve information about. If UNICODE or _UNICODE are defined, this parameter type is LPCWSTR, otherwise, the type is LPCSTR.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with the description of the data in the source file.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL

Remarks

This function supports both Unicode and ANSI strings.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXGetImageInfoFromFileInMemory, D3DXGetImageInfoFromResource


D3DXGetImageInfoFromFileInMemory

Retrieves information about a given image file in memory.

HRESULT D3DXGetImageInfoFromFileInMemory(
  LPCVOID pSrcData,
  UINT SrcDataSize,
  D3DXIMAGE_INFO * pSrcInfo
);

Parameters

pSrcData
[in] VOID pointer to the source file in memory.
SrcDataSize
[in] Size of file in memory, in bytes. .
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with the description of the data in the source file.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXGetImageInfoFromFile, D3DXGetImageInfoFromResource


D3DXGetImageInfoFromResource

Retrieves information about a given image in a resource.

HRESULT D3DXGetImageInfoFromResource(
  HMODULE hSrcModule,
  LPCTSTR pSrcFile,
  D3DXIMAGE_INFO * pSrcInfo
);

Parameters

hSrcModule
[in] Module where the resource is loaded. Set this parameter to NULL to specify the module associated with the image that the operating system used to create the current process.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with the description of the data in the source file.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXGetImageInfoFromResourceW. Otherwise, the function call resolves to D3DXGetImageInfoFromResourceA because ANSI strings are being used.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXGetImageInfoFromFile, D3DXGetImageInfoFromFileInMemory


D3DXLoadSurfaceFromFile

Loads a surface from a file.

HRESULT D3DXLoadSurfaceFromFile(
  LPDIRECT3DSURFACE9 pDestSurface,
  CONST PALETTEENTRY* pDestPalette,
  CONST RECT* pDestRect,
  LPCTSTR pSrcFile,
  CONST RECT* pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadSurfaceFromFileW. Otherwise, the function call resolves to D3DXLoadSurfaceFromFileA because ANSI strings are being used.

This function handles conversion to and from compressed texture formats and supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromFile is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Requirements

Header: Declared in D3dx9tex.h.

See Also

Texturing Functions


D3DXLoadSurfaceFromFileInMemory

Loads a surface from a file in memory.

HRESULT D3DXLoadSurfaceFromFileInMemory(
  LPDIRECT3DSURFACE9 pDestSurface,
  CONST PALETTEENTRY * pDestPalette,
  CONST RECT * pDestRect,
  LPCVOID pSrcData,
  UINT SrcData,
  CONST RECT * pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcData
[in] Pointer to the file in memory from which to load the surface.
SrcData
[in] Size of the file in memory, in bytes.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file or NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

This function handles conversion to and from compressed texture formats and supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromFileInMemory is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Requirements

Header: Declared in D3dx9tex.h.

See Also

Texturing Functions


D3DXLoadSurfaceFromMemory

Loads a surface from memory.

HRESULT D3DXLoadSurfaceFromMemory(
  LPDIRECT3DSURFACE9 pDestSurface,
  CONST PALETTEENTRY * pDestPalette,
  CONST RECT * pDestRect,
  LPCVOID pSrcMemory,
  D3DFORMAT SrcFormat,
  UINT SrcPitch,
  CONST PALETTEENTRY * pSrcPalette,
  CONST RECT * pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcMemory
[in] Pointer to the upper left corner of the source image in memory.
SrcFormat
[in] Member of the D3DFORMAT enumerated type, the pixel format of the source image.
SrcPitch
[in] Pitch of source image, in bytes. For DXT formats, this number should represent the width of one row of cells, in bytes.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcRect
[in] Pointer to a RECT structure. Specifies the dimensions of the source image in memory. This value cannot be NULL.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromMemory is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Requirements

Header: Declared in D3dx9tex.h.

See Also

Texturing Functions


D3DXLoadSurfaceFromResource

Loads a surface from a resource.

HRESULT D3DXLoadSurfaceFromResource(
  LPDIRECT3DSURFACE9 pDestSurface,
  CONST PALETTEENTRY * pDestPalette,
  CONST RECT * pDestRect,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  CONST RECT * pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadSurfaceFromResourceW. Otherwise, the function call resolves to D3DXLoadSurfaceFromResourceA because ANSI strings are being used.

The resource being loaded must be of type RT_BITMAP or RT_RCDATA. Resource type RT_RCDATA is used to load formats other than bitmaps (such as .tga, .jpg, and .dds).

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromFile is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Requirements

Header: Declared in D3dx9tex.h.

See Also

Texturing Functions


D3DXLoadSurfaceFromSurface

Loads a surface from another surface with color conversion.

HRESULT D3DXLoadSurfaceFromSurface(
  LPDIRECT3DSURFACE9 pDestSurface,
  CONST PALETTEENTRY * pDestPalette,
  CONST RECT * pDestRect,
  LPDIRECT3DSURFACE9 pSrcSurface,
  CONST PALETTEENTRY * pSrcPalette,
  CONST RECT * pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the source surface.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire surface.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromSurface is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Requirements

Header: Declared in D3dx9tex.h.

See Also

Texturing Functions


D3DXLoadVolumeFromFile

Loads a volume from a file.

HRESULT D3DXLoadVolumeFromFile(
  LPDIRECT3DVOLUME9 pDestVolume,
  CONST PALETTEENTRY * pDestPalette,
  CONST D3DBOX * pDestBox,
  LPCTSTR pSrcFile,
  CONST D3DBOX * pSrcBox,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] Combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadVolumeFromFileW. Otherwise, the function call resolves to D3DXLoadVolumeFromFileA because ANSI strings are being used.

This function handles conversion to and from compressed texture formats and supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromFile is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXLoadVolumeFromFileInMemory, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromResource, D3DXLoadVolumeFromVolume, Texturing Functions


D3DXLoadVolumeFromFileInMemory

Loads a volume from a file in memory.

HRESULT D3DXLoadVolumeFromFileInMemory(
  LPDIRECT3DVOLUME9 pDestVolume,
  CONST PALETTEENTRY * pDestPalette,
  CONST D3DBOX * pDestBox,
  LPCVOID pSrcData,
  UINT SrcDataSize,
  CONST D3DBOX * pSrcBox,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcData
[in] Pointer to the file in memory from which to load the volume.
SrcDataSize
[in] Size in bytes of the file in memory.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] Combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

This function handles conversion to and from compressed texture formats and supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromFileInMemory is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromResource, D3DXLoadVolumeFromVolume, Texturing Functions


D3DXLoadVolumeFromMemory

Loads a volume from memory.

HRESULT D3DXLoadVolumeFromMemory(
  LPDIRECT3DVOLUME9 pDestVolume,
  CONST PALETTEENTRY * pDestPalette,
  CONST D3DBOX * pDestBox,
  LPCVOID pSrcMemory,
  D3DFORMAT SrcFormat,
  UINT SrcRowPitch,
  UINT SrcSlicePitch,
  CONST PALETTEENTRY * pSrcPalette,
  CONST D3DBOX * pSrcBox,
  DWORD Filter,
  D3DCOLOR ColorKey
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcMemory
[in] Pointer to the top-left corner of the source volume in memory.
SrcFormat
[in] Member of the D3DFORMAT enumerated type, the pixel format of the source volume.
SrcRowPitch
[in] Pitch of source image, in bytes. For DXT formats (compressed texture formats), this number should represent the size of one row of cells, in bytes.
SrcSlicePitch
[in] Pitch of source image, in bytes. For DXT formats (compressed texture formats), this number should represent the size of one slice of cells, in bytes.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. NULL is not a valid value for this parameter.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromMemory is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromResource, D3DXLoadVolumeFromVolume, Texturing Functions


D3DXLoadVolumeFromResource

Loads a volume from a resource.

HRESULT D3DXLoadVolumeFromResource(
  LPDIRECT3DVOLUME9 pDestVolume,
  CONST PALETTEENTRY * pDestPalette,
  CONST D3DBOX * pDestBox,
  HMODULE hSrcModule,
  LPCSTR pSrcResource,
  CONST D3DBOX * pSrcBox,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO * pSrcInfo
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the file name of the source image. If UNICODE or _UNICODE are defined, this parameter type is LPCWSTR, otherwise, the type is LPCSTR.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] Combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following values: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

The resource being loaded must be a bitmap resource(RT_BITMAP).

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromFile is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

This function supports both Unicode and ANSI strings.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromFileInMemory, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromVolume, Texturing Functions


D3DXLoadVolumeFromVolume

Loads a volume from another volume.

HRESULT D3DXLoadVolumeFromVolume(
  LPDIRECT3DVOLUME9 pDestVolume,
  CONST PALETTEENTRY * pDestPalette,
  CONST D3DBOX * pDestBox,
  LPDIRECT3DVOLUME9 pSrcVolume,
  CONST PALETTEENTRY * pSrcPalette,
  CONST D3DBOX * pSrcBox,
  DWORD Filter,
  D3DCOLOR ColorKey
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcVolume
[in] A Pointer to an IDirect3DVolume9 interface. Specifies the source volume.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromVolume is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the surface.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromFileInMemory, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromResource, Texturing Functions


D3DXSaveSurfaceToFile

Saves a surface to a file.

HRESULT D3DXSaveSurfaceToFile(
  LPCTSTR pDestFile,
  D3DXIMAGE_FILEFORMAT DestFormat,
  LPDIRECT3DSURFACE9 pSrcSurface,
  CONST PALETTEENTRY * pSrcPalette,
  CONST RECT * pSrcRect
);

Parameters

pDestFile
[in] Pointer to a string that specifies the file name of the destination image. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcSurface
[in] Pointer to IDirect3DSurface9 interface, containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveSurfaceToFileW. Otherwise, the function call resolves to D3DXSaveSurfaceToFileA because ANSI strings are being used.

This function handles conversion to and from compressed texture formats.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXSaveTextureToFile, D3DXSaveVolumeToFile


D3DXSaveSurfaceToFileInMemory

Saves a surface to an image file.

HRESULT D3DXSaveSurfaceToFileInMemory(
  LPD3DXBUFFER * ppDestBuf,
  D3DXIMAGE_FILEFORMAT DestFormat,
  LPDIRECT3DSURFACE9 pSrcSurface,
  CONST PALETTEENTRY * pSrcPalette,
  CONST RECT * pSrcRect
);

Parameters

ppDestBuf
[out] Address of a pointer to an ID3DXBuffer that will store the image.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcSurface
[in] Pointer to IDirect3DSurface9 interface containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following:

D3DERR_INVALIDCALL

Remarks

This function handles conversion to and from compressed texture formats.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXSaveVolumeToFileInMemory


D3DXSaveTextureToFile

Saves a texture to a file.

HRESULT D3DXSaveTextureToFile(
  LPCTSTR pDestFile,
  D3DXIMAGE_FILEFORMAT DestFormat,
  LPDIRECT3DBASETEXTURE9 pSrcTexture,
  CONST PALETTEENTRY * pSrcPalette
);

Parameters

pDestFile
[in] Pointer to a string that specifies the file name of the destination image. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcTexture
[in] Pointer to IDirect3DBaseTexture9 interface, containing the texture to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveTextureToFileW. Otherwise, the function call resolves to D3DXSaveTextureToFileA because ANSI strings are being used.

This function handles conversion to and from compressed texture formats.

If the volume is nondynamic (because of a usage parameter set to 0 at the creation) and located in video memory (the memory pool set to D3DPOOL_DEFAULT), D3DXSaveTextureToFile will fail because D3DX cannot lock nondynamic volumes located in video memory.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXSaveSurfaceToFile, D3DXSaveVolumeToFile


D3DXSaveTextureToFileInMemory

Saves a texture to an image file.

HRESULT D3DXSaveTextureToFileInMemory(
  LPD3DXBUFFER * ppDestBuf,
  D3DXIMAGE_FILEFORMAT DestFormat,
  LPDIRECT3DBASETEXTURE9 pSrcTexture,
  CONST PALETTEENTRY * pSrcPalette
);

Parameters

ppDestBuf
[out] Address of a pointer to an ID3DXBuffer that will store the image.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcTexture
[in] Pointer to IDirect3DBaseTexture9 interface containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following:

D3DERR_INVALIDCALL

Remarks

This function handles conversion to and from compressed texture formats.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXSaveSurfaceToFileInMemory, D3DXSaveVolumeToFileInMemory


D3DXSaveVolumeToFile

Saves a volume to a file on disk.

HRESULT D3DXSaveVolumeToFile(
  LPCTSTR pDestFile,
  D3DXIMAGE_FILEFORMAT DestFormat,
  LPDIRECT3DVOLUME9 pSrcVolume,
  CONST PALETTEENTRY * pSrcPalette,
  CONST D3DBOX * pSrcBox
);

Parameters

pDestFile
[in] Pointer to a string that specifies the file name of the destination image. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcVolume
[in] Pointer to IDirect3DVolume9 interface containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveVolumeToFileW. Otherwise, the function call resolves to >D3DXSaveVolumeToFileA because ANSI strings are being used.

This function handles conversion to and from compressed texture formats.

If the volume is nondynamic (because of a usage parameter set to 0 at the creation) and located in video memory (the memory pool set to D3DPOOL_DEFAULT), D3DXSaveTextureToFile will fail because D3DX cannot lock nondynamic volumes located in video memory.

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXSaveSurfaceToFile, D3DXSaveTextureToFile, D3DXSaveVolumeToFileInMemory


D3DXSaveVolumeToFileInMemory

Saves a volume to a buffer. The method creates an ID3DXBuffer buffer to store the data, and returns that object.

HRESULT D3DXSaveVolumeToFileInMemory(
  LPD3DXBUFFER * ppDestBuf,
  D3DXIMAGE_FILEFORMAT DestFormat,
  LPDIRECT3DVOLUME9 pSrcVolume,
  CONST PALETTEENTRY * pSrcPalette,
  CONST D3DBOX * pSrcBox
);

Parameters

ppDestBuf
[out] Address of a pointer to an ID3DXBuffer buffer that will store the image.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcVolume
[in] Pointer to IDirect3DVolume9 interface containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be the following: D3DERR_INVALIDCALL

Requirements

Header: Declared in D3dx9tex.h.

See Also

D3DXSaveVolumeToFile


UVAtlas Functions

D3DX supplies the following UVAtlas functions:

  • D3DXUVAtlasCreate
  • D3DXUVAtlasPack
  • D3DXUVAtlasPartition
  • D3DXComputeIMTFromPerVertexSignal
  • D3DXComputeIMTFromPerTexelSignal
  • D3DXComputeIMTFromSignal
  • D3DXComputeIMTFromTexture

The UVAtlas functions compute an optimal, unique texture parameterization for an input mesh using a per-face integrated metric tensor.

See Also

Using UVAtlas (Direct3D 9)


D3DXUVAtlasCreate

Create a UV atlas for a mesh.

HRESULT D3DXUVAtlasCreate(
  LPD3DXMESH pMesh,
  UINT dwMaxChartNumber,
  FLOAT fMaxStretch,
  UINT dwWidth,
  UINT dwHeight,
  FLOAT fGutter,
  DWORD dwTextureIndex,
  CONST DWORD *pdwAdjacency,
  CONST DWORD *pdwFalseEdges,
  FLOAT *pfIMTArray,
  LPD3DXUVATLASCB pCallback,
  FLOAT fCallbackFrequency,
  LPVOID pUserContent,
  DWORD dwOptions,
  LPD3DXMESH *ppMeshOut,
  LPD3DXBUFFER *ppFacePartitioning,
  LPD3DXBUFFER *ppVertexRemapArray,
  FLOAT *pfMaxStretchOut,
  UINT *pdwNumChartsOut
);

Parameters

pMesh
[in] Pointer to an input mesh (see ID3DXMesh) which contains the object geometry for calculating the atlas. At a minimum, the mesh must contain position data and 2D texture coordinates.
dwMaxChartNumber
[in] The maximum number of charts to partition the mesh into. See remarks about the partitioning modes. Use 0 to tell D3DX that the atlas should be parameterized based on stretch.
fMaxStretch
[in] The amount of stretching allowed. 0 means no stretching is allowed, 1 means any amount of stretching can be used.
dwWidth
[in] Texture width.
dwHeight
[in] Texture height.
fGutter
[in] The minimum distance, in texels, between two charts on the atlas. The gutter is always scaled by the width; so, if a gutter of 2.5 is used on a 512x512 texture, then the minimum distance between two charts is 2.5 / 512.0 texels.
dwTextureIndex
[in] Zero-based texture coordinate index that identifies which set of texture coordinates to use.
pdwAdjacency
[in] A pointer to an array of adjacency data. with 3 DWORDs per face, indicating which triangles are adjacent to each other (see ID3DXBaseMesh::GenerateAdjacency).
pdwFalseEdges
[in] An array with 3 DWORDS per face. Each face indicates if an edge is false or not. A non-false edge is indicated by -1, a false edge is indicated by any other value. This enables the parameterization of a mesh of quads where the edges down the middle of each quad will not be cut.
pfIMTArray
[in] A pointer to an array of integrated metric tensors that describes how to stretch a triangle (see IntegratedMetricTensor).
pCallback
[in] A pointer to a callback function (see LPD3DXUVATLASCB) that is useful for monitoring progress.
fCallbackFrequency
[in] Specify how often D3DX will call the callback; a reasonable default value is 0.0001f.
pUserContent
[in] Pointer to a user-defined value which is passed to the callback function; typically used by an application to pass a pointer to a data structure that provides context information for the callback function.
dwOptions
[in] Specify the quality of the charts generated. See D3DXUVATLAS.
ppMeshOut
[in] Pointer to the created mesh with the atlas (see ID3DXMesh).
ppFacePartitioning
[out] A pointer to an array of the final face-partioning data. Each element contains one DWORD per face (see ID3DXBuffer).
ppVertexRemapArray
[out] A pointer to an array of remapped vertices. Each array element identifies the original vertex that each final vertex came from (if the vertex was split during remapping). Each array element contains one DWORD per vertex.
pfMaxStretchOut
[out] A pointer to the maximum stretch value generated by the atlas algorithm. The range is between 0.0 and 1.0.
pdwNumChartsOut
[out] A pointer to the number of charts created by the atlas algorithm. If dwMaxChartNumber is too low, this parameter will return the minimum number of charts required to create an atlas.

Return Values

If the function succeeds, the return value is D3D_OK; otherwise, the value is D3DERR_INVALIDCALL.

Remarks

D3DXUVAtlasCreate can partition mesh geometry two ways:

  • Based on the number of charts
  • Based on the maximum allowed stretch. If the maximum allowed stretch is 0, each triangle will likely be in its own chart.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

UV Atlas Command-Line Tool (uvatlas.exe)


D3DXUVAtlasPack

Pack mesh partitioning data into an atlas.

HRESULT D3DXUVAtlasPack(
  LPD3DXMESH pMesh,
  UINT dwWidth,
  UINT dwHeight,
  FLOAT fGutter,
  DWORD dwTextureIndex,
  CONST DWORD * pdwPartitionResultAdjacency,
  LPD3DXUVATLASCB pCallback,
  FLOAT fCallbackFrequency,
  LPVOID pUserContent,
  DWORD dwOptions,
  LPD3DXBUFFER pFacePartitioning
);

Parameters

pMesh
[in] Pointer to an input mesh (see ID3DXMesh) which contains the object geometry for calculating the atlas. At a minimum, the mesh must contain position data and 2D texture coordinates.
dwWidth
[in] Texture width.
dwHeight
[in] Texture height.
fGutter
[in] The minimum distance, in texels, between two charts on the atlas. The gutter is always scaled by the width; so, if a gutter of 2.5 is used on a 512x512 texture, then the minimum distance between two charts is 2.5 / 512.0 texels.
dwTextureIndex
[in] Zero-based texture coordinate index that identifies which set of texture coordinates to use.
pdwPartitionResultAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. It should be derived from the ppPartitionResultAdjacency returned from D3DXUVAtlasPartition. This value cannot be NULL, because Pack needs to know where charts were cut in the partition step in order to find the edges of each chart.
pCallback
[in] A pointer to a callback function (see LPD3DXUVATLASCB) that is useful for monitoring progress.
fCallbackFrequency
[in] Specify how often D3DX will call the callback; a reasonable default value is 0.0001f.
pUserContent
[in] A void pointer to be passed back to the callback function.
dwOptions
[in] This options parameter is currently reserved.
pFacePartitioning
[in] A pointer to an ID3DXBuffer containing the array of the final face-partioning. Each element contains one DWORD per face.

Return Values

If the function succeeds, the return value is D3D_OK; otherwise, the value is D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.


D3DXUVAtlasPartition

Create a UV atlas for a mesh.

HRESULT D3DXUVAtlasPartition(
  LPD3DXMESH pMesh,
  UINT dwMaxChartNumber,
  FLOAT fMaxStretch,
  DWORD dwTextureIndex,
  CONST DWORD *pdwAdjacency,
  CONST DWORD *pdwFalseEdges,
  FLOAT *pfIMTArray,
  LPD3DXUVATLASCB pCallback,
  FLOAT fCallbackFrequency,
  LPVOID pUserContent,
  DWORD dwOptions,
  LPD3DXMESH *ppMeshOut,
  LPD3DXBUFFER pFacePartitioning,
  LPD3DXBUFFER *ppVertexRemapArray,
  LPD3DXBUFFER *ppPartitionResultAdjacency,
  FLOAT *pfMaxStretchOut,
  UINT *pdwNumChartsOut
);

Parameters

pMesh
[in] Pointer to an input mesh (see ID3DXMesh) that contains the object geometry for calculating the atlas. At a minimum, the mesh must contain position data and 2D texture coordinates.
dwMaxChartNumber
[in] The maximum number of charts to partition the mesh into. See remarks about the partitioning modes. Use 0 to tell D3DX that the atlas should be parameterized based on stretch.
fMaxStretch
[in] The amount of stretching allowed. 0 means no stretching is allowed, 1 means any amount of stretching can be used.
dwTextureIndex
[in] Zero-based texture coordinate index that identifies which set of texture coordinates to use.
pdwAdjacency
[in] A pointer to an array of adjacency data with 3 DWORDs per face, indicating which triangles are adjacent to each other (see ID3DXBaseMesh::GenerateAdjacency).
pdwFalseEdges
[in] An array with 3 DWORDS per face. Each face indicates if an edge is false or not. A non-false edge is indicated by -1, a false edge is indicated by any other value. This enables the parameterization of a mesh of quads where the edges down the middle of each quad will not be cut.
pfIMTArray
[in] A pointer to an array of integrated metric tensors that describes how to stretch a triangle (see IntegratedMetricTensor).
pCallback
[in] A pointer to a callback function (see LPD3DXUVATLASCB) that is useful for monitoring progress.
fCallbackFrequency
[in] Specify how often D3DX will call the callback; a reasonable default value is 0.0001f.
pUserContent
[in] Pointer to a user-defined value that is passed to the callback function; typically used by an application to pass a pointer to a data structure that provides context information for the callback function.
dwOptions
[in] Specify the quality of the charts generated by combining one or more D3DXUVATLAS flags.
ppMeshOut
[in] Pointer to the created mesh with the atlas (see ID3DXMesh).
pFacePartitioning
[out] A pointer to an array of the final face-partioning data. Each element contains one DWORD per face (see ID3DXBuffer).
ppVertexRemapArray
[out] A pointer to an array of remapped vertices. Each array element identifies the original vertex each final vertex came from (if the vertex was split during remapping). Each array element contains one DWORD per vertex.
ppPartitionResultAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. This buffer will contain an array of three DWORDs per face that specify the three neighbors for each face in the output mesh. This parameter must not be NULL, because the subsequent call to D3DXUVAtlasPack() requires it.
pfMaxStretchOut
[out] A pointer to the maximum stretch value generated by the atlas algorithm. The range is between 0.0 and 1.0.
pdwNumChartsOut
[out] A pointer to the number of charts created by the atlas algorithm. If dwMaxChartNumber is too low, this parameter will return the minimum number of charts required to create an atlas.

Return Values

If the function succeeds, the return value is D3D_OK; otherwise, the value is D3DERR_INVALIDCALL.

Remarks

D3DXUVAtlasPartition is similar to D3DXUVAtlasCreate, except that D3DXUVAtlasPartition does not performing the final packing step.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

UVAtlas Functions, UV Atlas Command-Line Tool (uvatlas.exe)


D3DXComputeIMTFromPerTexelSignal

Calculate per-triangle IMT's from per-texel data. This function is similar to D3DXComputeIMTFromTexture, but it uses a float array to pass in the data, and it can calculate higher dimensional values than 4.

HRESULT D3DXComputeIMTFromPerTexelSignal(
  LPD3DXMESH pMesh,
  DWORD dwTextureIndex,
  FLOAT * pfTexelSignal,
  UINT uWidth,
  UINT uHeight,
  UINT uSignalDimension,
  UINT uComponents,
  DWORD dwOptions,
  LPD3DXUVATLASCB pStatusCallback,
  LPVOID pUserContext,
  LPD3DXBUFFER * ppIMTData
);

Parameters

pMesh
[in] A pointer to an input mesh (see ID3DXMesh) which contains the object geometry for calculating the IMT.
dwTextureIndex
[in] Zero-based texture coordinate index that identifies which set of texture coordinates to use.
pfTexelSignal
[in] A pointer to an array of input texels from which IMT will be computed. The array size is uWidth*uHeight*uComponents.
uWidth
[in] Texture width in pixels.
uHeight
[in] Texture height in pixels.
uSignalDimension
[in] The number of floats per-component in each element of the signal array.
uComponents
[in] The number of components in each texel.
dwOptions
[in] Texture wrap options. This is a combination of one or more D3DXIMT FLAGS.
pStatusCallback
[in] A pointer to a callback function to monitor IMT computation progress.
pUserContext
[in] A pointer to a user-defined variable which is passed to the status callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function.
ppIMTData
[out] A pointer to the buffer (see ID3DXBuffer) containing the returned IMT array. This array can be provided as input to the D3DX UVAtlas Functions to prioritize texture-space allocation in the texture parameterization.

Return Values

If the function succeeds, the return value is D3D_OK; otherwise, the value is D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

Using UVAtlas (Direct3D 9)


D3DXComputeIMTFromPerVertexSignal

Calculate per-triangle IMT's from from per-vertex data. This function allows you to calculate the IMT based off of any value in a mesh (color, normal, etc).

HRESULT D3DXComputeIMTFromPerVertexSignal(
  LPD3DXMESH pMesh,
  CONST FLOAT * pfVertexSignal,
  UINT uSignalDimension,
  UINT uSignalStride,
  DWORD dwOptions,
  LPD3DXUVATLASCB pStatusCallback,
  LPVOID pUserContext,
  LPD3DXBUFFER * ppIMTData
);

Parameters

pMesh
[in] A pointer to an input mesh (see ID3DXMesh) which contains the object geometry for calculating the IMT.
pfVertexSignal
[in] A pointer to an array of per-vertex data from which IMT will be computed. The array size is uSignalStride * v, where v is the number of vertices in the mesh.
uSignalDimension
[in] The number of floats per vertex.
uSignalStride
[in] The number of bytes per vertex in the array. This must be a multiple of sizeof(float)
dwOptions
[in] Texture wrap options. This is a combination of one or more D3DXIMT FLAGS.
pStatusCallback
[in] A pointer to a callback function to monitor IMT computation progress.
pUserContext
[in] A pointer to a user-defined variable which is passed to the status callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function.
ppIMTData
[out] A pointer to the buffer (see ID3DXBuffer) containing the returned IMT array. This array can be provided as input to the D3DX UVAtlas Functions to prioritize texture-space allocation in the texture parameterization.

Return Values

If the function succeeds, the return value is D3D_OK; otherwise, the value is D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

Using UVAtlas (Direct3D 9)


D3DXComputeIMTFromSignal

Calculates per-triangle IMT's from a custom application-specified signal that varies over the surface of the mesh (generally at a higher frequency than vertex data). The signal is evaluated via a user-specified callback function.

HRESULT D3DXComputeIMTFromSignal(
  LPD3DXMESH pMesh,
  DWORD dwTextureIndex,
  UINT uSignalDimension,
  FLOAT fMaxUVDistance,
  DWORD dwOptions,
  LPD3DXIMTSIGNALCALLBACK pSignalCallback,
  VOID * pUserData,
  LPD3DXUVATLASCB pStatusCallback,
  LPVOID pUserContext,
  LPD3DXBUFFER * ppIMTData
);

Parameters

pMesh
[in] A pointer to an input mesh (see ID3DXMesh) which contains the object geometry for calculating the IMT.
dwTextureIndex
[in] Zero-based texture coordinate index that identifies which set of texture coordinates to use.
uSignalDimension
[in] The number of components in each data point in the signal.
fMaxUVDistance
[in] The maximum distance between vertices; the algorithm continues subdividing until the distance between all vertices is less than or equal to fMaxUVDistance.
dwOptions
[in] Texture wrap options. This is a combination of one or more D3DXIMT FLAGS.
pSignalCallback
[in] A pointer to a user-provided evaluator function, which will be used to compute the signal value at arbitrary U,V coordinates. The function follows the prototype of LPD3DXIMTSIGNALCALLBACK.
pUserData
[in] A pointer to a user-defined value which is passed to the signal callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function.
pStatusCallback
[in] A pointer to a callback function to monitor IMT computation progress.
pUserContext
[in] A pointer to a user-defined variable which is passed to the status callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function.
ppIMTData
[out] A pointer to the buffer (see ID3DXBuffer) containing the returned IMT array. This array can be provided as input to the D3DX UVAtlas Functions to prioritize texture-space allocation in the texture parameterization.

Return Values

If the function succeeds, the return value is D3D_OK; otherwise, the value is D3DERR_INVALIDCALL.

Remarks

This function requires that the input mesh contain a signal-to-mesh texture mapping (ie. texture coordinates). It allows the user to define a signal arbitrarily over the surface of the mesh.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

Using UVAtlas (Direct3D 9)


D3DXComputeIMTFromTexture

Calculates per-triangle IMT's from a texture mapped onto a mesh, to be used optionally as input to the D3DX UVAtlas Functions.

HRESULT D3DXComputeIMTFromTexture(
  LPD3DXMESH pMesh,
  LPDIRECT3DTEXTURE9 pTexture,
  DWORD dwTextureIndex,
  DWORD dwOptions,
  LPD3DXUVATLASCB pStatusCallback,
  LPVOID pUserContext,
  LPD3DXBUFFER * ppIMTData
);

Parameters

pMesh
[in] A pointer to an input mesh (see ID3DXMesh) which contains the object geometry for calculating the IMT.
pTexture
[in] A pointer to the texture (see IDirect3DTexture9) that is mapped to the mesh.
dwTextureIndex
[in] Zero-based texture coordinate index that identifies which set of texture coordinates to use.
dwOptions
[in] Texture wrap options. This is a combination of one or more D3DXIMT FLAGS.
pStatusCallback
[in] A pointer to a callback function to monitor IMT computation progress.
pUserContext
[in] A pointer to a user-defined variable which is passed to the status callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function.
ppIMTData
[out] A pointer to the buffer (see ID3DXBuffer) containing the returned IMT array. This array can be provided as input to the D3DX UVAtlas Functions to prioritize texture-space allocation in the texture parameterization.

Return Values

If the function succeeds, the return value is D3D_OK; otherwise, the value is D3DERR_INVALIDCALL.

Remarks

Given a texture that maps over the surface of the mesh, the algorithm computes the IMT for each face. This will cause triangles containing lower-frequency signal data to take up less space in the final texture atlas when parameterized with the UVAtlas functions. The texture is assumed to be interpolated over the mesh bilinearly.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

Using UVAtlas (Direct3D 9)


Callback Functions

This section contains information about the following callback functions.

  • LPD3DXFILL2D
  • LPD3DXFILL3D
  • LPD3DXIMTSIGNALCALLBACK
  • LPD3DXSHPRTSIMCB
  • LPD3DXUVATLASCB


LPD3DXFILL2D

Function type used by the texture fill functions.

Syntax

typedef VOID (WINAPI *LPD3DXFILL2D)(
    D3DXVECTOR4* pOut,
    CONST D3DXVECTOR2* pTexCoord,
    CONST D3DXVECTOR2* pTexelSize,
    LPVOID pData,
);

Parameters

pOut - Pointer to a vector, which the function uses to return its result. X, Y, Z, and W will be mapped to R, G, B, and A, respectively.

pTexCoord - Pointer to a vector containing the coordinates of the texel currently being evaluated. Texture coordinate components for texture and volume textures range from 0 to 1. Texture coordinate components for cube textures range from -1 to 1.

pTexelSize - Pointer to a vector containing the dimensions of the current texel.

pData - Pointer to user data.

Return Value

No return value.

Remarks

Be sure to specify the Windows Data Types calling convention when declaring the callback function. Otherwise, stack overflows can occur.

Header | d3dx9tex.h
Import Library | d3dx9.lib
Minimum Operating System | Windows 98

See Also

LPD3DXFILL3D


LPD3DXFILL3D

Function type used by the texture fill functions.

Syntax

typedef VOID (WINAPI *LPD3DXFILL2D)(
    D3DXVECTOR4* pOut,
    CONST D3DXVECTOR3* pTexCoord,
    CONST D3DXVECTOR3* pTexelSize,
    LPVOID pData,
);

Parameters

pOut - Pointer to a vector, which the function uses to return its result. X, Y, Z, and W will be mapped to R, G, B, and A, respectively.

pTexCoord - Pointer to a vector containing the coordinates of the texel currently being evaluated. Texture coordinate components for texture and volume textures range from 0 to 1. Texture coordinate components for cube textures range from -1 to 1.

pTexelSize - Pointer to a vector containing the dimensions of the current texel.

pData - Pointer to user data.

Return Value

No return value.

Remarks

Be sure to specify the Windows Data Types calling convention when declaring the callback function. Otherwise, stack overflows can occur.

Header | d3dx9tex.h
Import Library | d3dx9.lib
Minimum Operating System | Windows 98

See Also

LPD3DXFILL2D


LPD3DXIMTSIGNALCALLBACK

Function prototype used by D3DXComputeIMTFromSignal to describe a user-defined signal in an input mesh's u,v space. The function evaluates a procedural signal of dimension uSignalDimension at the provided u,v coordinate.

Syntax

typedef HRESULT (WINAPI* LPD3DXIMTSIGNALCALLBACK)
     (CONST D3DXVECTOR2 *uv,
      UINT uPrimitiveID,
      UINT uSignalDimension,
      VOID *pUserData,
      FLOAT *pfSignalOut);

Parameters

[in] uv - A pointer to a vector that contains the vertex texture coordinate.

[in] uPrimitiveId - The index of the input triangle on the mesh for which the signal should be calculated.

[in] uSignalDimension - The number of floats to store in the array of signal data (pfSignalOut).

[in] pUserData - The pUserData pointer passed in to D3DXComputeIMTFromSignal.

[out] pfSignalOut - An array of floats, that contains the signal data.

Return Value

This function must be implemented to return S_OK.

Remarks

Be sure to specify the Windows Data Types calling convention when declaring the callback function. Otherwise, stack overflows can occur.

Header | d3dx9mesh.h
Import Library | d3dx9.lib


LPD3DXSHPRTSIMCB

Callback function for Precomputed Radiance Transfer (PRT) simulation and compression.

Syntax

typedef HRESULT (WINAPI *LPD3DXSHPRTSIMCB)(
    FLOAT fPercentDone,
    LPVOID lpUserContext
);

Parameters

fPercentDone - Floating point number between 0 and 1.0 that represents the percentage of calculations completed (between 0 and 100 percent).

lpUserContext - Pointer to a user-defined value which is passed to the callback function; typically used by an application to pass a pointer to a data structure that provides context information for the callback function.

Return Value

This function must be implemented to return S_OK to keep running the simulator. Any other value will halt the simulator.

Remarks

Be sure to specify the Windows Data Types calling convention when declaring the callback function. Otherwise, stack overflows can occur.

Header | d3dx9mesh.h
Import Library | d3dx9.lib
Minimum Operating System | Windows 98


LPD3DXUVATLASCB

Callback function for UVAtlas.

Syntax

typedef HRESULT (*LPD3DXUVATLASCB (
    FLOAT fPercentDone,
    LPVOID lpUserContext
);

Parameters

[out] fPercentDone - Floating point number between 0 and 1.0 that represents the percentage of calculations completed (between 0 and 100 percent).

[in] lpUserContext - Pointer to a user-defined value which is passed to the callback function; typically used by an application to pass a pointer to a data structure that provides context information for the callback function.

Return Value

This function must be implemented to return S_OK to keep running the simulator. Any other value will halt the simulator.

Remarks

Be sure to specify the Windows Data Types calling convention when declaring the callback function. Otherwise, stack overflows can occur.

Header | d3dx9mesh.h
Import Library | d3dx9.lib
Minimum Operating System | Windows 98


Macros

This section contains reference information for the macros provided by the D3DX utility library.

Macros

  • D3DSINCOSCONST1
  • D3DSINCOSCONST2
  • D3DXToDegree
  • D3DXToRadian
  • D3DXTX_VERSION


D3DSINCOSCONST1

Creates the first constant (in register src2) for the sincos - ps pixel shader instruction.

#define D3DSINCOSCONST1  -1.5500992e-006f, -2.1701389e-005f,  0.0026041667f, 0.00026041668f

Return Values

Returns the first constant needed by sincos - ps.

Requirements

Header: Declared in D3dx9types.h.

See Also

D3DSINCOSCONST2


D3DSINCOSCONST2

Creates the second constant (in register src3) for the sincos - ps pixel shader instruction.

#define D3DSINCOSCONST2 -0.020833334f, -0.12500000f, 1.0f, 0.50000000f

Return Values

Returns the second constant needed by sincos - ps.

Requirements

Header: Declared in D3dx9types.h.

See Also

sincos - ps D3DSINCOSCONST1

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


D3DXToDegree

Converts radians into degrees.

#define D3DXToDegree(radian) ((radian) * (180.0f / D3DX_PI))

Parameters

radian
The value, in radians, to convert to degrees.

Return Values

The macro returns the radian value in degrees.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXToRadian D3DX_PI

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


D3DXToRadian

Converts degrees into radians.

#define D3DXToRadian(degree) ((degree) * (D3DX_PI / 180.0f))

Parameters

degree
The value, in degrees, to convert to radians.

Return Values

The macro returns the degree value in radians.

Requirements

Header: Declared in D3dx9math.h.

See Also

D3DXToDegree, D3DX_PI


D3DXTX_VERSION

Version token that creates a procedural texture filler in effects. This macro is used by the D3DXFillxxxTX functions.

#define D3DXTX_VERSION (_Major,_Minor) (('T' << 24) | ('X' << 16) | ((_Major) << 8) | (_Minor))

Return Values

The macro returns the procedural texture version token.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

D3DXFillTextureTX D3DXFillCubeTextureTX D3DXFillVolumeTextureTX

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


D3DX Structures

This section contains information about the structures included in the D3DX utility library.

  • D3DXATTRIBUTERANGE
  • D3DXATTRIBUTEWEIGHTS
  • D3DXBONECOMBINATION
  • D3DXCOLOR
  • D3DXCOLOR Extensions
  • D3DXCONSTANT_DESC
  • D3DXCONSTANTTABLE_DESC
  • D3DXFLOAT16
  • D3DXFLOAT16 Extensions
  • D3DXFONT_DESC
  • D3DXFRAME
  • D3DXIMAGE_INFO
  • D3DXINTERSECTINFO
  • D3DXKEY_CALLBACK
  • D3DXKEY_QUATERNION
  • D3DXKEY_VECTOR3
  • D3DXMATERIAL
  • D3DXMATRIX
  • D3DXMATRIX Extensions
  • D3DXMATRIXA16
  • D3DXMESHCONTAINER
  • D3DXMESHDATA
  • D3DXPATCHINFO
  • D3DXPLANE
  • D3DXPLANE Extensions
  • D3DXQUATERNION
  • D3DXQUATERNION Extensions
  • D3DXRTE_DESC
  • D3DXRTS_DESC
  • D3DXSHADER_CONSTANTINFO
  • D3DXSHADER_CONSTANTTABLE
  • D3DXSHADER_STRUCTMEMBERINFO
  • D3DXSHADER_TYPEINFO
  • D3DXSHMATERIAL
  • D3DXSHPRTSPLITMESHCLUSTERDATA
  • D3DXSHPRTSPLITMESHVERTDATA
  • D3DXTRACK_DESC
  • D3DXVECTOR2
  • D3DXVECTOR2 Extensions
  • D3DXVECTOR3
  • D3DXVECTOR3 Extensions
  • D3DXVECTOR4
  • D3DXVECTOR4 Extensions
  • D3DXWeldEpsilons


D3DXATTRIBUTERANGE

Stores an attribute table entry.

typedef struct D3DXATTRIBUTERANGE {
    DWORD AttribId;
    DWORD FaceStart;
    DWORD FaceCount;
    DWORD VertexStart;
    DWORD VertexCount;
} D3DXATTRIBUTERANGE, *LPD3DXATTRIBUTERANGE;

Members

AttribId
Attribute table identifier.
FaceStart
Starting face.
FaceCount
Face count.
VertexStart
Starting vertex.
VertexCount
Vertex count.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

The LPD3DXATTRIBUTERANGE type is defined as a pointer to the D3DXATTRIBUTERANGE structure.

typedef D3DXATTRIBUTERANGE* LPD3DXATTRIBUTERANGE;


D3DXATTRIBUTEWEIGHTS

Specifies mesh weight attributes.

typedef struct D3DXATTRIBUTEWEIGHTS {
    FLOAT Position;
    FLOAT Boundary;
    FLOAT Normal;
    FLOAT Diffuse;
    FLOAT Specular;
    FLOAT Texcoord[8];
    FLOAT Tangent;
    FLOAT Binormal;
} D3DXATTRIBUTEWEIGHTS, *LPD3DXATTRIBUTEWEIGHTS;

Members

Position
Position.
Boundary
Blend weight.
Normal
Normal.
Diffuse
Diffuse lighting value.
Specular
Specular lighting value.
Texcoord
Eight texture coordinates.
Tangent
Tangent.
Binormal
Binormal.

Remarks

This structure describes how a simplification operation will consider vertex data when calculating relative costs between collapsing edges. For example, if the Normal field is 0.0, the simplification operation will ignore the vertex normal component when calculating the error for the collapse. However, if the Normal field is 1.0, the simplification operation will use the vertex normal component. If the Normal field is 2.0, double the amount of errors; if the Normal field is 4.0, then quadruple the number of errors, and so on.

The LPD3DXATTRIBUTEWEIGHTS type is defined as a pointer to the D3DXATTRIBUTEWEIGHTS structure.

    typedef D3DXATTRIBUTEWEIGHTS* LPD3DXATTRIBUTEWEIGHTS;

See Also

D3DXCreateSPMesh, D3DXGeneratePMesh, D3DXSimplifyMesh


D3DXBONECOMBINATION

Describes a subset of the mesh that has the same attribute and bone combination.

typedef struct D3DXBONECOMBINATION {
    DWORD AttribId;
    DWORD FaceStart;
    DWORD FaceCount;
    DWORD VertexStart;
    DWORD VertexCount;
    DWORD * BoneId;
} D3DXBONECOMBINATION, *LPD3DXBONECOMBINATION;

Members

AttribId
Attribute table identifier.
FaceStart
Starting face.
FaceCount
Face count.
VertexStart
Starting vertex.
VertexCount
Vertex count.
BoneId

Pointer to an array of values that identify each of the bones that can be drawn in a single drawing call. Note that the array can be of variable length to accommodate variable length bone combinations of ID3DXSkinInfo::ConvertToIndexedBlendedMesh.

The size of the array varies based on the type of mesh generated. A non-indexed mesh array size is equal to the number of weights per vertex (pMaxVertexInfl in ID3DXSkinInfo::ConvertToBlendedMesh). An indexed mesh array size is equal to the number of bone matrix palette entries (paletteSize in ID3DXSkinInfo::ConvertToIndexedBlendedMesh).

Remarks

The subset of the mesh described by D3DXBONECOMBINATION can be rendered in a single drawing call.


D3DXCOLOR

Describes color values.

typedef struct D3DXCOLOR {
    FLOAT r;
    FLOAT g;
    FLOAT b;
    FLOAT a;
} D3DXCOLOR, *LPD3DXCOLOR;

Members

r
Red component of the color.
g
Green component of the color.
b
Blue component of the color.
a
Alpha component of the color.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXCOLOR Extensions, which implement overloaded constructors, as well as assignment, unary, and binary (including equality) operators.


D3DXCOLOR Extensions

Supplies the following operator overloads and type casts for D3DXCOLOR structures.

Syntax

typedef struct D3DXCOLOR
{
#ifdef __cplusplus
public:
    D3DXCOLOR() {}
    D3DXCOLOR( DWORD argb );
    D3DXCOLOR( CONST FLOAT * );
    D3DXCOLOR( CONST D3DXFLOAT16 * );
    D3DXCOLOR( CONST D3DCOLORVALUE& );
    D3DXCOLOR( FLOAT r, FLOAT g, FLOAT b, FLOAT a );

    // casting
    operator DWORD () const;

    operator FLOAT* ();
    operator CONST FLOAT* () const;

    operator D3DCOLORVALUE* ();
    operator CONST D3DCOLORVALUE* () const;

    operator D3DCOLORVALUE& ();
    operator CONST D3DCOLORVALUE& () const;

    // assignment operators
    D3DXCOLOR& operator += ( CONST D3DXCOLOR& );
    D3DXCOLOR& operator -= ( CONST D3DXCOLOR& );
    D3DXCOLOR& operator *= ( FLOAT );
    D3DXCOLOR& operator /= ( FLOAT );

    // unary operators
    D3DXCOLOR operator + () const;
    D3DXCOLOR operator - () const;

    // binary operators
    D3DXCOLOR operator + ( CONST D3DXCOLOR& ) const;
    D3DXCOLOR operator - ( CONST D3DXCOLOR& ) const;
    D3DXCOLOR operator * ( FLOAT ) const;
    D3DXCOLOR operator / ( FLOAT ) const;

    friend D3DXCOLOR operator * ( FLOAT, CONST D3DXCOLOR& );

    BOOL operator == ( CONST D3DXCOLOR& ) const;
    BOOL operator != ( CONST D3DXCOLOR& ) const;

#endif //__cplusplus
    FLOAT r, g, b, a;
} D3DXCOLOR, *LPD3DXCOLOR;

Members

For more information about structure members, refer to D3DXCOLOR.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.


D3DXCONSTANTTABLE_DESC

A description of the constant table.

typedef struct D3DXCONSTANTTABLE_DESC {
    LPCSTR Creator;
    DWORD Version;
    UINT Constants;
} D3DXCONSTANTTABLE_DESC, *LPD3DXCONSTANTTABLE_DESC;

Members

Creator
Name of the constant table creator.
Version
Shader version.
Constants
Number of constants in the constant table.

See Also

D3DXCONSTANT_DESC


D3DXCONSTANT_DESC

A description of a constant in a constant table.

typedef struct D3DXCONSTANT_DESC {
    LPCSTR Name;
    D3DXREGISTER_SET RegisterSet;
    UINT RegisterIndex;
    UINT RegisterCount;
    D3DXPARAMETER_CLASS Class;
    D3DXPARAMETER_TYPE Type;
    UINT Rows;
    UINT Columns;
    UINT Elements;
    UINT StructMembers;
    UINT Bytes;
    LPCVOID DefaultValue;
} D3DXCONSTANT_DESC, *LPD3DXCONSTANT_DESC;

Members

Name
Name of the constant.
RegisterSet
Constant data type. See D3DXREGISTER_SET.
RegisterIndex
Zero-based index of the constant in the table.
RegisterCount
Number of registers that contain data.
Class
Parameter class. See D3DXPARAMETER_CLASS.
Type
Parameter type. See D3DXPARAMETER_TYPE.
Rows
Number of rows.
Columns
Number of columns.
Elements
Number of elements in the array.
StructMembers
Number of structure member sub-parameters.
Bytes
Data size in number of bytes.
DefaultValue
Pointer to the default value.

See Also

D3DXCONSTANTTABLE_DESC


D3DXEVENT_DESC

Describes an animation event.

typedef struct D3DXEVENT_DESC {
    D3DXEVENT_TYPE Type;
    UINT Track;
    DOUBLE StartTime;
    DOUBLE Duration;
    D3DXTRANSITION_TYPE Transition;
    union {
        FLOAT Weight;
        FLOAT Speed;
        DOUBLE Position;
        BOOL Enable;
    };
} D3DXEVENT_DESC, *LPD3DXEVENT_DESC;

Members

Type
Event type, as defined in D3DXEVENT_TYPE.
Track
Event track identifier.
StartTime
Start time of the event in global time.
Duration
Duration of the event in global time.
Transition
Transition style of the event, as defined in D3DXTRANSITION_TYPE.
Weight
Track weight for the event.
Speed
Track speed for the event.
Position
Track position for the event.
Enable
Enable flag.

Requirements

Header: Declared in D3dx9anim.h.


D3DXFLOAT16

Describes a 16-bit floating point vector.

typedef struct D3DXFLOAT16 {
    WORD Value;
} D3DXFLOAT16, *LPD3DXFLOAT16;

Members

Value
The 16-bit data.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXFLOAT16 Extensions, which implement overloaded constructors and assignment, unary, and binary (including equality) operators.


D3DXFLOAT16 Extensions

Supplies operator overloads and type casts for D3DXFLOAT16 structures.

Syntax

typedef struct D3DXFLOAT16
{
#ifdef __cplusplus
public:
    D3DXFLOAT16() {};
    D3DXFLOAT16( FLOAT );
    D3DXFLOAT16( CONST D3DXFLOAT16& );

    // casting
    operator FLOAT ();

    // binary operators
    BOOL operator == ( CONST D3DXFLOAT16& ) const;
    BOOL operator != ( CONST D3DXFLOAT16& ) const;

protected:
#endif //__cplusplus
    WORD value;
} D3DXFLOAT16, *LPD3DXFLOAT16;

Members

For more information about structure members, refer to D3DXFLOAT16.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.


D3DXFONT_DESC

Defines the attributes of a font.

typedef struct D3DXFONT_DESC {
    INT Height;
    UINT Width;
    UINT Weight;
    UINT MipLevels;
    BOOL Italic;
    BYTE CharSet;
    BYTE OutputPrecision;
    BYTE Quality;
    BYTE PitchAndFamily;
    TCHAR FaceName[LF_FACESIZE];
} D3DXFONT_DESC, *LPD3DXFONT_DESC;

Members

Height
Height, in logical units, of the font's character cell or character.
Width
Width, in logical units, of characters in the font.
Weight
Weight of the font in the range from 0 through 1000.
MipLevels
Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created. If the value is 1, the texture space is mapped identically to the screen space.
Italic
Set to TRUE for an Italic font.
CharSet
Character set.
OutputPrecision
Output precision. The output precision defines how closely the output must match the requested font height, width, character orientation, escapement, pitch, and font type.
Quality
Output quality.
PitchAndFamily
Pitch and family of the font.
FaceName
A null-terminated string or characters that specifies the typeface name of the font. The length of the string must not exceed 32 characters, including the terminating null character. If FaceName is an empty string, the first font that matches the other specified attributes will be used. If the compiler settings require Unicode, the data type TCHAR resolves to WCHAR; otherwise, the data type resolves to CHAR. See Remarks.

Remarks

The compiler setting also determines the structure type. If Unicode is defined, the D3DXFONT_DESC structure type resolves to a D3DXFONT_DESCW; otherwise the structure type resolves to a D3DXFONT_DESCA.

Possible values of the above members are given in the GDI LOGFONT structure.

See Also

ID3DXFont::GetDesc


D3DXFRAME

Encapsulates a transform frame in a transformation frame hierarchy.

typedef struct D3DXFRAME {
    LPSTR Name;
    D3DXMATRIX TransformationMatrix;
    LPD3DXMESHCONTAINER pMeshContainer;
    D3DXFRAME * pFrameSibling;
    D3DXFRAME * pFrameFirstChild;
} D3DXFRAME, *LPD3DXFRAME;

Members

Name
Name of the frame.
TransformationMatrix
Transformation matrix.
pMeshContainer
Pointer to the mesh container.
pFrameSibling
Pointer to a sibling frame.
pFrameFirstChild
Pointer to a child frame.

Remarks

An application can derive from this structure to add other data.


D3DXIMAGE_INFO

Returns a description of the original contents of an image file.

typedef struct D3DXIMAGE_INFO {
    UINT Width;
    UINT Height;
    UINT Depth;
    UINT MipLevels;
    D3DFORMAT Format;
    D3DRESOURCETYPE ResourceType;
    D3DXIMAGE_FILEFORMAT ImageFileFormat;
} D3DXIMAGE_INFO, *LPD3DXIMAGE_INFO;

Members

Width
Width of original image in pixels.
Height
Height of original image in pixels.
Depth
Depth of original image in pixels.
MipLevels
Number of mip levels in original image.
Format
A value from the D3DFORMAT enumerated type that most closely describes the data in the original image.
ResourceType
Represents the type of the texture stored in the file. It is either D3DRTYPE_TEXTURE, D3DRTYPE_VOLUMETEXTURE, or D3DRTYPE_CubeTexture.
ImageFileFormat
Represents the format of the image file.


D3DXINTERSECTINFO

Describes a ray-triangle intersection.

typedef struct D3DXINTERSECTINFO {
    DWORD FaceIndex;
    FLOAT U;
    FLOAT V;
    FLOAT Dist;
} D3DXINTERSECTINFO, *LPD3DXINTERSECTINFO;

Members

FaceIndex
Index of the triangle that hit the ray.
U
Barycentric coordinate within the triangle where the ray intersects.
V
Barycentric coordinate within the triangle where the ray intersects.
Dist
Distance along the ray where the intersection occurred.

Remarks

Barycentric coordinates define a point inside a triangle in terms of the triangle's vertices. For a more in-depth description of barycentric coordinates, see Mathworld's Barycentric Coordinates Description.


D3DXKEY_CALLBACK

Describes a callback key for use in key frame animation.

typedef struct D3DXKEY_CALLBACK {
    FLOAT Time;
    LPVOID pCallbackData;
} D3DXKEY_CALLBACK, *LPD3DXKEY_CALLBACK;

Members

Time
Key frame time stamp.
pCallbackData
Pointer to user callback data.


D3DXKEY_QUATERNION

Describes a quaternion key for use in key frame animation. A quaternion key is a quaternion value at a given time.

typedef struct D3DXKEY_QUATERNION {
    FLOAT Time;
    D3DXQUATERNION Value;
} D3DXKEY_QUATERNION, *LPD3DXKEY_QUATERNION;

Members

Time
Time value.
Value
D3DXQUATERNION quaternion that supplies rotation values.


D3DXKEY_VECTOR3

Describes a vector key for use in key frame animation. It specifies a vector at a given time. This is used for scale and translation keys.

typedef struct D3DXKEY_VECTOR3 {
    FLOAT Time;
    D3DXVECTOR3 Value;
} D3DXKEY_VECTOR3, *LPD3DXKEY_VECTOR3;

Members

Time
Key frame time stamp.
Value
D3DXVECTOR3 3D vector that supplies scale and/or translation values.


D3DXMATERIAL

Returns material information saved in Direct3D (.x) files.

typedef struct D3DXMATERIAL {
    D3DMATERIAL9 MatD3D;
    LPSTR pTextureFilename;
} D3DXMATERIAL, *LPD3DXMATERIAL;

Members

MatD3D
D3DMATERIAL9 structure that describes the material properties.
pTextureFilename
Pointer to a string that specifies the file name of the texture.

Remarks

The D3DXLoadMeshFromX and D3DXLoadMeshFromXof functions return an array of D3DXMATERIAL structures that specify the material color and name of the texture for each material in the mesh. The application is then required to load the texture.

The LPD3DXMATERIAL type is defined as a pointer to the D3DXMATERIAL structure.

typedef struct D3DXMATERIAL* LPD3DXMATERIAL;

See Also

D3DXLoadMeshFromX, D3DXLoadMeshFromXof


D3DXMATRIX

Describes a matrix.

typedef struct D3DXMATRIX {
    struct {
        FLOAT _11;
        FLOAT _12;
        FLOAT _13;
        FLOAT _14;
        FLOAT _21;
        FLOAT _22;
        FLOAT _23;
        FLOAT _24;
        FLOAT _31;
        FLOAT _32;
        FLOAT _33;
        FLOAT _34;
        FLOAT _41;
        FLOAT _42;
        FLOAT _43;
        FLOAT _44;
    };
} D3DXMATRIX, *LPD3DXMATRIX;

Members

_11
An element of the first row of the matrix.
_12
An element of the first row of the matrix.
_13
An element of the first row of the matrix.
_14
An element of the first row of the matrix.
_21
An element of the second row of the matrix.
_22
An element of the second row of the matrix.
_23
An element of the second row of the matrix.
_24
An element of the second row of the matrix.
_31
An element of the third row of the matrix.
_32
An element of the third row of the matrix.
_33
An element of the third row of the matrix.
_34
An element of the third row of the matrix.
_41
An element of the fourth row of the matrix.
_42
An element of the fourth row of the matrix.
_43
An element of the fourth row of the matrix.
_44
An element of the fourth row of the matrix.

Remarks

This structure inherits members from the D3DMATRIX structure. C programmers cannot use the D3DXMATRIX structure. They must use the D3DMATRIX structure.

In D3DX, the _34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by -1 instead.

C++ programmers can take advantage of operator overloading and type casting with the D3DXMATRIX Extensions, which implement overloaded constructors and assignment, unary, and binary (including equality) operators.

See Also

D3DMATRIX, Transforms (Direct3D 9)


D3DXMATRIXA16

Defines a 16-byte aligned matrix.

Syntax

typedef struct _D3DXMATRIXA16 : public D3DXMATRIX
{
    _D3DXMATRIXA16();
    _D3DXMATRIXA16( CONST FLOAT * f);
    _D3DXMATRIXA16( CONST D3DMATRIX& m);
    _D3DXMATRIXA16( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                    FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                    FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                    FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );
    void* operator new(size_t s);
    void* operator new[](size_t s);

    // The two operators below are not virtual operators. If you cast
    //   to D3DXMATRIX, do not delete using them
    void operator delete(void* p);
    void operator delete[](void* p);

    struct _D3DXMATRIXA16& operator=(CONST D3DXMATRIX& rhs);
} _D3DXMATRIXA16;

typedef D3DX_ALIGN16 _D3DXMATRIXA16 D3DXMATRIXA16, *LPD3DXMATRIXA16;

Members

_ij
The (i, j) component of the matrix, where i is the row number and j is the column number. For example, _34 means the same as [a34], the component in the third row and fourth column.

Remarks

A 16-byte aligned matrix, when used by D3DX math functions, has been optimized for improved performance on Intel Pentium 4 processors. Matrices are aligned independent of where they are created: on the program stack, in the heap, or in global scope. Alignment is accomplished using __declspec(align(16)), which works with Visual C++ .NET and with Visual C++ 6.0 only when the processor pack is installed. Unfortunately, there is no way to detect the processor pack, so byte alignment is turned on by default only with Visual C++ .NET.

Vectors and quaternions are not byte aligned in D3DX. When using vectors and quaternions with D3DX math functions, use _declspec(align(16)) to generate byte aligned vectors and quaternions, because they will perform significantly better. The definition of _declspec is shown here.

#define D3DX_ALIGN16 __declspec(align(16))

Other compilers interpret D3DXMATRIXA16 as D3DXMATRIX. Using this structure on a compiler that does not actually align the matrix can be problematic because it will not expose bugs that ignore alignment. For example, if a D3DXMATRIXA16 object is inside a structure or class, a memcpy might be done with tight packing (ignoring 16-byte boundaries). This would cause build breaks if the compiler were to sometime add matrix aligning.

C++ programmers can take advantage of operator overloading and type casting with the D3DXMATRIX Extensions, which implement overloaded constructors and assignment, unary, and binary (including equality) operators.

See Also

D3DXMATRIX, Transforms (Direct3D 9)


D3DXMATRIX Extensions

Supplies the following operator overloads and type casts for D3DXMATRIX structures. The _D3DXMATRIXA16 structure provides 16-bit versions of overloads and type casts.

Syntax

#ifdef __cplusplus
typedef struct D3DXMATRIX : public D3DMATRIX
{
public:
    D3DXMATRIX() {};
    D3DXMATRIX( CONST FLOAT * );
    D3DXMATRIX( CONST D3DMATRIX& );
    D3DXMATRIX( CONST D3DXFLOAT16 * );
    D3DXMATRIX( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );

    // access grants
    FLOAT& operator () ( UINT Row, UINT Col );
    FLOAT  operator () ( UINT Row, UINT Col ) const;

    // casting operators
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXMATRIX& operator *= ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator += ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator -= ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator *= ( FLOAT );
    D3DXMATRIX& operator /= ( FLOAT );

    // unary operators
    D3DXMATRIX operator + () const;
    D3DXMATRIX operator - () const;

    // binary operators
    D3DXMATRIX operator * ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator + ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator - ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator * ( FLOAT ) const;
    D3DXMATRIX operator / ( FLOAT ) const;

    friend D3DXMATRIX operator * ( FLOAT, CONST D3DXMATRIX& );

    BOOL operator == ( CONST D3DXMATRIX& ) const;
    BOOL operator != ( CONST D3DXMATRIX& ) const;

} D3DXMATRIX, *LPD3DXMATRIX;

#else //!__cplusplus
typedef struct _D3DMATRIX D3DXMATRIX, *LPD3DXMATRIX;
#endif //!__cplusplus

#ifdef __cplusplus
typedef struct _D3DXMATRIXA16 : public D3DXMATRIX
{
    _D3DXMATRIXA16() {}
    _D3DXMATRIXA16( CONST FLOAT * );
    _D3DXMATRIXA16( CONST D3DMATRIX& );
    _D3DXMATRIXA16( CONST D3DXFLOAT16 * );
    _D3DXMATRIXA16( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                    FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                    FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                    FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );

    // new operators
    void* operator new   ( size_t );
    void* operator new[] ( size_t );

    // delete operators
    void operator delete   ( void* );   // These are NOT virtual; Do not
    void operator delete[] ( void* );   // cast to D3DXMATRIX and delete.

    // assignment operators
    _D3DXMATRIXA16& operator = ( CONST D3DXMATRIX& );

} _D3DXMATRIXA16;

#else //!__cplusplus
typedef D3DXMATRIX  _D3DXMATRIXA16;
#endif //!__cplusplus

Members

For more information about structure members, refer to D3DXMATRIX or D3DXMATRIXA16.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.


D3DXMESHCONTAINER

Encapsulates a mesh object in a transformation frame hierarchy.

typedef struct D3DXMESHCONTAINER {
    LPSTR Name;
    D3DXMESHDATA MeshData;
    LPD3DXMATERIAL pMaterials;
    LPD3DXEFFECTINSTANCE pEffects;
    DWORD NumMaterials;
    DWORD * pAdjacency;
    LPD3DXSKININFO pSkinInfo;
    D3DXMESHCONTAINER * pNextMeshContainer;
} D3DXMESHCONTAINER, *LPD3DXMESHCONTAINER;

Members

Name
Mesh name.
MeshData
Type of data in the mesh. See D3DXMESHDATA.
pMaterials
Array of mesh materials. See D3DXMATERIAL.
pEffects
Pointer to a set of default effect parameters. See D3DXEFFECTINSTANCE.
NumMaterials
Number of materials in the mesh.
pAdjacency
Pointer to an array of three DWORDs per triangle of the mesh that contains adjacency information.
pSkinInfo
Pointer to the skin information interface. See ID3DXSkinInfo.
pNextMeshContainer
Pointer to the next mesh container.

Remarks

An application can derive from this structure to add other data.


D3DXMESHDATA

Mesh data structure.

typedef struct D3DXMESHDATA {
    D3DXMESHDATATYPE Type;
    union {
        LPD3DXMESH pMesh;
        LPD3DXPMESH pPMesh;
        LPD3DXPATCHMESH pPatchMesh;
    };
} D3DXMESHDATA, *LPD3DXMESHDATA;

Members

Type
Defines the mesh data type. See D3DXMESHDATATYPE.
pMesh
Pointer to a mesh. See ID3DXMesh.
pPMesh
Pointer to a progressive mesh. See ID3DXPMesh.
pPatchMesh
Pointer to a patch mesh. See ID3DXPatchMesh.

Requirements

Header: Declared in D3DX9Mesh.h.

See Also

D3DXMESHCONTAINER


D3DXPATCHINFO

Structure that contains the attributes of a patch mesh.

typedef struct D3DXPATCHINFO {
    D3DXPATCHMESHTYPE PatchType;
    D3DDEGREETYPE Degree;
    D3DBASISTYPE Basis;
} D3DXPATCHINFO, *LPD3DXPATCHINFO;

Members

PatchType
The patch type. For information about patch types, see D3DXPATCHMESHTYPE.
Degree
Degree of the curves used to construct the patch. For information about the degrees supported, see D3DDEGREETYPE.
Basis
Type of curve used to construct the patch. For information about the basis types supported, see D3DBASISTYPE.

Remarks

A mesh is a set of faces, each of which is described by a simple polygon. Objects can be created by connecting several meshes together. A patch mesh is constructed from patches. A patch is a four-sided piece of geometry constructed from curves. The type of curve used and the order of the curve can be varied so that the patch surface will fit almost any surface shape.

The following types of patch combinations are supported:

Patch Type | Basis | Degree
Rectangle | Bezier | 2,3,5
Rectangle | B-Spline | 2,3,5
Rectangle | Catmull-Rom | 3
Triangle | Bezier | 2,3,5
N-patch | N/A | 3

See Also

D3DRECTPATCH_INFO, D3DTRIPATCH_INFO, D3DXCreatePatchMesh


D3DXPLANE

Describes a plane.

typedef struct D3DXPLANE {
    FLOAT a;
    FLOAT b;
    FLOAT c;
    FLOAT d;
} D3DXPLANE, *LPD3DXPLANE;

Members

a
The a coefficient of the clipping plane in the general plane equation. See Remarks.
b
The b coefficient of the clipping plane in the general plane equation. See Remarks.
c
The c coefficient of the clipping plane in the general plane equation. See Remarks.
d
The d coefficient of the clipping plane in the general plane equation. See Remarks.

Remarks

The members of the D3DXPLANE structure take the form of the general plane equation. They fit into the general plane equation so that ax + by + cz + dw = 0.

C++ programmers can take advantage of operator overloading and type casting with the D3DXPLANE Extensions which implement overloaded constructors and assignment, unary, and binary (including equality) operators.


D3DXPLANE Extensions

Supplies the following operator overloads and type casts for D3DXPLANE structures.

Syntax

typedef struct D3DXPLANE
{
#ifdef __cplusplus
public:
    D3DXPLANE() {}
    D3DXPLANE( CONST FLOAT* );
    D3DXPLANE( CONST D3DXFLOAT16* );
    D3DXPLANE( FLOAT a, FLOAT b, FLOAT c, FLOAT d );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXPLANE& operator *= ( FLOAT );
    D3DXPLANE& operator /= ( FLOAT );

    // unary operators
    D3DXPLANE operator + () const;
    D3DXPLANE operator - () const;

    // binary operators
    D3DXPLANE operator * ( FLOAT ) const;
    D3DXPLANE operator / ( FLOAT ) const;

    friend D3DXPLANE operator * ( FLOAT, CONST D3DXPLANE& );

    BOOL operator == ( CONST D3DXPLANE& ) const;
    BOOL operator != ( CONST D3DXPLANE& ) const;

#endif //__cplusplus
    FLOAT a, b, c, d;
} D3DXPLANE, *LPD3DXPLANE;

Remarks

For more information about structure members, refer to D3DXPLANE.

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.


D3DXQUATERNION

Describes a quaternion.

typedef struct D3DXQUATERNION {
    FLOAT x;
    FLOAT y;
    FLOAT z;
    FLOAT w;
} D3DXQUATERNION, *LPD3DXQUATERNION;

Members

x
The x-component.
y
The y-component.
z
The z-component.
w
The w-component.

Remarks

Quaternions add a fourth element to the [ x, y, z] values that define a vector, resulting in arbitrary 4D vectors. However, the following illustrates how each element of a unit quaternion relates to an axis-angle rotation (where q represents a unit quaternion (x, y, z, w), axis is normalized, and theta is the desired CCW rotation about the axis):

q.x = sin(theta/2) * axis.x
q.y = sin(theta/2) * axis.y
q.z = sin(theta/2) * axis.z
q.w = cos(theta/2)

C++ programmers can take advantage of operator overloading and type casting with the D3DXQUATERNION Extensions, which implement overloaded constructors and assignment, unary, and binary (including equality) operators.

See Also

Vectors, Vertices, and Quaternions (Direct3D 9)


D3DXQUATERNION Extensions

Supplies the following operator overloads and type casts for D3DXQUATERNION structures.

Syntax

typedef struct D3DXQUATERNION
{
#ifdef __cplusplus
public:
    D3DXQUATERNION() {}
    D3DXQUATERNION( CONST FLOAT * );
    D3DXQUATERNION( CONST D3DXFLOAT16 * );
    D3DXQUATERNION( FLOAT x, FLOAT y, FLOAT z, FLOAT w );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXQUATERNION& operator += ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator -= ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator *= ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator *= ( FLOAT );
    D3DXQUATERNION& operator /= ( FLOAT );

    // unary operators
    D3DXQUATERNION  operator + () const;
    D3DXQUATERNION  operator - () const;

    // binary operators
    D3DXQUATERNION operator + ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator - ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator * ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator * ( FLOAT ) const;
    D3DXQUATERNION operator / ( FLOAT ) const;

    friend D3DXQUATERNION operator * (FLOAT, CONST D3DXQUATERNION& );

    BOOL operator == ( CONST D3DXQUATERNION& ) const;
    BOOL operator != ( CONST D3DXQUATERNION& ) const;

#endif //__cplusplus
    FLOAT x, y, z, w;
} D3DXQUATERNION, *LPD3DXQUATERNION;

Remarks

For more information about structure members, refer to D3DXQUATERNION.

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.


D3DXRTE_DESC

Describes an off-screen render target used by an instance of ID3DXRenderToEnvMap.

typedef struct D3DXRTE_DESC {
    UINT Size;
    UINT MipLevels;
    D3DFORMAT Format;
    BOOL DepthStencil;
    D3DFORMAT DepthStencilFormat;
} D3DXRTE_DESC, *LPD3DXRTE_DESC;

Members

Size
Width and height in pixels.
MipLevels
Maximum level of detail (LOD) number.
Format
Color buffer format.
DepthStencil
Indicates if the z-buffer is needed.
DepthStencilFormat
Format of the depth buffer.

Remarks

This method is used to return the creation parameters used when creating an ID3DXRenderToEnvMap object.


D3DXRTS_DESC

Describes a render surface.

typedef struct D3DXRTS_DESC {
    UINT Width;
    UINT Height;
    D3DFORMAT Format;
    BOOL DepthStencil;
    D3DFORMAT DepthStencilFormat;
} D3DXRTS_DESC, *LPD3DXRTS_DESC;

Members

Width
Width of the render surface, in pixels.
Height
Height of the render surface, in pixels.
Format
Member of the D3DFORMAT enumerated type, describing the pixel format of the render surface.
DepthStencil
If TRUE, the render surface supports a depth-stencil surface; otherwise this member is set to FALSE.
DepthStencilFormat
If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type, describing the depth-stencil format of the render surface.

See Also

ID3DXRenderToSurface::GetDesc


D3DXSHADER_CONSTANTINFO

typedef struct D3DXSHADER_CONSTANTINFO {
    DWORD Name;
    WORD RegisterSet;
    WORD RegisterIndex;
    WORD RegisterCount;
    WORD Reserved;
    DWORD TypeInfo;
    DWORD DefaultValue;
} D3DXSHADER_CONSTANTINFO, *LPD3DXSHADER_CONSTANTINFO;

Members

Name
Offset from the beginning of this structure, in bytes, to the string that contains the constant information.
RegisterSet
Register set. See D3DXREGISTER_SET.
RegisterIndex
The register index.
RegisterCount
Number of registers.
Reserved
Reserved.
TypeInfo
Offset from the beginning of this structure, in bytes, to the string that contains the D3DXSHADER_TYPEINFO information.
DefaultValue
Offset from the beginning of this structure, in bytes, to the string that contains the default value.


D3DXSHADER_CONSTANTTABLE

Helper structure for managing a shader constant table. This can also be done using ID3DXConstantTable.

typedef struct D3DXSHADER_CONSTANTTABLE {
    DWORD Size;
    DWORD Creator;
    DWORD Version;
    DWORD Constants;
    DWORD ConstantInfo;
    DWORD Flags;
    DWORD Target;
} D3DXSHADER_CONSTANTTABLE, *LPD3DXSHADER_CONSTANTTABLE;

Members

Size
Size of the structure. See Remarks.
Creator
Offset from the beginning of this structure, in bytes, to the string that contains the name of the creator.
Version
Shader version.
Constants
Number of constants.
ConstantInfo
Array of constant information, D3DXSHADER_CONSTANTINFO[Constants]. See D3DXSHADER_CONSTANTINFO.
Flags
The D3DXSHADER Flags flags used to compile the shader.
Target
Offset into the string that contains the target.

Remarks

Shader constant information is included in a tab-delimited table of comments. All offsets are measured in bytes from the beginning of the structure. Entries in the constant table are sorted by Creator in ascending order.

A shader constant table can be managed with the ID3DXConstantTable interfaces. Alternatively, you can manage the constant table with D3DXSHADER_CONSTANTTABLE.

This size member is often initialized using the following:

D3DXSHADER_CONSTANTTABLE constantTable;
constantTable.Size = sizeof(D3DXSHADER_CONSTANTTABLE)

See Also

D3DXGetShaderConstantTable


D3DXSHADER_STRUCTMEMBERINFO

A helper structure containing member structure information.

typedef struct D3DXSHADER_STRUCTMEMBERINFO {
    DWORD Name;
    DWORD TypeInfo;
} D3DXSHADER_STRUCTMEMBERINFO, *LPD3DXSHADER_STRUCTMEMBERINFO;

Members

Name
Offset from the beginning of this structure, in bytes, to the string that contains the structure member name.
TypeInfo
Offset from the beginning of this structure, in bytes, to the string that contains the type information. See D3DXSHADER_TYPEINFO.

See Also

D3DXSHADER_TYPEINFO


D3DXSHADER_TYPEINFO

A helper structure containing member type information.

typedef struct D3DXSHADER_TYPEINFO {
    WORD Class;
    WORD Type;
    WORD Rows;
    WORD Columns;
    WORD Elements;
    WORD StructMembers;
    DWORD StructMemberInfo;
} D3DXSHADER_TYPEINFO, *LPD3DXSHADER_TYPEINFO;

Members

Class
Shader object type. See D3DXPARAMETER_CLASS.
Type
Data type. See D3DXPARAMETER_TYPE.
Rows
Number of matrix rows (matrices).
Columns
Number of columns (vectors and matrices).
Elements
Array dimension.
StructMembers
Number of structure members.
StructMemberInfo
Array of structure member information, D3DXSHADER_STRUCTMEMBERINFO[StructMembers]. See D3DXSHADER_STRUCTMEMBERINFO.

Remarks

The type information is part of D3DXSHADER_STRUCTMEMBERINFO.

See Also

D3DXSHADER_CONSTANTINFO


D3DXSHMATERIAL

Spherical harmonic (SH) precomputed radiance transfer (PRT) material characteristics.

typedef struct D3DXSHMATERIAL {
    D3DCOLORVALUE Diffuse;
    BOOL bMirror;
    BOOL bSubSurf;
    FLOAT RelativeIndexOfRefraction;
    D3DCOLORVALUE Absorption;
    D3DCOLORVALUE ReducedScattering;
} D3DXSHMATERIAL, *LPD3DXSHMATERIAL;

Members

Diffuse
Diffuse albedo of the surface. This value is ignored if the object is a mirror.
bMirror
Must be set to FALSE.
bSubSurf
Set to TRUE to enable subsurface scattering; any object that does subsurface scattering cannot be a mirror.
RelativeIndexOfRefraction
Relative index of refraction is the ratio between two absolute indexes of refraction. An index of refraction is the ratio of the sine of the angle of incidence to the sine of the angle of refraction.
Absorption
The absorption coefficient is a parameter to the volume rendering equation used to model light propagation in a participating medium.
ReducedScattering
The reduced scattering coefficient is a parameter to the volume rendering equation used to model light propagation in a participating medium.

Remarks

Non-spectral scenes use the red channel from the materials instead of the luminance value.

For more information about PRT see:

  • Jensen, Henrik Wann, et al. Siggraph Proceedings: A Practical Model for Subsurface Light Transport, 2001.


D3DXSHPRTSPLITMESHCLUSTERDATA

typedef struct D3DXSHPRTSPLITMESHCLUSTERDATA {
    UINT uVertStart;
    UINT uVertLength;
    UINT uFaceStart;
    UINT uFaceLength;
    UINT uClusterStart;
    UINT uClusterLength;
} D3DXSHPRTSPLITMESHCLUSTERDATA, *LPD3DXSHPRTSPLITMESHCLUSTERDATA;

Members

uVertStart
Initial vertex into remapped vertex array.
uVertLength
Number of vertices in this supercluster.
uFaceStart
Initial index into face array.
uFaceLength
Number of faces in this supercluster.
uClusterStart
Initial index into cluster array.
uClusterLength
Number of clusters in this supercluster array.

See Also

D3DXSHPRTCompSplitMeshSC


D3DXSHPRTSPLITMESHVERTDATA

typedef struct D3DXSHPRTSPLITMESHVERTDATA {
    UINT uVertRemap;
    UINT uSubCluster;
    UINT ucVertStatus;
} D3DXSHPRTSPLITMESHVERTDATA, *LPD3DXSHPRTSPLITMESHVERTDATA;

Members

uVertRemap
Vertex in original mesh this corresponds to.
uSubCluster
Cluster index, relative to the supercluster.
ucVertStatus
1 if vertex has valid data, 0 if it is "full".

Remarks

Allocated in D3DXSHPRTCompSplitMeshSC.


D3DXTRACK_DESC

Describes an animation track and specifies blending weight, speed, and position for the track at a given time.

typedef struct D3DXTRACK_DESC {
    D3DXPRIORITY_TYPE Priority;
    FLOAT Weight;
    FLOAT Speed;
    DOUBLE Position;
    BOOL Enable;
} D3DXTRACK_DESC, *LPD3DXTRACK_DESC;

Members

Priority
Priority type, as defined in D3DXPRIORITY_TYPE.
Weight
Weight value. The weight determines the proportion of this track to blend with other tracks.
Speed
Speed value. This is used similarly to a multiplier to scale the period of the track.
Position
Time position of the track, in the local timeframe of its current animation set.
Enable
Track enable/disable. To enable, set to TRUE. To disable, set to FALSE.

Remarks

Tracks with the same priority are blended together, and the two resulting values are then blended using the priority blend factor. A track must have an animation set (stored separately) associated with it.


D3DXVECTOR2

Describes a vector in 2D space.

typedef struct D3DXVECTOR2 {
    FLOAT x;
    FLOAT y;
} D3DXVECTOR2, *LPD3DXVECTOR2;

Members

x
The x-component.
y
The y-component.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXVECTOR2 Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.


D3DXVECTOR2 Extensions

Supplies the following operator overloads and type casts for D3DXVECTOR2 structures. The D3DXVECTOR2_16F structure provides 16-bit versions of overloads and type casts.

Syntax

typedef struct D3DXVECTOR2
{
#ifdef __cplusplus
public:
    D3DXVECTOR2() {};
    D3DXVECTOR2( CONST FLOAT * );
    D3DXVECTOR2( CONST D3DXFLOAT16 * );
    D3DXVECTOR2( FLOAT x, FLOAT y );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR2& operator += ( CONST D3DXVECTOR2& );
    D3DXVECTOR2& operator -= ( CONST D3DXVECTOR2& );
    D3DXVECTOR2& operator *= ( FLOAT );
    D3DXVECTOR2& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR2 operator + () const;
    D3DXVECTOR2 operator - () const;

    // binary operators
    D3DXVECTOR2 operator + ( CONST D3DXVECTOR2& ) const;
    D3DXVECTOR2 operator - ( CONST D3DXVECTOR2& ) const;
    D3DXVECTOR2 operator * ( FLOAT ) const;
    D3DXVECTOR2 operator / ( FLOAT ) const;

    friend D3DXVECTOR2 operator * ( FLOAT, CONST D3DXVECTOR2& );

    BOOL operator == ( CONST D3DXVECTOR2& ) const;
    BOOL operator != ( CONST D3DXVECTOR2& ) const;

public:
#endif //__cplusplus
    FLOAT x, y;
} D3DXVECTOR2, *LPD3DXVECTOR2;

typedef struct D3DXVECTOR2_16F
{
#ifdef __cplusplus
public:
    D3DXVECTOR2_16F() {};
    D3DXVECTOR2_16F( CONST FLOAT * );
    D3DXVECTOR2_16F( CONST D3DXFLOAT16 * );
    D3DXVECTOR2_16F( CONST D3DXFLOAT16 &x, CONST D3DXFLOAT16 &y );

    // casting
    operator D3DXFLOAT16* ();
    operator CONST D3DXFLOAT16* () const;

    // binary operators
    BOOL operator == ( CONST D3DXVECTOR2_16F& ) const;
    BOOL operator != ( CONST D3DXVECTOR2_16F& ) const;

public:
#endif //__cplusplus
    D3DXFLOAT16 x, y;

} D3DXVECTOR2_16F, *LPD3DXVECTOR2_16F;

Remarks

For more information about structure members, refer to D3DXVECTOR2.

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.


D3DXVECTOR3

Describes a vector in three-dimensional (3D) space.

typedef struct D3DXVECTOR3 {
    FLOAT x;
    FLOAT y;
    FLOAT z;
} D3DXVECTOR3, *LPD3DXVECTOR3;

Members

x
The x-component.
y
The y-component.
z
The z-component.

Remarks

This structure inherits the x, y and z members from the D3DVECTOR structure. C programmers cannot use the D3DXVECTOR3 structure. They must use the D3DVECTOR structure.

C++ programmers can take advantage of operator overloading and type casting with the D3DXVECTOR3 Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.


D3DXVECTOR3 Extensions

Supplies the following operator overloads and type casts for D3DXVECTOR3 structures. The D3DXVECTOR3_16F structure provides 16-bit versions of overloads and type casts.

Syntax

#ifdef __cplusplus
typedef struct D3DXVECTOR3 : public D3DVECTOR
{
public:
    D3DXVECTOR3() {};
    D3DXVECTOR3( CONST FLOAT * );
    D3DXVECTOR3( CONST D3DVECTOR& );
    D3DXVECTOR3( CONST D3DXFLOAT16 * );
    D3DXVECTOR3( FLOAT x, FLOAT y, FLOAT z );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR3& operator += ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator -= ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator *= ( FLOAT );
    D3DXVECTOR3& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR3 operator + () const;
    D3DXVECTOR3 operator - () const;

    // binary operators
    D3DXVECTOR3 operator + ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator - ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator * ( FLOAT ) const;
    D3DXVECTOR3 operator / ( FLOAT ) const;

    friend D3DXVECTOR3 operator * ( FLOAT, CONST struct D3DXVECTOR3& );

    BOOL operator == ( CONST D3DXVECTOR3& ) const;
    BOOL operator != ( CONST D3DXVECTOR3& ) const;

} D3DXVECTOR3, *LPD3DXVECTOR3;

#else //!__cplusplus
typedef struct _D3DVECTOR D3DXVECTOR3, *LPD3DXVECTOR3;
#endif //!__cplusplus

typedef struct D3DXVECTOR3_16F
{
#ifdef __cplusplus
public:
    D3DXVECTOR3_16F() {};
    D3DXVECTOR3_16F( CONST FLOAT * );
    D3DXVECTOR3_16F( CONST D3DVECTOR& );
    D3DXVECTOR3_16F( CONST D3DXFLOAT16 * );
    D3DXVECTOR3_16F( CONST D3DXFLOAT16 &x, CONST D3DXFLOAT16 &y, CONST D3DXFLOAT16 &z );

    // casting
    operator D3DXFLOAT16* ();
    operator CONST D3DXFLOAT16* () const;

    // binary operators
    BOOL operator == ( CONST D3DXVECTOR3_16F& ) const;
    BOOL operator != ( CONST D3DXVECTOR3_16F& ) const;

public:
#endif //__cplusplus
    D3DXFLOAT16 x, y, z;

} D3DXVECTOR3_16F, *LPD3DXVECTOR3_16F;

Remarks

For more information about structure members, refer to D3DXVECTOR3.

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.


D3DXVECTOR4

Describes a vector in 4D space.

typedef struct D3DXVECTOR4 {
    FLOAT x;
    FLOAT y;
    FLOAT z;
    FLOAT w;
} D3DXVECTOR4, *LPD3DXVECTOR4;

Members

x
The x-component.
y
The y-component.
z
The z-component.
w
The w-component.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXVECTOR4 Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.


D3DXVECTOR4 Extensions

Supplies the following operator overloads and type casts for D3DXVECTOR4 structures. The D3DXVECTOR4_16F structure provides 16-bit versions of overloads and type casts.

Syntax

typedef struct D3DXVECTOR4
{
#ifdef __cplusplus
public:
    D3DXVECTOR4() {};
    D3DXVECTOR4( CONST FLOAT* );
    D3DXVECTOR4( CONST D3DXFLOAT16 * );
    D3DXVECTOR4( CONST D3DVECTOR& xyz, FLOAT w );
    D3DXVECTOR4( FLOAT x, FLOAT y, FLOAT z, FLOAT w );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR4& operator += ( CONST D3DXVECTOR4& );
    D3DXVECTOR4& operator -= ( CONST D3DXVECTOR4& );
    D3DXVECTOR4& operator *= ( FLOAT );
    D3DXVECTOR4& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR4 operator + () const;
    D3DXVECTOR4 operator - () const;

    // binary operators
    D3DXVECTOR4 operator + ( CONST D3DXVECTOR4& ) const;
    D3DXVECTOR4 operator - ( CONST D3DXVECTOR4& ) const;
    D3DXVECTOR4 operator * ( FLOAT ) const;
    D3DXVECTOR4 operator / ( FLOAT ) const;

    friend D3DXVECTOR4 operator * ( FLOAT, CONST D3DXVECTOR4& );

    BOOL operator == ( CONST D3DXVECTOR4& ) const;
    BOOL operator != ( CONST D3DXVECTOR4& ) const;

public:
#endif //__cplusplus
    FLOAT x, y, z, w;
} D3DXVECTOR4, *LPD3DXVECTOR4;

typedef struct D3DXVECTOR4_16F
{
#ifdef __cplusplus
public:
    D3DXVECTOR4_16F() {};
    D3DXVECTOR4_16F( CONST FLOAT * );
    D3DXVECTOR4_16F( CONST D3DXFLOAT16 * );
    D3DXVECTOR4_16F( CONST D3DXVECTOR3_16F& xyz, CONST D3DXFLOAT16& w );
    D3DXVECTOR4_16F( CONST D3DXFLOAT16& x, CONST D3DXFLOAT16& y, CONST D3DXFLOAT16& z, CONST D3DXFLOAT16& w );

    // casting
    operator D3DXFLOAT16* ();
    operator CONST D3DXFLOAT16* () const;

    // binary operators
    BOOL operator == ( CONST D3DXVECTOR4_16F& ) const;
    BOOL operator != ( CONST D3DXVECTOR4_16F& ) const;

public:
#endif //__cplusplus
    D3DXFLOAT16 x, y, z, w;

} D3DXVECTOR4_16F, *LPD3DXVECTOR4_16F;

Remarks

For more information about structure members, refer to D3DXVECTOR4.

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.


D3DXWeldEpsilons

Specifies tolerance values for each vertex component when comparing vertices to determine if they are similar enough to be welded together.

typedef struct D3DXWeldEpsilons {
    FLOAT Position;
    FLOAT BlendWeights;
    FLOAT Normal;
    FLOAT PSize;
    FLOAT Specular;
    FLOAT Diffuse;
    FLOAT Texcoord[8];
    FLOAT Tangent;
    FLOAT Binormal;
    FLOAT Tess Factor;
} D3DXWeldEpsilons, *LPD3DXWeldEpsilons;

Members

Position
Position
BlendWeights
Blend weight
Normal
Normal
PSize
Point size value
Specular
Specular lighting value
Diffuse
Diffuse lighting value
Texcoord
Eight texture coordinates
Tangent
Tangent
Binormal
Binormal
Tess Factor
Tessellation factor

Remarks

The LPD3DXWeldEpsilons type is defined as a pointer to the D3DXWeldEpsilons structure.

typedef D3DXWELDEPSILONS *LPD3DXWELDEPSILONS;

See Also

D3DXWeldVertices


D3DX Enumerations

This section contains information about the following enumerated types and flags used with D3DX.

  • D3DXCALLBACK_SEARCH_FLAGS
  • D3DXCLEANTYPE
  • D3DXCOMPRESSION_FLAGS
  • D3DXEFFECTDEFAULTTYPE
  • D3DXERR
  • D3DXEVENT_TYPE
  • D3DXIMAGE_FILEFORMAT
  • D3DXIMT FLAGS
  • D3DXINCLUDE_TYPE
  • D3DXMESH
  • D3DXMESHDATATYPE
  • D3DXMESHOPT
  • D3DXMESHSIMP
  • D3DXPARAMETER_CLASS
  • D3DXPARAMETER_TYPE
  • D3DXPATCHMESH
  • D3DXPATCHMESHTYPE
  • D3DXPLAYBACK_TYPE
  • D3DXPRIORITY_TYPE
  • D3DXREGISTER_SET
  • D3DXSHCOMPRESSQUALITYTYPE
  • D3DXSHGPUSIMOPT
  • D3DXTANGENT
  • D3DXTRANSITION_TYPE
  • D3DXUVATLAS
  • D3DXWeldEpsilonsFLAGS
  • MAX_FVF_DECL_SIZE


D3DXCALLBACK_SEARCH_FLAGS

Flags used to obtain callback information.

typedef enum D3DXCALLBACK_SEARCH_FLAGS
{
    D3DXCALLBACK_SEARCH_EXCLUDING_INITIAL_POSITION = 1,
    D3DXCALLBACK_SEARCH_BEHIND_INITIAL_POSITION = 2,
    D3DXEDT_FORCE_DWORD = 0x7fffffff,
} D3DXCALLBACK_SEARCH_FLAGS, *LPD3DXCALLBACK_SEARCH_FLAGS;

Constants

D3DXCALLBACK_SEARCH_EXCLUDING_INITIAL_POSITION
Exclude callbacks located at the initial position from the search.
D3DXCALLBACK_SEARCH_BEHIND_INITIAL_POSITION
Reverse the callback search direction.
D3DXEDT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.


D3DXCLEANTYPE

Defines operations to perform on vertices in preparation for mesh cleaning.

typedef enum D3DXCLEANTYPE
{
    D3DXCLEAN_BACKFACING = 1,
    D3DXCLEAN_BOWTIES = 2,
    D3DXCLEAN_SKINNING = D3DXCLEAN_BACKFACING,
    D3DXCLEAN_OPTIMIZATION = D3DXCLEAN_BACKFACING,
    D3DXCLEAN_SIMPLIFICATION = D3DXCLEAN_BACKFACING | D3DXCLEAN_BOWTIES,
} D3DXCLEANTYPE, *LPD3DXCLEANTYPE;

Constants

D3DXCLEAN_BACKFACING
Merge triangles that share the same vertex indices but have face normals pointing in opposite directions (back-facing triangles). Unless the triangles are not split by adding a replicated vertex, mesh adjacency data from the two triangles may conflict.
D3DXCLEAN_BOWTIES
If a vertex is the apex of two triangle fans (a bowtie) and mesh operations will affect one of the fans, then split the shared vertex into two new vertices. Bowties can cause problems for operations such as mesh simplification that remove vertices, because removing one vertex affects two distinct sets of triangles.
D3DXCLEAN_SKINNING
Use this flag to prevent infinite loops during skinning setup mesh operations.
D3DXCLEAN_OPTIMIZATION
Use this flag to prevent infinite loops during mesh optimization operations.
D3DXCLEAN_SIMPLIFICATION
Use this flag to prevent infinite loops during mesh simplification operations.


D3DXCOMPRESSION_FLAGS

Defines the compression mode used for storing compressed animation set data.

typedef enum D3DXCOMPRESSION_FLAGS
{
    D3DXCOMPRESS_DEFAULT = 0,
    D3DXCOMPRESS_STRONG = 1,
    D3DXCOMPRESS_FORCE_DWORD = 0x7fffffff,
} D3DXCOMPRESSION_FLAGS, *LPD3DXCOMPRESSION_FLAGS;

Constants

D3DXCOMPRESS_DEFAULT
Implements fast compression.
D3DXCOMPRESS_STRONG
Implements slow compression. Typically results in a better quality compressed animation set than if D3DXCOMPRESS_DEFAULT is used.
D3DXCOMPRESS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.


D3DXEFFECTDEFAULTTYPE

Effect data types. The data is contained in the pValue member of D3DXEFFECTDEFAULT.

typedef enum D3DXEFFECTDEFAULTTYPE
{
    D3DXEDT_STRING = 1,
    D3DXEDT_FLOATS = 2,
    D3DXEDT_DWORD = 3,
    D3DXEDT_FORCE_DWORD = 0x7fffffff,
} D3DXEFFECTDEFAULTTYPE, *LPD3DXEFFECTDEFAULTTYPE;

Constants

D3DXEDT_STRING
The data type is a NULL-terminated ASCII text string.
D3DXEDT_FLOATS
The data type is an array of type float. The number of float types in the array is specified by NumBytes in D3DXEFFECTDEFAULT.
D3DXEDT_DWORD
The data type is a DWORD.
D3DXEDT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.


D3DXERR

Errors are represented by negative values and cannot be combined. The following is a list of values that can be returned by methods included with the D3DX utility library. See the individual method descriptions for lists of the values that each can return. These lists are not necessarily comprehensive.

typedef enum D3DXERR
{
    D3DXERR_CANNOTMODIFYINDEXBUFFER,
    D3DXERR_INVALIDMESH,
    D3DXERR_CANNOTATTRSORT,
    D3DXERR_SKINNINGNOTSUPPORTED,
    D3DXERR_TOOMANYINFLUENCES,
    D3DXERR_INVALIDDATA,
    D3DXERR_LOADEDMESHASNODATA,
    D3DXERR_DUPLICATENAMEDFRAGMENT,
    D3DXERR_CANNOTREMOVELASTITEM,
} D3DXERR, *LPD3DXERR;

Constants

D3DXERR_CANNOTMODIFYINDEXBUFFER
The index buffer cannot be modified.
D3DXERR_INVALIDMESH
The mesh is invalid.
D3DXERR_CANNOTATTRSORT
Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
D3DXERR_SKINNINGNOTSUPPORTED
Skinning is not supported.
D3DXERR_TOOMANYINFLUENCES
Too many influences specified.
D3DXERR_INVALIDDATA
The data is invalid.
D3DXERR_LOADEDMESHASNODATA
The mesh has no data.
D3DXERR_DUPLICATENAMEDFRAGMENT
A fragment with that name already exists.
D3DXERR_CANNOTREMOVELASTITEM
The last item cannot be deleted.

Remarks

The facility code _FACDD is used to generate error codes, as in the following macros.

#define _FACDD                  0x876
#define MAKE_DDHRESULT( code )  MAKE_HRESULT( 1, _FACDD, code )
enum _D3DXERR {
    D3DXERR_CANNOTMODIFYINDEXBUFFER = MAKE_DDHRESULT(2900),
    D3DXERR_INVALIDMESH             = MAKE_DDHRESULT(2901),
    ...
    };


D3DXEVENT_TYPE

Describes the type of events that can be keyed by the animation controller.

typedef enum D3DXEVENT_TYPE
{
    D3DXEVENT_TRACKSPEED = 0,
    D3DXEVENT_TRACKWEIGHT = 1,
    D3DXEVENT_TRACKPOSITION = 2,
    D3DXEVENT_TRACKENABLE = 3,
    D3DXEVENT_PRIORITYBLEND = 4,
    D3DXEDT_FORCE_DWORD = 0x7fffffff,
} D3DXEVENT_TYPE, *LPD3DXEVENT_TYPE;

Constants

D3DXEVENT_TRACKSPEED
Track speed.
D3DXEVENT_TRACKWEIGHT
Track weight.
D3DXEVENT_TRACKPOSITION
Track position.
D3DXEVENT_TRACKENABLE
Enable flag.
D3DXEVENT_PRIORITYBLEND
Priority blend value.
D3DXEDT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.


D3DXIMAGE_FILEFORMAT

Describes the supported image file formats. See Remarks for descriptions of these formats.

typedef enum D3DXIMAGE_FILEFORMAT
{
    D3DXIFF_BMP = 0,
    D3DXIFF_JPG = 1,
    D3DXIFF_TGA = 2,
    D3DXIFF_PNG = 3,
    D3DXIFF_DDS = 4,
    D3DXIFF_PPM = 5,
    D3DXIFF_DIB = 6,
    D3DXIFF_HDR = 7,
    D3DXIFF_PFM = 8,
    D3DXIFF_FORCE_DWORD = 0x7fffffff,
} D3DXIMAGE_FILEFORMAT, *LPD3DXIMAGE_FILEFORMAT;

Constants

D3DXIFF_BMP
Windows bitmap (BMP) file format.
D3DXIFF_JPG
Joint Photographics Experts Group (JPEG) compressed file format.
D3DXIFF_TGA
Truevision (Targa, or TGA) image file format.
D3DXIFF_PNG
Portable Network Graphics (PNG) file format.
D3DXIFF_DDS
DirectDraw surface (DDS) file format.
D3DXIFF_PPM
Portable pixmap (PPM) file format.
D3DXIFF_DIB
Windows device-independent bitmap (DIB) file format.
D3DXIFF_HDR
High dynamic range (HDR) file format.
D3DXIFF_PFM
Portable float map file format.
D3DXIFF_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Functions that begin with D3DXLoadxxx support all of the formats listed. Functions that begin with D3DXSavexxx support all but the Truevision (.tga) and portable pixmap (.ppm) formats.

The following table lists the available input and output formats.

File Extension | Description
.bmp | Windows bitmap format. Contains a header that describes the resolution of the device on which the rectangle of pixels was created, the dimensions of the rectangle, the size of the array of bits, a logical palette, and an array of bits that defines the relationship between pixels in the bitmapped image and entries in the logical palette.
.dds | DirectDraw Surface file format. Stores textures, volume textures, and cubic environment maps, with or without mipmap levels, and with or without pixel compression. See DDS File Reference.
.dib | Windows DIB. Contains an array of bits combined with structures that specify width and height of the bitmapped image, color format of the device where the image was created, and resolution of the device used to create that image.
.hdr | HDR format. Encodes each pixel as an RGBE 32-bit color, with 8 bits of mantissa for red, green, and blue, and a shared 8-bit exponent. Each channel is separately compressed with run-length encoding (RLE).
.jpg | JPEG standard. Specifies variable compression of 24-bit RGB color and 8-bit gray-scale Tagged Image File Format (TIFF) image document files.
.pfm | Portable float map format. A raw floating point image format, without any compression. The file header specifies image width, height, monochrome or color, and machine word order. Pixel data is stored as 32-bit floating point values, with 3 values per pixel for color, and one value per pixel for monochrome.
.png | PNG format. A non-proprietary bitmap format using lossless compression.
.ppm | Portable Pixmap format. A binary or ASCII file format for color images that includes image height and width and the maximum color component value.
.tga | Targa or Truevision Graphics Adapter format. Supports depths of 8, 15, 16, 24, and 32 bits, including 8-bit gray scale, and contains optional color palette data, image (x, y) origin and size data, and pixel data.

See Types of Bitmaps (GDI+) for more information on some of these formats.


D3DXIMT FLAGS

Texture wrapping options for IMT computation APIs.

typedef enum D3DXIMT_FLAGS
{
    D3DXIMT_WRAP_U = 1,
    D3DXIMT_WRAP_V = 2,
    D3DXIMT_WRAP_UV = 3,
} D3DXIMT FLAGS, *LPD3DXIMT FLAGS;

Constants

D3DXIMT_WRAP_U
The texture wraps in the U direction.
D3DXIMT_WRAP_V
The texture wraps in the V direction.
D3DXIMT_WRAP_UV
The texture wraps in both the U and V direction.

See Also

D3DXComputeIMTFromSignal, D3DXComputeIMTFromTexture, D3DXComputeIMTFromPerTexelSignal, D3DXComputeIMTFromPerVertexSignal


D3DXINCLUDE_TYPE

Describes the location for the include file.

typedef enum D3DXINCLUDE_TYPE
{
    D3DXINC_LOCAL = 0,
    D3DXINC_SYSTEM = 1,
    D3DXINC_FORCE_DWORD = 0x7fffffff,
} D3DXINCLUDE_TYPE, *LPD3DXINCLUDE_TYPE;

Constants

D3DXINC_LOCAL
Look in the local project for the include file.
D3DXINC_SYSTEM
Look in the system path for the include file.
D3DXINC_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.


D3DXMESH

Flags used to specify creation options for a mesh.

typedef enum D3DXMESH
{
    D3DXMESH_32BIT = 0x001,
    D3DXMESH_DONOTCLIP = 0x002,
    D3DXMESH_POINTS = 0x004,
    D3DXMESH_RTPATCHES = 0x008,
    D3DXMESH_NPATCHES = 0x4000,
    D3DXMESH_VB_SYSTEMMEM = 0x010,
    D3DXMESH_VB_MANAGED = 0x020,
    D3DXMESH_VB_WRITEONLY = 0x040,
    D3DXMESH_VB_DYNAMIC = 0x080,
    D3DXMESH_VB_SOFTWAREPROCESSING = 0x8000,
    D3DXMESH_IB_SYSTEMMEM = 0x100,
    D3DXMESH_IB_MANAGED = 0x200,
    D3DXMESH_IB_WRITEONLY = 0x400,
    D3DXMESH_IB_DYNAMIC = 0x800,
    D3DXMESH_IB_SOFTWAREPROCESSING = 0x10000,
    D3DXMESH_VB_SHARE = 0x1000,
    D3DXMESH_USEHWONLY = 0x2000,
    D3DXMESH_SYSTEMMEM = 0x110,
    D3DXMESH_MANAGED = 0x220,
    D3DXMESH_WRITEONLY = 0x440,
    D3DXMESH_DYNAMIC = 0x880,
    D3DXMESH_SOFTWAREPROCESSING = 0x18000,
} D3DXMESH, *LPD3DXMESH;

Constants

D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. See Remarks.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-patch enhancement using Direct3D.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED usage flag for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_SOFTWAREPROCESSING
Use the D3DUSAGE_SOFTWAREPROCESSING usage flag for vertex buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED usage flag for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_SOFTWAREPROCESSING
Use the D3DUSAGE_SOFTWAREPROCESSING usage flag for index buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers.
D3DXMESH_USEHWONLY
Use hardware processing only. For mixed-mode device, this flag will cause the system to use hardware (if supported in hardware) or will default to software processing.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_SOFTWAREPROCESSING
Equivalent to specifying both D3DXMESH_VB_SOFTWAREPROCESSING and D3DXMESH_IB_SOFTWAREPROCESSING.

Remarks

A 32-bit mesh (D3DXMESH_32BIT) can theoretically support (2^32)-1 faces and vertices. However, allocating memory for a mesh that large on a 32-bit operating system is not practical.


D3DXMESHDATATYPE

Defines the type of mesh data present in D3DXMESHDATA.

typedef enum D3DXMESHDATATYPE
{
    D3DXMESHTYPE_MESH = 0x001,
    D3DXMESHTYPE_PMESH = 0x002,
    D3DXMESHTYPE_PATCHMESH = 0x003,
    D3DXEDT_FORCE_DWORD = 0x7fffffff,
} D3DXMESHDATATYPE, *LPD3DXMESHDATATYPE;

Constants

D3DXMESHTYPE_MESH
The data type is a mesh. See ID3DXMesh.
D3DXMESHTYPE_PMESH
The data type is a progressive mesh. See ID3DXPMesh.
D3DXMESHTYPE_PATCHMESH
The data type is a patch mesh. See ID3DXPatchMesh.
D3DXEDT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

See Also

D3DXMESHDATA


D3DXMESHOPT

Specifies the type of mesh optimization to be performed.

typedef enum D3DXMESHOPT
{
    D3DXMESHOPT_COMPACT = 0x01000000,
    D3DXMESHOPT_ATTRSORT = 0x02000000,
    D3DXMESHOPT_VERTEXCACHE = 0x04000000,
    D3DXMESHOPT_STRIPREORDER = 0x08000000,
    D3DXMESHOPT_IGNOREVERTS = 0x10000000,
    D3DXMESHOPT_DONOTSPLIT = 0x20000000,
    D3DXMESHOPT_DEVICEINDEPENDENT = 0x40000000,
} D3DXMESHOPT, *LPD3DXMESHOPT;

Constants

D3DXMESHOPT_COMPACT
Reorders faces to remove unused vertices and faces.
D3DXMESHOPT_ATTRSORT
Reorders faces to optimize for fewer attribute bundle state changes and enhanced ID3DXBaseMesh::DrawSubset performance.
D3DXMESHOPT_VERTEXCACHE
Reorders faces to increase the cache hit rate of vertex caches.
D3DXMESHOPT_STRIPREORDER
Reorders faces to maximize length of adjacent triangles.
D3DXMESHOPT_IGNOREVERTS
Optimize the faces only; do not optimize the vertices.
D3DXMESHOPT_DONOTSPLIT
While attribute sorting, do not split vertices that are shared between attribute groups.
D3DXMESHOPT_DEVICEINDEPENDENT
Affects the vertex cache size. Using this flag specifies a default vertex cache size that works well on legacy hardware.

Remarks

The D3DXMESHOPT_STRIPREORDER and D3DXMESHOPT_VERTEXCACHE optimization flags are mutually exclusive.

The D3DXMESHOPT_SHAREVB flag has been removed from this enumeration. Use D3DXMESH_VB_SHARE instead, in D3DXMESH.


D3DXMESHSIMP

Specifies simplification options for a mesh.

typedef enum D3DXMESHSIMP
{
    D3DXMESHSIMP_VERTEX = 1,
    D3DXMESHSIMP_FACE = 2,
} D3DXMESHSIMP, *LPD3DXMESHSIMP;

Constants

D3DXMESHSIMP_VERTEX
The mesh will be simplified by the number of vertices specified in the MinValue parameter.
D3DXMESHSIMP_FACE
The mesh will be simplified by the number of faces specified in the MinValue parameter.

See Also

D3DXGeneratePMesh, D3DXSimplifyMesh


D3DXPARAMETER_CLASS

The type of object.

typedef enum D3DXPARAMETER_CLASS
{
    D3DXPC_SCALAR,
    D3DXPC_VECTOR,
    D3DXPC_MATRIX_ROWS,
    D3DXPC_MATRIX_COLUMNS,
    D3DXPC_OBJECT,
    D3DXPC_STRUCT,
    D3DXPC_FORCE_DWORD = 0x7fffffff,
} D3DXPARAMETER_CLASS, *LPD3DXPARAMETER_CLASS;

Constants

D3DXPC_SCALAR
Constant is a scalar.
D3DXPC_VECTOR
Constant is a vector.
D3DXPC_MATRIX_ROWS
Constant is a row major matrix.
D3DXPC_MATRIX_COLUMNS
Constant is a column major matrix.
D3DXPC_OBJECT
Constant is either a texture, shader, or a string.
D3DXPC_STRUCT
Constant is a structure.
D3DXPC_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

See Also

D3DXSHADER_TYPEINFO, D3DXCONSTANT_DESC


D3DXPARAMETER_TYPE

Describes the data contained by the enumeration.

typedef enum D3DXPARAMETER_TYPE
{
    D3DXPT_VOID,
    D3DXPT_BOOL,
    D3DXPT_INT,
    D3DXPT_FLOAT,
    D3DXPT_STRING,
    D3DXPT_TEXTURE,
    D3DXPT_TEXTURE1D,
    D3DXPT_TEXTURE2D,
    D3DXPT_TEXTURE3D,
    D3DXPT_TEXTURECUBE,
    D3DXPT_SAMPLER,
    D3DXPT_SAMPLER1D,
    D3DXPT_SAMPLER2D,
    D3DXPT_SAMPLER3D,
    D3DXPT_SAMPLERCUBE,
    D3DXPT_PIXELSHADER,
    D3DXPT_VERTEXSHADER,
    D3DXPT_PIXELFRAGMENT,
    D3DXPT_VERTEXFRAGMENT,
    D3DXPT_UNSUPPORTED,
    D3DXPT_FORCE_DWORD = 0x7fffffff,
} D3DXPARAMETER_TYPE, *LPD3DXPARAMETER_TYPE;

Constants

D3DXPT_VOID
Parameter is a void pointer.
D3DXPT_BOOL
Parameter is a Boolean. Any non-zero value passed into ID3DXConstantTable::SetBool, ID3DXConstantTable::SetBoolArray, ID3DXConstantTable::SetValue, ID3DXConstantTable::SetVector, or ID3DXConstantTable::SetVectorArray will be mapped to 1 (TRUE) before being written into the constant table; otherwise, the value will be set to 0 in the constant table.
D3DXPT_INT
Parameter is an integer. Any floating-point values passed into ID3DXConstantTable::SetValue, ID3DXConstantTable::SetVector, or ID3DXConstantTable::SetVectorArray will be rounded off (to zero decimal places) before being written into the constant table.
D3DXPT_FLOAT
Parameter is a floating-point number.
D3DXPT_STRING
Parameter is a string.
D3DXPT_TEXTURE
Parameter is a texture.
D3DXPT_TEXTURE1D
Parameter is a 1D texture.
D3DXPT_TEXTURE2D
Parameter is a 2D texture.
D3DXPT_TEXTURE3D
Parameter is a 3D texture.
D3DXPT_TEXTURECUBE
Parameter is a cube texture.
D3DXPT_SAMPLER
Parameter is a sampler.
D3DXPT_SAMPLER1D
Parameter is a 1D sampler.
D3DXPT_SAMPLER2D
Parameter is a 2D sampler.
D3DXPT_SAMPLER3D
Parameter is a 3D sampler.
D3DXPT_SAMPLERCUBE
Parameter is a cube sampler.
D3DXPT_PIXELSHADER
Parameter is a pixel shader.
D3DXPT_VERTEXSHADER
Parameter is a vertex shader.
D3DXPT_PIXELFRAGMENT
Parameter is a pixel shader fragment.
D3DXPT_VERTEXFRAGMENT
Parameter is a vertex shader fragment.
D3DXPT_UNSUPPORTED
Parameter is not supported.
D3DXPT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

See Also

D3DXSHADER_TYPEINFO, D3DXCONSTANT_DESC


D3DXPATCHMESH

Not used. Use D3DXPATCHMESHTYPE instead to specify mesh patch types.

typedef enum D3DXPATCHMESH
{
    D3DXPATCHMESH_DEFAULT = 0,
} D3DXPATCHMESH, *LPD3DXPATCHMESH;

Constants

D3DXPATCHMESH_DEFAULT
Not used.


D3DXPATCHMESHTYPE

Mesh patch types.

typedef enum D3DXPATCHMESHTYPE
{
    D3DXPATCHMESH_RECT = 0x001,
    D3DXPATCHMESH_TRI = 0x002,
    D3DXPATCHMESH_NPATCH = 0x003,
    D3DXPATCHMESH_FORCE_DWORD = 0x7fffffff,
} D3DXPATCHMESHTYPE, *LPD3DXPATCHMESHTYPE;

Constants

D3DXPATCHMESH_RECT
Rectangle patch mesh type.
D3DXPATCHMESH_TRI
Triangle patch mesh type.
D3DXPATCHMESH_NPATCH
N-patch mesh type.
D3DXPATCHMESH_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Triangle patches have three sides and are described in D3DTRIPATCH_INFO. Rectangle patches are four-sided and are described in D3DRECTPATCH_INFO.

See Also

Using Higher-Order Primitives (Direct3D 9)


D3DXPLAYBACK_TYPE

Defines the type of animation set looping modes used for playback.

typedef enum D3DXPLAYBACK_TYPE
{
    D3DXPLAY_LOOP = 0,
    D3DXPLAY_ONCE = 1,
    D3DXPLAY_PINGPONG = 2,
    D3DXEDT_FORCE_DWORD = 0x7fffffff,
} D3DXPLAYBACK_TYPE, *LPD3DXPLAYBACK_TYPE;

Constants

D3DXPLAY_LOOP
The animation repeats endlessly.
D3DXPLAY_ONCE
The animation plays once, and then it stops on the last frame.
D3DXPLAY_PINGPONG
The animation alternates endlessly between playing forward and playing backward.
D3DXEDT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.


D3DXPRIORITY_TYPE

Defines the priority type to which an animation track is assigned.

typedef enum D3DXPRIORITY_TYPE
{
    D3DXPRIORITY_LOW = 0,
    D3DXPRIORITY_HIGH = 1,
    D3DXEDT_FORCE_DWORD = 0x7fffffff,
} D3DXPRIORITY_TYPE, *LPD3DXPRIORITY_TYPE;

Constants

D3DXPRIORITY_LOW
Track should be blended with all the low-priority tracks before the low-priority blend is mixed with the high-priority blend.
D3DXPRIORITY_HIGH
Track should be blended with all the high-priority tracks before the high-priority blend is mixed with the low-priority blend.
D3DXEDT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Tracks with the same priority are blended together, and the two resulting values are then blended using the priority blend factor.


D3DXREGISTER_SET

Data type of the register.

typedef enum D3DXREGISTER_SET
{
    D3DXRS_BOOL,
    D3DXRS_INT4,
    D3DXRS_FLOAT4,
    D3DXRS_SAMPLER,
    D3DXPC_FORCE_DWORD = 0x7fffffff,
} D3DXREGISTER_SET, *LPD3DXREGISTER_SET;

Constants

D3DXRS_BOOL
Boolean value.
D3DXRS_INT4
4D integer number.
D3DXRS_FLOAT4
4D floating-point number.
D3DXRS_SAMPLER
The register contains 4D sampler data.
D3DXPC_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

See Also

D3DXSHADER_CONSTANTINFO, D3DXCONSTANT_DESC


D3DXSHCOMPRESSQUALITYTYPE

Spherical harmonic (SH) compression setting.

typedef enum D3DXSHCOMPRESSQUALITYTYPE
{
    D3DXSHCQUAL_UNCOMPRESSED = 1,
    D3DXSHCQUAL_FASTLOWQUALITY = 1,
    D3DXSHCQUAL_SLOWHIGHQUALITY = 2,
    D3DXSHCQUAL_FORCE_DWORD = 0x7fffffff,
} D3DXSHCOMPRESSQUALITYTYPE, *LPD3DXSHCOMPRESSQUALITYTYPE;

Constants

D3DXSHCQUAL_UNCOMPRESSED
The data is uncompressed.
D3DXSHCQUAL_FASTLOWQUALITY
The data compression is low quality, but is fast to compress.
D3DXSHCQUAL_SLOWHIGHQUALITY
The data compression is high quality, but is slow to compress.
D3DXSHCQUAL_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.


D3DXSHGPUSIMOPT

Describes the resolution of the shadow z-buffer that will be used in Precomputed Radiance Transfer (PRT) direct lighting simulation on the GPU. A higher quality z-buffer can also be specified to reduce noise in the results of the direct lighting simulation, although the simulation will be slower.

typedef enum D3DXSHGPUSIMOPT
{
    D3DXSHGPUSIMOPT_SHADOWRES256 = 1,
    D3DXSHGPUSIMOPT_SHADOWRES512 = 0,
    D3DXSHGPUSIMOPT_SHADOWRES1024 = 2,
    D3DXSHGPUSIMOPT_SHADOWRES2048 = 3,
    D3DXSHGPUSIMOPT_HIGHQUALITY = 4,
    D3DXSHGPUSIMOPT_FORCE_DWORD = 0x7fffffff,
} D3DXSHGPUSIMOPT, *LPD3DXSHGPUSIMOPT;

Constants

D3DXSHGPUSIMOPT_SHADOWRES256
Low resolution simulation. A 256 x 256 pixel texture is used in the simulation to encode the shadow z-buffer.
D3DXSHGPUSIMOPT_SHADOWRES512
Medium resolution simulation. A 512 x 512 pixel texture is used in the simulation to encode the shadow z-buffer. This is the default value.
D3DXSHGPUSIMOPT_SHADOWRES1024
High resolution simulation. A 1024 x 1024 pixel texture is used in the simulation to encode the shadow z-buffer.
D3DXSHGPUSIMOPT_SHADOWRES2048
Highest resolution simulation. A 2048 x 2048 pixel texture is used in the simulation to encode the shadow z-buffer.
D3DXSHGPUSIMOPT_HIGHQUALITY
The simulation is of high precision, regardless of the selected resolution. Setting this value will reduce noise in the results of the direct lighting simulation, although the simulation will be slower. May be combined with one of the resolution values.
D3DXSHGPUSIMOPT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

Only one of the resolution values may be specified, and may be combined with the high-quality value.


D3DXTANGENT

Defines settings used for mesh tangent frame computations.

typedef enum D3DXTANGENT
{
    D3DXTANGENT_WRAP_U = 0x01,
    D3DXTANGENT_WRAP_V = 0x02,
    D3DXTANGENT_WRAP_UV = 0x03,
    D3DXTANGENT_DONT_NORMALIZE_PARTIALS = 0x04,
    D3DXTANGENT_DONT_ORTHOGONALIZE = 0x08,
    D3DXTANGENT_ORTHOGONALIZE_FROM_V = 0x010,
    D3DXTANGENT_ORTHOGONALIZE_FROM_U = 0x020,
    D3DXTANGENT_WEIGHT_BY_AREA = 0x040,
    D3DXTANGENT_WEIGHT_EQUAL = 0x080,
    D3DXTANGENT_WIND_CW = 0x0100,
    D3DXTANGENT_CALCULATE_NORMALS = 0x0200,
    D3DXTANGENT_GENERATE_IN_PLACE = 0x0400,
} D3DXTANGENT, *LPD3DXTANGENT;

Constants

D3DXTANGENT_WRAP_U
Texture coordinate values in the u direction are between 0 and 1. In this case a texture coordinate set will be chosen that minimizes the perimeter of the triangle. See Texture Wrapping (Direct3D 9).
D3DXTANGENT_WRAP_V
Texture coordinate values in the v direction are between 0 and 1. In this case a texture coordinate set will be chosen that minimizes the perimeter of the triangle. See Texture Wrapping (Direct3D 9).
D3DXTANGENT_WRAP_UV
Texture coordinate values in both u and v directions are between 0 and 1. In this case a texture coordinate set will be chosen that minimizes the perimeter of the triangle. See Texture Wrapping (Direct3D 9).
D3DXTANGENT_DONT_NORMALIZE_PARTIALS
Do not normalize partial derivatives with respect to texture coordinates. If not normalized, the scale of the partial derivatives is proportional to the scale of the 3D model divided by the scale of the triangle in (u, v) space. This scale value provides a measure of how much the texture is stretched in a given direction. The resulting vector length is a weighted sum of the lengths of the partial derivatives.
D3DXTANGENT_DONT_ORTHOGONALIZE
Do not transform texture coordinates to orthogonal Cartesian coordinates. Mutually exclusive with D3DXTANGENT_ORTHOGONALIZE_FROM_U and D3DXTANGENT_ORTHOGONALIZE_FROM_V.
D3DXTANGENT_ORTHOGONALIZE_FROM_V
Compute the partial derivative with respect to texture coordinate v independently for each vertex, and then compute the partial derivative with respect to u as the cross product of the partial derivative with respect to v and the normal vector. Mutually exclusive with D3DXTANGENT_DONT_ORTHOGONALIZE and D3DXTANGENT_ORTHOGONALIZE_FROM_U.
D3DXTANGENT_ORTHOGONALIZE_FROM_U
Compute the partial derivative with respect to texture coordinate u independently for each vertex, and then compute the partial derivative with respect to v as the cross product of the normal vector and the partial derivative with respect to u. Mutually exclusive with D3DXTANGENT_DONT_ORTHOGONALIZE and D3DXTANGENT_ORTHOGONALIZE_FROM_V.
D3DXTANGENT_WEIGHT_BY_AREA
Weight the direction of the computed per-vertex normal or partial derivative vector according to the areas of triangles attached to that vertex. Mutually exclusive with D3DXTANGENT_WEIGHT_EQUAL.
D3DXTANGENT_WEIGHT_EQUAL
Compute a unit-length normal vector for each triangle of the input mesh. Mutually exclusive with D3DXTANGENT_WEIGHT_BY_AREA.
D3DXTANGENT_WIND_CW
Vertices are ordered in a clockwise direction around each triangle. The computed normal vector direction is therefore inverted 180 degrees from the direction computed using counterclockwise vertex ordering.
D3DXTANGENT_CALCULATE_NORMALS
Compute the per-vertex normal vector for each triangle of the input mesh, and ignore any normal vectors already in the input mesh.
D3DXTANGENT_GENERATE_IN_PLACE
The results are stored in the original input mesh, and the output mesh is not used.

See Also

D3DXComputeTangentFrameEx


D3DXTRANSITION_TYPE

Defines the transition style between values of a mesh animation.

typedef enum D3DXTRANSITION_TYPE
{
    D3DXTRANSITION_LINEAR = 0x000,
    D3DXTRANSITION_EASEINEASEOUT = 0x001,
    D3DXEDT_FORCE_DWORD = 0x7fffffff,
} D3DXTRANSITION_TYPE, *LPD3DXTRANSITION_TYPE;

Constants

D3DXTRANSITION_LINEAR
Linear transition between values.
D3DXTRANSITION_EASEINEASEOUT
Ease-in, ease-out spline transition between values.
D3DXEDT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

Remarks

The calculation for the ramp from ease in to ease out is calculated as follows:

Q(t) = 2(x - y)t3 + 3(y - x)t2 + x.

where the ramp is a function Q(t) with the following properties:

  • Q(t) is a cubic spline.
  • Q(t) interpolates between x and y as t ranges from 0 to 1.
  • Q(t) is horizontal when t = 0 and t = 1.

Mathematically, this translates into:

Q(t) = At3 + Bt2 + Ct + D (and therefore, Q'(t) = 3At2 + 2Bt + C)
2a) Q(0) = x
2b) Q(1) = y

3a) Q'(0) = 0
3b) Q'(1) = 0

Solving for A, B, C, D:

D = x   (from 2a)
C = 0  (from 3a)
3A + 2B = 0 (from 3b)
A + B = y - x (from 2b and D = x)

Therefore:

A = 2(x - y), B = 3(y - x), C = 0, D = x.


D3DXUVATLAS

Defines options for performing geodesic distance calculations, when fitting a texture to a curved surface. Use this flag to choose between high quality vs fast calculations when computing a texture atlas.

typedef enum _D3DXUVATLAS
{
    D3DXUVATLAS_DEFAULT = 1,
    D3DXUVATLAS_GEODESIC_FAST = 2,
    D3DXUVATLAS_GEODESIC_QUALITY = 3,
} D3DXUVATLAS;

Constants

D3DXUVATLAS_DEFAULT
Meshes with more than 25k faces will have the fast geodasic distance method applied to them while meshes with fewer than 25k faces will have the higher quality geodesic distance method applied to them instead.
D3DXUVATLAS_GEODESIC_FAST
Uses approximations to improve charting speed at the cost of added stretch or more charts being output for the mesh.
D3DXUVATLAS_GEODESIC_QUALITY
Provides better quality charts, but requires more time and memory than fast.


D3DXWeldEpsilonsFLAGS

Options for welding together vertices.

typedef enum D3DXWeldEpsilonsFLAGS
{
    D3DXWeldEpsilons_WELDALL = 1,
    D3DXWeldEpsilons_WELDPARTIALMATCHES = 2,
    D3DXWeldEpsilons_DONOTREMOVEVERTICES = 4,
    D3DXWeldEpsilons_DONOTSPLIT = 8,
} D3DXWeldEpsilonsFLAGS, *LPD3DXWeldEpsilonsFLAGS;

Constants

D3DXWeldEpsilons_WELDALL
Weld together all vertices that are at the same location. Using this flag avoids an epsilon comparison between vertex components.
D3DXWeldEpsilons_WELDPARTIALMATCHES
If a given vertex component is within epsilon, modify partially matched vertices so that both components are identical. If all components are equal, remove one of the vertices.
D3DXWeldEpsilons_DONOTREMOVEVERTICES
Instructs the weld to allow only modifications to vertices and not removal. This flag is valid only if D3DXWeldEpsilons_WELDPARTIALMATCHES is set. It is useful to modify vertices to be equal, but not to allow vertices to be removed.
D3DXWeldEpsilons_DONOTSPLIT
Instructs the weld not to split vertices that are in separate attribute groups. When the ID3DXMesh::Optimize, ID3DXPMesh::Optimize, or ID3DXPMesh::OptimizeBaseLOD methods are called with the D3DXMESHOPT_ATTRSORT flag, then the D3DXMESHOPT_DONOTSPLIT flag will also be set. Setting this flag can slow down software vertex processing.

See Also

D3DXWeldEpsilons, D3DXWeldVertices


MAX_FVF_DECL_SIZE

This constant is the maximum number of vertex declarators for a mesh.

typedef enum
{
    MAX_FVF_DECL_SIZE = MAXD3DDECLLENGTH + 1,
} MAX_FVF_DECL_SIZE;

Constants

MAX_FVF_DECL_SIZE
The maximum number of elements in the vertex declaration. The additional (+1) is for D3DDECL_END.

Remarks

MAXD3DDECLLENGTH is defined as a maximum of 64 (see d3d9types.h). This does not include the "end" marker vertex element.

See Also

ID3DXBaseMesh, IDirect3DVertexDeclaration9::GetDeclaration, ID3DXSPMesh::GetDeclaration, D3DXDeclaratorFromFVF, ID3DXSkinInfo


D3DX Constants

This section contains reference information for the constants defined in D3DX.

  • D3DX_CHANNEL - Texture channel constants
  • D3DXERR - Error constants
  • D3DX_FILTER - Texture filter constants
  • D3DX_NORMALMAP - Normal map generation constants
  • D3DXSHADER Flags - Shader compile options
  • D3DXSPRITE - Sprite render constants
  • Other D3DX Constants - Other constants


D3DX_CHANNEL

The following flags are used to specify which channels in a texture to operate on.

#define | Description
D3DX_CHANNEL_RED | Indicates the red channel should be used.
D3DX_CHANNEL_BLUE | Indicates the blue channel should be used.
D3DX_CHANNEL_GREEN | Indicates the green channel should be used.
D3DX_CHANNEL_ALPHA | Indicates the alpha channel should be used.
D3DX_CHANNEL_LUMINANCE | Indicates the luminances of the red, green, and blue channels should be used.

Constant Information

Header | d3dx9tex.h
Minimum operating system | Windows 98


D3DX_FILTER

The following flags are used to specify which channels in a texture to operate on.

#define | Description
D3DX_FILTER_NONE | No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT | Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_LINEAR | Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_TRIANGLE | Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.
D3DX_FILTER_BOX | Each pixel is computed by averaging a 2x2(x2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_MIRROR_U | Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V | Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W | Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR | Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_DITHER | The resulting image must be dithered using a 4x4 ordered dither algorithm.
D3DX_FILTER_SRGB_IN | Input data is in sRGB (gamma 2.2) color space.
D3DX_FILTER_SRGB_OUT | The output data is in sRGB (gamma 2.2) color space.
D3DX_FILTER_SRGB | Same as specifying D3DX_FILTER_SRGB_IN | D3DX_FILTER_SRGB_OUT.

Each valid filter must contain exactly one of the following flags: D3DX_FILTER_NONE, D3DX_FILTER_POINT, D3DX_FILTER_LINEAR, D3DX_FILTER_TRIANGLE, or D3DX_FILTER_BOX. In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter: D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, D3DX_FILTER_MIRROR_W, D3DX_FILTER_MIRROR, D3DX_FILTER_DITHER, D3DX_FILTER_SRGB_IN, D3DX_FILTER_SRGB_OUT or D3DX_FILTER_SRGB.

Specifying D3DX_DEFAULT for this parameter is usually the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER. However, D3DX_DEFAULT can have different meanings, depending on which method uses the filter. For example:

  • When using D3DXCreateTextureFromFileEx, D3DX_DEFAULT maps to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
  • When using D3DXFilterTexture, D3DX_DEFAULT maps to D3DX_FILTER_BOX if the texture size is a power of two, and D3DX_FILTER_BOX | D3DX_FILTER_DITHER otherwise.

Reference each method to check for information about how D3DX_DEFAULT filter is mapped.

Constant Information

Header | d3dx9tex.h
Minimum operating system | Windows 98


D3DX_NORMALMAP

Normal maps generation constants.

#define | Description
D3DX_NORMALMAP_MIRROR_U | Indicates that pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_NORMALMAP_MIRROR_V | Indicates that pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_NORMALMAP_MIRROR | Same as specifying D3DX_NORMALMAP_MIRROR_U | D3DX_NORMALMAP_MIRROR_V.
D3DX_NORMALMAP_INVERTSIGN | Inverts the direction of each normal.
D3DX_NORMALMAP_COMPUTE_OCCLUSION | Computes the per-pixel occlusion term and encodes it into the alpha. An alpha of 1 means that the pixel is not obscured in any way, and an alpha of 0 means that the pixel is completely obscured.

Constant Information

Header | d3dx9tex.h
Minimum operating system | Windows 98

See Also

D3DXComputeNormalMap


D3DXSHADER Flags

The following flags are used for parsing, compiling, or assembling shaders:

  • Parser Flags
  • Compiler Flags
  • Assembler Flags
  • Remarks

Parser Flags

Parse time flags are only used by the effect system (before effect compilation) when you create an effect compiler. For example, you could create a compiler object with D3DXSHADER_PACKMATRIX_COLUMNMAJOR, and then use that compiler object repeatedly with different compiler flags to generate specialized code.

#define | Description
D3DXSHADER_PACKMATRIX_COLUMNMAJOR | Unless explicitly specified, matrices will be packed in column-major order (each vector will be in a single column) when passed to and from the shader. This is generally more efficient because it allows vector-matrix multiplication to be performed using a series of dot products.
D3DXSHADER_PACKMATRIX_ROWMAJOR | Unless explicitly specified, matrices will be packed in row-major order (each vector will be in a single row) when passed to or from the shader.

The effect system will use Parser Flags when called by the following functions:

  • D3DXCompileShader
  • D3DXCompileShaderFromFile
  • D3DXCompileShaderFromResource
  • ID3DXEffectCompiler::CompileEffect

Compiler Flags

The DirectX 10 HLSL compiler is now the default compiler. See DirectX 10 HLSL Compiler (Direct3D 10) for details.

The following table details the flags available in Direct3D 9 and Direct3D 10.

#define | fxc switch | Description | Direct3D 9 | Direct3D 10
D3DXSHADER_AVOID_FLOW_CONTROL | /Gfa | This is a hint to the compiler to avoid using flow-control instructions. | Yes | Yes
D3DXSHADER_DEBUG | /Zi | Insert debug filename, line numbers, and type and symbol information during shader compile. | Yes | Yes
D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY | /Gec | Compile ps_1_x shaders as ps_2_0. Effects that specify ps_1_x targets will instead compile to ps_2_0 targets because this is the minimum shader version supported by the DirectX 10 shader compiler. This flag has no effect when used with higher level compile targets. | No | Yes
D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT | N/A | Force the compiler to compile against the next highest available software target for pixel shaders. This flag also turns optimizations off and debugging on. | Yes | Yes
D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT | N/A | Force the compiler to compile against the next highest available software target for vertex shaders. This flag also turns optimizations off and debugging on. | Yes | Yes
D3DXSHADER_IEEE_STRICTNESS | /Gis | Disable optimizations that may cause the output of a compiled shader program to differ from the output of a program compiled with the DirectX 9 shader compiler due to small precision erros in floating point math. | No | Yes
D3DXSHADER_NO_PRESHADER | /Op | Disables preshaders. The compiler will not pull out static expressions for evaluation on the host CPU. Additionally, the compiler will not loft any expressions when compiling stand-alone functions. | Yes | Yes
D3DXSHADER_OPTIMIZATION_LEVEL0 | /O0 | Lowest optimization level. May produce slower code but will do so more quickly. This may be useful in a highly iterative shader development cycle. | No | Yes
D3DXSHADER_OPTIMIZATION_LEVEL1 | /O1 | Second lowest optimization level. | No | Yes
D3DXSHADER_OPTIMIZATION_LEVEL2 | /O2 | Second highest optimization level. | No | Yes
D3DXSHADER_OPTIMIZATION_LEVEL3 | /O3 | Highest optimization level. Will produce best possible code but may take significantly longer to do so. This will be useful for final builds of an application where performance is the most important factor. | No | Yes
D3DXSHADER_PARTIALPRECISION | /Gpp | Force all computations in the resulting shader to occur at partial precision. This may result in faster evaluation of shaders on some hardware. | Yes | Yes
D3DXSHADER_PREFER_FLOW_CONTROL | /Gfp | This is a hint to the compiler to prefer using flow-control instructions. | Yes | Yes
D3DXSHADER_SKIPOPTIMIZATION | /Od | Instruct the compiler to skip optimization steps during code generation. Unless you are trying to isolate a problem in your code and you suspect the compiler, using this option is not recommended. | Yes | Yes
D3DXSHADER_SKIPVALIDATION | /Vd | Do not validate the generated code against known capabilities and constraints. This option is recommended only when compiling shaders that are known to work (that is, shaders that have compiled before without this option). Shaders are always validated by the runtime before they are set to the device. | Yes | Yes
D3DXSHADER_USE_LEGACY_D3DX9_31_DLL | /LD | Enable the use of the original Direct3D 9 HLSL compiler. OCT2006_d3dx9_31_x86.cab or OCT2006_d3dx9_31_x64.cab must be included as part of the applications redist. This flag is required to compile ps_1_x shaders without using the promotion flag to ps_2_0. Specifying this flag when obtaining an ID3DXEffectCompiler interface causes subsequent calls to ID3DXEffectCompiler::CompileEffect and ID3DXEffectCompiler::CompileShader through this object to use the legacy compiler. | Yes | No

The effect system will use Compiler Flags when called by the following functions:

  • D3DXCompileShader (or D3DXCompileShaderFromFile or D3DXCompileShaderFromResource)
  • ID3DXEffectCompiler::CompileEffect (or ID3DXEffectCompiler::CompileShader)

In addition, you can use compiler flags when creating an effect by calling D3DXCreateEffect (or D3DXCreateEffectFromFile or D3DXCreateEffectFromResource).

  • If you pass in an uncompiled .fx file, the effect system will use the flag input parameter during compilation.
  • If you pass in a compiled effect, the effect system will ignore the compiler flags since they are not needed to load the effect.

Assembler Flags

Assembler flags are used by the effect system to optimize shader and effect assembly code.

#define | Description
D3DXSHADER_DEBUG | Insert debug filename, line numbers, and type and symbol information during shader compile.
D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT | Force the compiler to compile against the next highest available software target for pixel shaders. This flag also turns optimizations off and debugging on.
D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT | Force the compiler to compile against the next highest available software target for vertex shaders. This flag also turns optimizations off and debugging on.
D3DXSHADER_SKIPVALIDATION | Do not validate the generated code against known capabilities and constraints. This option is recommended only when compiling shaders that are known to work (that is, shaders that have compiled before without this option). Shaders are always validated by the runtime before they are set to the device.

The effect system will use Assembler Flags when called by the following functions:

  • D3DXAssembleShader
  • D3DXAssembleShaderFromFile
  • D3DXAssembleShaderFromResource

Remarks

Applying Compiler Flags or Assembler Flags to the incorrect API will fail shader validation. Check the Direct3D error code return value from the function (with the DirectX Error Lookup Tool) to help track down this error.


D3DXSPRITE

The following flags are used to specify sprite rendering options to the flags parameter in the ID3DXSprite::Begin method:

#define | Description
D3DXSPRITE_DONOTSAVESTATE | The device state is not to be saved or restored when ID3DXSprite::Begin or ID3DXSprite::End is called.
D3DXSPRITE_DONOTMODIFY_RENDERSTATE | The device render state is not to be changed when ID3DXSprite::Begin is called. The device is assumed to be in a valid state to draw vertices containing UsageIndex = 0 in the D3DDECLUSAGE_POSITION, D3DDECLUSAGE_TEXCOORD, and D3DDECLUSAGE_COLOR data.
D3DXSPRITE_OBJECTSPACE | The world, view, and projection transforms are not modified. The transforms currently set to the device are used to transform the sprites when the batched sprites are drawn (when ID3DXSprite::Flush or ID3DXSprite::End is called). If this flag is not specified, then world, view, and projection transforms are modified so that sprites are drawn in screen-space coordinates.
D3DXSPRITE_BILLBOARD | Each sprite will be rotated about its center so that it is facing the viewer. ID3DXSprite::SetWorldViewLH or ID3DXSprite::SetWorldViewRH must be called first.
D3DXSPRITE_ALPHABLEND | Enables alpha blending with D3DRS_ALPHATESTENABLE set to TRUE (for nonzero alpha). D3DBLEND_SRCALPHA will be the source blend state, and D3DBLEND_INVSRCALPHA will be the destination blend state in calls to IDirect3DDevice9::SetRenderState. See Alpha Blending State (Direct3D 9). ID3DXFont expects this flag to be set when drawing text.
D3DXSPRITE_SORT_TEXTURE | Sort sprites by texture prior to drawing. This can improve performance when drawing non-overlapping sprites of uniform depth. You may also combine D3DXSPRITE_SORT_TEXTURE with either D3DXSPRITE_SORT_DEPTH_FRONTTOBACK or D3DXSPRITE_SORT_DEPTH_BACKTOFRONT. This will sort the list of sprites by depth first and texture second.
D3DXSPRITE_SORT_DEPTH_FRONTTOBACK | Sprites are sorted by depth in front-to-back order prior to drawing. This procedure is recommended when drawing opaque sprites of varying depths. You may combine D3DXSPRITE_SORT_DEPTH_FRONTTOBACK with D3DXSPRITE_SORT_TEXTURE to sort first by depth, and second by texture.
D3DXSPRITE_SORT_DEPTH_BACKTOFRONT | Sprites are sorted by depth in back-to-front order prior to drawing. This procedure is recommended when drawing transparent sprites of varying depths. You may combine D3DXSPRITE_SORT_DEPTH_BACKTOFRONT with D3DXSPRITE_SORT_TEXTURE to sort first by depth, and second by texture.
D3DXSPRITE_DO_NOT_ADDREF_TEXTURE | Disables calling AddRef() on every draw, and Release() on Flush() for better performance.

Constant Information

Header | d3dx9core.h
Minimum operating system | Windows 98


Other D3DX Constants

Other D3DX constants include the following:

16-Bit Floating Point Numbers

#define | Description
D3DX_16F_DIG | Number of decimal digits of precision
D3DX_16F_EPSILON | Smallest such that 1.0 + epsilon != 1.0
D3DX_16F_MANT_DIG | Number of bits in mantissa
D3DX_16F_MAX | Maximum value
D3DX_16F_MAX_10_EXP | Maximum decimal exponent
D3DX_16F_MAX_EXP | Maximum binary exponent
D3DX_16F_MIN | Minimum positive value
D3DX_16F_MIN_10_EXP | Minimum decimal exponent
D3DX_16F_MIN_EXP | Minimum binary exponent
D3DX_16F_RADIX | Exponent radix
D3DX_16F_ROUNDS | Addition rounding: near
D3DX_1BYPI | 1/pi
D3DX_PI | pi
D3DX_DEFAULT_FLOAT | Maximum float value

These #defines are declared in d3dx9.h and d3dx9math.h.

PRT Constants

#define | Description
D3DXSH_MINORDER | Lowest allowable order of the simulation.
D3DXSH_MAXORDER | Highest allowable order of the simulation.

These #defines are declared in d3dx9math.h. For more about PRT, see Precomputed Radiance Transfer (Direct3D 9).

Texture Constants

#define | Description
D3DFMT_FROM_FILE | Take the format exactly from a file.
D3DX_DEFAULT | A default value.
D3DX_DEFAULT_NONPOW2 | Do not round up numbers such as width or height to a power of two.
D3DX_FROM_FILE | Take the texture dimensions exactly from a file.

These #defines are declared in d3dx9.h.

Other D3DX Constants

The UNUSED16 and D3DX_VERSION constants defined in D3dx9mesh.h and D3dx9core.h are used internally. Do not use these constants.


HLSL Shader Reference (Direct3D 9 HLSL)

This page has been deprecated. See the HLSL Reference for DirectX.


Variable Declaration Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Basic Types (Direct3D 9 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Vector Type Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Matrix Type Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Shader Type Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Sampler Type Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Struct Type Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


User-Defined Type Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Flow-Control Statement Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Flow Control (DirectX HLSL).


Function Declaration Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Functions (DirectX HLSL).


Function Parameter-List Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Functions (DirectX HLSL).


Statement Block Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Statements (DirectX HLSL).


Shader Semantic Syntax (Direct3D 9 HLSL)

This page has been deprecated. See Variables (DirectX HLSL).


Fragment Declaration Syntax (Direct3D 9 HLSL)

Each HLSL function can be converted into a shader fragment with the addition of a fragment declaration.

Syntax

fragmentKeyword FragmentName = compile_fragment shaderProfile FunctionName();

where:

fragmentKeyword | Required keyword. Either pixelfragment or vertexfragment.
FragmentName | An ASCII text string that specifies the compiled fragment name.
compile_fragment | Required keyword.
shaderProfile | The shader model to compile against. Any valid vertex shader profile (see D3DXGetVertexShaderProfile) or pixel shader profile (see D3DXGetPixelShaderProfile).
FunctionName() | The shader function name, followed by parentheses.

Shared fragment parameters are marked by adding an 'r_' prefix to their semantic. Here is an example of a vertex shader fragment declaration from the FragmentLinker Sample:

void AmbientDiffuse( float3 vPosWorld: r_PosWorld,
                     float3 vNormalWorld: r_NormalWorld,
                     out float4 vColor: COLOR0 )
{
    // Compute the light vector
    float3 vLight = normalize( g_vLightPosition - vPosWorld );

    // Compute the ambient and diffuse components of illumination
    vColor = g_vLightColor * g_vMaterialAmbient;
    vColor += g_vLightColor * g_vMaterialDiffuse * saturate( dot( vLight, vNormalWorld ) );
}
vertexfragment AmbientDiffuseFragment = compile_fragment vs_1_1 AmbientDiffuse();

In this example, the r_PosWorld and r_NormalWorld semantics identify that these two parameters are shared parameters among other fragments.


Appendix (Direct3D 9 HLSL)

This page has been deprecated. See Appendix (DirectX HLSL).


HLSL Intrinsic Functions

This page has been deprecated. See Intrinsic Functions (DirectX HLSL).


abs (Direct3D 9 HLSL)

This page has been deprecated. See abs (DirectX HLSL).


acos (Direct3D 9 HLSL)

This page has been deprecated. See acos (DirectX HLSL).


all (Direct3D 9 HLSL)

This page has been deprecated. See all (DirectX HLSL).


any (Direct3D 9 HLSL)

This page has been deprecated. See any (DirectX HLSL).


asin (Direct3D 9 HLSL)

This page has been deprecated. See asin (DirectX HLSL).


atan (Direct3D 9 HLSL)

This page has been deprecated. See atan (DirectX HLSL).


atan2 (Direct3D 9 HLSL)

This page has been deprecated. See atan2 (DirectX HLSL).


ceil (Direct3D 9 HLSL)

This page has been deprecated. See ceil (DirectX HLSL).


clamp (Direct3D 9 HLSL)

This page has been deprecated. See clamp (DirectX HLSL).


clip (Direct3D 9 HLSL)

This page has been deprecated. See clip (DirectX HLSL).


cos (Direct3D 9 HLSL)

This page has been deprecated. See cos (DirectX HLSL).


cosh (Direct3D 9 HLSL)

This page has been deprecated. See cosh (DirectX HLSL).


cross (Direct3D 9 HLSL)

This page has been deprecated. See cross (DirectX HLSL).


D3DCOLORtoUBYTE4 (Direct3D 9 HLSL)

This page has been deprecated. See D3DCOLORtoUBYTE4 (DirectX HLSL).


ddx (Direct3D 9 HLSL)

This page has been deprecated. See ddx (DirectX HLSL).


ddy (Direct3D 9 HLSL)

This page has been deprecated. See ddy (DirectX HLSL).


degrees (Direct3D 9 HLSL)

This page has been deprecated. See degrees (DirectX HLSL).


determinant (Direct3D 9 HLSL)

This page has been deprecated. See determinant (DirectX HLSL).


distance (Direct3D 9 HLSL)

This page has been deprecated. See distance (DirectX HLSL).


dot (Direct3D 9 HLSL)

This page has been deprecated. See dot (DirectX HLSL).


exp (Direct3D 9 HLSL)

This page has been deprecated. See exp (DirectX HLSL).


exp2 (Direct3D 9 HLSL)

This page has been deprecated. See exp2 (DirectX HLSL).


faceforward (Direct3D 9 HLSL)

This page has been deprecated. See faceforward (DirectX HLSL).


floor (Direct3D 9 HLSL)

This page has been deprecated. See floor (DirectX HLSL).


fmod (Direct3D 9 HLSL)

This page has been deprecated. See fmod (DirectX HLSL).


frac (Direct3D 9 HLSL)

This page has been deprecated. See frac (DirectX HLSL).


frexp (Direct3D 9 HLSL)

This page has been deprecated. See frexp (DirectX HLSL).


fwidth (Direct3D 9 HLSL)

This page has been deprecated. See fwidth (DirectX HLSL).


isfinite (Direct3D 9 HLSL)

This page has been deprecated. See isfinite (DirectX HLSL).


isinf (Direct3D 9 HLSL)

This page has been deprecated. See isinf (DirectX HLSL).


isnan (Direct3D 9 HLSL)

This page has been deprecated. See isnan (DirectX HLSL).


ldexp (Direct3D 9 HLSL)

This page has been deprecated. See ldexp (DirectX HLSL).


length (Direct3D 9 HLSL)

This page has been deprecated. See length (DirectX HLSL).


lerp (Direct3D 9 HLSL)

This page has been deprecated. See lerp (DirectX HLSL).


lit (Direct3D 9 HLSL)

This page has been deprecated. See lit (DirectX HLSL).


log (Direct3D 9 HLSL)

This page has been deprecated. See log (DirectX HLSL).


log2 (Direct3D 9 HLSL)

This page has been deprecated. See log2 (DirectX HLSL).


log10 (Direct3D 9 HLSL)

This page has been deprecated. See log10 (DirectX HLSL).


max (Direct3D 9 HLSL)

This page has been deprecated. See max (DirectX HLSL).


min (Direct3D 9 HLSL)

This page has been deprecated. See min (DirectX HLSL).


modf (Direct3D 9 HLSL)

This page has been deprecated. See modf (DirectX HLSL).


mul (Direct3D 9 HLSL)

This page has been deprecated. See mul (DirectX HLSL).


noise (Direct3D 9 HLSL)

This page has been deprecated. See noise (DirectX HLSL).


normalize (Direct3D 9 HLSL)

This page has been deprecated. See normalize (DirectX HLSL).


pow (Direct3D 9 HLSL)

This page has been deprecated. See pow (DirectX HLSL).


radians (Direct3D 9 HLSL)

This page has been deprecated. See radians (DirectX HLSL).


reflect (Direct3D 9 HLSL)

This page has been deprecated. See reflect (DirectX HLSL).


refract (Direct3D 9 HLSL)

This page has been deprecated. See refract (DirectX HLSL).


round (Direct3D 9 HLSL)

This page has been deprecated. See round (DirectX HLSL).


rsqrt (Direct3D 9 HLSL)

This page has been deprecated. See rsqrt (DirectX HLSL).


saturate (Direct3D 9 HLSL)

This page has been deprecated. See saturate (DirectX HLSL).


sign (Direct3D 9 HLSL)

This page has been deprecated. See sign (DirectX HLSL).


sin (Direct3D 9 HLSL)

This page has been deprecated. See sin (DirectX HLSL).


sincos (Direct3D 9 HLSL)

This page has been deprecated. See sincos (DirectX HLSL).


sinh (Direct3D 9 HLSL)

This page has been deprecated. See sinh (DirectX HLSL).


smoothstep (Direct3D 9 HLSL)

This page has been deprecated. See smoothstep (DirectX HLSL).


sqrt (Direct3D 9 HLSL)

This page has been deprecated. See sqrt (DirectX HLSL).


step (Direct3D 9 HLSL)

This page has been deprecated. See step (DirectX HLSL).


tan (Direct3D 9 HLSL)

This page has been deprecated. See tan (DirectX HLSL).


tanh (Direct3D 9 HLSL)

This page has been deprecated. See tanh (DirectX HLSL).


tex1D (Direct3D 9 HLSL)

This page has been deprecated. See tex1D (DirectX HLSL).


tex1Dbias (Direct3D 9 HLSL)

This page has been deprecated. See tex1Dbias (DirectX HLSL).


tex1Dlod (Direct3D 9 HLSL)

This page has been deprecated. See tex1Dlod (DirectX HLSL).


tex1Dgrad (Direct3D 9 HLSL)

This page has been deprecated. See tex1Dgrad (DirectX HLSL).


tex1Dproj (Direct3D 9 HLSL)

This page has been deprecated. See tex1Dproj (DirectX HLSL).


tex2D (Direct3D 9 HLSL)

This page has been deprecated. See tex2D (DirectX HLSL).


tex2Dbias (Direct3D 9 HLSL)

This page has been deprecated. See tex2Dbias (DirectX HLSL).


tex2Dlod (Direct3D 9 HLSL)

This page has been deprecated. See tex2Dlod (DirectX HLSL).


tex2Dgrad (Direct3D 9 HLSL)

This page has been deprecated. See tex2Dgrad (DirectX HLSL).


tex2Dproj (Direct3D 9 HLSL)

This page has been deprecated. See tex2Dproj (DirectX HLSL).


tex3D (Direct3D 9 HLSL)

This page has been deprecated. See tex3D (DirectX HLSL).


tex3Dbias (Direct3D 9 HLSL)

This page has been deprecated. See tex3Dbias (DirectX HLSL).


tex3Dlod (Direct3D 9 HLSL)

This page has been deprecated. See tex3Dlod (DirectX HLSL).


tex3Dgrad (Direct3D 9 HLSL)

This page has been deprecated. See tex3Dgrad (DirectX HLSL).


tex3Dproj (Direct3D 9 HLSL)

This page has been deprecated. See tex3Dproj (DirectX HLSL).


texCUBE (Direct3D 9 HLSL)

This page has been deprecated. See texCUBE (DirectX HLSL).


texCUBEbias (Direct3D 9 HLSL)

This page has been deprecated. See texCUBEbias (DirectX HLSL).


texCUBElod (Direct3D 9 HLSL)

This page has been deprecated. See texCUBElod (DirectX HLSL).


texCUBEgrad (Direct3D 9 HLSL)

This page has been deprecated. See texCUBEgrad (DirectX HLSL).


texCUBEproj (Direct3D 9 HLSL)

This page has been deprecated. See texCUBEproj (DirectX HLSL).


transpose (Direct3D 9 HLSL)

This page has been deprecated. See transpose (DirectX HLSL).


Effect Reference

Effects are a higher level abstraction that take advantage of vertex and pixel shaders to encapsulate rendering effects. Effects can be written with the high-level language or with the shader assembly language.

Here are the API topics.

  • Effect Interfaces
  • Effect Functions
  • Effect Structures
  • Effect Constants
  • Effect Format
  • DirectX Standard Annotations and Semantics Reference

As an alternative to using the API to create effects, you can also use a command line compile tool. See Effect-Compiler Tool.


Effect Interfaces

Effects are implemented with the following interfaces.

Interface | Derives from
ID3DXBaseEffect | IUnknown
ID3DXEffect | ID3DXBaseEffect
ID3DXEffectCompiler | ID3DXBaseEffect
ID3DXEffectPool | IUnknown
ID3DXEffectStateManager | IUnknown
ID3DXInclude | None


ID3DXBaseEffect

Provides methods for getting and setting effect parameters such as constants, functions, shaders, and techniques.

ID3DXBaseEffect
ID3DXEffect
ID3DXEffectCompiler

ID3DXBaseEffect Members

Method | Description
ID3DXBaseEffect::GetAnnotation | Gets the handle of an annotation.
ID3DXBaseEffect::GetAnnotationByName | Gets the handle of an annotation by looking up its name.
ID3DXBaseEffect::GetBool | Gets a BOOL value.
ID3DXBaseEffect::GetBoolArray | Gets an array of BOOL values.
ID3DXBaseEffect::GetDesc | Gets the effect description.
ID3DXBaseEffect::GetFloat | Gets a floating point value.
ID3DXBaseEffect::GetFloatArray | Gets an array of floating point values.
ID3DXBaseEffect::GetFunction | Gets the handle of a function.
ID3DXBaseEffect::GetFunctionByName | Gets the handle of a function by looking up its name.
ID3DXBaseEffect::GetFunctionDesc | Gets a function description.
ID3DXBaseEffect::GetInt | Gets an integer.
ID3DXBaseEffect::GetIntArray | Gets an array of integers.
ID3DXBaseEffect::GetMatrix | Gets a nontransposed matrix.
ID3DXBaseEffect::GetMatrixArray | Gets an array of nontransposed matrices.
ID3DXBaseEffect::GetMatrixPointerArray | Gets an array of pointers to nontransposed matrices.
ID3DXBaseEffect::GetMatrixTranspose | Gets a transposed matrix.
ID3DXBaseEffect::GetMatrixTransposeArray | Gets an array of transposed matrices.
ID3DXBaseEffect::GetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
ID3DXBaseEffect::GetParameter | Gets the handle of a top-level parameter or a structure member parameter.
ID3DXBaseEffect::GetParameterByName | Gets the handle of a top-level parameter or a structure member parameter by looking up its name.
ID3DXBaseEffect::GetParameterBySemantic | Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic with a case-insensitive search.
ID3DXBaseEffect::GetParameterDesc | Gets a parameter or annotation description.
ID3DXBaseEffect::GetParameterElement | Get the handle of an array element parameter.
ID3DXBaseEffect::GetPass | Gets the handle of a pass.
ID3DXBaseEffect::GetPassByName | Gets the handle of a pass by looking up its name.
ID3DXBaseEffect::GetPassDesc | Gets a pass description.
ID3DXBaseEffect::GetPixelShader | Gets a pixel shader.
ID3DXBaseEffect::GetString | Gets a string.
ID3DXBaseEffect::GetTechnique | Gets the handle of a technique.
ID3DXBaseEffect::GetTechniqueByName | Gets the handle of a technique by looking up its name.
ID3DXBaseEffect::GetTechniqueDesc | Gets a technique description.
ID3DXBaseEffect::GetTexture | Gets a texture.
ID3DXBaseEffect::GetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.
ID3DXBaseEffect::GetVector | Gets a vector.
ID3DXBaseEffect::GetVectorArray | Gets an array of vectors.
ID3DXBaseEffect::GetVertexShader | Gets a vertex shader.
ID3DXBaseEffect::SetArrayRange | Set the range of an array to pass to the device.
ID3DXBaseEffect::SetBool | Sets a BOOL value.
ID3DXBaseEffect::SetBoolArray | Sets an array of Boolean values.
ID3DXBaseEffect::SetFloat | Sets a floating point value.
ID3DXBaseEffect::SetFloatArray | Sets an array of floating point values.
ID3DXBaseEffect::SetInt | Sets an integer.
ID3DXBaseEffect::SetIntArray | Sets an array of integers.
ID3DXBaseEffect::SetMatrix | Sets a non-transposed matrix.
ID3DXBaseEffect::SetMatrixArray | Sets an array of nontransposed matrices.
ID3DXBaseEffect::SetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
ID3DXBaseEffect::SetMatrixTranspose | Sets a transposed matrix.
ID3DXBaseEffect::SetMatrixTransposeArray | Sets an array of transposed matrices.
ID3DXBaseEffect::SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
ID3DXBaseEffect::SetString | Sets a string.
ID3DXBaseEffect::SetTexture | Sets a texture.
ID3DXBaseEffect::SetValue | Set the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures.
ID3DXBaseEffect::SetVector | Sets a vector.
ID3DXBaseEffect::SetVectorArray | Sets an array of vectors.

Remarks

The LPD3DXBASEEFFECT type is defined as a pointer to this interface.

typedef interface ID3DXBaseEffect ID3DXBaseEffect;
typedef interface ID3DXBaseEffect *LPD3DXBASEEFFECT;

See Also

D3DXCreateEffect

Requirements

Header: Declared in D3DX9Effect.h.

Library: Use D3dx9.lib.


ID3DXBaseEffect::GetAnnotation

Gets the handle of an annotation.

D3DXHANDLE GetAnnotation(
  D3DXHANDLE hObject,
  UINT Index
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
Index
[in] Annotation index.

Return Values

Returns the handle of the specified annotation, or NULL if the index was invalid. See Handles.

Remarks

Annotations are user-specific data that can be attached to any technique, pass, or parameter. See Handles.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetAnnotationByName

Gets the handle of an annotation by looking up its name.

D3DXHANDLE GetAnnotationByName(
  D3DXHANDLE hObject,
  LPCSTR pName
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
pName
[in] String containing the annotation name.

Return Values

Returns the handle of the specified annotation, or NULL if the name was not found. See Handles.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetBool

Gets a BOOL value.

HRESULT GetBool(
  D3DXHANDLE hParameter,
  BOOL* pb
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pb
[out] Returns a Boolean value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetBool


ID3DXBaseEffect::GetBoolArray

Gets an array of BOOL values.

HRESULT GetBoolArray(
  D3DXHANDLE hParameter,
  BOOL* pB,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[out] Returns an array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetBoolArray


ID3DXBaseEffect::GetDesc

Gets the effect description.

HRESULT GetDesc(
  D3DXEFFECT_DESC* pDesc
);

Parameters

pDesc
[out] Returns a description of the effect. See D3DXEFFECT_DESC.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetFloat

Gets a floating point value.

HRESULT GetFloat(
  D3DXHANDLE hParameter,
  FLOAT* pf
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns a floating point value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetFloat


ID3DXBaseEffect::GetFloatArray

Gets an array of floating point values.

HRESULT GetFloatArray(
  D3DXHANDLE hParameter,
  FLOAT* pf,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns an array of floating point values.
Count
[in] Number of floating point values in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetFloatArray


ID3DXBaseEffect::GetFunction

Gets the handle of a function.

D3DXHANDLE GetFunction(
  UINT Index
);

Parameters

Index
[in] Function index.

Return Values

Returns the handle of the specified function, or NULL if the index was invalid. See Handles.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetFunctionByName

Gets the handle of a function by looking up its name.

D3DXHANDLE GetFunctionByName(
  LPCSTR pName
);

Parameters

pName
[in] String containing the function name.

Return Values

Returns the handle of the specified function, or NULL if the name was not found. See Handles.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetFunctionDesc

Gets a function description.

HRESULT GetFunctionDesc(
  D3DXHANDLE hFunction,
  D3DXFUNCTION_DESC* pDesc
);

Parameters

hFunction
[in] Function handle. See Handles.
pDesc
[out] Returns a description of the function. See D3DXFUNCTION_DESC.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetInt

Gets an integer.

HRESULT GetInt(
  D3DXHANDLE hParameter,
  INT* pn
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an integer.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetInt


ID3DXBaseEffect::GetIntArray

Gets an array of integers.

HRESULT GetIntArray(
  D3DXHANDLE hParameter,
  INT* pn,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an array of integers.
Count
[in] Number of integers in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetIntArray


ID3DXBaseEffect::GetMatrix

Gets a nontransposed matrix.

HRESULT GetMatrix(
  D3DXHANDLE hParameter,
  D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a nontransposed matrix. See D3DXMATRIX.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrix is larger than the source matrix, only the upper-left components of the destination matrix will be filled, and the remaining components will be set to zero.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetMatrix


ID3DXBaseEffect::GetMatrixArray

Gets an array of nontransposed matrices.

HRESULT GetMatrixArray(
  D3DXHANDLE hParameter,
  D3DXMATRIX* pMatrix,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetMatrixArray


ID3DXBaseEffect::GetMatrixPointerArray

Gets an array of pointers to nontransposed matrices.

HRESULT GetMatrixPointerArray(
  D3DXHANDLE hParameter,
  D3DXMATRIX ** ppMatrix,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[out] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXBaseEffect::GetMatrixTranspose

Gets a transposed matrix.

HRESULT GetMatrixTranspose(
  D3DXHANDLE hParameter,
  D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a transposed matrix. See D3DXMATRIX.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrix is larger than the source matrix, only the upper-left elements of the destination matrix will be filled, and the remaining destination matrix components will be set to zero.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetMatrixTranspose


ID3DXBaseEffect::GetMatrixTransposeArray

Gets an array of transposed matrices.

HRESULT GetMatrixTransposeArray(
  D3DXHANDLE hParameter,
  D3DXMATRIX* pMatrix,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetMatrixTransposeArray


ID3DXBaseEffect::GetMatrixTransposePointerArray

Sets an array of pointers to transposed matrices.

HRESULT GetMatrixTransposePointerArray(
  D3DXHANDLE hParameter,
  D3DXMATRIX** ppMatrix,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXBaseEffect::GetParameter

Gets the handle of a top-level parameter or a structure member parameter.

D3DXHANDLE GetParameter(
  D3DXHANDLE hParameter,
  UINT Index
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
Index
[in] Parameter index.

Return Values

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXBaseEffect::GetParameterByName

Gets the handle of a top-level parameter or a structure member parameter by looking up its name.

D3DXHANDLE GetParameterByName(
  D3DXHANDLE hParameter,
  LPCSTR pName
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
pName
[in] String containing the parameter name.

Return Values

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXBaseEffect::GetParameterBySemantic

Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic with a case-insensitive search.

D3DXHANDLE GetParameterBySemantic(
  D3DXHANDLE hParameter,
  LPCSTR pSemantic
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
pSemantic
[in] String containing the semantic name.

Return Values

Returns the handle of the first parameter that matches the specified semantic, or NULL if the semantic was not found. See Handles.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXBaseEffect::GetParameterDesc

Gets a parameter or annotation description.

HRESULT GetParameterDesc(
  D3DXHANDLE hParameter,
  D3DXPARAMETER_DESC* pDesc
);

Parameters

hParameter
[in] Parameter or annotation handle. See Handles.
pDesc
[out] Returns a description of the specified parameter or annotation. See D3DXPARAMETER_DESC.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetParameterElement

Get the handle of an array element parameter.

D3DXHANDLE GetParameterElement(
  D3DXHANDLE hParameter,
  UINT ElementIndex
);

Parameters

hParameter
[in] Handle of the array. See Handles.
ElementIndex
[in] Array element index.

Return Values

Returns the handle of the specified parameter, or NULL if either hParameter or ElementIndex is invalid. See Handles.

Remarks

This method is used to get an element of a parameter that is an array.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXBaseEffect::GetPass

Gets the handle of a pass.

D3DXHANDLE GetPass(
  D3DXHANDLE hTechnique,
  UINT Index
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
Index
[in] Index for the pass.

Return Values

Returns the handle of the specified pass inside the specified technique, or NULL if the index was invalid. See Handles.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetPassByName

Gets the handle of a pass by looking up its name.

D3DXHANDLE GetPassByName(
  D3DXHANDLE hTechnique,
  LPCSTR pName
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
pName
[in] String containing the pass name.

Return Values

Returns the handle of the first pass inside the specified technique that has the specified name, or NULL if the name was not found. See Handles.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetPassDesc

Gets a pass description.

HRESULT GetPassDesc(
  D3DXHANDLE hPass,
  D3DXPASS_DESC* pDesc
);

Parameters

hPass
[in] Pass handle. See Handles.
pDesc
[out] Returns a description of the specified pass. See D3DXPASS_DESC.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Note If an effect is created with D3DXFX_NOT_CLONEABLE, this method will return NULL pointers (in D3DXPASS_DESC) to the shader functions.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetPixelShader

Gets a pixel shader.

HRESULT GetPixelShader(
  D3DXHANDLE hParameter,
  LPDIRECT3DPIXELSHADER9* ppPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppPShader
[out] Returns a pixel shader object. See IDirect3DPixelShader9 object.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXBaseEffect::GetString

Gets a string.

HRESULT GetString(
  D3DXHANDLE hParameter,
  LPCSTR* ppString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppString
[out] Returns a string identified by hParameter.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetString


ID3DXBaseEffect::GetTechnique

Gets the handle of a technique.

D3DXHANDLE GetTechnique(
  UINT Index
);

Parameters

Index
[in] Technique index.

Return Values

Returns the handle of the specified technique, or NULL if the index was invalid. See Handles.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXBaseEffect::GetTechniqueByName

Gets the handle of a technique by looking up its name.

D3DXHANDLE GetTechniqueByName(
  LPCSTR pName
);

Parameters

pName
[in] String containing the technique name.

Return Values

Returns the handle of the first technique that has the specified name, or NULL if the name was not found. See Handles.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXBaseEffect::GetTechniqueDesc

Gets a technique description.

HRESULT GetTechniqueDesc(
  D3DXHANDLE hTechnique,
  D3DXTECHNIQUE_DESC* pDesc
);

Parameters

hTechnique
[in] Technique handle. See Handles.
pDesc
[out] Returns a description of the technique. See D3DXTECHNIQUE_DESC.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXBaseEffect::GetTexture

Gets a texture.

HRESULT GetTexture(
  D3DXHANDLE hParameter,
  LPDIRECT3DBASETEXTURE9* ppTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppTexture
[out] Returns a texture object. See IDirect3DBaseTexture9.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetTexture


ID3DXBaseEffect::GetValue

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.

HRESULT GetValue(
  D3DXHANDLE hParameter,
  LPVOID pData,
  UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[out] Returns a buffer containing the value.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know your buffer is large enough to contain the entire parameter, and you want to skip size validation.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetValue


ID3DXBaseEffect::GetVector

Gets a vector.

HRESULT GetVector(
  D3DXHANDLE hParameter,
  D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns a 4D vector.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vector is larger than the source vector, only the initial components of the destination vector will be filled, and the remaining components will be set to zero.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetVector


ID3DXBaseEffect::GetVectorArray

Gets an array of vectors.

HRESULT GetVectorArray(
  D3DXHANDLE hParameter,
  D3DXVECTOR4* pVector,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns an array of 4D floating point vectors.
Count
[in] Number of vectors in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vectors are larger than the source vectors, only the initial components of each destination vector will be filled, and the remaining destination vector components will be set to zero.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::SetVectorArray


ID3DXBaseEffect::GetVertexShader

Gets a vertex shader.

HRESULT GetVertexShader(
  D3DXHANDLE hParameter,
  LPDIRECT3DVERTEXSHADER9* ppVShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppVShader
[out] Returns a vertex shader object. See IDirect3DVertexShader9.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXBaseEffect::SetArrayRange

Set the range of an array to pass to the device.

HRESULT SetArrayRange(
  D3DXHANDLE hParameter,
  UINT Start,
  UINT Stop
);

Parameters

hParameter
[in] Unique identifier. See Handles.
Start
[in] Start index.
Stop
[in] Stop index.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.


ID3DXBaseEffect::SetBool

Sets a BOOL value.

HRESULT SetBool(
  D3DXHANDLE hParameter,
  BOOL b
);

Parameters

hParameter
[in] Unique identifier. See Handles.
b
[in] Boolean value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetBool


ID3DXBaseEffect::SetBoolArray

Sets an array of Boolean values.

HRESULT SetBoolArray(
  D3DXHANDLE hParameter,
  CONST BOOL* pB,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[in] Array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetBoolArray


ID3DXBaseEffect::SetFloat

Sets a floating point value.

HRESULT SetFloat(
  D3DXHANDLE hParameter,
  FLOAT f
);

Parameters

hParameter
[in] Unique identifier. See Handles.
f
[in] Floating point value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetFloat


ID3DXBaseEffect::SetFloatArray

Sets an array of floating point values.

HRESULT SetFloatArray(
  D3DXHANDLE hParameter,
  CONST FLOAT* pf,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[in] Array of floating point values.
Count
[in] Number of floating point values in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetFloatArray


ID3DXBaseEffect::SetInt

Sets an integer.

HRESULT SetInt(
  D3DXHANDLE hParameter,
  INT n
);

Parameters

hParameter
[in] Unique identifier. See Handles.
n
[in] Integer value.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetInt


ID3DXBaseEffect::SetIntArray

Sets an array of integers.

HRESULT SetIntArray(
  D3DXHANDLE hParameter,
  CONST INT* pn,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetIntArray


ID3DXBaseEffect::SetMatrix

Sets a non-transposed matrix.

HRESULT SetMatrix(
  D3DXHANDLE hParameter,
  CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a nontransposed matrix. See D3DXMATRIX.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data. In other words, each vector is contained in a row.

If the destination matrix is smaller than the source matrix, the additional components of the source matrix will be ignored.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetMatrix


ID3DXBaseEffect::SetMatrixArray

Sets an array of nontransposed matrices.

HRESULT SetMatrixArray(
  D3DXHANDLE hParameter,
  CONST D3DXMATRIX* pMatrix,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXBaseEffect::SetMatrixPointerArray

Sets an array of pointers to nontransposed matrices.

HRESULT SetMatrixPointerArray(
  D3DXHANDLE hParameter,
  CONST D3DXMATRIX** ppMatrix,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXBaseEffect::SetMatrixTranspose

Sets a transposed matrix.

HRESULT SetMatrixTranspose(
  D3DXHANDLE hParameter,
  CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrix is smaller than the source matrix, the additional components of the source matrix will be ignored.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetMatrixTranspose


ID3DXBaseEffect::SetMatrixTransposeArray

Sets an array of transposed matrices.

HRESULT SetMatrixTransposeArray(
  D3DXHANDLE hParameter,
  CONST D3DXMATRIX* pMatrix,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXBaseEffect::SetMatrixTransposePointerArray

Sets an array of pointers to transposed matrices.

HRESULT SetMatrixTransposePointerArray(
  D3DXHANDLE hParameter,
  CONST D3DXMATRIX** ppMatrix,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXBaseEffect::SetString

Sets a string.

HRESULT SetString(
  D3DXHANDLE hParameter,
  LPCSTR pString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pString
[in] String to set.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetString


ID3DXBaseEffect::SetTexture

Sets a texture.

HRESULT SetTexture(
  D3DXHANDLE hParameter,
  LPDIRECT3DBASETEXTURE9 pTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pTexture
[in] Texture object. See IDirect3DBaseTexture9.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetTexture


ID3DXBaseEffect::SetValue

Set the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures.

HRESULT SetValue(
  D3DXHANDLE hParameter,
  LPCVOID pData,
  UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[in] Pointer to a buffer containing data.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know your buffer is large enough to contain the entire parameter, and you want to skip size validation.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method can be used in place of nearly all the effect set API calls.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetValue


ID3DXBaseEffect::SetVector

Sets a vector.

HRESULT SetVector(
  D3DXHANDLE hParameter,
  CONST D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Pointer to a 4D vector.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vector is smaller than the source vector, the additional components of the source vector will be ignored.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetVector


ID3DXBaseEffect::SetVectorArray

Sets an array of vectors.

HRESULT SetVectorArray(
  D3DXHANDLE hParameter,
  CONST D3DXVECTOR4* pVector,
  UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Array of 4D floating point vectors.
Count
[in] Number of vectors in the array.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vectors are smaller than the source vectors, the additional components of the source vectors will be ignored.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXBaseEffect::GetVectorArray


ID3DXEffect

Used to set and query effects, and to choose techniques. An effect object can contain multiple techniques to render the same effect.

ID3DXEffect Members

ID3DXBaseEffect
ID3DXEffect
ID3DXEffectCompiler
Method | Description
ID3DXEffect::ApplyParameterBlock | Apply the values in a state block to the current effect system state.
ID3DXEffect::Begin | Starts an active technique.
ID3DXEffect::BeginParameterBlock | Start capturing state changes in a parameter block.
ID3DXEffect::BeginPass | Begins a pass, within the active technique.
ID3DXEffect::CloneEffect | Creates a copy of an effect.
ID3DXEffect::CommitChanges | Propagate state changes that occur inside of an active pass to the device before rendering.
ID3DXEffect::DeleteParameterBlock | Delete a parameter block.
ID3DXEffect::End | Ends an active technique.
ID3DXEffect::EndParameterBlock | Stop capturing effect parameter state changes.
ID3DXEffect::EndPass | End an active pass.
ID3DXEffect::FindNextValidTechnique | Searches for the next valid technique, starting at the technique after the specified technique.
ID3DXEffect::GetCurrentTechnique | Gets the current technique.
ID3DXEffect::GetDevice | Retrieves the device associated with the effect.
ID3DXEffect::GetPool | Gets a pointer to the pool of shared parameters.
ID3DXEffect::GetStateManager | Get the effect state manager.
ID3DXEffect::IsParameterUsed | Determines if a parameter is used by the technique.
ID3DXEffect::OnLostDevice | Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost, or before resetting a device.
ID3DXEffect::OnResetDevice | Use this method to re-acquire resources and save initial state.
ID3DXEffect::SetRawValue | Set a contiguous range of shader constants with a memory copy.
ID3DXEffect::SetStateManager | Set the effect state manager.
ID3DXEffect::SetTechnique | Sets the active technique.
ID3DXEffect::ValidateTechnique | Validate a technique.

Remarks

The ID3DXEffect interface is obtained by calling D3DXCreateEffect, D3DXCreateEffectFromFile, or D3DXCreateEffectFromResource.

The LPD3DXEFFECT type is defined as a pointer to this interface.

typedef interface ID3DXEffect ID3DXEffect;
typedef interface ID3DXEffect *LPD3DXEFFECT;

See Also

D3DXCreateEffect, D3DXCreateEffectFromFile, D3DXCreateEffectFromResource

Requirements

Header: Declared in D3DX9Effect.h.

Library: Use D3dx9.lib.


ID3DXEffect::ApplyParameterBlock

Apply the values in a state block to the current effect system state.

HRESULT ApplyParameterBlock(
  D3DXHANDLE  hParameterBlock
);

Parameters

hParameterBlock
[in] A handle to the parameter block. This is the handle returned by ID3DXEffect::EndParameterBlock.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

Capture effect parameter state changes in a parameter block by calling BeginParameterBlock; stop capturing state changes by calling EndParameterBlock. These state changes include any effect parameter changes that occur inside of a technique (including those outside of a pass). Once you are done with the parameter block, call DeleteParameterBlock to recover memory.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

ID3DXEffect::BeginParameterBlock, ID3DXEffect::EndParameterBlock, ID3DXEffect::DeleteParameterBlock


ID3DXEffect::Begin

Starts an active technique.

HRESULT Begin(
  UINT* pPasses,
  DWORD Flags
);

Parameters

pPasses
[out] Pointer to a value returned that indicates the number of passes needed to render the current technique.
Flags
[in] DWORD that determines if state modified by an effect is saved and restored. The default value 0 specifies that ID3DXEffect::Begin and ID3DXEffect::End will save and restore all state modified by the effect (including pixel and vertex shader constants). Valid flags can be seen at Effect State Save and Restore Flags.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

An application sets one active technique in the effect system by calling ID3DXEffect::Begin. The effect system responds by capturing all the pipeline state that can be changed by the technique in a state block. An application signals the end of a technique by calling ID3DXEffect::End, which uses the state block to restore the original state. The effect system therefore takes care of saving state when a technique becomes active and restoring state when a technique ends. If you choose to disable this save and restore functionality, see D3DXFX_DONOTSAVESAMPLERSTATE.

Within the ID3DXEffect::Begin and ID3DXEffect::End pair, an application uses ID3DXEffect::BeginPass to set the active pass, ID3DXEffect::CommitChanges if any state changes occured after the pass was activated, and ID3DXEffect::EndPass to end the active pass.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::BeginParameterBlock

Start capturing state changes in a parameter block.

HRESULT BeginParameterBlock();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

Capture effect parameter state changes until EndParameterBlock is called. Effect parameters include any state changes outside of a pass. Delete parameter blocks if they are no longer needed by calling DeleteParameterBlock.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

ID3DXEffect::EndParameterBlock, ID3DXEffect::ApplyParameterBlock, ID3DXEffect::DeleteParameterBlock


ID3DXEffect::BeginPass

Begins a pass, within the active technique.

HRESULT BeginPass(
  UINT Pass
);

Parameters

Pass
[in] A zero-based integer index into the technique.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

An application sets one active pass (within one active technique) in the effect system by calling ID3DXEffect::BeginPass. An application signals the end of the active pass by calling ID3DXEffect::EndPass. ID3DXEffect::BeginPass and ID3DXEffect::EndPass must occur in a matching pair, within a matching pair of ID3DXEffect::Begin and ID3DXEffect::End calls.

If the application changes any effect state using any of the Effect::Setx methods inside of a ID3DXEffect::BeginPass/ID3DXEffect::EndPass matching pair, the application must call ID3DXEffect::CommitChanges to set the update the device with the state changes. If no state changes occur within a ID3DXEffect::BeginPass and ID3DXEffect::EndPass matching pair, it is not necessary to call ID3DXEffect::CommitChanges.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::CloneEffect

Creates a copy of an effect.

HRESULT CloneEffect(
  LPDIRECT3DDEVICE9 pDevice,
  LPD3DXEFFECT* ppEffect
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the effect.
ppEffect
[out] Pointer to an ID3DXEffect interface, containing the cloned effect.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

Note This function will not clone an effect if the user specifies D3DXFX_NOT_CLONEABLE during effect creation.

To update shared and non-shared parameters in an active technique of a cloned effect, see ID3DXEffect::CommitChanges.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::CommitChanges

Propagate state changes that occur inside of an active pass to the device before rendering.

HRESULT CommitChanges();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

If the application changes any effect state using any of the ID3DXEffect::Setx methods inside of an ID3DXEffect::BeginPass/ID3DXEffect::EndPass matching pair, the application must call ID3DXEffect::CommitChanges before any DrawxPrimitive call to propagate state changes to the device before rendering. If no state changes occur within a ID3DXEffect::BeginPass and ID3DXEffect::EndPass matching pair, it is not necessary to call ID3DXEffect::CommitChanges.

This is slightly different for any shared parameters in a cloned effect. When a technique is active on a cloned effect (that is, when ID3DXEffect::Begin has been called but and ID3DXEffect::End has not been called), ID3DXEffect::CommitChanges updates parameters that are not shared as expected. To update a shared parameter (only for a cloned effect whose technique is active), call ID3DXEffect::End to deactivate the technique and ID3DXEffect::Begin to reactivate the technique before calling ID3DXEffect::CommitChanges.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::DeleteParameterBlock

Delete a parameter block.

HRESULT DeleteParameterBlock(
  D3DXHANDLE  hParameterBlock
);

Parameters

hParameterBlock
[in] A handle to the parameter block. This is the handle returned by ID3DXEffect::EndParameterBlock.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

Parameter blocks are blocks of effect states. Use a parameter block to record state changes so that they can be applied later on with a single API call. When no longer needed, delete the parameter block to reduce memory usage.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

ID3DXEffect::BeginParameterBlock, ID3DXEffect::EndParameterBlock


ID3DXEffect::End

Ends an active technique.

HRESULT End();

Parameters

None.

Return Values

This method always returns the value S_OK.

Remarks

All rendering in an effect is done within a matching pair of ID3DXEffect::Begin and ID3DXEffect::End calls. After all passes are rendered, ID3DXEffect::End must be called to end the active technique. The effect system responds by using the state block created when ID3DXEffect::Begin was called, to automatically restore the pipeline state before ID3DXEffect::Begin.

By default, the effect system takes care of saving state prior to a technique, and restoring state after a technique. If you choose to disable this save and restore functionality, see D3DXFX_DONOTSAVESAMPLERSTATE.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::EndParameterBlock

Stop capturing effect parameter state changes.

D3DXHANDLE EndParameterBlock();

Parameters

None.

Return Values

Returns a handle to the parameter state block.

Remarks

All effect parameters that change state (after calling BeginParameterBlock and before calling EndParameterBlock) will be saved in an effect parameter state block. Use ApplyParameterBlock to apply this block of state changes to the effect system. Once you are finished with a state block use DeleteParameterBlock to free the memory.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

ID3DXEffect::BeginParameterBlock, ID3DXEffect::ApplyParameterBlock, ID3DXEffect::DeleteParameterBlock


ID3DXEffect::EndPass

End an active pass.

HRESULT EndPass();

Parameters

None.

Return Values

This method always returns the value S_OK.

Remarks

An application signals the end of rendering an active pass by calling ID3DXEffect::EndPass. Each ID3DXEffect::EndPass must be part of a matching pair of ID3DXEffect::BeginPass and ID3DXEffect::EndPass calls.

Each matching pair of ID3DXEffect::BeginPass and ID3DXEffect::EndPass calls must be located within a matching pair of ID3DXEffect::Begin and ID3DXEffect::End calls.

If the application changes any effect state using any of the Effect::Setx methods inside of a ID3DXEffect::BeginPass/ID3DXEffect::EndPass matching pair, the application must call ID3DXEffect::CommitChanges before any DrawxPrimitive call to propagate state changes to the device before rendering.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::FindNextValidTechnique

Searches for the next valid technique, starting at the technique after the specified technique.

HRESULT FindNextValidTechnique(
  D3DXHANDLE hTechnique,
  D3DXHANDLE* pTechnique
);

Parameters

hTechnique
[in] Unique identifier to a technique. See Handles. Specify NULL for this parameter to find the first valid technique.
pTechnique
[out] Pointer to an identifier for the next technique. NULL is returned if this is the last technique. See Handles.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXTECHNIQUE_DESC, ID3DXEffect::ValidateTechnique


ID3DXEffect::GetCurrentTechnique

Gets the current technique.

D3DXHANDLE GetCurrentTechnique();

Parameters

None.

Return Values

A unique identifier to the current technique. See Handles.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::GetDevice

Retrieves the device associated with the effect.

HRESULT GetDevice(
  LPDIRECT3DDEVICE9* ppDevice
);

Parameters

ppDevice
[out] Address of a pointer to an IDirect3DDevice9 interface, representing the device associated with the effect.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count for the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using the IDirect3DDevice9 interface or you will have a memory leak.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::GetPool

Gets a pointer to the pool of shared parameters.

HRESULT GetPool(
  LPD3DXEFFECTPOOL* ppPool
);

Parameters

ppPool
[out] Pointer to a ID3DXEffectPool object.

Return Values

This method always returns the value S_OK.

Remarks

Pools contain shared parameters between effects. See Cloning and Sharing.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::GetStateManager

Get the effect state manager.

HRESULT GetStateManager(
  LPD3DXEFFECTSTATEMANAGER* ppManager
);

Parameters

ppManager
[out] Returns a pointer to the state manager. See ID3DXEffectStateManager.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

The ID3DXEffectStateManager is a user-implemented interface that furnishes callbacks into an application for setting device state from an effect.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

ID3DXEffect::SetStateManager


ID3DXEffect::IsParameterUsed

Determines if a parameter is used by the technique.

BOOL IsParameterUsed(
  D3DXHANDLE hParameter,
  D3DXHANDLE hTechnique
);

Parameters

hParameter
[in] Unique identifier for the parameter. See Handles.
hTechnique
[in] Unique identifier for the technique. See Handles.

Return Values

Returns TRUE if the parameter is being used and returns FALSE if the parameter is not being used.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::OnLostDevice

Use this method to release all references to video memory resources and delete all stateblocks. This method should be called whenever a device is lost, or before resetting a device.

HRESULT OnLostDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method should be called whenever the device is lost or before the user calls IDirect3DDevice9::Reset. Even if the device was not actually lost, ID3DXEffect::OnLostDevice is responsible for freeing stateblocks and other resources that may need to be released before resetting the device. As a result, the font object cannot be used again before calling IDirect3DDevice9::Reset and then ID3DXEffect::OnResetDevice.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::OnResetDevice

Use this method to re-acquire resources and save initial state.

HRESULT OnResetDevice();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXEffect::OnResetDevice should be called each time the device is reset (using IDirect3DDevice9::Reset), before any other methods are called. This is a good place to re-acquire video-memory resources and capture state blocks.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::SetRawValue

Set a contiguous range of shader constants with a memory copy.

HRESULT SetRawValue(
  D3DXHANDLE Handle,
  void * pData,
  DWORD OffsetInBytes,
  DWORD Bytes
);

Parameters

Handle
[in] Handle to the value to set, or the name of the value passed in as a string. Passing in a handle is more efficient. See Handles.
pData
[in] Pointer to a buffer containing the data to be set. SetRawValue checks for valid memory, but does not do any checking for valid data.
OffsetInBytes
[in] Number of bytes between the beginning of the effect data and the beginning of the effect constants you are going to set.
Bytes
[in] The size of the buffer to be set, in bytes.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following:E_INVALIDCALL.

Remarks

SetRawValue is a very fast way to set effect constants since it performs a memory copy without performing validation or any data conversion (like converting a row-major matrix to a column-major matrix). Use SetRawValue to set a series of contiguous effect constants. For instance, you could set an array of twenty matrices with 20 calls to ID3DXBaseEffect::SetMatrix or by using a single SetRawValue.

All values are expected to be either matrix4x4s or float4s and all matrices are expected to be in column-major order. Int or float values are cast into a float4; therefore, it is highly recommended that you use SetRawValue with only float4 or matrix4x4 data.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::SetStateManager

Set the effect state manager.

HRESULT SetStateManager(
  LPD3DXEFFECTSTATEMANAGER pManager
);

Parameters

pManager
[in] A pointer to the state manager. See ID3DXEffectStateManager.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

Remarks

The ID3DXEffectStateManager is a user-implemented interface that furnishes callbacks into an application for setting device state from an effect.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

ID3DXEffect::GetStateManager


ID3DXEffect::SetTechnique

Sets the active technique.

HRESULT SetTechnique(
  D3DXHANDLE hTechnique
);

Parameters

hTechnique
[in] Unique handle to the technique. See Handles.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffect::ValidateTechnique

Validate a technique.

HRESULT ValidateTechnique(
  D3DXHANDLE hTechnique
);

Parameters

hTechnique
[in] Unique identifier. See Handles.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

ID3DXEffect::SetTechnique


ID3DXEffectCompiler

The ID3DXEffectCompiler interface compiles an effect from a function or from a vertex shader.

ID3DXBaseEffect
ID3DXEffect
ID3DXEffectCompiler

ID3DXEffectCompiler Members

Method | Description
ID3DXEffectCompiler::CompileEffect | Compile an effect.
ID3DXEffectCompiler::CompileShader | Compiles a shader from an effect that contains one or more functions.
ID3DXEffectCompiler::GetLiteral | Gets a literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.
ID3DXEffectCompiler::SetLiteral | Toggles the literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.

Remarks

The ID3DXEffectCompiler interface is obtained by calling D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromFile, or D3DXCreateEffectCompilerFromResource.

The LPD3DXEFFECTCOMPILER type is defined as a pointer to this interface.

typedef interface ID3DXEffectCompiler ID3DXEffectCompiler;
typedef interface ID3DXEffectCompiler *LPD3DXEFFECTCOMPILER;

See Also

D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromFile, D3DXCreateEffectCompilerFromResource

Requirements

Header: Declared in D3DX9Effect.h.

Library: Use D3dx9.lib.


ID3DXEffectCompiler::CompileEffect

Compile an effect.

HRESULT CompileEffect(
  DWORD Flags,
  LPD3DXBUFFER * ppEffect,
  LPD3DXBUFFER * ppErrorMsgs
);

Parameters

Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppEffect
[out, retval] Buffer containing the compiled effect. For more information about accessing the buffer, see ID3DXBuffer.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Values

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value will be E_FAIL.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectCompiler::CompileShader

Compiles a shader from an effect that contains one or more functions.

HRESULT CompileShader(
  D3DXHANDLE hFunction,
  LPCSTR pTarget,
  DWORD Flags,
  LPD3DXBUFFER* ppShader,
  LPD3DXBUFFER* ppErrorMsgs,
  LPD3DXCONSTANTTABLE* ppConstantTable
);

Parameters

hFunction
[in] Unique identifier to the function to be compiled. This value must not be NULL. See Handles.
pTarget
[in] Pointer to a shader profile which determines the shader instruction set. See D3DXGetVertexShaderProfile or D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Compile options identified by various flags. The Direct3D 10 HLSL compiler is now the default. See D3DXSHADER Flags for details.
ppShader
[out, retval] Buffer containing the compiled shader. The compiler shader is an array of DWORDs. For more information about accessing the buffer, see ID3DXBuffer.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.
ppConstantTable
[out] Returns an ID3DXConstantTable interface, which can be used to access shader constants. This value may be NULL.

Return Values

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value will be E_FAIL.

Remarks

Targets can be specified for vertex shaders, pixel shaders, and texture fill functions.

Vertex shader targets | vs_1_1, vs_2_0, vs_2_sw, vs_3_0
Pixel shader targets | ps_1_1, ps_1_2, ps_1_3, ps_1_4, ps_2_0, ps_2_sw, ps_3_0
Texture fill targets | tx_0, tx_1

This method compiles a shader from a function that is written in a C-like language. For more information, see HLSL Shader Reference (Direct3D 9 HLSL).

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXGetShaderConstantTable


ID3DXEffectCompiler::GetLiteral

Gets a literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.

HRESULT GetLiteral(
  D3DXHANDLE hParameter,
  BOOL* pLiteral
);

Parameters

hParameter
[in] Unique identifier to a parameter. See Handles.
pLiteral
[out] Returns True if the parameter is a literal, and False otherwise.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This methods only changes whether the parameter is a literal or not. To change the value of a parameter, use a method like ID3DXBaseEffect::SetBool or ID3DXBaseEffect::SetValue.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

Usages and Literals, ID3DXEffectCompiler::SetLiteral


ID3DXEffectCompiler::SetLiteral

Toggles the literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.

HRESULT SetLiteral(
  D3DXHANDLE hParameter,
  BOOL Literal
);

Parameters

hParameter
[in] Unique identifier to a parameter. See Handles.
Literal
[in] Set to True to make the parameter a literal, and False if the parameter can change value during the shader lifetime.

Return Values

If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This methods only changes whether the parameter is a literal or not. To change the value of a parameter, use a method like ID3DXBaseEffect::SetBool or ID3DXBaseEffect::SetValue.

This function must be called before the effect is compiled. Here is an example of how one might use this function:

    LPD3DXEFFECTCOMPILER pEffectCompiler;
    char errors[1000];
    HRESULT hr;

    hr = D3DXCreateEffectCompilerFromFile("shader.fx",
                                          NULL, NULL, 0,
                                          &pEffectCompiler,
                                          &errors);

    //In the fx file, literalInt is declared as an int.
    //By calling this function, the compiler will treat
    //it as a literal (i.e. #define)
    hr = pEffectCompiler->SetLiteral("literalInt", TRUE);

    //create ten different variations of the same effect
    LPD3DXBUFFER pEffects[10];
    LPD3DXBUFFER pErrors;
    for(int i = 0; i < 10; ++i)
    {
        hr = pEffectCompiler->SetInt("literalInt", i);

        hr = pEffectCompiler->CompileEffect(0, &pEffects[i], &pErrors);
    }

Requirements

Header: Declared in D3DX9Shader.h.

See Also

Usages and Literals, ID3DXEffectCompiler::GetLiteral


ID3DXEffectPool

Applications use the ID3DXEffectPool interface to identify parameters that are going to be shared across effects. See parameter sharing in Cloning and Sharing. This interface has no methods.

Remarks

The ID3DXEffectPool interface is obtained by calling D3DXCreateEffectPool.

The LPD3DXEFFECTPOOL type is defined as a pointer to this interface.

typedef interface ID3DXEffectPool ID3DXEffectPool;
typedef interface ID3DXEffectPool *LPD3DXEFFECTPOOL;

Requirements

Header: Declared in D3DX9Effect.h.

Library: Use D3dx9.lib.


ID3DXEffectStateManager

This is a user-implemented interface that allows a user to set the device state from an effect. Each of the methods in this interface must be implemented by the user and will then be used as callbacks to the application when either of the following occur:
  • An effect calls ID3DXEffect::BeginPass.
  • Effect state is dynamically updated by calling the appropriate state change API. See individual method pages for details.

When an application uses the state manager to implement custom callbacks, an effect no longer automatically saves and restores state when calling ID3DXEffect::BeginPass and ID3DXEffect::EndPass. Because the application has implemented a custom save and restore behavior in the callbacks, this automatic behavior is bypassed.

ID3DXEffectStateManager Members

Method | Description
ID3DXEffectStateManager::LightEnable | A callback function that must be implemented by a user to enable/disable a light.
ID3DXEffectStateManager::SetFVF | A callback function that must be implemented by a user to set a FVF code.
ID3DXEffectStateManager::SetLight | A callback function that must be implemented by a user to set a light.
ID3DXEffectStateManager::SetMaterial | A callback function that must be implemented by a user to set material state.
ID3DXEffectStateManager::SetNPatchMode | A callback function that must be implemented by a user to set the number of subdivision segments for N-patches.
ID3DXEffectStateManager::SetPixelShader | A callback function that must be implemented by a user to set a pixel shader.
ID3DXEffectStateManager::SetPixelShaderConstantB | A callback function that must be implemented by a user to set an array of vertex shader Boolean constants.
ID3DXEffectStateManager::SetPixelShaderConstantF | A callback function that must be implemented by a user to set an array of vertex shader floating-point constants.
ID3DXEffectStateManager::SetPixelShaderConstantI | A callback function that must be implemented by a user to set an array of vertex shader integer constants.
ID3DXEffectStateManager::SetRenderState | A callback function that must be implemented by a user to set render state.
ID3DXEffectStateManager::SetSamplerState | A callback function that must be implemented by a user to set a sampler.
ID3DXEffectStateManager::SetTexture | A callback function that must be implemented by a user to set a texture.
ID3DXEffectStateManager::SetTextureStageState | A callback function that must be implemented by a user to set the texture stage state.
ID3DXEffectStateManager::SetTransform | A callback function that must be implemented by a user to set a transform.
ID3DXEffectStateManager::SetVertexShader | A callback function that must be implemented by a user to set a vertex shader.
ID3DXEffectStateManager::SetVertexShaderConstantB | A callback function that must be implemented by a user to set an array of vertex shader Boolean constants.
ID3DXEffectStateManager::SetVertexShaderConstantF | A callback function that must be implemented by a user to set an array of vertex shader floating-point constants.
ID3DXEffectStateManager::SetVertexShaderConstantI | A callback function that must be implemented by a user to set an array of vertex shader integer constants.

Remarks

A user creates an ID3DXEffectStateManager interface by implementing a class that derives from this interface, and implementing all the interface methods. Once the interface is created, you can get or set the state manager within an effect using ID3DXEffect::GetStateManager and ID3DXEffect::SetStateManager.

The LPD3DXEFFECTSTATEMANAGER type is defined as a pointer to this interface.

typedef interface ID3DXEffectStateManager ID3DXEffectStateManager;
typedef interface ID3DXEffectStateManager *LPD3DXEFFECTSTATEMANAGER;


ID3DXEffectStateManager::LightEnable

A callback function that must be implemented by a user to enable/disable a light.

HRESULT LightEnable(
  DWORD Index,
  BOOL Enable
);

Parameters

Index
[in] The zero-based index of the light. This is the same index in IDirect3DDevice9::SetLight.
Enable
[in] True to enable the light, false otherwise.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::LightEnable) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetFVF

A callback function that must be implemented by a user to set a FVF code.

HRESULT SetFVF(
  DWORD FVF
);

Parameters

FVF
[in] The FVF constant, that detemines how to interpret vertex data. See D3DFVF.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetFVF) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetLight

A callback function that must be implemented by a user to set a light.

HRESULT SetLight(
  DWORD Index,
  CONST D3DLight9* pLight
);

Parameters

Index
[in] The zero-based index of the light. This is the same index in IDirect3DDevice9::SetLight.
pLight
[in] The light object. See D3DLIGHT9.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetLight) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetMaterial

A callback function that must be implemented by a user to set material state.

HRESULT SetMaterial(
  CONST D3DMATERIAL9* pMaterial
);

Parameters

pMaterial
[in] A pointer to the material state. See D3DMATERIAL9.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetMaterial) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetNPatchMode

A callback function that must be implemented by a user to set the number of subdivision segments for N-patches.

HRESULT SetNPatchMode(
  FLOAT nSegments
);

Parameters

nSegments
[in] Break the surface into this number of subdivisions. This is the same as the number used by IDirect3DDevice9::SetNPatchMode.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetNPatchMode) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetPixelShader

A callback function that must be implemented by a user to set a pixel shader.

HRESULT SetPixelShader(
  LPDIRECT3DPIXELSHADER9 pShader
);

Parameters

pShader
[in] A pointer to a pixel shader object. See IDirect3DPixelShader9.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetPixelShader) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetPixelShaderConstantB

A callback function that must be implemented by a user to set an array of vertex shader Boolean constants.

HRESULT SetPixelShaderConstantB(
  UINT StartRegister,
  CONST BOOL* pConstantData,
  UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of Boolean constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetPixelShaderConstantB) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetPixelShaderConstantF

A callback function that must be implemented by a user to set an array of vertex shader floating-point constants.

HRESULT SetPixelShaderConstantF(
  UINT StartRegister,
  CONST FLOAT* pConstantData,
  UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of floating-point constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetPixelShaderConstantF) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetPixelShaderConstantI

A callback function that must be implemented by a user to set an array of vertex shader integer constants.

HRESULT SetPixelShaderConstantI(
  UINT StartRegister,
  CONST INT* pConstantData,
  UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of integer constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetPixelShaderConstantI) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetRenderState

A callback function that must be implemented by a user to set render state.

HRESULT SetRenderState(
  D3DRENDERSTATETYPE State,
  DWORD Value
);

Parameters

State
[in] The render state to set. D3DRENDERSTATETYPE
Value
[in] The render state value. See Effect States.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetRenderState) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetSamplerState

A callback function that must be implemented by a user to set a sampler.

HRESULT SetSamplerState(
  DWORD Sampler,
  D3DSAMPLERSTATETYPE Type,
  DWORD Value
);

Parameters

Sampler
[in] The zero-based sampler number.
Type
[in] Identifies sampler state, which can specify the filtering, addressing, or the border color. See D3DSAMPLERSTATETYPE.
Value
[in] A value from one of the sampler state types in Type.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetSamplerState) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetTexture

A callback function that must be implemented by a user to set a texture.

HRESULT SetTexture(
  DWORD Stage,
  LPDIRECT3DBASETEXTURE9 pTexture
);

Parameters

Stage
[in] The stage to which the texture is assigned. This is the index value in IDirect3DDevice9::SetTexture or IDirect3DDevice9::SetTextureStageState.
pTexture
[in] A pointer to the texture object. This can be any of the Direct3D texture types (cube, volume, etc.). See IDirect3DBaseTexture9.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetTexture) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetTextureStageState

A callback function that must be implemented by a user to set the texture stage state.

HRESULT SetTextureStageState(
  DWORD Stage,
  D3DTEXTURESTAGESTATETYPE Type,
  DWORD Value
);

Parameters

Stage
[in] The stage that the texture is assigned to. This is the index value in IDirect3DDevice9::SetTexture or IDirect3DDevice9::SetTextureStageState.
Type
[in] Defines the type of operation that a texture stage will perform. See D3DTEXTURESTAGESTATETYPE.
Value
[in] Can be either an operation (D3DTEXTUREOP) or an argument value (D3DTA), depending on what is chosen for Type.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetTextureStageState) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetTransform

A callback function that must be implemented by a user to set a transform.

HRESULT SetTransform(
  D3DTRANSFORMSTATETYPE State,
  CONST D3DMATRIX* pMatrix
);

Parameters

State
[in] The type of transform to apply the matrix to. See D3DTRANSFORMSTATETYPE.
pMatrix
[in] A transformation matrix. See D3DMATRIX.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetTransform) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetVertexShader

A callback function that must be implemented by a user to set a vertex shader.

HRESULT SetVertexShader(
  LPDIRECT3DVERTEXSHADER9 pShader
);

Parameters

pShader
[in] A pointer to a vertex shader object. See IDirect3DVertexShader9.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetVertexShader) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetVertexShaderConstantB

A callback function that must be implemented by a user to set an array of vertex shader Boolean constants.

HRESULT SetVertexShaderConstantB(
  UINT StartRegister,
  CONST BOOL* pConstantData,
  UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of Boolean constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetVertexShaderConstantB) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetVertexShaderConstantF

A callback function that must be implemented by a user to set an array of vertex shader floating-point constants.

HRESULT SetVertexShaderConstantF(
  UINT StartRegister,
  CONST FLOAT* pConstantData,
  UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of floating-point constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetVertexShaderConstantF) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXEffectStateManager::SetVertexShaderConstantI

A callback function that must be implemented by a user to set an array of vertex shader integer constants.

HRESULT SetVertexShaderConstantI(
  UINT StartRegister,
  CONST INT* pConstantData,
  UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of integer constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Values

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetVertexShaderConstantI) will fail.

Requirements

Header: Declared in D3DX9Effect.h.


ID3DXInclude

ID3DXInclude is a user-implemented interface to provide callbacks for #include directives during shader compilation. Each of the methods in this interface must be implemented by the user which will then be used as callbacks to the application when one of the following occurs:

  • An HLSL shader that contains a #include is compiled by calling one of the D3DXCompileShader*** functions.
  • An assembly shader #include is assembled by calling any of the D3DXAssembleShader*** functions.
  • An effect that contains a #include is compiled by by calling any of the D3DXCreateEffect*** or D3DXCreateEffectCompiler*** functions.

ID3DXInclude Members

Method | Description
ID3DXInclude::Close | A user-implemented method for closing a shader #include file.
ID3DXInclude::Open | A user-implemented method for opening and reading the contents of a shader #include file.

Remarks

A user creates an ID3DXInclude interface by implementing a class that derives from this interface, and implementing all the interface methods.

The LPD3DXINCLUDE type is defined as a pointer to this interface.

typedef interface ID3DXInclude ID3DXInclude;
typedef interface ID3DXInclude *LPD3DXINCLUDE;


ID3DXInclude::Close

A user-implemented method for closing a shader #include file.

HRESULT Close(
  LPCVOID pData
);

Parameters

pData
[in] Pointer to the returned buffer that contains the include directives. This is the pointer that was returned by the corresponding ID3DXInclude::Open call.

Return Values

The user-implemented method should return S_OK. If the callback fails when reading the #include file, the API that caused the callback to be called will fail. This is one of the following:

  • The HLSL shader will fail one of the D3DXCompileShader*** functions.
  • The assembly shader will fail one of the D3DXAssembleShader*** functions.
  • The effect will fail one of the D3DXCreateEffect*** or D3DXCreateEffectCompiler*** functions.

Remarks

If ID3DXInclude::Open was successful, ID3DXInclude::Close is guaranteed to be called before the API using this interface returns.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXInclude::Open


ID3DXInclude::Open

A user-implemented method for opening and reading the contents of a shader #include file.

HRESULT Open(
  D3DXINCLUDE_TYPE IncludeType,
  LPCSTR pFileName,
  LPCVOID pParentData,
  LPCVOID * ppData,
  UINT * pBytes
);

Parameters

IncludeType
[in] The location of the #include file. See D3DXINCLUDE_TYPE.
pFileName
[in] Name of the #include file.
pParentData
[in] Pointer to the container that includes the #include file.
ppData
[out] Pointer to the returned buffer that contains the include directives. This pointer remains valid until ID3DXInclude::Close is called.
pBytes
[out] Number of bytes returned in ppData.

Return Values

The user-implemented method should return S_OK. If the callback fails when reading the #include file, the API that caused the callback to be called will fail. This is one of the following:

  • The HLSL shader will fail one of the D3DXCompileShader*** functions.
  • The assembly shader will fail one of the D3DXAssembleShader*** functions.
  • The effect will fail one of the D3DXCreateEffect*** or D3DXCreateEffectCompiler*** functions.

Requirements

Header: Declared in D3DX9Shader.h.

See Also

ID3DXInclude::Close


Effect Functions

There are several functions that help create and compile effects.

  • D3DXCreateEffect
  • D3DXCreateEffectEx
  • D3DXCreateEffectCompiler
  • D3DXCreateEffectCompilerFromFile
  • D3DXCreateEffectCompilerFromResource
  • D3DXCreateEffectFromFile
  • D3DXCreateEffectFromFileEx
  • D3DXCreateEffectFromResource
  • D3DXCreateEffectFromResourceEx
  • D3DXCreateEffectPool
  • D3DXDisassembleEffect


D3DXCreateEffect

Create an effect from an ASCII or binary effect description.

HRESULT D3DXCreateEffect(
  LPDIRECT3DDEVICE9 pDevice,
  LPCVOID pSrcData,
  UINT SrcDataLen,
  CONST D3DXMACRO * pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXEFFECTPOOL pPool,
  LPD3DXEFFECT * ppEffect,
  LPD3DXBUFFER * ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device that will create the effect. See IDirect3DDevice9.
pSrcData
[in] Pointer to a buffer containing an effect description.
SrcDataLen
[in] Length of the effect data, in bytes.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] If pSrcData contains a text effect, flags can be a combination of D3DXSHADER Flags and D3DXFX flags; otherwise, pSrcData contains a binary effect and the only flags honored are D3DXFX flags. The Direct3D 10 HLSL compiler is now the default. See DirectX 10 HLSL Compiler (Direct3D 10) for details.
pPool
[in] Pointer to a ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a pointer to an ID3DXEffect interface.
ppCompilationErrors
[out] Returns a buffer containing a listing of compile errors.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

E_OUTOFMEMORY

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCreateEffectEx

Creates an effect from an ASCII or binary effect description. This function is an extended version of D3DXCreateEffect that allows an application to control which parameters are ignored by the effects system.

HRESULT D3DXCreateEffectEx(
  LPDIRECT3DDEVICE9 pDevice,
  LPCVOID pSrcData,
  UINT SrcDataLen,
  CONST D3DXMACRO * pDefines,
  LPD3DXINCLUDE pInclude,
  LPCSTR pSkipConstants,
  DWORD Flags,
  LPD3DXEFFECTPOOL pPool,
  LPD3DXEFFECT * ppEffect,
  LPD3DXBUFFER * ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device that will create the effect. See IDirect3DDevice9.
pSrcData
[in] Pointer to a buffer containing an effect description.
SrcDataLen
[in] Length of the effect data, in bytes.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
pSkipConstants
[in] A string of effect parameters that will be ignored by the effect system. The string must be NULL terminated, and needs to contain the name of each application-managed constant separated by a semicolon.
Flags
[in] If pSrcData contains a text effect, flags can be a combination of D3DXSHADER Flags and D3DXFX flags; otherwise, pSrcData contains a binary effect and the only flags honored are D3DXFX flags. The Direct3D 10 HLSL compiler is now the default. See DirectX 10 HLSL Compiler (Direct3D 10) for details.
pPool
[in] Pointer to an ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a pointer to an ID3DXEffect interface.
ppCompilationErrors
[out] Returns a buffer containing a list of compile errors.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

E_OUTOFMEMORY

Remarks

This function is an extended version of D3DXCreateEffect that allows an application to specify which effect constants will be managed by the application. A constant that is managed by the application is ignored by the effects system. That is, the application is responsible for initializing the constant as well as saving and restoring its state whenever appropriate.

This function checks each constant in pSkipConstants to see that:

  • It is bound to a constant register.
  • It is only used in HLSL shader code.

If a constant is named in the string that is not present in the effect, it is ignored.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXCreateEffectFromFileEx, D3DXCreateEffectFromResourceEx


D3DXCreateEffectCompiler

Creates an effect compiler from an ASCII effect description.

HRESULT D3DXCreateEffectCompiler(
  LPCSTR pSrcData,
  UINT SrcDataLen,
  CONST D3DXMACRO * pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXEFFECTCOMPILER * ppEffectCompiler,
  LPD3DXBUFFER * ppParseErrors
);

Parameters

pSrcData
[in] Pointer to a buffer containing an effect description.
SrcDataLen
[in] Length, in bytes, of the effect data.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by various flags (see D3DXSHADER Flags). The Direct3D 10 HLSL compiler is now the default. See DirectX 10 HLSL Compiler (Direct3D 10) for details.
ppEffectCompiler
[out, retval] Address of a pointer to an ID3DXEffectCompiler interface containing the effect compiler.
ppParseErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface containing any error messages that occurred during compilation. This parameter can be set to NULL to ignore error messages.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXCreateEffectCompilerFromFile, D3DXCreateEffectCompilerFromResource


D3DXCreateEffectCompilerFromFile

Creates an effect compiler from an ASCII effect description.

HRESULT D3DXCreateEffectCompilerFromFile(
  LPCTSTR pSrcFile,
  CONST D3DXMACRO* pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXEFFECTCOMPILER * ppEffectCompiler,
  LPD3DXBUFFER * ppParseErrors
);

Parameters

pSrcFile
[in] Pointer to the filename. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by various flags (see D3DXSHADER Flags). The Direct3D 10 HLSL compiler is now the default. See DirectX 10 HLSL Compiler (Direct3D 10) for details.
ppEffectCompiler
[out, retval] Address of a pointer to an ID3DXEffectCompiler interface, containing the effect compiler.
ppParseErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing any error messages that occurred during compilation. This parameter can be set to NULL to ignore error messages.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the LPCTSTR data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectCompilerFromFileW. Otherwise, the function call resolves to D3DXCreateEffectCompilerFromFileA because ANSI strings are being used.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromResource


D3DXCreateEffectCompilerFromResource

Creates an ID3DXEffectCompiler from an ASCII effect description.

HRESULT D3DXCreateEffectCompilerFromResource(
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  CONST D3DXMACRO * pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXEFFECTCOMPILER * ppEffectCompiler,
  LPD3DXBUFFER * ppParseErrors
);

Parameters

hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to the resource. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by various flags (see D3DXSHADER Flags). The Direct3D 10 HLSL compiler is now the default. See DirectX 10 HLSL Compiler (Direct3D 10) for details.
ppEffectCompiler
[out, retval] Address of a pointer to an ID3DXEffectCompiler interface, containing the effect compiler.
ppParseErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing any error messages that occurred during compilation. This parameter can be set to NULL to ignore error messages.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the LPCTSTR data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectCompilerFromResourceW. Otherwise, the function call resolves to D3DXCreateEffectCompilerFromResourceA because ANSI strings are being used.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromFile


D3DXCreateEffectFromFile

Create an effect from an ASCII or binary effect description.

HRESULT D3DXCreateEffectFromFile(
  LPDIRECT3DDEVICE9 pDevice,
  LPCTSTR pSrcFile,
  CONST D3DXMACRO * pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXEFFECTPOOL pPool,
  LPD3DXEFFECT * ppEffect,
  LPD3DXBUFFER * ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device that will create the effect. See IDirect3DDevice9.
pSrcFile
[in] Pointer to the filename. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Optional NULL-terminated array of preprocessor macro definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] If pSrcFile contains a text effect, flags can be a combination of D3DXSHADER Flags and D3DXFX flags; otherwise, pSrcFile contains a binary effect and the only flags honored are D3DXFX flags. The Direct3D 10 HLSL compiler is now the default. See DirectX 10 HLSL Compiler (Direct3D 10) for details.
pPool
[in] Pointer to a ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a pointer to a buffer containing the compiled effect. See ID3DXEffect.
ppCompilationErrors
[out] Returns a pointer to a buffer containing a listing of compile errors. See ID3DXBuffer.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

E_OUTOFMEMORY

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the LPCTSTR data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectFromFileW. Otherwise, the function call resolves to D3DXCreateEffectFromFileA because ANSI strings are being used.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCreateEffectFromFileEx

Create an effect from an ASCII or binary effect description. This function is an extended version of D3DXCreateEffectFromFile that allows an application to control which parameters are ignored by the effects system.

HRESULT D3DXCreateEffectFromFileEx(
  LPDIRECT3DDEVICE9 pDevice,
  LPCTSTR pSrcFile,
  CONST D3DXMACRO * pDefines,
  LPD3DXINCLUDE pInclude,
  LPCSTR pSkipConstants,
  DWORD Flags,
  LPD3DXEFFECTPOOL pPool,
  LPD3DXEFFECT * ppEffect,
  LPD3DXBUFFER * ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device that will create the effect. See IDirect3DDevice9.
pSrcFile
[in] Pointer to the filename. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Optional NULL-terminated array of preprocessor macro definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
pSkipConstants
[in] A string of effect parameters that will be ignored by the effect system. The string must be NULL terminated, and needs to contain the name of each application-managed constant separated by a semicolon.
Flags
[in] If pSrcFile contains a text effect, flags can be a combination of D3DXSHADER Flags and D3DXFX flags; otherwise, pSrcFile contains a binary effect and the only flags honored are D3DXFX flags. The Direct3D 10 HLSL compiler is now the default. See DirectX 10 HLSL Compiler (Direct3D 10) for details.
pPool
[in] Pointer to a ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a pointer to a buffer containing the compiled effect. See ID3DXEffect.
ppCompilationErrors
[out] Returns a pointer to a buffer containing a listing of compile errors. See ID3DXBuffer.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

E_OUTOFMEMORY

Remarks

This function is an extended version of D3DXCreateEffectFromFile that allows an application to specify which effect constants will be managed by the application. A constant that is managed by the application is ignored by the effects system. That is, the application is responsible for initializing the constant as well as saving and restoring its state whenever appropriate.

This function checks each constant in pSkipConstants to see that:

  • It is bound to a constant register.
  • It is only used in HLSL shader code.

If a constant is named in the string that is not present in the effect, it is ignored.

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the LPCTSTR data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectFromFileW. Otherwise, the function call resolves to D3DXCreateEffectFromFileA because ANSI strings are being used.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXCreateEffectEx, D3DXCreateEffectFromResourceEx


D3DXCreateEffectFromResource

Create an effect from an ASCII or binary effect description.

HRESULT D3DXCreateEffectFromResource(
  LPDIRECT3DDEVICE9 pDevice,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  CONST D3DXMACRO * pDefines,
  LPD3DXINCLUDE pInclude,
  DWORD Flags,
  LPD3DXEFFECTPOOL pPool,
  LPD3DXEFFECT * ppEffect,
  LPD3DXBUFFER * ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device.
hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to the resource. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] If hSrcModule contains a text effect, flags can be a combination of D3DXSHADER Flags and D3DXFX flags; otherwise, hSrcModule contains a binary effect and the only flags honored are D3DXFX flags. The Direct3D 10 HLSL compiler is now the default. See DirectX 10 HLSL Compiler (Direct3D 10) for details.
pPool
[in] Pointer to a ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a buffer containing the compiled effect.
ppCompilationErrors
[out] Returns a buffer containing a listing of compile errors.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

E_OUTOFMEMORY

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the LPCTSTR data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectFromResourceW. Otherwise, the function call resolves to D3DXCreateEffectFromResourceA because ANSI strings are being used.

D3DXCreateEffectFromResource loads data from a resource of type RT_RCDATA. See MSDN for more information about Windows resources.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCreateEffectFromResourceEx

Create an effect from an ASCII or binary effect description. This is an extended version of D3DXCreateEffectFromResource that allows an application to control which parameters are ignored by the effects system.

HRESULT D3DXCreateEffectFromResourceEx(
  LPDIRECT3DDEVICE9 pDevice,
  HMODULE hSrcModule,
  LPCTSTR pSrcResource,
  CONST D3DXMACRO * pDefines,
  LPD3DXINCLUDE pInclude,
  LPCSTR pSkipConstants,
  DWORD Flags,
  LPD3DXEFFECTPOOL pPool,
  LPD3DXEFFECT * ppEffect,
  LPD3DXBUFFER * ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device.
hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to the resource. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
pSkipConstants
[in] A string of effect parameters that will be ignored by the effect system. The string must be NULL terminated, and needs to contain the name of each application-managed constant separated by a semicolon.
Flags
[in] If pSrcResource contains a text effect, flags can be a combination of D3DXSHADER Flags and D3DXFX flags; otherwise, pSrcResource contains a binary effect and the only flags honored are D3DXFX flags. The Direct3D 10 HLSL compiler is now the default. See DirectX 10 HLSL Compiler (Direct3D 10) for details.
pPool
[in] Pointer to an ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a buffer containing the compiled effect.
ppCompilationErrors
[out] Returns a buffer containing a listing of compile errors.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

E_OUTOFMEMORY

Remarks

This function is an extended version of D3DXCreateEffectFromResource that allows an application to specify which effect constants will be managed by the application. A constant that is managed by the application is ignored by the effects system. That is, the application is responsible for initializing the constant as well as saving and restoring its state whenever appropriate.

This function checks each constant in pSkipConstants to see that:

  • It is bound to a constant register.
  • It is only used in HLSL shader code.

If a constant is named in the string that is not present in the effect, it is ignored.

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the LPCTSTR data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectFromResourceW. Otherwise, the function call resolves to D3DXCreateEffectFromResourceA because ANSI strings are being used.

D3DXCreateEffectFromResource loads data from a resource of type RT_RCDATA. See MSDN for more information about Windows resources.

Requirements

Header: Declared in D3DX9Effect.h.

See Also

D3DXCreateEffectEx, D3DXCreateEffectFromFileEx


D3DXCreateEffectPool

Create an effect pool. A pool is used to share parameters between effects.

HRESULT D3DXCreateEffectPool(
  LPD3DXEFFECTPOOL* ppPool
);

Parameters

ppPool
[out] Returns a pointer to the created pool.

Return Values

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value will be E_FAIL.

Remarks

For effects within a pool, shared parameters with the same name share values.

Requirements

Header: Declared in D3DX9Effect.h.


D3DXDisassembleEffect

Disassemble an effect.

HRESULT D3DXDisassembleEffect(
  LPD3DXEFFECT pEffect,
  BOOL EnableColorCode,
  LPD3DXBUFFER * ppDisassembly
);

Parameters

pEffect
[in] Pointer to an ID3DXEffect interface that contains the effect.
EnableColorCode
[in] Enable color coding to make the disassembly easier to read.
ppDisassembly
[out] Returns a buffer containing the disassembled shader. See ID3DXBuffer.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA.

E_OUTOFMEMORY

Requirements

Header: Declared in D3DX9Effect.h.


Effect Structures

This section contains information about the structures used by effects.

  • D3DXEFFECT_DESC
  • D3DXEFFECTDEFAULT
  • D3DXEFFECTINSTANCE
  • D3DXFRAGMENT_DESC
  • D3DXFUNCTION_DESC
  • D3DXMACRO
  • D3DXPARAMETER_DESC
  • D3DXPASS_DESC
  • D3DXSEMANTIC
  • D3DXTECHNIQUE_DESC


D3DXEFFECT_DESC

Describes an effect object.

typedef struct D3DXEFFECT_DESC {
    LPCSTR Creator;
    UINT Parameters;
    UINT Techniques;
    UINT Functions;
} D3DXEFFECT_DESC, *LPD3DXEFFECT_DESC;

Members

Creator
String that contains the name of the effect creator.
Parameters
Number of parameters used for effect.
Techniques
Number of techniques that can render the effect.
Functions
Number of functions that can render the effect.

Remarks

An effect object can contain multiple rendering techniques and parameters for the same effect.


D3DXEFFECTDEFAULT

Effect default parameters.

typedef struct D3DXEFFECTDEFAULT {
    LPSTR pParamName;
    D3DXEFFECTDEFAULTTYPE Type;
    DWORD NumBytes;
    LPVOID pValue;
} D3DXEFFECTDEFAULT, *LPD3DXEFFECTDEFAULT;

Members

pParamName
Parameter name.
Type
Data type in pValue. For more information, see D3DXEFFECTDEFAULTTYPE
NumBytes
Size, in bytes, of the data pointed to by pValue.
pValue
Pointer to the memory location that contains the data.


D3DXEFFECTINSTANCE

Data type for managing a set of default effect parameters.

typedef struct D3DXEFFECTINSTANCE {
    LPSTR pEffectFilename;
    DWORD NumDefaults;
    LPD3DXEFFECTDEFAULT pDefaults;
} D3DXEFFECTINSTANCE, *LPD3DXEFFECTINSTANCE;

Members

pEffectFilename
Name of the effect file.
NumDefaults
Number of default parameters.
pDefaults
Pointer to an array of D3DXEFFECTDEFAULT elements, each of which contains an effect parameter.


D3DXFRAGMENT_DESC

Describes an annotation used by an effect object.

typedef struct D3DXFRAGMENT_DESC {
    LPCSTR Name;
    DWORD Target;
} D3DXFRAGMENT_DESC, *LPD3DXFRAGMENT_DESC;

Members

Name
Fragment name.
Target
Fragment compile target. The compile target identifies the shader type (vertex or pixel) and the version number.


D3DXFUNCTION_DESC

Describes a function used by an effect.

typedef struct D3DXFUNCTION_DESC {
    LPCSTR Name;
    UINT Annotations;
} D3DXFUNCTION_DESC, *LPD3DXFUNCTION_DESC;

Members

Name
Function name.
Annotations
Unused. This member will always be set to zero by ID3DXBaseEffect::GetFunctionDesc.


D3DXMACRO

Describes preprocessor definitions used by an effect object.

typedef struct D3DXMACRO {
    LPCSTR Name;
    LPCSTR Definition;
} D3DXMACRO, *LPD3DXMACRO;

Members

Name
Preprocessor name.
Definition
Definition name.

Remarks

To use D3DXMACROs in more than one line, prefix each new line character with a backslash (like a #define in the C language). For example:

sample=
macro.Name = "DO_CODE_BLOCK";
macro.Definition =
    "/* here is a block of code */\\\n"
    "{ do something ... }\\\n";

Notice the 3 backslash characters at the end of the line. The first two are required to output a single '\', followed by the newline character "\n". Optionally, you may also want to terminate your lines using "\\\r\n".

See Also

D3DXCreateEffectFromFile


D3DXPARAMETER_DESC

Describes a parameter used for an effect object.

typedef struct D3DXPARAMETER_DESC {
    LPCSTR Name;
    LPCSTR Semantic;
    D3DXPARAMETER_CLASS Class;
    D3DXPARAMETER_TYPE Type;
    UINT Rows;
    UINT Columns;
    UINT Elements;
    UINT Annotations;
    UINT StructMembers;
    DWORD Flags;
    UINT Bytes;
} D3DXPARAMETER_DESC, *LPD3DXPARAMETER_DESC;

Members

Name
Name of the parameter.
Semantic
Semantic meaning, also called the usage.
Class
Parameter class. Set this to one of the values in D3DXPARAMETER_CLASS.
Type
Parameter type. Set this to one of the values in D3DXPARAMETER_TYPE.
Rows
Number of rows in the array.
Columns
Number of columns in the array.
Elements
Number of elements in the array.
Annotations
Number of annotations.
StructMembers
Number of structure members.
Flags
Parameter attributes. See Effect Constants.
Bytes
The size of the parameter, in bytes.


D3DXPASS_DESC

Describes a pass for an effect object.

typedef struct D3DXPASS_DESC {
    LPCSTR Name;
    UINT Annotations;
    CONST DWORD * pVertexShaderFunction;
    CONST DWORD * pPixelShaderFunction;
} D3DXPASS_DESC, *LPD3DXPASS_DESC;

Members

Name
String value used for the pass.
Annotations
Annotations are user-specific data that can be attached to any technique, pass, or parameter. See Add Information to Effect Parameters with_Annotations.
pVertexShaderFunction
Pointer to the vertex shader function. If an effect is created with D3DXFX_NOT_CLONEABLE, this structure will return a NULL pointer when called by ID3DXBaseEffect::GetPassDesc.
pPixelShaderFunction
Pointer to the pixel shader function. If an effect is created with D3DXFX_NOT_CLONEABLE, this structure will return a NULL pointer when called by ID3DXBaseEffect::GetPassDesc.

See Also

ID3DXBaseEffect::GetPassDesc


D3DXSEMANTIC

Semantics map a parameter to vertex or pixel shader registers. They can also be optional descriptive strings attached to non-register parameters.

typedef struct D3DXSEMANTIC {
    UINT Usage;
    UINT UsageIndex;
} D3DXSEMANTIC, *LPD3DXSEMANTIC;

Members

Usage
Options that identify how resources are used. See D3DDECLUSAGE.
UsageIndex
Options that modify how the usage is interpreted. The usage and usage index make up a vertex declaration. See Vertex Declaration (Direct3D 9).

Remarks

Semantics are required for vertex and pixel shader, input and output registers.


D3DXTECHNIQUE_DESC

Describes a technique used by an effect.

typedef struct D3DXTECHNIQUE_DESC {
    LPCSTR Name;
    UINT Passes;
    UINT Annotations;
} D3DXTECHNIQUE_DESC, *LPD3DXTECHNIQUE_DESC;

Members

Name
String that contains the technique name.
Passes
Number of rendering passes the technique requires. See Remarks.
Annotations
The number of annotations. See Add Information to Effect Parameters with_Annotations.

Remarks

Some video cards can render two textures in a single pass. However, if a card does not have this capability, it is often possible to render the same effect in two passes, using one texture for each pass.


Effect Constants

These are shader and effect constants.

  • D3DX_PARAMETER
  • D3DXFX

Effects use Handles to reference techniques, passes, annotations, and parameters.

typedef LPCSTR D3DXHANDLE


D3DX_PARAMETER

These flags provide additional information about effect parameters.

#define | Description
D3DX_PARAMETER_ANNOTATION | This parameter is marked as an annotation. See Add Information to Effect Parameters with Annotations.
D3DX_PARAMETER_LITERAL | This parameter is marked as a literal value. Literal parameters cannot change after compile, allowing the compiler to optimize their usage. Shared parameters cannot be marked as a literal. See Usages and Literals.
D3DX_PARAMETER_SHARED | The value of a parameter will be shared by all effects in the same namespace. Changing the value in one effect will change it in all shared effects. See Sharing Parameters. D3DX_PARAMETER_SHARED cannot be combined with D3DX_PARAMETER_LITERAL or D3DX_PARAMETER_ANNOTATION.

Effect parameter constants are used by D3DXPARAMETER_DESC.


D3DXFX

Options for saving and creating effects.

Effect State Save and Restore Flags
Name | Description
D3DXFX_DONOTSAVESTATE | No state is saved when calling ID3DXEffect::Begin or restored when calling ID3DXEffect::End.
D3DXFX_DONOTSAVESAMPLERSTATE | A stateblock saves state when calling ID3DXEffect::Begin and restores state when calling ID3DXEffect::End.
D3DXFX_DONOTSAVESHADERSTATE | A stateblock saves state (except shaders and shader constants) when calling ID3DXEffect::Begin and restores state when calling ID3DXEffect::End.
Effect Creation Flag
Name | Description
D3DXFX_NOT_CLONEABLE | The effect will be non-cloneable and will not contain any shader binary data. ID3DXBaseEffect::GetPassDesc will not return shader function pointers. Setting this flag reduces effect memory usage by about 50% because it eliminates the need for the effect system to keep a copy of the shaders in memory. This flag is used by D3DXCreateEffect, D3DXCreateEffectFromFile, and D3DXCreateEffectFromResource.
D3DXFX_LARGEADDRESS_HANDLE | Define this value before including d3dx9.h so that your application fails to compile when attempting to pass strings into D3DXHANDLE parameters. This will aid in making sure that valid information is being passed to the runtime.
D3DXFX_LARGEADDRESSAWARE Enables the allocation of an effect resource into the uppder address space of a machine. One important limitation is that you cannot use strings and handles interchangeably. For example, the following would no longer work.
g_pEffect->SetMatrix( "g_mWorldViewProjection", &mWorldViewProjection );
Instead, a method such as ID3DXBaseEffect::GetParameterByName must be used to store the handle of the parameter, which is then used to pass variables to the effect.

The effect system uses state blocks to save and restore state automatically. For more information about state blocks, see State Blocks Save and Restore State (Direct3D 9).

Linker flag

Setting the linker flag LARGE_ADDRESS_AWARE = 1 will will allow the application to allocate resources past the 2GB address limit when needed.


Effect Format

This section contains reference information for the effect format.

An effect is made up of parameters, techniques, and functions.

  • Parameters
  • Techniques and Passes
  • Effect Function Syntax

These are made up of id's, semantics, annotations, etc.

  • Cloning and Sharing
  • Expressions
  • Handles
  • Effect States
  • Usages and Literals
  • Validation


Parameters

Parameters are effect variables.

Syntax

usage  type  id  [: semantic]  [< annotation(s) >]  [= expression];

Parameters can be read from and written to by the application with ID3DXEffect or ID3DXEffectCompiler.

Parameters can be referenced in functions and in techniques (specifically, in the right side of state assignments).

  • usage - Scope of the parameter. See Usages and Literals.
  • type - Any valid HLSL Shader Reference (Direct3D 9 HLSL) type.
  • id - A unique name.
  • semantic - A tag following identifer rules that typically indicates the usage of the parameter. Must be a particular type.
  • annotations - Zero or more pieces of user-specific information. May be any type. See Add Information to Effect Parameters with Annotations.
  • expression - Initializes the parameter's value. See Expressions.

Parameters can be initialized to any valid HLSL Shader Reference (Direct3D 9 HLSL) expression that reduces to a literal value.

Parameter values are not changed by the execution of state assignment or function calls.


Techniques and Passes

Techniques provide the rendering muscle. A technique encapsulates the effect state that determines a rendering style. A technique is made up of one or more passes.

Techniques

The syntax for calling a technique is as follows:

technique [ id ]  [< annotation(s) >]
    { pass(es) }

Where:

  • id is an optional unique name.
  • annotation is zero or more optional pieces of user-specific information. See Add Information to Effect Parameters with_Annotations.
  • pass(es) is zero or more passes. Each pass contains state assignments. See below.

Passes

A pass contains the state assignments required to render.

pass  [ id ]  [< annotation(s) >]
    { state assignment(s) }

Where:

  • id is an optional unique name.
  • annotation is one or more optional piece of user-specific information. See Add Information to Effect Parameters with_Annotations.
  • assignment(s) assigns zero or more state values, or evaluates one or more expressions. See Effect States and Expressions.

Passes ignore all but the last assignment in a set of repeated assignments to the same state.


Effect Function Syntax

A function is the building block for a shader created in the high-level language. If you prefer to write shaders in a C-style language instead of in assembly language, you will want to write functions.

Syntax

type id ( [ parameters ] )
    { body }

Functions do not change parameter values in an effect.

  • type - Any valid HLSL Shader Reference (Direct3D 9 HLSL) type.
  • id - A unique name.
  • parameters - Function parameters.
  • body - The body of the function.

Functions are built from the high-level language. See HLSL Shader Reference (Direct3D 9 HLSL).


Cloning and Sharing

Cloning Parameters

Cloning has the following restrictions.

  • Clones inherit the original effect's pool. See the Sharing Parameters section.
  • Clones inherit the original effect's techniques, passes, parameters, and annotations (including all annotations added with ID3DXEffect).
  • Clones inherit the original effect's dynamically added annotations.
  • Cloning onto a new device will fail if the original effect's pool was not NULL and the original effect contained a shared device-dependent parameter (such as a texture or shader).

Sharing Parameters

A pool is a buffer that shares effect parameters between different effects. To add parameters to a pool, specify a shared usage when the effect is created.

A pool has the following restrictions.

  • A parameter is added to the pool the first time an effect containing that (shared) parameter is added to the pool.
  • A pool gets initial values from the first shared parameter; parameters shared subsequently get their values from the pool.
  • A parameter is deleted from the pool when all effect references to the shared parameter are released.
  • All effects in the pool that contain the same (shared) device-dependent parameter must have the same device.

NULL can be used to specify no pool, in which case no parameters are shared. This is almost equivalent to specifying a unique pool just for this effect. The single difference is that when the effect is cloned, the clone will not share its shared parameters with the original.


Expressions

Expressions are mathematical or logical statements that are used on the right hand side of an equals sign. There are many types of expressions.

Expressions

  1. Variable Reference
    ( variable ) or<variable >
  2. Numeric Scalar
    scalar
  3. Numeric Expression
    ( numeric expression )

    All standard numeric HLL expressions are supported here.

  4. Constructor
    type ( constructor arguments )
  5. List of Initializers
    { scalar value [, scalar value ...  ] }

    The scalars must be literal scalar values.

    The number of initializers must be compatible with the variable (state) on the left hand side of the equals sign.

  6. OR Expression
    token [ | token ... ]

    The tokens must be compatible with the variable (state) on the left hand side of the equals sign.

    The tokens are not case sensitive.

  7. NULL
    NULL

    NULL can only be assigned to a shader, sampler, or a texture object.

  8. Assembly Block
    asm { code }

    PS Assembly Blocks must be assigned to the PIXELSHADER state.

    VS Assembly Blocks must be assigned to the VERTEXSHADER state.

  9. Sampler State Block
    sampler_state { [ state = expression ; [ state = ... ] ] }

    Sampler state blocks are sequences of un-indexed sampler stage state or texture assignments.

    Sampler state blocks must be assigned to the SAMPLER effect state.

  10. Effect State State Block
    stateblock_state { [ state [ [index] ] = expression;
    [ state [ [index] ] = ... ] ] }

    State blocks are sequences of general state. State blocks can be nested, but cannot contain circular references.

    State blocks must be assigned to the STATEBLOCK effect state.

  11. HLSL Compile
    compile target entrypoint ( [ arguments ] )

    The vertex shader vs_m_n target indicates D3DVS_VERSION(m, n) vertex shader version. The pixel shader ps_m_n target indicates D3DPS_VERSION(m, n) pixel shader version.

    Vertex shader high-level language compile expressions can only be assigned to the VERTEXSHADER effect state. Pixel shader high-level language compile expressions can only be assigned to the PIXELSHADER effect state.


Handles

Handles provide an efficient means for referencing the techniques, passes, annotations, and parameters with ID3DXEffectCompiler or ID3DXEffect. They are generated dynamically when you call functions of the form Get[Parameter|Annotation|Function|Technique|Pass][ByName|BySemantic|Element].

While running a program, generating a handle to the same object multiple times will return the same handle back every time. But don't rely on the handle staying constant when you run your program multiple times. Also be aware that handles generated by different instances of ID3DXEffect and ID3DXEffectCompiler will be different.

If you view the header files, you'll notice that handles (D3DXHANDLEs) are technically string pointers.

The handles that you pass into functions such as GetParameter[ByName|Element|BySemantic] or GetAnnotation[ByName] can be in three forms as follows:

  1. Handles that were returned by functions such as GetParameter[ByName|Element|BySemantic].
  2. Strings such as MyVariableName, MyTechniqueName, or MyArray[0].
  3. Handle = NULL. There are four cases.
    • If it is a method return value, the method failed to find the handle.
    • If a NULL handle is passed in as the first parameter of GetParameter[ByName|Element|BySemantic], the function returns a top-level parameter. Conversely, if the handle is non-NULL, the function returns a structure member or element identified by the handle.
    • If a NULL handle is passed in as the first argument of ValidateTechnique or the second argument of IsParameterUsed, the current technique is validated.
    • If a NULL handle is passed in as the first argument of FindNextValidTechnique, the search for a valid technique starts at the first technique in the effect.

Performance tip At the start of your application, perform an initialization pass to generate handles from the strings. From that point on, use only handles. Passing in strings instead of generated handles is slower.

Examples

Here are some examples using the Get[Parameter|Annotation|Function|Technique|Pass][ByName|BySemantic|Element] functions to generate handles.

// Gets handle of second top-level parameter handle in the effect file
h1 = GetParameter(NULL, 1);

// Gets handle of the third struct member of MyStruct
h2 = GetParameter("MyStruct", 2);

// Gets handle of the third array element handle of MyArray
h3 = GetParameterElement("MyArray", 2);

// Gets handle of first member of h1 (that is, the second top-level param)
h4 = GetParameter(h1, 0);

// Gets handle of MyStruct.Data
h5 = GetParameterByName("MyStruct", "Data");
// or
h6 = GetParameterByName(NULL, "MyStruct.Data");

// Gets handle of MyStruct.Data.SubData
h7 = GetParameterByName("MyStruct.Data", "SubData");
// or
h8 = GetParameterByName(NULL, "MyStruct.Data.SubData");

// Gets handle of fifth annotation of h1 (that is, second top-level param)
h9 = GetAnnotation(h1, 4);

// Gets handle of MyStruct's annotation, called Author
h10 = GetAnnotationByName("MyStruct", "Author");
// or
h11 = GetParameterByName(NULL, "MyStruct@Author");


Effect States

Effect states are used to initialize pipeline states in preparation for vertex and pixel processing.

effect state [ [index] ] = expression;

Where:

  • effect state - Similar to the traditional fixed function pipeline states. A complete list of states is provided below.
  • [ [index] ] - Optional integer index. The index identifies a particular state within an array of effect states. The outer brackets indicate that an index is optional. If an index is used, be sure to use the inner brackets.
  • expression - State assignment expression. See Expressions.

Each state has a native data type. This is the data type that the state expects values to be in when the effect assigns them. The data types that each state expects are listed below.

Note that the effect interface will attempt to cast values to the appropriate type as early as possible. Literal values can be cast at compile time. Non-literals (i.e. regular variables) need to be cast when the appropriate Set methods are called. For example, the effect interface will cast values set using ID3DXBaseEffect::SetBool, ID3DXBaseEffect::SetValue, and other similar functions if necessary. For better performance ensure that the values passed to the effect interface are already the correct type and will not need casting. If the runtime is unable to cast a value, an error is returned.

Effect states can be broken up into the following categories:

  • Light States
  • Material States
  • Render States
    • Pixel Pipe Render States
    • Vertex Pipe Render States
  • Sampler States
  • Sampler Stage States
  • Shader States
  • Shader Constant States
  • Texture States
  • Texture Stage States
  • Transform States

Light States

To enable the best performance for applying an effect, all components of a light or a material should be specified in the effect file. States that you fail to declare are set to some default value because there is no way for Direct3D to set light states individually.

Light State | Type | Values
LightAmbient[n] | float4 | See the Ambient member of D3DLIGHT9.
LightAttenuation0[n] | float | See the Attenuation0 member of D3DLIGHT9.
LightAttenuation1[n] | float | See the Attenuation1 member of D3DLIGHT9.
LightAttenuation2[n] | float | See the Attenuation2 member of D3DLIGHT9.
LightDiffuse[n] | float4 | See the Diffuse member of D3DLIGHT9.
LightDirection[n] | float3 | See the Direction member of D3DLIGHT9.
LightEnable[n] | bool | True or False. See the bEnable argument in IDirect3DDevice9::LightEnable.
LightFalloff[n] | float | D3DCOLORVALUE. See the Falloff member of D3DLIGHT9.
LightPhi[n] | float | See the Phi member of D3DLIGHT9.
LightPosition[n] | float3 | See the Position member of D3DLIGHT9.
LightRange[n] | float | See the Range member of D3DLIGHT9.
LightSpecular[n] | float4 | See the Specular member of D3DLIGHT9.
LightTheta[n] | float | See the Theta member of D3DLIGHT9.
LightType[n] | dword | Same value as the array of up to n D3DLIGHTTYPE values without the D3DLIGHT_ prefix.

Example:

LightEnable[0] = TRUE;
LightType[0] = POINT;
LightPosition[0] = float3<10.0f, 1.0f, 23.0f>;
LightAmbient[0] = float4<0.7f, 0.0f, 0.0f, 1.0f>;

This will enable lighting, make point lighting the type, set the light postion to float3<10.0f, 1.0f, 23.0f>, and set the ambient color to float4<0.7f, 0.0f, 0.0f, 1.0f>.

Material States

States that you fail to declare are set to some default value because there is no way for Direct3D to set material states individually.

Material State | Type | Values
MaterialAmbient | float4 | Same value as Ambient
MaterialDiffuse | float4 | Same value as Diffuse
MaterialEmissive | float4 | Same value as Emissive
MaterialPower | float | Same value as Power
MaterialSpecular | float4 | Same value as Specular

Example:

MaterialDiffuse = float4<0.7f, 0.0f, 0.0f, 1.0f>;
MaterialPower = 3.0f;

This will set the diffuse color to float4<0.7f, 0.0f, 0.0f, 1.0f> and make the power of the material 3.0f.

Render States

There are two types of render states:

  • Pixel Pipe Render States
  • Vertex Pipe Render States

Pixel Pipe Render States

Effect file render states have names similar to the fixed function pipeline states, often with the prefix removed.

Render State | Type | Values
AlphaBlendEnable | bool | True or False. Same values as D3DRS_ALPHABLENDENABLE in D3DRENDERSTATETYPE.
AlphaFunc | dword | Same values as D3DCMPFUNC without the D3DCMP_ prefix. See D3DRS_ALPHAFUNC.
AlphaRef | dword | Same values as D3DRS_ALPHAREF.
AlphaTestEnable | dword | True or False. See D3DRS_ALPHATESTENABLE.
BlendOp | dword | Same values as D3DBLENDOP without the D3DBLENDOP_ prefix.
ColorWriteEnable | dword | Bitwise combination of RED|GREEN|BLUE|ALPHA. See D3DRS_COLORWRITEENABLE.
DepthBias | float | Same values as D3DRS_DEPTHBIAS.
DestBlend | dword | Same values as D3DBLEND without the D3DBLEND_ prefix.
DitherEnable | bool | True or False. Same values as D3DRS_DITHERENABLE.
FillMode | dword | Same values as D3DFILLMODE without the D3DFILL_ prefix.
LastPixel | dword | True or False. See D3DRS_LASTPIXEL.
ShadeMode | dword | Same values as D3DSHADEMODE without the D3DSHADE_ prefix.
SlopeScaleDepthBias | float | Same values as D3DRS_SLOPESCALEDEPTHBIAS.
SrcBlend | dword | Same values as D3DBLEND without the D3DBLEND_ prefix.
StencilEnable | bool | True or False. Same values as D3DRS_STENCILENABLE.
StencilFail | dword | Same values as D3DSTENCILCAPS without the D3DSTENCILCAP_ prefix. See D3DRS_STENCILFAIL.
StencilFunc | dword | Same values as D3DCMPFUNC without the D3DCMP_ prefix. See D3DRS_STENCILFUNC.
StencilMask | dword | Same values as D3DRS_STENCILMASK.
StencilPass | dword | Same values as D3DSTENCILCAPS without the D3DSTENCILCAP_ prefix. See D3DRS_STENCILPASS.
StencilRef | int | Same values as D3DRS_STENCILREF.
StencilWriteMask | dword | Same values as D3DRS_STENCILWRITEMASK.
StencilZFail | dword | Same values as D3DSTENCILCAPS without the D3DSTENCILCAP_ prefix. See D3DRS_STENCILZFAIL.
TextureFactor | dword | Same values as D3DCOLOR. Same values as D3DRS_TEXTUREFACTOR.
Wrap0 - Wrap15 dword Values are the same as the values used by D3DRS_WRAP0. Valid values are:
  • COORD0 (which corresponds to D3DWRAPCOORD_0)
  • COORD1 (which corresponds to D3DWRAPCOORD_1)
  • COORD2 (which corresponds to D3DWRAPCOORD_2)
  • COORD3 (which corresponds to D3DWRAPCOORD_3)
  • U (which corresponds to D3DWRAP_U)
  • V (which corresponds to D3DWRAP_V)
  • W (which corresponds to D3DWRAP_W)
ZEnable | dword | Same values as D3DZBUFFERTYPE without the D3DZB_ prefix.
ZFunc | dword | Same values as D3DCMPFUNC without the D3DCMP_ prefix. See D3DRS_ZFUNC.
ZWriteEnable | bool | True or False. See D3DRS_ZWRITEENABLE.

Example:

AlphaBlendEnable = TRUE;
FillMode = WIREFRAME;

This will enable alpha blending and make all geometries render in wireframe.

Vertex Pipe Render States

Effect file render states have names similar to the fixed function pipeline states, often with the prefix removed.

Render State | Type | Values
Ambient | float4 | Same values as D3DRS_AMBIENT.
AmbientMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_AMBIENTMATERIALSOURCE.
Clipping | bool | True or False. Same values as D3DRS_CLIPPING.
ClipPlaneEnable | dword | Bitwise combination of D3DCLIPPLANE0 - D3DCLIPPLANE5 macros. See D3DCLIPPLANEn and D3DRS_CLIPPLANEENABLE.
ColorVertex | bool | True or False. Same values as D3DRS_COLORVERTEX.
CullMode | dword | Same values as D3DCULL without the D3DCULL_ prefix.
DiffuseMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_DIFFUSEMATERIALSOURCE.
EmissiveMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_EMISSIVEMATERIALSOURCE.
FogColor | dword | Same values as D3DCOLOR. See D3DRS_FOGCOLOR.
FogDensity | float | Same values as D3DRS_FOGDENSITY.
FogEnable | bool | True or False. Same values as D3DRS_FOGENABLE.
FogEnd | float | Same values as D3DRS_FOGEND.
FogStart | float | Same values as D3DRS_FOGSTART.
FogTableMode | dword | Same values as D3DFOGMODE. See D3DRS_FOGTABLEMODE in D3DRENDERSTATETYPE.
FogVertexMode | dword | Same values as D3DFOGMODE without the D3DFOG_ prefix.
IndexedVertexBlendEnable | bool | True or False. Same values as D3DRS_INDEXEDVERTEXBLENDENABLE.
Lighting | bool | True or False. Same values as D3DRS_LIGHTING.
LocalViewer | bool | True or False. Same values as D3DRS_LOCALVIEWER.
MultiSampleAntialias | bool | Same values as D3DRS_MULTISAMPLEANTIALIAS.
MultiSampleMask | dword | Same values as D3DRS_MULTISAMPLEMASK.
NormalizeNormals | bool | True or False. Same values as D3DRS_NORMALIZENORMALS.
PatchSegments | float | Same values as nSegments in IDirect3DDevice9::SetNPatchMode.
PointScale_A | float | Same values as D3DRS_POINTSCALE_A.
PointScale_B | float | Same values as D3DRS_POINTSCALE_B.
PointScale_C | float | Same values as D3DRS_POINTSCALE_C.
PointScaleEnable | bool | Same values as D3DRS_POINTSCALEENABLE.
PointSize | float | Same values as D3DRS_POINTSIZE.
PointSize_Min | float | Same values as D3DRS_POINTSIZE_MIN.
PointSize_Max | float | Same values as D3DRS_POINTSIZE_MAX without the D3DRS_ prefix.
PointSpriteEnable | bool | True or False. Same values as D3DRS_POINTSPRITEENABLE.
RangeFogEnable | bool | True or False. Same values as D3DRS_RANGEFOGENABLE.
SpecularEnable | bool | True or False. Same values as D3DRS_SPECULARENABLE.
SpecularMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_SPECULARMATERIALSOURCE.
TweenFactor | float | Same values as D3DRS_TWEENFACTOR.
VertexBlend | dword | Same values as D3DVERTEXBLENDFLAGS without the D3DVBF_ prefix. See D3DRS_VERTEXBLEND.

Example:

Ambient = float4<0.7f, 0.0f, 0.0f, 1.0f>;
CullMode = CCW;
FogColor = 0xff0000;

This will make the ambient color float4<0.7f, 0.0f, 0.0f, 1.0f>, set the backface culling mode to counter-clockwise, and set the fog color to red.

Sampler States

A sampler state represents a sampler object.

State | Type | Values
Sampler | sampler | NULL, or a sampler state block.

Sampler Stage States

Sampler stage states are used to sample textures. Sampler state determines filtering types and texture addressing modes.

Sampler State | Type | Values
AddressU[16] | dword | Same values as D3DTEXTUREADDRESS without the D3DTADDRESS_ prefix. See D3DSAMP_ADDRESSU.
AddressV[16] | dword | Same values as D3DTEXTUREADDRESS without the D3DTADDRESS_ prefix. See D3DSAMP_ADDRESSV.
AddressW[16] | dword | Same values as D3DTEXTUREADDRESS without the D3DTADDRESS_ prefix. See D3DSAMP_ADDRESSW.
BorderColor[16] | D3DCOLOR | Same values as D3DTEXTUREFILTERTYPE without the D3DTEXF_ prefix. See D3DSAMP_BORDERCOLOR.
MagFilter[16] | dword | Same values as D3DTEXTUREFILTERTYPE without the D3DTEXF_ prefix. See D3DSAMP_MAGFILTER.
MaxAnisotropy[16] | dword | Same values as D3DSAMP_MAXANISOTROPY without the D3DSAMP_ prefix.
MaxMipLevel[16] | int | Same values as D3DSAMP_MAXMIPLEVEL without the D3DSAMP_ prefix.
MinFilter[16] | dword | Same values as D3DSAMP_MINFILTER without the D3DSAMP_ prefix.
MipFilter[16] | dword | Same values as D3DSAMP_MIPFILTER without the D3DSAMP_ prefix.
MipMapLodBias[16] | float | Same values as D3DSAMP_MIPMAPLODBIAS without the D3DSAMP_ prefix.
SRGBTexture | float | Same value as D3DSAMP_SRGBTEXTURE without the D3DSAMP_ prefix.

Example:

AddressU[0] = CLAMP;
AddressV[0] = CLAMP;
AddressW[0] = CLAMP;

This clamps UVW values to be in between 0 and 1.

Shader States

There are only two effect shader states: one associated with a vertex shader object and the other associated with a pixel shader object.

Shader State | Type | Values
PixelShader | pixelshader | NULL, an assembly block, a compile target, or a pixel shader parameter.
VertexShader | vertexshader | NULL, an assembly block, a compile target, or a pixel shader parameter.

Example:

VertexShader = compile vs_1_1 VSTexture();
PixelShader  = NULL;

This will compile VSTexture, a vertex shader defined earlier in the .fx file, to the vertex shader version 1.1, and then set that compiled shader as the vertex shader. The pixel shader is assigned to null.

Shader Constant States

Shader constant states are used to access shader constant parameters.

Shader Constant State | Type | Values
PixelShaderConstant | float[m[n]] | m x n array of floats; m and n are optional.
PixelShaderConstant1 | float4 | One 4D float.
PixelShaderConstant2 | float4x2 | Two 4D floats.
PixelShaderConstant3 | float4x3 | Three 4D floats.
PixelShaderConstant4 | float4x4 | Four 4D floats.
PixelShaderConstantB | bool[m[n]] | m x n array of bools; m and n are optional.
PixelShaderConstantI | int[m[n]] | m x n array of ints. m and n are optional.
PixelShaderConstantF | float[m[n]] | m x n array of floats. m and n are optional.
VertexShaderConstant | float[m[n]] | m x n array of floats. m and n are optional.
VertexShaderConstant1 | float4 | One 4D float.
VertexShaderConstant2 | float4x2 | Two 4D floats.
VertexShaderConstant3 | float4x3 | Three 4D floats.
VertexShaderConstant4 | float4x4 | Four 4D floats.
VertexShaderConstantB | bool[m[n]] | m x n array of bools. m and n are optional.
VertexShaderConstantI | int[m[n]] | m x n array of ints. m and n are optional.
VertexShaderConstantF | float[m[n]] | m x n array of floats. m and n are optional.

Texture States

Texture states initialize textures used by the multitexture blender.

Texture State | Type | Values
Texture[8] | texture | NULL, or a texture parameter.

Texture Stage States

Texture stage states set up textures and the texture stages in the multitexture blender.

Texture Stage State | Type | Values
AlphaOp[8] | dword | Same as D3DTEXTUREOP without the D3DTOP_ prefix. See D3DTSS_ALPHAOP.
AlphaArg0[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_ALPHAARG0.
AlphaArg1[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_ALPHAARG1.
AlphaArg2[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_ALPHAARG2.
ColorArg0[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_COLORARG0.
ColorArg1[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_COLORARG1.
ColorArg2[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_COLORARG2.
ColorOp[8] | dword | Same as D3DTEXTUREOP without the D3DTOP_ prefix. See D3DTSS_COLOROP.
BumpEnvLScale[8] | float | Same values as D3DTSS_BUMPENVLSCALE without the D3DTSS_TCI prefix.
BumpEnvLOffset[8] | float | Same values as D3DTSS_BUMPENVLOFFSET without the D3DTSS_TCI prefix.
BumpEnvMat00[8] | float | Same values as D3DTSS_BUMPENVMAT00.
BumpEnvMat01[8] | float | Same values as D3DTSS_BUMPENVMAT01.
BumpEnvMat10[8] | float | Same values as D3DTSS_BUMPENVMAT10.
BumpEnvMat11[8] | float | Same values as D3DTSS_BUMPENVMAT11.
ResultArg[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_RESULTARG.
TexCoordIndex[8] | dword | Same values as D3DTSS_TEXCOORDINDEX without the D3DTSS_TCI prefix.
TextureTransformFlags[8] | dword | Same values as D3DTEXTURETRANSFORMFLAGS values without the D3DTTFF_ prefix. See D3DTSS_TEXTURETRANSFORMFLAGS.

Transform States

Set transform states to initialize transformation matrices. Effects use transposed matrices for efficiency. You can provide transposed matrices to an effect, or an effect will automatically transpose the matrices before using them.

Transform State | Type | Values
ProjectionTransform | float4x4 | A 4x4 matrix of floats. Same values as D3DTS_PROJECTION without the D3DTS_ prefix.
TextureTransform[8] | float4x4 | A 4x4 matrix of floats. Same values as D3DTRANSFORMSTATETYPE without the D3DTS_ prefix.
ViewTransform | float4x4 | A 4x4 matrix of floats. Same values as D3DTS_VIEW without the D3DTS_ prefix.
WorldTransform | float4x4 | A 4x4 matrix of floats.


Usages and Literals

Usage is similar to a parameter's scope, because it defines the scope in which the parameter is valid.

Value | Description
const | The parameter will be constant within the scope of all functions. (Note that such parameters can still be written to with either ID3DXEffect or ID3DXEffectCompiler, because this occurs outside the scope of all functions.)
shared | The parameter will be shared in the effect pool.
static | The parameter will be invisible to the application, that is, you cannot access them from ID3DXEffect or ID3DXEffectCompiler.

Marking a parameter as literal indicates that its value will never change. This enables the effect compiler to do extra optimization.

Only non-shared top-level parameters can be marked as literal. Parameters can only be marked as literal with ID3DXEffectCompiler. Literal values cannot be set with ID3DXEffect.


Validation

Validation is performed during the effect compile. To validate the current technique, specify NULL as the technique handle to be validated.

Validation will fail for any of the following:

  • If the specified technique handle does not exist.
  • If the application of any state in any pass of the technique fails.
  • If device validation fails after the application of all the states in any pass of the technique.
  • If the PIXELSHADER or VERTEXSHADER effect states are assigned invalid shaders in any pass of the technique.
  • If the device caps do not support cube mapping, and a TEXTURE effect state is assigned a value of type textureCUBE in any pass of the technique.
  • If the device caps do not support volume mapping and a TEXTURE effect state is assigned a value of type texture3D in any pass of the technique.

For more information, see Effect States.


DirectX Standard Annotations and Semantics Reference

Standard annotations and semantics (DXSAS) provide a method of using shaders in a standard way that enables shaders to be used with tools, applications, and game engines. DXSAS defines a set of semantics and annotations that are attached to host application values and effect parameters for the purpose of sharing effects. In order for these annotations and semantics to be useful, they must be implemented in both the host application and the effect file. This document describes the DXSAS standard which leverages the power of the DirectX Effect Framework to enable host applications and tools to share DirectX effects (.fx files) programmatically, as well as to design interaction with UI.

Background Information

Standard annotations and semantics are designed to bind effect and X-file parameters to host application values. The D3DX Effect Framework (or effects) encapsulates rendering state. By encapsulating rendering state (including vertex, texture, and pixel processing state) in an effect, you can create a library of effects covering a wide range of rendering options. This might include options such as rendering on different types of hardware, or rendering with single or multi-pass blending. For more information on the effect framework, you should refer to Effect Reference. DXSAS builds on top of this framework allowing for a more consistent experience for developers. Once the rendering setup is encapsulated in an effect, the DXSAS standard allows the effect developer to expose the intent of the effect parameters through annotations. These annotations can then be read by any host application or tool (not just the one that was designed to use the effect) that is compliant with the standard will understand how to use the effect in the manner that was designed.

Standardizing the set of effect semantics and annotations that host applications support allow effect authors to create effects that can be used in multiple projects and thus promote a wider community of effect users. The DXSAS standard makes files readable by developers, exchangeable between tools, and enables developers to leverage 3rd party tools for authoring effects for their pipeline.

This document describes the DXSAS standard which uses annotations to express the intent of effect parameters, as well as defining a collection of host application values that host applications agree to make available to an effect.

Authoring Effects with Standard Annotations and Semantics

As you can see from the figure below, the DXSAS standard requires annotations in an effect file, as well as a host application that follows the guidelines described here to work with the file.

The host application must implement the user interface logic and the host environment. To implement DXSAS-compliant effects, read the following topics:

  • The Global Parameter defines information pertinent to the effect, such as the version, or the effect author.
  • Data Binding defines the collection of parameters (as well as their type and structure) that can be used by an effect that can be set by the host application exposed to effects.
  • To associate a user-interface control with an effect parameter, use a UI Annotation. These annotations include: SasUiMax, SasUiMin, SasUiSteps, SasUiStepsPower, and SasUiStride.
  • To initialize an effect parameter with data contained in an external file, use a Parameter Initialization Annotation.
  • When data is transferred between the host application and an effect (or vice versa), Casting and Conversion will occur when the types do not exactly match. This section specifies how data is written when the source and target types differ. In addition, use ParameterValueModifiers to modify how the host application should interpret data read from the effect parameter. These annotations include: SasNormalize and SasUnits.

Case Sensitivity

All identifiers, semantics, and annotation values are case insensitive. Annotation names (not values) are case sensitive. Annotation names are recognized by the D3DX effects system and therefore SAS annotation names are as well.


Global Parameter

Each DXSAS compliant effect must define, as a minimum, a single global effect parameter with the global semantic. The global parameter can also use one or more optional annotations. The syntax is as follows:

int VariableName : SasGlobal
<
    SasVersion
    [OptionalAnnotations]
>;

where:

  • VariableName is a user-specified, ASCII text string variable name.
  • SasGlobal is the semantic keyword that identifies this parameter as the global DXSAS parameter.
  • SasVersion is the only required annotation.
  • OptionalAnnotations can include the following:
    • SasEffectAuthor
    • SasEffectAuthoringSoftware
    • SasEffectCategory
    • SasEffectCompany
    • SasEffectDescription
    • SasEffectHelp
    • SasEffectRevision

SasVersion

The only required annotation is SasVersion. It is declared like this:

int3 SasVersion = { major, minor, revision };

where:

  • major indicates the DXSAS major release. Major releases of DXSAS can contain sweeping changes to the set of semantics and annotations defined. Semantics and annotations can be added and removed and, in general, backward compatibility with previous releases is not guaranteed.
  • minor indicates the SAS minor release. Minor releases of DXSAS can include the addition of new semantics or annotations. Additionally, semantics and annotations may be marked as deprecated in the DXSAS standard. Deprecated semantics and annotations must still be supported by host applications but can emit a warning diagnostic when such a semantic or annotation is used. Minor releases are backward compatible with previous releases.
  • revision indicates the DXSAS revision. Revisions of DXSAS exist only as a means to fix bugs, remove ambiguity, and refine the standard. Revisions to the standard are backward compatible with previous releases.

The current version is 1.0.0. There is no default value for this annotation.

SasEffectAuthor

This declares the person who created the effect. It is declared like this:

string SasEffectAuthor = "value";

where value is a string that identifies the effect author. The default is an empty string.

SasEffectAuthoringSoftware

This declares the software that the effect was authored on. It is declared like this:

string SasEffectAuthoringSoftware = "value";

where value is a string that identifies the effect authoring software. The default is an empty string.

SasEffectCategory

This declares the effect category. It is declared like this:

string SasEffectCategory = "value";

where value is a string that identifies the effect category. The default is an empty string. The category is expressed via a path-like value using the forward slash as a delimiter. Effects can only belong to one category as there is no syntax for expressing inclusion in multiple paths within a single SasEffectCategory value. The value of this annotation is not treated as case-sensitive by the host application.

SasEffectCompany

This declares the company that created the effect. It is declared like this:

string SasEffectCompany = "value";

where value is a string that identifies the name of the company that owns the effect. The default is an empty string.

SasEffectDescription

This describes the effect. It is declared like this:

string SasEffectDescription = "value";

where value is a string that describes the effect. The default is an empty string.

SasEffectHelp

This is a help string that can be displayed to the user whenever help on the associated effect is requested. It is declared like this:

string SasEffectHelp = "value";

where value is a string that can be displayed if the user requests help. The default is an empty string.

SasEffectRevision

This annotation allows tools and users to record the revision number of the associated effect file. For example, users could insert appropriate keywords in the value of this annotation to invoke keyword substitution in their favorite revision control software. It is declared like this:

string SasEffectRevision = "value";

where value is a string that identifies the effect revision. The default is an empty string.

Examples

Here is an example that uses only the single, required annotation:

int gp : SasGlobal
<
  int3 SasVersion = {1,0,0};
>;

Here is an example that uses the required annotation and several optional annotations:

int gp : SasGlobal
<
  int3 SasVersion = {1,0,0};
  string SasEffectAuthoring = "Mike's Shader";
  string SasEffectAuthoringSoftware = "fxe 2.5.4";
  string SasEffectCategory = "/surface/procedural/wood";
  string SasEffectCompany = "Microsoft Corporation";
  string SasEffectDescription = "Renders an irridescent surface.";
  string SasEffectHelp = "For more information, see http://somelocation/skin.htm";
  string SasEffectRevision = "$Revision$";
>;


Data Binding

Use SasHostParameterValue Collection to define the collection of host application values, as well as their type and members, exposed to effects. Use the SasBindAddress annotation in an effect file to associate an effect parameter with its corresponding parameter in the host application.

SasHostParameterValue Collection

The SasHostParameterValue is defined using effect file (.fx) syntax. While the syntax is very similar to the effect file syntax, some differences exist. For example, object types, such as texture2d, samplers, and strings, are not valid in actual effect files, but are valid in the SasHostParameterValue. A host application can implement SasHostParameterValue in any way so long as it conforms to the description below; the actual definition is located in the DXSAS standard effect include file ([SDK Root]/Utilities/Source/Sas/Sas.fxh).

Note that arrays in the SasHostParameterValue such as Lights or Cameras have unbounded length. This means that effects can bind to any arbitrary index in those arrays and host applications must provide meaningful defaults in the cases where no application value can be provided.

Some types and constants are required to be defined in the DXSAS standard include, as noted in the definition of the standard include. This allows effects to easily bind aggregated values from the SasHostParameterValue to structured effect parameters.

SasHostParameterValue Collection | Type | Member
Time | float | Sas.Time.Now
 | float | Sas.Time.Last
 | int | Sas.Time.FrameNumber
Environment Map | textureCUBE | Sas.EnvironmentMap
Camera | SasCamera | Sas.Camera
 | float4x4 | Sas.Camera.WorldToView
 | float4x4 | Sas.Camera.Projection
 | float2 | Sas.Camera.NearFarClipping
Light | SasAmbientLight | AmbientLight[ZeroOrMore];
 | int | Sas.NumAmbientLights
 | SasAmbientLight | DirectionalLight[ZeroOrMore];
 | int | Sas.NumDirectionalLights
 | SasAmbientLight | PointLight[ZeroOrMore];
 | int | Sas.NumPointLights
 | SasAmbientLight | SpotLight[ZeroOrMore];
 | int | Sas.NumSpotLights
Shadow | float4x4 | Sas.Shadow[ZeroOrMore].WorldToShadow
 | texture2D | Sas.Shadow[ZeroOrMore].ShadowMap
Skeleton | float4x4 | Sas.Skeleton.MeshToJointToWorld[OneOrMore]
 | int | Sas.Skeleton.NumJoints

Time

The host application's virtual clock or time value. Members include:

  • Sas.Time.Now - the value of the host application virtual clock at the point at which the effect will be rendered.
  • Sas.Time.Last - the value of Now at the previous render.
  • Sas.Time.FrameNumber - the counter value that is incremented once per rendered frame.

Effects must properly handle the fact that the values of these members can potentially wrap around during extremely long execution times. Now and Last may have very large values.

Environment Map

A cubic environment map. Host applications must provide a valid cube texture if an effect attempts to bind to Sas.EnvironmentMap.

Camera

The camera currently being rendered. Members include:

  • Sas.Camera.WorldToView - the composite world-view matrix for the camera.
  • Sas.Camera.Projection - the projection matrix for the camera.
  • Sas.Camera.NearFarClipping - the values of the near and far clipping planes.

Light

One or more scene lights. The collection of lights is declared as an array where:

  • Color - an RGB color. The default value is (0,0,0).
  • Direction - the light direction. The default value is (0,0,0).
  • Range - the distance from the light where the light rays have no effect on the scene. The default value is 0.
  • Theta - the inner cone angle of a spotlight, measured in radians. The default value is 0.
  • Phi - the outer cone angle of a spotlight, measured in radians. The default value is 0.

The number of lights must be set to the number of lights bound into the associated array. Effects can choose to ignore the number of lights and bind to any element of one of the light arrays. Therefore, host applications must provide a valid binding for elements beyond the number of lights in the array.

ZeroOrMore implies that the array may have any number of elements.

Shadow

Shadow buffers which consists of:

  • WorldToShadow - an array of matrices.
  • ShadowMap - a 2D texture file.

ZeroOrMore implies that the array may have any number of elements (zero means an empty array).

An effect would declare a sampler as follows:

texture2D Shadow
<
  string SasBindAddress = "Sas.Shadow[0].ShadowMap";
>;

sampler ShadowSampler = shadow_sampler(Shadow);

Skeleton

The set of frames that compose the currently rendering object. Frame examples are bones and transforms. This includes:

  • MeshToJointToWorld - an array of matrices.
  • NumJoints - the number of joints in the skeleton.

OneOrMore implies that the array has at least one and may contain any number of elements.

The definition supports both rigid and skinned mesh objects using the same set of SasHostParameterValue Collection values with different interpretation.

SasBindAddress

This annotation is added to the top of an effect file to associate an effect parameter with its corresponding parameter defined in the SasHostParameterValue Collection. The annotation is declared like this:

string SasBindAddress = "SasHostParameterValue";

This example binds the effect world matrix to the MeshToJointToWorld matrix:

float4x3 World
<
  string SasBindAddress = "Sas.Skeleton.MeshToJointToWorld[0]";
>;

This annotation tells the host application that it needs to set the value of the effect world matrix using the data in the MeshToJointToWorld matrix.

The bind address annotation syntax was defined to be very similar with the syntax used by ID3DXEffect to get and set effect parameters. The only difference between the DXSAS grammar and ID3DXEffect methods is the addition of the asterisk index token. Here is another example using the asterisk index:

float3 LightColors[6]
<
  string SasBindAddress = "Sas.Light[*].Color";
>;

The asterisk index token denotes that all elements of the particular host envirnmant value array (color in this case) should be bound in the associated parameter. Multiple asterisk index tokens allow effects to bind to sub-elements of an array of structures without the need to bind the entire structure itself. This example binds the color values of the first six lights to an effect parameter.


UI Annotation

Use this annotation to associate an effect parameter with a UI control in the host environment. This will allow a user to interactively control an effect parameter through the host application.

DXSAS defines a set of standard controls in terms of the data model and basic behavior that effect authors can expect from host applications. The control annotation is used like this:

string SasUiControl = "ControlType";

where ControlType is one of the following:

ControlType | Description | Internal Data Type | Control Property Annotations
None | No control should be shown. Note that a control is visible if SasUiVisible is True and the control type is any type other than None. | n/a | n/a
Any | This implies that no special control is requested. The control presented is the result of application-defined behavior. | n/a | n/a
ColorPicker | Represent a color value as a color swatch. The value is packed into the XYZ components of the associated vector. The W component of the associated vector is always set to one. | floatN where N is 1 to 4 inclusive. | SasUiEnum
Direction | A direction vector. | floatN where N is 2 to 4 inclusive. | None
FilePicker | A dialog box that allows the user to browse and select a file. | string | None
ListPicker | A list of string values from which the user can select one entry. The values are generated from the SasUiEnum annotation. | An array of strings along with an integer value containing the index of the selected string value. | SasUiEnum
Numeric | A set of numerical input controls (such as text boxes). | floatMxN where M and N are 1 to 4 inclusive. | SasUiMin, SasUiMax, SasUiStride
Slider | A set of sliders. | floatMxN where M and N are 1 to 4 inclusive | SasUiMin, SasUiMax, SasUiSteps, SasUiStepsPower
String | An text box for editing string content. | string | None

If the internal data type is not identical to the associated parameter's type, casting will occur when data is transfered from the host application parameter to the effect parameter.

The default is the string "None".

UI Common Properties

SasUiDescription

Use this annotation to specify a string to describe a tool. This could be used for UI elements such as tool tips.

string SasUiDescription = "descriptive string";

For instance:

float3 UpNormal
<
  string SasUiDescription = "The normalized up vector";
>;

The default is an empty string.

SasUiLabel

Use this annotation to specify a string to label any UI control.

string SasUiLabel = "some label;

Here is an example:

float3 UpNormal
<
  string SasUiLabel = "Normal that points up.";
>;

The default is an empty string.

SasUiVisible

Use this annotation to specify whether the associated parameter should be displayed to the user.

bool SasUiVisible = false;

If set to True, the host application should display a UI control for editing the annotated effect parameter. If false, no UI is displayed in the host application.

Here is an example:

float3 UpNormal
<
  string SasUiVisible = false;
>;

The default is True.

UI Control Properties

Control property annotations are additional modifiers that help determine how a particular control operates.

SasUiEnum

This annotation allows you to restrict the range of values for a control. The annotation contains a string of values delimited by commas.

The default is an empty string.

SasUiMax

This annotation specifies the maximum value of the associated parameter. It can only be associated with a numerically-typed parameter. The maximum value of the parameter will actually be calculated as:

MaxValue = min(FLT_MAX, PARAMETER_TYPE_MAX);

PARAMETER_TYPE_MAX is the maximum value for the type used by the associated parameter. This means that the value of the parameter, taking into account the SasUiMax annotation is calculated as:

ParameterValue = min(NewParameterValue, MaxValue);

The default value is FLT_MAX as defined in Math.h.

SasUiMin

This annotation specifies the minimum value of the associated parameter. It can only be associated with any numerically-typed parameter. The minimum value of the parameter will actually be calculated as:

MinValue = max(-FLT_MAX, PARAMETER_TYPE_MIN);

PARAMETER_TYPE_MIN is the minimum value for the type used by the associated parameter. This means that the value of the parameter, taking into account the SasUiMin annotation is calculated as:

ParameterValue = max(NewParameterValue, MinValue);

The default value is -FLT_MAX as defined in Math.h.

SasUiSteps

This annotation specifies the number of steps that can be used when incrementing or decrementing the associated parameter value. The annotation is only meaningful on a numerically-typed parameter. Zero specifies that the host application will choose a reasonable number of steps.

The default value is 0.

SasUiStepsPower

This annotation specifies the exponent in the power function, which has the range [0.0f, 1.0f]. Host applications must implement the following method when calculating parameter values:

ParameterValue = ((SasUiMax - SasUiMin) x pow(UI_VALUE, SasUiStepsPower) + SasUiMin

The default value is 1.0f.

SasUiStride

This annotation specifies the increment that should be used when incrementing or decrementing this value. Unlike SasUiSteps, SasUiStride is useful with a spinner control, for instance, where the data is unbounded and the user would rather increment the parameter value by stride rather than by a pre-defined number of steps. Host applications should increment (or decrement depending on the control behavior) by the value of SasUiStride as follows:

ParameterValue = ParameterValue +/- SasUiStride

The default value is 1.0f.


Parameter Initialization Annotation

Use this annotation to define the contents of an external file as the initialization value for an effect parameter. For example:

string SasResourceAddress = "Value";

where Value is an ASCII text string that may contain an absolute or relative path. A relative path is relative to the directory that contains the effect file.

Here is an example:

texture2D DetailTexture
<
    string SasResourceAddress = "noise.dds";
>;

The default value is an empty string.


Casting and Conversion

When transferring values between the host application and an effect parameter, data is written as expected when the source data type (in the host application) matches the destination data type (in the effect parameter). When the data types differ, casting will occur as the source data is rearranged to fit the destination.

DXSAS defines the following type conversion rules. These are a superset of the effect (.fx) and HLSL type conversion rules. DXSAS also defines some Parameter Value Modifiers that can affect the value being transferred from the host application to a bound parameter.

Type Casting

The following table lists the casting that will occur when one data type is transferred to another data type:

Source Type | Destination Type | Behavior
float | int | Round towards zero.
float, int | bool | Values not equal to 0 - based on a not-equal-to comparison to 0 (int) or 0.0 (float) - are considered to be true, otherwise the value is considered to be false.
int | float |
bool | int, float | False is converted to zero.True is converted to one.
texture1D, texture2D, texture3D, textureCUBE | texture | Destination texture is treated as the source texture type.
string | texture1D, texture2D, texture3D, textureCUBE | String value is treated as a resource address and resolved in the same way as the Parameter Initialization Annotation. If the resource address cannot be resolved, the cast is invalid and the host applications must return an error. If the resource is resolved properly, the type of the expression is treated as the same type as the resolved resource.

Class Casting

In addition to the type casting rules described above, DXSAS defines the set of casting rules necessary to convert between class types. Column matrices (N x 1), row matrices (1 x N), and numeric structures are treated as vectors.

Effect matrix parameters and HLSL matrix variables can define whether the value is a row-major or column-major matrix; however, the DirectX APIs always treat D3DMATRIX and D3DXMATRIX as row-major.

Source Class | Destination Class | Behavior
Scalar | Scalar | Apply Type Casting.
Scalar | Vector | Replicate the scalar source value into every component of the destination vector after applying the type casting and conversion behavior described in Type Casting.
Scalar | Matrix | Replicate the scalar source value into every component of the destination matrix after applying the type casting and conversion behavior described in Type Casting.
Scalar | Object | Invalid cast. Host applications must return an error.
Scalar | Structure | Valid only if the destination structure contains only numeric elements. If valid, replicate the scalar source value into every component of the destination structure after applying the type casting and conversion behavior described in Type Casting.
Vector | Scalar | The destination scalar receives the value of the first component of the source vector after applying the type casting and conversion behavior described in Type Casting.
Vector | Vector | Invalid cast if the destination vector has more components than the source vector. The destination vector receives the left-most values of the source vector after applying the type casting and conversion behavior described in Type Casting. The remaining right-most components of the source vector are lost.
Vector | Matrix | Invalid cast unless the source vector has the same number of components as the destination matrix. If the cast is valid, the behavior of the vector-to-vector cast is then applied.
Vector | Object | Invalid cast. Host applications must return an error.
Vector | Structure | Valid only if the destination structure has only numeric elements and does not contain more elements than the source vector has components. The destination structure's elements receive the left-most components of the source vector after applying the type casting and conversion behavior described in Type Casting.
Matrix | Scalar | The destination scalar receives the value of the upper-left-most value of the source matrix after applying the type casting and conversion behavior described in Type Casting.
Matrix | Vector | Invalid cast unless the source matrix has the same number of components as the destination vector. If the cast is valid, the behavior of the vector-to-vector cast above is then applied.
Matrix | Matrix | Invalid cast if the destination matrix has more components than the source matrix. The destination matrix receives the upper-left-most values of the source matrix after applying the type casting and conversion behavior described in Type Casting. The remaining lower-right-most components of the source matrix are lost.
Matrix | Object | Invalid cast. Host applications must return an error.
Matrix | Structure | The size of the structure must be equal to the size of the matrix and all components of the structure must be numeric.
Object | Scalar | Invalid cast. Host applications must return an error.
Object | Vector | Invalid cast. Host applications must return an error.
Object | Matrix | Invalid cast. Host applications must return an error.
Object | Object | Valid if the types of the objects are identical and in accordance with the behavior defined in Type Casting.
Structure | Scalar | Valid if the source structure contains at least one numeric member. The destination scalar receives the value of the source structure's first numeric member after applying the type casting and conversion behavior described in Type Casting.
Structure | Vector | The source structure must be at least the size of the vector. The first components must be numeric up to the size of the destination vector.
Structure | Matrix | The source structure must be at least the size of the vector. The first components must be numeric up to the size of the destination vector.
Structure | Structure | The destination structure must not be larger than the source structure. A valid cast must exist between all respective source and destination components.

Parameter Value Modifiers

Parameter modifier annotations add additional information to a parameter so the parameter's data can be interpreted properly. For instance, a vector may need to be expressed with normalized data or a length may be measured in inches. Parameter value modifier annotations express this additional information so that host applications can transform values correctly when data is transferred to an effect parameter.

These are the parameter modifiers:

Parameter Value Modifier Annotations | Description
SasNormalize | Specify whether a vector is normalized or not.
SasUnits | Specify the units of measure for a parameter.

SasNormalize

The SasNormalize annotation denotes that the associated parameter should be a normalized value whenever it is assigned. This annotation only affects float2, float3, and float4 parameters.

string SasNormalize = "Value";

where Value is either True or False.

Here is an example:

float3 UpNormal
<
  bool SasNormalize = "True";
>;

SasUnits

The effect parameter data is in the following units:

string SasUnits = "Value";

where Value is one of the following:

Measurement Type | Value | Description
No Units | empty string | No units
Distance | mm | Millimeters
 | cm | Centimeters
 | m | Meters
 | km | Kilometers
Angle | rad | Radians
Time | ms | Milliseconds
 | sec | Seconds
 | min | Minutes
 | hr | Hours
Linear Velocity | mm/sec | Millimeters per second
 | cm/sec | Centimeters per second
 | m/sec | Meters per second
 | m/hr | Meters per hour
 | km/hr | Kilometers per hour
Linear Acceleration | mm/sec2 | Millimeters per second squared
 | cm/sec2 | Centimeters per second squared
 | m/sec2 | Meters per second squared
 | m/hr2 | Meters per hour squared
 | km/hr2 | Kilometers per hour squared
Angular Velocity | rad/sec | Radians per second
Angular Acceleration | rad/sec2 | Radians per second squared
Area | mm2 | Millimeters squared
 | cm2 | Centimeters squared
 | m2 | Meters squared
 | km2 | Kilometers squared
Volume | mm3 | Millimeters cubed
 | cm3 | Centimeters cubed
 | m3 | Meters cubed
 | km3 | Kilometers cubed


Asm Shader Reference

Shaders drive the programmable graphics pipeline.

Vertex Shader Reference

  • vs_1_1
  • vs_2_0
  • vs_2_x
  • vs_3_0

Vertex Shader Differences summarizes the differences between vertex shader versions.

Pixel Shader Reference

  • ps_1_1, ps_1_2, ps_1_3, ps_1_4
  • ps_2_0
  • ps_2_0
  • ps_3_0

Pixel Shader Differences summarizes the differences between pixel shader versions.

Behavior of Constant Registers in Assembly Shaders

There are two ways to set constant registers in an assembly shader:

  • Declare a shader constant in assembly code using one of the def* instructions.
  • Use one of the Set***ShaderConstant* API methods.

Direct3D 9 Shader Constants

In Direct3D 9 the lifetime of defined constants in a given shader is confined to the execution of that shader only (and is non-overridable). Defined constants in Direct3D 9 have no side effects outside of the shader.

Here's an example using Direct3D 9:

Given:
    Create shader1 which references c4 and defines it with the def instruction

Scenario 1:
    Call Set***Shader shader1
    Call Set***ShaderConstant* to set c4
    Call Draw
    Result: The shader will see the def'd value in c4

Given:
    Scenario 1 has just completed
    Create shader2 (which references c4 but does not use the def instruction
      to define it)

Scenario 2:
    Call Set***Shader shader2
    Call Draw
    Result: The shader will see the value last set in c4 by
     Set***ShaderConstant* in scenario 1. This is because shader 2
     didn't def c4.

In Direct3D 9, calling Get***ShaderConstant* will only retrieve constant values set via Set***ShaderConstant*.

Direct3D 8 Shader Constants

This behavior is different in Direct3D 8.x.

Given:
    Create shader1 which references c4 and defines it with the def instruction

Scenario 1 (repeated with Direct3D 8):
    Call Set***Shader with shader1
    Call Set***ShaderConstant to set c4
    Call Draw
    Result: The shader will see the value in c4 from Set***ShaderConstant

In Direct3D 8.x Set***ShaderConstant takes effect immediately. Consider this scenario:

Given:
    Create shader1 which references c4 and defines it with the def instruction

Scenario 3:
    Call Set***Shader with shader1
    Call Draw
    Result: The shader will see the def'd value in c4

Given:
    Scenario 3 has just completed
    Create shader2 (which references c4 but does not use the def instruction
      to define it)

Scenario 4 :
    Call Set***Shader with shader2
    Call Draw
    Result: The shader will see the def'd value in c4 (set by def in shader 1)

The undesirable result is that the order in which the shaders are set could affect the observed behavior of individual shaders.

Shader Driver Model Requirements

Direct3D 9 interfaces are restricted to device driver interface (DDI) drivers that are DirectX 7-level and above. To check the DDI level, run the DirectX Diagnostic Tool and examine the saved text file.

For reference, Direct3D 8 interfaces work only on DDI drivers that are DirectX 6-level and above.

Shader Binary Format

The bitwise layout of the shader instruction stream is defined in D3d9types.h. If you want to design your own shader compiler or construction tools and you want more information about the shader token stream, refer to the Direct3D 9 Driver Development Kit (DDK).

C-like Shader Language

See HLSL Shader Reference (Direct3D 9 HLSL) to experience a C-like shader language.


Vertex Shaders

  • vs_1_1
  • vs_2_0
  • vs_2_x
  • vs_3_0
  • Vertex Shader Differences
  • Vertex Shader Instructions
  • Vertex Shader Registers

To see the newest features introduced in shader model 3, see:

  • Shader Model 3 (Direct3D 9)


vs_1_1

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • Instructions - vs_1_1 contains a list of the available instructions.
  • Registers - vs_1_1 lists the different types of registers used by the vertex shader ALU.
  • Vertex Shader Register Modifiers are used to modify the way an instruction works.
  • Vertex Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied or written.
  • Destination Register Masking determines what components of the destination register get written.


vs_2_0

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • Instructions - vs_2_0 contains a list of the available instructions.
  • Registers - vs_2_0 lists the different types of registers used by the vertex shader ALU.
  • Vertex Shader Register Modifiers are used to modify the way an instruction works.
  • Vertex Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.
  • Destination Register Masking determines what components of the destination register get written.

Instruction Count

Each vertex shader can have up to 256 instructions stored. The number of instructions run can be much higher (because of the loop/rep support), and is capped by D3DCAPS9.MaxVShaderInstructionsExecuted, which should be at least 0xFFFF.


vs_2_x

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

Vertex shader version vs_2_x extends the feature set supported by vs_2_0. Each additional feature is represented by a corresponding cap in the D3DCAPS9 structure within D3DVS20CAPS. To use any of the enhanced features represented by these caps, the vertex shader version must be specified as vs_2_x.

  • Instructions - vs_2_x contains a list of the available instructions.
  • Registers - vs_2_x lists the different types of registers used by the vertex shader ALU.
  • Vertex Shader Register Modifiers are used to modify the way an instruction works.
  • Vertex Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.
  • Destination Register Masking determines what components of the destination register get written.

New Features

New features are as follows:

Dynamic Flow Control

If DynamicFlowControlDepth > 0, then the following dynamic flow control instructions are supported:

  • if_comp - vs
  • break - vs
  • break_comp - vs

If D3DVS20CAPS_PREDICATION is also set, the following additional flow control instructions are supported:

  • setp_comp - vs
  • if pred - vs
  • callnz pred - vs
  • breakp - vs

The range of values for dynamic flow control depth is 0 to 24 and is equal to the nesting depth of the dynamic flow control instructions (see Flow Control Nesting Limits for details). If this cap is zero, the device does not support dynamic flow control instructions.

Number of Temporary Registers

NumTemps represents the number of Temporary Registers supported by the device. The range of values for this cap is 12 to 32.

Static Flow Control Nesting Depth

StaticFlowControlDepth represents the nesting depth of two types of static flow control instructions: loop - vs/rep - vs and call - vs/callnz bool - vs/if bool - vs. loop - vs/rep - vs instructions can be nested up to StaticFlowControlDepth deep. Independently, call - vs/callnz bool - vs instructions can be nested up to StaticFlowControlDepth deep. If D3DVS20CAPS_PREDICATION is also set, then callnz pred - vs is counted toward the nesting depth of call - vs/callnz bool - vs/if bool - vs (see Flow Control Nesting Limits for details).

Predication

If D3DVS20CAPS_PREDICATION is set, the device supports setp_comp - vs and instruction predication. If DynamicFlowControlDepth is also greater then 0, then the following additional dynamic flow control instructions are supported:

  • if pred - vs
  • callnz pred - vs
  • breakp - vs

Instruction Count

Each vertex shader can have up to 256 instructions stored. The number of instructions run can be much higher (because of the loop/rep support), and is capped by MaxVShaderInstructionsExecuted, which should be at least 0xFFFF.


vs_3_0

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

Vertex shader version vs_3_0 extends the feature set supported by vs_2_x. Each of the features in vs_2_X that requires a cap to be set, is available in vs_3_0 without requiring the cap.

  • Instructions - vs_3_0 contains a list of the available instructions.
  • Registers - vs_3_0 lists the different types of registers used by the vertex shader ALU.
  • Vertex Shader Register Modifiers are used to modify the way an instruction works.
  • Vertex Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.
  • Destination Register Masking determines what components of the destination register get written.

New Features

New features of vertex shader version vs_3_0 are listed in the following sections.

Indexing Registers

In the earlier shader models, only the constant register bank could be indexed. In this model, the following register banks can be indexed, using the loop counter register (aL):

  • Input register (v#)
  • Output register (o#)

Vertex Textures

This shader model supports texture lookup in the vertex shader using texldl. The vertex engine has four texture sampler stages (distinct from the displacement map sampler and the texture samplers in the pixel engine) that can be used to sample textures set at those stages. See Vertex Textures in vs_3_0 (Direct3D 9).

Vertex Stream Frequency

This feature allows a subset of the input registers to be initialized at a rate different from once per vertex. See Drawing Non-Indexed Geometry.

Shader Output

Similar to vs_2_0, the output of the shader can vary with static flow control. Be careful with dynamic branching as this can cause shader outputs to vary per vertex. This will produce unpredictable results on different hardware.

Dynamic flow control

All dynamic flow control instructions are supported. The maximum nesting depth value allowed is 24. (See Flow Control Nesting Limits for details.)

Temporary Registers

A total of 32 temporary registers (r#) is supported.

Static Flow Control

The maximum nesting depth for loop - vs/rep - vs is 4. The maximum nesting depth for call - vs/callnz bool - vs/callnz pred - vs is 4. For if bool - vs, the maximum nesting depth value allowed is 24. (See Flow Control Nesting Limits for details.)

Predication

Instruction predication is supported. Use setp_comp - vs to set the predicate register.

Instruction Count

Each vertex shader is allowed anywhere from 512 up to the number of slots in MaxVertexShader30InstructionSlots in D3DCAPS9. The number of instructions run can be much higher because of the loop/rep support; however, this is capped by MaxVShaderInstructionsExecuted in D3DCAPS9 which should be at least 0xFFFF.

Device Caps

If Vertex Shader 3_0 is supported, the following caps are supported in hardware (at a minimum):

Cap | Capability
Shader caps
  • DynamicFlowControlDepth is 24
  • NumTemps is 32
  • StaticFlowControlDepth is 4
  • Predication is supported.
GuardBandLeft, GuardBandTop, GuardBandRight, GuardBandBottom | 8K
VertexShaderVersion | 3_0
MaxVertexShaderConst | 256
MaxVertexShader30InstructionSlots | 512
Fog support | D3DPRASTERCAPS_FOGVERTEX
VertexTextureFilterCaps
  • D3DPTFILTERCAPS_MINFPOINT
  • D3DPTFILTERCAPS_MAGFPOINT
D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET | Vertex elements in a vertex declaration can share the same stream offset.
Vertex formats
  • D3DDECLTYPE_UBYTE4
  • D3DDECLTYPE_UBYTE4N
  • D3DDECLTYPE_SHORT2N
  • D3DDECLTYPE_SHORT4N
  • D3DDECLTYPE_FLOAT16_2
  • D3DDECLTYPE_FLOAT16_4


Vertex Shader Differences

Instruction Slots

Each version supports a differing number of maximum instruction slots.

Version | Maximum number of instruction slots
vs_1_1 | 128
vs_2_0 | 256
vs_2_x | 256
vs_3_0 | 512 minimum, and up to the number of slots in D3DCAPS9.MaxVertexShader30InstructionSlots. See D3DCAPS9.

For information about the limitations of software shaders, see Software Shaders.

Flow Control Nesting Limits

  • See Flow Control Nesting Limits.

vs_1_1 Features

New instructions:

See Instructions - vs_1_1.

New registers:

See Registers - vs_1_1.

vs_2_0 Features

New features:

  • Static flow control
  • All four components of the Address Register (a0) are available.

New instructions:

  • Setup instructions - defb - vs, defi - vs
  • Arithmetic instructions - abs - vs, crs - vs, lrp - vs, mova - vs, nrm - vs, pow - vs, sgn - vs, sincos - vs
  • Static flow control instructions - call - vs, callnz bool - vs, else - vs, endif - vs, endloop - vs, endrep - vs, if bool - vs, label - vs, loop - vs, rep - vs, ret - vs

New registers:

  • Constant Boolean Register (b#)
  • Constant Integer Register (i#)
  • Loop Counter Register (aL)

vs_2_x Features

New features (D3DCAPS9.VS20Caps):

  • Dynamic flow control
  • Nesting for dynamic and static flow control instructions
  • Number of Temporary Registers (r#) increased
  • Predication

New Instructions:

  • Dynamic flow control instructions - break - vs, break_comp - vs, breakp - vs, callnz pred - vs, if_comp - vs, if pred - vs, setp_comp - vs

New registers:

  • Predicate Register (p0)

vs_3_0 Features

New features :

  • Texture lookup
  • Indexable Output Registers (o#)
  • Number of Temporary Registers (r#) increased to 32

New instructions:

  • Setup instruction - dcl_samplerType - vs
  • Texture instruction - texldl - vs

New registers:

  • Sampler (s#)


Vertex Shader Instructions

  • Instructions - vs_1_1
  • Instructions - vs_2_0
  • Instructions - vs_2_x
  • Instructions - vs_3_0
  • Vertex Shader Register Modifiers
  • Flow Control Nesting Limits


Instructions - vs_1_1

This section contains reference information for the vertex shader version 1_1 instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | New
add - vs | Add two vectors | 1 |  | x | x
dcl_usage input register - vs | Declare input vertex registers (see Registers - vs_1_1) | 0 | x |  | x
def - vs | Define constants | 0 | x |  | x
dp3 - vs | Three-component dot product | 1 |  | x | x
dp4 - vs | Four-component dot product | 1 |  | x | x
dst - vs | Calculate the distance vector | 1 |  | x | x
exp - vs | Full precision 2x | 10 |  | x | x
exp - vs | Partial precision 2x | 1 |  | x | x
frc - vs | Fractional component | 3 |  | x | x
lit - vs | Partial lighting calculation | 1 |  | x | x
log - vs | Full precision log2(x) | 10 |  | x | x
logp - vs | Partial precision log2(x) | 1 |  | x | x
m3x2 - vs | 3x2 multiply | 2 |  | x | x
m3x3 - vs | 3x3 multiply | 3 |  | x | x
m3x4 - vs | 3x4 multiply | 4 |  | x | x
m4x3 - vs | 4x3 multiply | 3 |  | x | x
m4x4 - vs | 4x4 multiply | 4 |  | x | x
mad - vs | Multiply and add | 1 |  | x | x
max - vs | Maximum | 1 |  | x | x
min - vs | Minimum | 1 |  | x | x
mov - vs | Move | 1 |  | x | x
mul - vs | Multiply | 1 |  | x | x
nop - vs | No operation | 1 |  | x | x
rcp - vs | Reciprocal | 1 |  | x | x
rsq - vs | Reciprocal square root | 1 |  | x | x
sge - vs | Greater than or equal compare | 1 |  | x | x
slt - vs | Less than compare | 1 |  | x | x
sub - vs | Subtract | 1 |  | x | x
vs | Version | 0 | x |  | x


Instructions - vs_2_0

This section contains reference information for the vertex shader version 2_0 instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Flow control - These instructions add flow control capabilities such as loop...endloop, if...else...endif - vs, and subroutine calls.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Flow control | New
abs - vs | Absolute value | 1 |  | x |  | x
add - vs | Add two vectors | 1 |  | x |  |
call - vs | Call a subroutine | 2 |  |  | x | x
callnz bool - vs | Call a subroutine if a Boolean register is not zero | 3 |  |  | x | x
crs - vs | Cross product | 2 |  | x |  | x
dcl_usage input register - vs | Declare input vertex registers (see Registers - vs_2_0) | 0 | x |  |  |
def - vs | Define constants | 0 | x |  |  |
defb - vs | Define a Boolean constant | 0 | x |  |  | x
defi - vs | Define an integer constant | 0 | x |  |  | x
dp3 - vs | Three-component dot product | 1 |  | x |  |
dp4 - vs | Four-component dot product | 1 |  | x |  |
dst - vs | Calculate the distance vector | 1 |  | x |  |
else - vs | Begin an else - vs block | 1 |  |  | x | x
endif - vs | End an if bool - vs...else - vs block | 1 |  |  | x | x
endloop - vs | End of a loop - vs block | 2 |  |  | x | x
endrep - vs | End of a repeat block | 2 |  |  | x | x
exp - vs | Full precision 2x | 1 |  | x |  |
exp - vs | Partial precision 2x | 1 |  | x |  |
frc - vs | Fractional component | 1 |  | x |  |
if bool - vs | Begin an if bool - vs block (using a Boolean condition) | 3 |  |  | x | x
label - vs | Label | 0 |  |  | x | x
lit - vs | Partial lighting calculation | 3 |  | x |  |
log - vs | Full precision log2(x) | 1 |  | x |  |
logp - vs | Partial precision log2(x) | 1 |  | x |  |
loop - vs | Loop | 3 |  |  | x | x
lrp - vs | Linear interpolation | 2 |  | x |  | x
m3x2 - vs | 3x2 multiply | 2 |  | x |  |
m3x3 - vs | 3x3 multiply | 3 |  | x |  |
m3x4 - vs | 3x4 multiply | 4 |  | x |  |
m4x3 - vs | 4x3 multiply | 3 |  | x |  |
m4x4 - vs | 4x4 multiply | 4 |  | x |  |
mad - vs | Multiply and add | 1 |  | x |  |
max - vs | Maximum | 1 |  | x |  |
min - vs | Minimum | 1 |  | x |  |
mov - vs | Move | 1 |  | x |  |
mova - vs | Move data from a floating-point register to the address register (a0) | 1 |  | x |  | x
mul - vs | Multiply | 1 |  | x |  |
nop - vs | No operation | 1 |  | x |  |
nrm - vs | Normalize a 4D vector | 3 |  | x |  | x
pow - vs | xy | 3 |  | x |  | x
rcp - vs | Reciprocal | 1 |  | x |  |
rep - vs | Repeat | 3 |  |  | x | x
ret - vs | End of either a subroutine or main | 1 |  |  | x | x
rsq - vs | Reciprocal square root | 1 |  | x |  |
sge - vs | Greater than or equal compare | 1 |  | x |  |
sgn - vs | Sign | 3 |  | x |  | x
sincos - vs | Sine and cosine | 8 |  | x |  | x
slt - vs | Less than compare | 1 |  | x |  |
sub - vs | Subtract | 1 |  | x |  |
vs | Version | 0 | x |  |  |


Instructions - vs_2_x

This section contains reference information for the vertex shader version 2_x instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Flow control - These instructions add flow control capabilities such as loop - vs...endloop - vs, if bool - vs...else...endif, and subroutine calls.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Flow control | New
abs - vs | Absolute value | 1 |  | x |  |
add - vs | Add two vectors | 1 |  | x |  |
break - vs | Break out of a loop - vs...endloop - vs or rep...endrep block | 1 |  |  | x | x
break_comp - vs | Conditionally break out of a loop - vs...endloop - vs or rep...endrep block, with a comparison | 3 |  |  | x | x
breakp - vs | Break out of a loop - vs...endloop - vs or rep...endrep block, based on a predicate | 3 |  |  | x | x
call - vs | Call a subroutine | 2 |  |  | x |
callnz bool - vs | Call a subroutine if a Boolean register is not zero | 3 |  |  | x |
callnz pred - vs | Call a subroutine if a predicate register is not zero | 3 |  |  | x | x
crs - vs | Cross product | 2 |  | x |  |
dcl_usage input register - vs | Declare input vertex registers (see Registers - vs_2_x) | 0 | x |  |  |
def - vs | Define constants | 0 | x |  |  |
defb - vs | Define a Boolean constant | 0 | x |  |  |
defi - vs | Define an integer constant | 0 | x |  |  |
dp3 - vs | Three-component dot product | 1 |  | x |  |
dp4 - vs | Four-component dot product | 1 |  | x |  |
dst - vs | Calculate the distance vector | 1 |  | x |  |
else - vs | Begin an else - vs block | 1 |  |  | x |
endif - vs | End an if bool - vs...else - vs block | 1 |  |  | x |
endloop - vs | End of a loop - vs block | 2 |  |  | x |
endrep - vs | End of a repeat block | 2 |  |  | x |
exp - vs | Full precision 2x | 1 |  | x |  |
exp - vs | Partial precision 2x | 1 |  | x |  |
frc - vs | Fractional component | 1 |  | x |  |
if bool - vs | Begin an if bool - vs block (using a Boolean condition) | 3 |  |  | x |
if_comp - vs | Begin an if bool - vs block, with a comparison | 3 |  |  | x | x
if pred - vs | Begin an if bool - vs block with a predicate condition | 3 |  |  | x | x
label - vs | Label | 0 |  |  | x |
lit - vs | Partial lighting calculation | 3 |  | x |  |
log - vs | Full precision log2(x) | 1 |  | x |  |
logp - vs | Partial precision log2(x) | 1 |  | x |  |
loop - vs | Loop | 3 |  |  | x |
lrp - vs | Linear interpolation | 2 |  | x |  |
m3x2 - vs | 3x2 multiply | 2 |  | x |  |
m3x3 - vs | 3x3 multiply | 3 |  | x |  |
m3x4 - vs | 3x4 multiply | 4 |  | x |  |
m4x3 - vs | 4x3 multiply | 3 |  | x |  |
m4x4 - vs | 4x4 multiply | 4 |  | x |  |
mad - vs | Multiply and add | 1 |  | x |  |
max - vs | Maximum | 1 |  | x |  |
min - vs | Minimum | 1 |  | x |  |
mov - vs | Move | 1 |  | x |  |
mova - vs | Move data from a floating-point register to the address register (a0) | 1 |  | x |  |
mul - vs | Multiply | 1 |  | x |  |
nop - vs | No operation | 1 |  | x |  |
nrm - vs | Normalize a 4D vector | 3 |  | x |  |
pow - vs | xy | 3 |  | x |  |
rcp - vs | Reciprocal | 1 |  | x |  |
rep - vs | Repeat | 3 |  |  | x |
ret - vs | End of either a subroutine or main | 1 |  |  | x |
rsq - vs | Reciprocal square root | 1 |  | x |  |
setp_comp - vs | Set the predicate register | 1 |  |  | x | x
sge - vs | Greater than or equal compare | 1 |  | x |  |
sgn - vs | Sign | 3 |  | x |  |
sincos - vs | Sine and cosine | 8 |  | x |  |
slt - vs | Less than compare | 1 |  | x |  |
sub - vs | Subtract | 1 |  | x |  |
vs | Version | 0 | x |  |  |


Instructions - vs_3_0

This section contains reference information for the vertex shader version 3_0 instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Texture - These instructions support texture address lookup.
  • Flow control - These instructions add flow control such as loops, repeats, and if bool - vs...else...endif comparisons.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Texture | Flow control | New
abs - vs | Absolute value | 1 |  | x |  |  |
add - vs | Add two vectors | 1 |  | x |  |  |
break - vs | Break out of a loop - vs...endloop - vs or rep...endrep block | 1 |  |  |  | x |
break_comp - vs | Conditionally break out of a loop - vs...endloop - vs or rep...endrep block, with a comparison | 3 |  |  |  | x |
breakp - vs | Break out of a loop - vs...endloop - vs or rep...endrep block, based on a predicate | 3 |  |  |  | x |
call - vs | Call a subroutine | 2 |  |  |  | x |
callnz bool - vs | Call a subroutine if a Boolean register is not zero | 3 |  |  |  | x |
callnz pred - vs | Call a subroutine if a predicate register is not zero | 3 |  |  |  | x |
crs - vs | Cross product | 2 |  | x |  |  |
dcl_usage input register - vs | Declare input vertex registers (see Registers - vs_3_0) | 0 | x |  |  |  |
dcl_samplerType - vs | Declare the texture dimension for a sampler | 0 | x |  |  |  | x
def - vs | Define constants | 0 | x |  |  |  |
defb - vs | Declare a Boolean constant | 0 | x |  |  |  |
defi - vs | Declare an integer constant | 0 | x |  |  |  |
dp3 - vs | Three-component dot product | 1 |  | x |  |  |
dp4 - vs | Four-component dot product | 1 |  | x |  |  |
dst - vs | Distance | 1 |  | x |  |  |
else - vs | Begin an else block | 1 |  |  |  | x |
endif - vs | End an if bool - vs...else block | 1 |  |  |  | x |
endloop - vs | End of a loop - vs block | 2 |  |  |  | x |
endrep - vs | End of a repeat block | 2 |  |  |  | x |
exp - vs | Full precision 2x | 1 |  | x |  |  |
exp - vs | Partial precision 2x | 1 |  | x |  |  |
frc - vs | Fractional component | 1 |  | x |  |  |
if bool - vs | Begin an if bool - vs block (using a Boolean condition) | 3 |  |  |  | x |
if_comp - vs | Begin an if bool - vs block, with a comparison | 3 |  |  |  | x |
if pred - vs | Begin an if bool - vs block with a predicate condition | 3 |  |  |  | x |
label - vs | Label | 0 |  |  |  | x |
lit - vs | Calculate lighting | 3 |  | x |  |  |
log - vs | Full precision log2(x) | 1 |  | x |  |  |
logp - vs | Partial precision log2(x) | 1 |  | x |  |  |
loop - vs | Loop | 3 |  |  |  | x |
lrp - vs | Linear interpolation | 2 |  | x |  |  |
m3x2 - vs | 3x2 multiply | 2 |  | x |  |  |
m3x3 - vs | 3x3 multiply | 3 |  | x |  |  |
m3x4 - vs | 3x4 multiply | 4 |  | x |  |  |
m4x3 - vs | 4x3 multiply | 3 |  | x |  |  |
m4x4 - vs | 4x4 multiply | 4 |  | x |  |  |
mad - vs | Multiply and add | 1 |  | x |  |  |
max - vs | Maximum | 1 |  | x |  |  |
min - vs | Minimum | 1 |  | x |  |  |
mov - vs | Move | 1 |  | x |  |  |
mova - vs | Move data from a floating point register to an integer register | 1 |  | x |  |  |
mul - vs | Multiply | 1 |  | x |  |  |
nop - vs | No operation | 1 |  | x |  |  |
nrm - vs | Normalize | 3 |  | x |  |  |
pow - vs | xy | 3 |  | x |  |  |
rcp - vs | Reciprocal | 1 |  | x |  |  |
rep - vs | Repeat | 3 |  |  |  | x |
ret - vs | End of a subroutine | 1 |  |  |  | x |
rsq - vs | Reciprocal square root | 1 |  | x |  |  |
setp_comp - vs | Set the predicate register | 1 |  |  |  | x |
sge - vs | Greater than or equal compare | 1 |  | x |  |  |
sgn - vs | Sign | 3 |  | x |  |  |
sincos - vs | Sine and cosine | 8 |  | x |  |  |
slt - vs | Less than compare | 1 |  | x |  |  |
sub - vs | Subtract | 1 |  | x |  |  |
texldl - vs | Texture load with user-adjustable level-of-detail | See note 1 |  |  | x |  | x
vs | Version | 0 | x |  |  |  |

Notes:

  1. if the texture is a cube map, slots = 5; otherwise slots = 2


Flow Control Nesting Limits

Vertex shader flow control instructions have two special restrictions. Nesting depths restrict the number of instructions that can be called inside of each other. In addition, each instruction has an instruction slot count that applies against the maximum number of instruction that a shader can support.

Depth Count per Instruction for vs_2_0

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth:

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting | Static flow count
if bool - vs | 0 | 0 | 0 | 0 | 1
if_comp - vs | n/a | n/a | n/a | n/a | n/a
if pred - vs | n/a | n/a | n/a | n/a | n/a
else - vs | 0 | 0 | 0 | 0 | 1(if bool - vs only)
endif - vs | -1 | 0 | 0 | 0 | 0
rep - vs | 0 | 0 | 1 | 0 | 1
endrep - vs | 0 | 0 | -1 | 0 | 0
loop - vs | 0 | 0 | 1 | 0 | 1
endloop - vs | 0 | 0 | -1 | 0 | 0
break - vs | n/a | n/a | n/a | n/a | n/a
break_comp - vs | n/a | n/a | n/a | n/a | n/a
breakp - vs | n/a | n/a | n/a | n/a | n/a
call - vs | 0 | 0 | 0 | 1 | 1
callnz bool - vs | 0 | 0 | 0 | 1 | 1
callnz pred - vs | n/a | n/a | n/a | n/a | n/a
ret - vs | 0 | 0 | 0 | -1 | 0
setp_comp - vs | n/a | n/a | n/a | n/a | n/a

Nesting Depth

Nesting depth define how many instructions can be called inside of each other. Each type of instruction has one or more nesting limits:

Instruction Type | Maximum
Static nesting | Only limited by the static flow count
Dynamic nesting | n/a
loop/rep nesting | 1
call nesting | 1
Static flow count | 16

Depth Count per Instruction for vs_2_x

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth:

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting | Static flow count
if bool - vs | 1 | 0 | 0 | 0 | 1
if_comp - vs | 0 | 1 | 0 | 0 | 0
if pred - vs | 0 | 1 | 0 | 0 | 0
else - vs | 0 | 0 | 0 | 0 | 1(if bool - vs only)
endif - vs | -1(if bool - vs) | -1(if pred - vs or if_comp - vs) | 0 | 0 | 0
rep - vs | 0 | 0 | 1 | 0 | 1
endrep - vs | 0 | 0 | -1 | 0 | 0
loop - vs | 0 | 0 | 1 | 0 | 1
endloop - vs | 0 | 0 | -1 | 0 | 0
break - vs | 0 | 0 | 0 | 0 | 0
break_comp - vs | 0 | 1, -1 | 0 | 0 | 0
breakp - vs | 0 | 0 | 0 | 0 | 0
call - vs | 0 | 0 | 0 | 1 | 1
callnz bool - vs | 0 | 0 | 0 | 1 | 1
callnz pred - vs | 0 | 1 | 0 | 1 | 0
ret - vs | 0 | -1 (callnz pred - vs) | 0 | -1 | 0
setp_comp - vs | 0 | 0 | 0 | 0 | 0

Nesting Depth

Nesting depth define how many instructions can be called inside of each other. Each type of instruction has one or more nesting limits:

Instruction Type | Maximum
Static nesting | Only limited by the static flow count
Dynamic nesting | 0 or 24, see D3DCAPS9.VS20Caps.DynamicFlowControlDepth
loop/rep nesting | 1 to 4, see D3DCAPS9.VS20Caps.StaticFlowControlDepth
call nesting | 1 to 4, see D3DCAPS9.VS20Caps.StaticFlowControlDepth (independent of loop/rep limit)
Static flow count | 16

Depth Count per Instruction for vs_2_sw

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth:

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting | Static flow count
if bool - vs | 1 | 0 | 0 | 0 | n/a
if_comp - vs | 0 | 1 | 0 | 0 | n/a
if pred - vs | 0 | 1 | 0 | 0 | n/a
else - vs | 0 | 0 | 0 | 0 | n/a
endif - vs | -1(if bool - vs) | -1(if pred - vs or if_comp - vs) | 0 | 0 | n/a
rep - vs | 0 | 0 | 1 | 0 | n/a
endrep - vs | 0 | 0 | -1 | 0 | n/a
loop - vs | 0 | 0 | 1 | 0 | n/a
endloop - vs | 0 | 0 | -1 | 0 | n/a
break - vs | 0 | 0 | 0 | 0 | n/a
break_comp - vs | 0 | 1, -1 | 0 | 0 | n/a
breakp - vs | 0 | 0 | 0 | 0 | n/a
call - vs | 0 | 0 | 0 | 1 | n/a
callnz bool - vs | 0 | 0 | 0 | 1 | n/a
callnz pred - vs | 0 | 1 | 0 | 1 | n/a
ret - vs | 0 | -1 (callnz pred - vs) | 0 | -1 | n/a
setp_comp - vs | 0 | 0 | 0 | 0 | n/a

Nesting Depth

Nesting depth define how many instructions can be called inside of each other. Each type of instruction has one or more nesting limits:

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
loop/rep nesting | 4
call nesting | 4
Static flow count | No limit

Depth Count per Instruction for vs_3_0

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth:

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting | Static flow count
if bool - vs | 1 | 0 | 0 | 0 | n/a
if_comp - vs | 0 | 1 | 0 | 0 | n/a
if pred - vs | 0 | 1 | 0 | 0 | n/a
else - vs | 0 | 0 | 0 | 0 | n/a
endif - vs | -1(if bool - vs) | -1(if pred - vs or if_comp - vs) | 0 | 0 | n/a
rep - vs | 0 | 0 | 1 | 0 | n/a
endrep - vs | 0 | 0 | -1 | 0 | n/a
loop - vs | 0 | 0 | 1 | 0 | n/a
endloop - vs | 0 | 0 | -1 | 0 | n/a
break - vs | 0 | 0 | 0 | 0 | n/a
break_comp - vs | 0 | 1, -1 | 0 | 0 | n/a
breakp - vs | 0 | 0 | 0 | 0 | n/a
call - vs | 0 | 0 | 0 | 1 | n/a
callnz bool - vs | 0 | 0 | 0 | 1 | n/a
callnz pred - vs | 0 | 1 | 0 | 1 | n/a
ret - vs | 0 | -1 (callnz pred - vs) | 0 | -1 | n/a
setp_comp - vs | 0 | 0 | 0 | 0 | n/a

Nesting Depth

Nesting depth define how many instructions can be called inside of each other. Each type of instruction has one or more nesting limits:

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
loop/rep nesting | 4
call nesting | 4
Static flow count | No limit

Depth Count per Instruction for vs_3_sw

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth:

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting | Static flow count
if bool - vs | 1 | 0 | 0 | 0 | n/a
if_comp - vs | 0 | 1 | 0 | 0 | n/a
if pred - vs | 0 | 1 | 0 | 0 | n/a
else - vs | 0 | 0 | 0 | 0 | n/a
endif - vs | -1(if bool - vs) | -1(if pred - vs or if_comp - vs) | 0 | 0 | n/a
rep - vs | 0 | 0 | 1 | 0 | n/a
endrep - vs | 0 | 0 | -1 | 0 | n/a
loop - vs | 0 | 0 | 1 | 0 | n/a
endloop - vs | 0 | 0 | -1 | 0 | n/a
break - vs | 0 | 0 | 0 | 0 | n/a
break_comp - vs | 0 | 1, -1 | 0 | 0 | n/a
breakp - vs | 0 | 0 | 0 | 0 | n/a
call - vs | 0 | 0 | 0 | 1 | n/a
callnz bool - vs | 0 | 0 | 0 | 1 | n/a
callnz pred - vs | 0 | 1 | 0 | 1 | n/a
ret - vs | 0 | -1 (callnz pred - vs) | 0 | -1 | n/a
setp_comp - vs | 0 | 0 | 0 | 0 | n/a

Nesting Depth

Nesting depth define how many instructions can be called inside of each other. Each type of instruction has one or more nesting limits:

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
loop/rep nesting | 4
call nesting | 4
Static flow count | No limit


Instruction Modifiers

Instruction modifiers affect the result of the instruction before it is written into the destination register.

_sat

Saturates (or clamps) the instruction result to [0,1] range before writing to the destination register.

For example:

add_sat dst, src0, src1

Where:

dst = clamp_between_0_and_1(src0 + src1)

The _sat instruction modifier costs no additional instruction slots.

If supported, the _sat instruction modifier can be used with any instruction except: frc - vs, sincos - vs, and texldl - vs.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
_sat |  |  |  |  | x | x


abs - vs

Computes absolute value.

Syntax

abs dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  | x | x | x | x | x

This instruction works as shown here.

dest.x = abs(src.x)
dest.y = abs(src.y)
dest.z = abs(src.z)
dest.w = abs(src.w)


add - vs

Adds two vectors.

Syntax

add dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
add | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x + src1.x;
dest.y = src0.y + src1.y;
dest.z = src0.z + src1.z;
dest.w = src0.w + src1.w;


break - vs

Break out of the current loop at the nearest endloop - vs or endrep - vs.

Syntax

break

Remarks

This instruction is supported in the following versions.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break |  |  | x | x | x | x


break_comp - vs

Conditionally break out of the current loop at the nearest endloop - vs or endrep - vs.

Syntax

break_comp src0, src1

Where:

  • _comp is a comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required to select a single component.
  • src1 is a source register. Replicate swizzle is required to select a single component.

Remarks

This instruction is supported in the following versions.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break_comp |  |  | x | x | x | x

When the comparison is true, it breaks out of the current loop, as shown.

if (src0 comparison src1)
   jump to the corresponding endloop or endrep instruction;


breakp - vs

Conditionally break out of the current loop at the nearest endloop - vs or endrep - vs. Use one of the components of the predicate register as a condition to determine whether or not to perform the instruction.

Syntax

breakp [!]p0.{x|y|z|w}

Where:

  • [!] optional boolean NOT.
  • p0 is the predicate register. See Predicate Register.
  • {x|y|z|w} is the required replicate swizzle on p0.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
breakp |  |  | x | x | x | x


call - vs

Performs a function call to the instruction marked with the provided label.

Syntax

call l#

where l# is a label - vs marking the beginning of the subroutine to be called.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
call |  | x | x | x | x | x

This instruction does the following:

  1. Push address of the next instruction to the return address stack.
  2. Continue execution from the instruction marked by the label.

In vertex shader 2_0, nesting calls are not allowed.

In vertex shader 2_x, the nesting depth is limited by the StaticFlowControlDepth element of the D3DVSHADERCAPS2_0 structure. For more information, see IDirect3D9::GetDeviceCaps.

In vertex shader 3_0, four levels of call nesting are allowed.

Only forward calls are allowed. This means that the location of the label inside the vertex shader should be after the call instruction referencing it.

If a call instruction is invoked inside loop...endloop block, the value of the Loop Counter Register (aL) is accessible inside the subroutine.

If a subroutine is referencing the Loop Counter Register (aL) located outside of the subroutine, every instance of the call to this subroutine should be surrounded by a loop...endloop block.


callnz bool - vs

Call if not zero. Performs a conditional call to the instruction marked by the label index.

Syntax

callnz l#, [!]b#

where:

  • where l# is a label - vs marking the beginning of the subroutine to be called.
  • [!] is the optional boolean NOT modifier.
  • b# identifies a Constant Boolean Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz bool |  | x | x | x | x | x

This instruction does the following:

if (specified boolean register is not zero)
{
    Push address of the next instruction to the return address stack.
    Continue execution from the instruction marked by the label.
}

This instruction consumes one vertex shader instruction slot.


callnz pred - vs

Call if not zero, with a predicate. Performs a conditional call to the instruction marked by the label index. Predication uses a boolean value to determine whether of not to perform the instruction.

Syntax

callnz l#, [!]p0.{x|y|z|w}

where:

  • l# is a label - vs marking the beginning of the subroutine to be called.
  • [!] is an optional negate modifier.
  • p0 is the Predicate Register.
  • {x|y|z|w} is the required replicate swizzle on p0.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz pred |  |  | x | x | x | x

This instruction does the following:

if (specified register component is not zero)
{
    Push address of the next instruction to the return address stack.
    Continue execution from the instruction marked by the label.
}

This instruction consumes one vertex shader instruction slot.


crs - vs

Computes a cross product using the right-hand rule.

Syntax

crs dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
crs |  | x | x | x | x | x

This instruction works as shown here.

dest.x = src0.y * src1.z - src0.z * src1.y;
dest.y = src0.z * src1.x - src0.x * src1.z;
dest.z = src0.x * src1.y - src0.y * src1.x;

Some restrictions on use:

  • src0 cannot be the same register as dest.
  • src1 cannot be the same register as dest.
  • src0 cannot have any swizzle other than the default swizzle (.xyzw).
  • src1 cannot have any swizzle other than the default swizzle (.xyzw).
  • dest has to have exactly one of the following seven masks: .x | .y | .z | .xy | .xz | .yz | .xyz.
  • dest must be a temporary register.
  • dest must not be the same register as src0 or src1


dcl_samplerType - vs

Declare a vertex shader sampler.

Syntax

dcl_samplerType s#

where:

  • _samplerType defines the sampler data type. This determines how many coordinates are required by each texture coordinate when sampling. The following texture coordinate dimensions are defined.
    • _2d
    • _cube
    • _volume
  • s# identifies a sampler where s is an abbreviation for the sampler, and # is the sampler number. Samplers are pseudo registers because you cannot directly read or write to them.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_samplerType |  |  |  |  | x | x

All dcl_samplerType instructions must appear before the first executable instruction.


dcl_usage input register - vs

Declare the association between a vertex element usage and a usage index for a vertex shader input register.

Syntax

dcl_usage[usage_index] v#

Where:

  • dcl_usage identifies how the register data will be used. This is the same value as the members of D3DDECLUSAGE without the D3DDECLUSAGE prefix.
  • usage_index is an optional integer index between 0 and 15. It modifies the usage data. The index matches the usage index in a vertex declaration. See Vertex Declaration (Direct3D 9). The index is appended to the usage value (dcl_usage ) with no space. If it is not supplied, it is assumed to be 0.
  • v# is a Input Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_usage | x | x | x | x | x | x

All dcl_usage instructions must appear before the first executable instruction.


dcl_usage outut register - vs

The various types of output registers have been collapsed into twelve output registers (two for color, eight for texture, one for position, and one for fog and point size). These can be used for anything the user wants to interpolate for the pixel shader: texture coordinates, colors, fog, and so on.

Output registers require declarations that include semantics. For instance, the old position and point size registers are replaced by declaring an output register with a position or point-size semantic.

Of the twelve output registers, any ten (not necessarily o0 to o9) have four components (xyzw), another one must be declared as position (and must also include all four components), and optionally one more can be a scalar point size.

Syntax

The syntax for declaring output registers is similar to the declarations for the input register:

dcl_semantics o[.write_mask]

Where:

  • dcl_semantics can use the same set of semantics as for the input declaration. Semantic names come from D3DDECLUSAGE (and are paired with an index, such as position3). There always has to be one output register with the positiont0 semantic when not used for processing vertices. The positiont0 semantic and the pointsize0 semantic are the only ones that have meaning beyond simply allowing linkage from vertex to pixel shaders. For shaders with flow control, it is assumed that the worst case output is declared. There are no defaults if a shader does not actually output what it declares it should (due to flow control).
  • o is an output register. See Output_Registers.
  • write_mask indicates the same output register that can be declared multiple times (so different semantics can be applied to individual components), each time with a unique write mask. However, the same semantic cannot be used multiple times in a declaration. This means that vectors must be four components or less, and cannot go across four-component register boundaries (individual registers). When the point-size semantic is used, it should have full write mask because it is considered a scalar. When the position semantic is used, it should have a full write mask because all four components have to be written.

Remarks

Vertex shader versions | 3_0 | 3_sw
dcl_usage | x | x

All dcl_usage instructions must appear before the first executable instruction.

Declaration Examples

vs_3_0
dcl_color4     o3.x    // color4 is a semantic name.
dcl_texcoord3  o3.yz   // Different semantics can be packed into one register.
dcl_fog        o3.w
dcl_tangent    o4.xyz
dcl_position   o7.xyzw // position must be declared to some unique register
                       //   in a vertex shader, with all 4 components.

dcl_psize      o6      // Pointsize cannot have a mask
                       //   (that is, mask is full .xyzw)
                       // This is an implied scalar register.
                       // No other semantics can be assigned to any components
                       //   of this register.
                       // If pointsize declaration is not used (typical),
                       //   only 11 "out" registers are available, not 12.
                       // Pixel shaders cannot see this value.


def - vs

Defines vertex shader constants.

Syntax

def dst, float1, float2, float3, float4

where

  • dst is the destination register.
  • float1, float2, float3, float4 are four floating point numbers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
def | x | x | x | x | x | x

The def instruction defines a shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by API methods SetVertexShaderConstantF.

There are two ways to set a constant in a shader.

  1. Use def - vs to define the constant directly inside a shader.

    def - vs can only define floating-point constants.

  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetVertexShaderConstantF to set a floating-point constant.

See Also

defi - vs, defb - vs


defb - vs

Defines a Boolean constant value, which should be loaded anytime a shader is set to a device.

Syntax

defb dest, booleanValue

where

  • dst is the destination register.
  • booleanValue is a boolean value, either True or False.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defb |  | x | x | x | x | x

The defb - vs instruction defines a boolean shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the API method SetVertexShaderConstantB.

There are two ways to set a boolean constant in a shader.

  1. Use defb - vs to define the constant directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetVertexShaderConstantB to set a Boolean constant.

See Also

def - vs, defi - vs


defi - vs

Defines an integer constant value, which should be loaded anytime a shader is set to a device.

Syntax

defi dst, integerValue0, integerValue1, integerValue2, integerValue3
  • dst is the destination register.
  • integerValue# is a constant integer value.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defi |  | x | x | x | x | x

The defi instruction defines an integer shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the API method SetVertexShaderConstantI.

There are two ways to set an integer constant in a shader.

  1. Use defi to define the integer constant vector directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetVertexShaderConstantI to set an integer constant.

See Also

def - vs, defb - vs


dp3 - vs

Computes the three-component dot product of the source registers.

Syntax

dp3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp3 | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.w = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.x = dest.y = dest.z = dest.w;


dp4 - vs

Computes the four-component dot product of the source registers.

Syntax

dp4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp4 | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.w = (src0.x * src1.x) + (src0.y * src1.y) +
         (src0.z * src1.z) + (src0.w * src1.w);
dest.x = dest.y = dest.z = dest.w;


dst - vs

Calculates a distance vector.

Syntax

dst dest, src0, src1

where

  • dest is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dst | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.x = 1;
dest.y = src0.y * src1.y;
dest.z = src0.z;
dest.w = src1.w;

The first source operand (src0) is assumed to be the vector (ignored, d*d, d*d, ignored) and the second source operand (src1) is assumed to be the vector (ignored, 1/d, ignored, 1/d). The destination (dest) is the result vector (1, d, d*d, 1/d).


else - vs

Start of an else block.

Syntax

else

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
else |  | x | x | x | x | x

If the condition in the corresponding if bool - vs statement is true, the code enclosed by the if bool - vs statement and the matching endif is run. Otherwise, the code enclosed by the else...endif statements is run.

See Also

if bool - vs, endif - vs


endif - vs

Marks the end of an if bool - vs...else block.

Syntax

endif

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endif |  | x | x | x | x | x

See Also

if bool - vs, else - vs


endloop - vs

End of a loop...endloop block.

Syntax

endloop

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endloop |  | x | x | x | x | x

This instruction works as shown here.

LoopCounter += LoopStep;
LoopInterationCount = LoopIterationCount - 1;
if (LoopIterationCount > 0)
    Continue execution at the StartLoopOffset

endloop must follow the last instruction of a loop - vs block.

Example

loop aL, i3
    add r1, r0, c2[ aL ]
endloop


endrep - vs

End a rep - vs...endrep block.

Syntax

endrep

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endrep |  | x | x | x | x | x

Example

rep i2
    add r0, r0, c0
endrep


exp - vs

Provides full precision exponential 2x.

Syntax

exp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified. See Source Register Swizzling.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
exp | x | x | x | x | x | x

This instruction provides at least 21 bits of precision.

The following code fragment shows the operations performed:

dest.x = dest.y = dest.z = dest.w = (float)pow(2, src.replicateSwizzleComponent);


expp - vs

Provides partial precision exponential 2x.

Syntax

expp dst, src.{x|y|z|w}

Where:

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.
  • {x|y|z|w} is the required replicate swizzle on source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
expp | x | x | x | x | x | x

vs_1_1

The exp - vs instruction operates differently depending on vertex shader versions.

In vs_1_1, the expp instruction gives the following results:

v = the scalar value from the source register with a replicate swizzle

dest.x = pow(2, floor(v))
dest.y = v - floor(v)
dest.z = pow(2, v) (partial-precision)
dest.w = 1

In vs_2_0 and up, the expp instruction gives the following results:

v = the scalar value from the source register with a replicate swizzle

dest.x = dest.y = dest.z = dest.y = pow(2, v) (partial-precision)

vs_2_0

In vs_2_0 and up, the instruction works like this:

float V = the scalar value from the source register with a replicate swizzle

dest.x = dest.y = dest.z = dest.y = pow( 2, V ) (partial-precision)

The instruction provides at least 10 bits of precision.


frc - vs

Returns the fractional portion of each input component.

Syntax

frc dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
frc | x | x | x | x | x | x

The following code fragment shows conceptually how the instruction operates.

dest.x = src.x - (float)floor(src.x);
dest.y = src.y - (float)floor(src.y);
dest.z = src.z - (float)floor(src.z);
dest.w = src.w - (float)floor(src.w);

The floor function converts the argument passed in to the greatest integer that is less than (or equal to) the argument. This is converted to a float and then subtracted fom the original value. The resulting fractional value ranges from 0.0 through 1.0.

For version 1_1, the allowable write masks are .y and .xy (.x is not allowed).


if bool - vs

Starts an if...else...endif - vs block.

Syntax

if bool

where bool is a bool register number. See Constant Boolean Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if bool |  | x | x | x | x | x

If the source Boolean register in the if statement is true, the code enclosed by the if statement and the matching else is run. Otherwise, the code enclosed by the else...endif - vs statements is run. This instruction consumes one instruction slot.

if blocks can be nested.

An if block cannot straddle a loop block.

Example

This instruction provides conditional static flow control.

defb b2, TRUE

...

if b2
// Instructions to run if b2 is nonzero

else
// Instructions to run otherwise

endif

See Also

else - vs, endif - vs


if_comp - vs

Start an if bool - vs...else - vs...endif - vs block, with a condition based on values that could be computed in a shader. This instruction is used to skip a block of code, based on a condition.

Syntax

if_comp src0, src1

Where:

  • _comp is a comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required to select a component.
  • src1 is a source register. Replicate swizzle is required to select a component.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if_comp |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a condition.

if_lt src0, src1
   jump to the corresponding else or endif instruction;

Be careful using the equals and not equals comparison modes on floating point numbers. Because rounding occurs during during floating point calculations, the comparison can be done against an epsilon value (small nonzero number) to avoid errors.

Restrictions include:

  • if_comp...else - vs...endif - vs blocks (along with the predicated if blocks) can be nested up to 24 layers deep.
  • src0 and src1 registers require a replicate swizzle.
  • if_comp blocks must end with an else - vs or endif - vs instruction.
  • if_comp...else - vs...endif - vs blocks cannot straddle a loop block. The if_comp block must be completely inside, or outside the loop - vs block.

Example

This instruction provides conditional dynamic flow control.

if_lt r3.x, r4.y
// Instructions to run if r3.x < r4.y

else
// Instructions to run otherwise

endif


if pred - vs

Start of an if pred - vs...else - vs...endif - vs block, with the condition taken from the content of the predicate register.

Syntax

if [!]pred.replicateSwizzle

Where:

  • [!] an optional NOT modifier. This modifies the value in the predicate register.
  • pred is the predicate register, p0. See Predicate Register.
  • replicateSwizzle is a single component that is copied (or replicated) to all four components (swizzled). Valid components are: x, y, z, w or r, g, b, a.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if pred |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a channel of the predicate register. Each if_pred block must end with an else or endif instruction.

Restrictions include:

if_pred blocks can be nested. This counts to the total dynamic nesting depth along with if_comp blocks.

An if_pred block cannot straddle a loop block, it should be either completely inside it or surround it.


label - vs

Mark the next instruction as having a label index.

Syntax

label l#

where # identifies the label number.

For vs_2_0, and vs_2_x, the label number must be between between 0 and 15.

For vs_2_sw, vs_3_0 and vs_3_sw, the label number must be between between 0 and 2047.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
label |  | x | x | x | x | x

This instruction defines a label located at the next shader instruction. The label instruction can only be present directly after a ret instruction (which defines the end of the previous subroutine or main program).


lit - vs

Provides partial support for lighting by calculating lighting coefficients from two dot products and an exponent.

Syntax

lit dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
lit | x | x | x | x | x | x

The source vector is assumed to contain the values shown in the following pseudocode.

src.x = N*L        ; The dot product between normal and direction to light
src.y = N*H        ; The dot product between normal and half vector
src.z = ignored    ; This value is ignored
src.w = exponent   ; The value must be between -128.0 and 128.0

The following code fragment shows the operations performed.

dest.x = 1;
dest.y = 0;
dest.z = 0;
dest.w = 1;

float power = src.w;
const float MAXPOWER = 127.9961f;
if (power < -MAXPOWER)
    power = -MAXPOWER;          // Fits into 8.8 fixed point format
else if (power > MAXPOWER)
    power = -MAXPOWER;          // Fits into 8.8 fixed point format

if (src.x > 0)
{
    dest.y = src.x;
    if (src.y > 0)
    {
        // Allowed approximation is EXP(power * LOG(src.y))
        dest.z = (float)(pow(src.y, power));
    }
}

Reduced precision arithmetic is acceptable in evaluating the destination y component (dest.y). An implementation must support at least eight fraction bits in the power argument. Dot products are calculated with normalized vectors, and clamp limits are -128 to 128.

Error should correspond to a logp - vs and exp - vs combination, or no more than approximately one significant bit for an 8-bit color component.


log - vs

Full precision log2(x).

Syntax

log dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
log | x | x | x | x | x | x

The following code fragment shows the operations performed.

float v = abs(src);
if (v != 0)
{
    dest.x = dest.y = dest.z = dest.w =
        (float)(log(v)/log(2));
}
else
{
    dest.x = dest.y = dest.z = dest.w = -FLT_MAX;
}

This instruction accepts a scalar source whose sign bit is ignored. The result is replicated to all four channels.

This instruction provides 21 bits of precision.


logp - vs

Partial precision logp2(x).

Syntax

logp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
logp | x | x | x | x | x | x

The following code fragment shows the operations performed.

float f = abs(src);
if (f != 0)
    dest.x = dest.y = dest.z = dest.w = (float)(log(f)/log(2));
else
    dest.x = dest.y = dest.z = dest.w = -FLT_MAX;

This instruction provides logarithm base 2 partial precision, up to 10 bits.


loop - vs

Start a loop...endloop block.

Syntax

loop aL, i#

Where:

  • aL is the Loop Counter Register holding the current loop count.
  • i# is a Constant Integer Register. See remarks.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
loop |  | x | x | x | x | x
  • The Loop Counter Register (aL) holds the current loop count, and can be used for relative addressing into Constant Integer Register (c#) or Output Registers (o#) inside the loop block.
  • i#.x specifies the iteration count. The legal range is [0, 255]. Note that this instruction does not increment or decrement the value of i#.x.
  • i#.y specifies the initial value of the Loop Counter Register (aL) register. The legal range is [0, 255]. Note that this instruction does not increment or decrement the value of i#.y.
  • i#.z specifies the step/stride size. The legal range is [-128, 127].
  • i#.w is not used and must be set to 0.
  • Loop blocks may be nested. See Flow Control Nesting Limits.
  • When nested, the value of the Loop Counter Register (aL) refers to the immediate enclosing loop block.
  • Loop blocks are allowed to be either completely inside an if* block or completely surrounding it. No straddling is allowed.

Example

loop aL, i3
    add r1, r0, c2[aL]
endloop


lrp - vs

Interpolates linearly between the second and third source registers by a proportion specified in the first source register.

Syntax

lrp dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
lrp |  | x | x | x | x | x

This instruction performs the linear interpolation based on the following formula.

dest.x = src0.x * (src1.x - src2.x) + src2.x;
dest.y = src0.y * (src1.y - src2.y) + src2.y;
dest.z = src0.z * (src1.z - src2.z) + src2.z;
dest.w = src0.w * (src1.w - src2.w) + src2.w;


m3x2 - vs

Multiplies a 3-component vector by a 3x2 matrix.

Syntax

m3x2 dst, src0, src1

where

  • dst is the destination register. Result is a 2-component vector.
  • src0 is a source register representing a 3-component vector.
  • src1 is a source register representing a 3x2 matrix, which corresponds to the first of 2 consecutive registers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x2 | x | x | x | x | x | x

The xy mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following equations show how the instruction operates:

dest.x = (src0.x * src1.x) + (src0.x * src1.y) + (src0.x * src1.z);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z);

The input vector is in register src0. The input 3x2 matrix is in register src1 and the next higher register in the same register file, as shown in the following expansion. A 2D result is produced, leaving the other elements of the destination register (dest.z and dest.w) unaffected.

This operation is commonly used for 2D transforms. This instruction is implemented as a pair of dot products as shown here.

m3x2   r0.xy, r1, c0   which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1

Swizzle and negate modifiers are invalid for the src1 register. The dest and src0 register, or any of src1+i registers, cannot be the same.


m3x3 - vs

Multiplies a 3-component vector by a 3x3 matrix.

Syntax

m3x3 dst, src0, src1

where

  • dst is the destination register. Result is a 3-component vector.
  • src0 is a source register representing a 3-component vector.
  • src1 is a source register representing a 3x3 matrix, which corresponds to the first of 3 consecutive registers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x3 | x | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z);

The input vector is in register src0. The input 3x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming normal vectors during lighting computations. This instruction is implemented as a pair of dot products as shown below.

m3x3 r0.xyz, r1, c0  which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1
dp3   r0.z, r1, c2


m3x4 - vs

Multiplies a 3-component vector by a 3x4 matrix.

Syntax

m3x4 dst, src0, src1

where

  • dst is the destination register. Result is a 4-component vector.
  • src0 is a source register representing a 3-component vector.
  • src1 is a source register representing a 3x4 matrix, which corresponds to the first of 4 consecutive registers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x4 | x | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z);
dest.w = (src0.x * src4.x) + (src0.y * src4.y) + (src0.z * src4.z);

The input vector is in register src0. The input 3x4 matrix is in register src1 and the next three higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position vector by a matrix that has a projective effect but applies no translation. This instruction is implemented as a pair of dot products as shown here.

m3x4   r0.xyzw, r1, c0   will be expanded to:

dp3 r0.x, r1, c0
dp3 r0.y, r1, c1
dp3 r0.z, r1, c2
dp3 r0.w, r1, c3


m4x3 - vs

Multiplies a 4-component vector by a 4x3 matrix.

Syntax

m4x3 dst, src0, src1

where

  • dst is the destination register. Result is a 3-component vector.
  • src0 is a source register representing a 4-component vector.
  • src1 is a source register representing a 4x3 matrix, which corresponds to the first of 3 consecutive registers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x3 | x | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z) + (src0.w * src1.w);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z) + (src0.w * src2.w);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z) + (src0.w * src3.w);

The input vector is in register src0. The input 4x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming a position vector by a matrix that has no projective effect, such as occurs in model-space transformations. This instruction is implemented as a pair of dot products as shown below.

m4x3   r0.xyz, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2

Swizzle and negate modifiers are invalid for the src1 register. The dst and src0 register cannot be the same.


m4x4 - vs

Multiplies a 4-component vector by a 4x4 matrix.

Syntax

m4x4 dst, src0, src1

where

  • dst is the destination register. Result is a 4-component vector.
  • src0 is a source register representing a 4-component vector.
  • src1 is a source register representing a 4x4 matrix, which corresponds to the first of 4 consecutive registers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x4 | x | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

Swizzle and negate modifiers are invalid for the src0 register. The dest and src0 registers cannot be the same.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z) +
        (src0.w * src1.w);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z) +
        (src0.w * src2.w);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z) +
        (src0.w * src3.w);
dest.w = (src0.x * src4.x) + (src0.y * src4.y) + (src0.z * src4.z) +
        (src0.w * src4.w);

The input vector is in register src0. The input 4x4 matrix is in register src1, and the next three higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position by a projection matrix. This instruction is implemented as a series of dot products as shown here.

m4x4   r0.xyzw, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2
dp4   r0.w, r1, c3


mad - vs

Multiplies and adds sources.

Syntax

mad dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mad | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x * src1.x + src2.x;
dest.y = src0.y * src1.y + src2.y;
dest.z = src0.z * src1.z + src2.z;
dest.w = src0.w * src1.w + src2.w;


max - vs

Calculates the maximum of the sources.

Syntax

max dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
max | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x=(src0.x >= src1.x) ? src0.x : src1.x;
dest.y=(src0.y >= src1.y) ? src0.y : src1.y;
dest.z=(src0.z >= src1.z) ? src0.z : src1.z;
dest.w=(src0.w >= src1.w) ? src0.w : src1.w;


min - vs

Calculates the minimum of the sources.

Syntax

min dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
min | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x=(src0.x < src1.x) ? src0.x : src1.x;
dest.y=(src0.y < src1.y) ? src0.y : src1.y;
dest.z=(src0.z < src1.z) ? src0.z : src1.z;
dest.w=(src0.w < src1.w) ? src0.w : src1.w;


mov - vs

Move floating-point data between registers.

Syntax

mov dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mov | x | x | x | x | x | x

Can be used for floating point data. For version vs_1_1, it can also be used to write the address register. When used to update address registers, the values are converted from floating point using rounding to nearest.

The following code fragment shows the operations performed.

if(dest is an integer register)
{
    int intSrc = RoundToNearest(src.w);
    dest = intSrc;
}
else
{
    dest = src;
}


mova - vs

Move data from a floating point register to the Address Register, a0.

Syntax

mova dst, src

where

  • dst must be the Address Register, a0.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mova |  | x | x | x | x | x

Moves floating point data to an integer register. The values are converted from floating point using rounding to nearest.

The address register is the only destination register allowed.

The following code fragment shows the operations performed.

if(dest is an integer register)
{
    int intSrc = RoundToNearest(src);
    dest = intSrc;
}
else
{
    dest = src;
}

For versions 2_x and above, the address register is a component vector. Therefore, any write mask is allowed.

mova a0.xz, r0


mul - vs

Multiplies sources into the destination.

Syntax

mul dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mul | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x * src1.x;
dest.y = src0.y * src1.y;
dest.z = src0.z * src1.z;
dest.w = src0.w * src1.w;


nop - vs

No operation is performed.

Syntax

nop

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nop | x | x | x | x | x | x

This instruction performs a no-op, or no operation. The syntax for calling it is as follows:

nop


nrm - vs

Normalize a 3D vector.

Syntax

nrm dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nrm |  | x | x | x | x | x

This instruction works conceptually as shown here.

squareRootOfTheSum = (src0.x*src0.x + src0.y*src0.y + src0.z*src0.z)1/2;
dest.x = src0.x * (1 / squareRootOfTheSum);
dest.y = src0.y * (1 / squareRootOfTheSum);
dest.z = src0.z * (1 / squareRootOfTheSum);
dest.w = src0.w * (1 / squareRootOfTheSum);

The dest and src registers cannot be the same. The dest register must be a temporary register.

This instruction performs the linear interpolation based on the following formula.

float f = src0.x*src0.x + src0.y*src0.y + src0.z*src0.z;
if (f != 0)
    f = (float)(1/sqrt(f));
else
    f = FLT_MAX;

dest.x = src0.x*f;
dest.y = src0.y*f;
dest.z = src0.z*f;
dest.w = src0.w*f;


pow - vs

Full precision abs(src0)src1.

Syntax

pow dst, src0, src1

where

  • dst is the destination register.
  • src0 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.
  • src1 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
pow |  | x | x | x | x | x

This instruction works as shown here.

dest = pow(abs(src0), src1);

This is a scalar instruction, therefore the source registers should have replicate swizzles to indicate which channels are used.

The scalar result is replicated to all four output channels.

This instruction could be expanded as exp(src1 * log(src0)).

Precision is not lower than 15 bits.

The dest register should be a temporary register, and should not be the same register as src1.


rcp - vs

Computes the reciprocal of the source scalar.

Syntax

rcp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rcp | x | x | x | x | x | x

The following code fragment shows the operations performed.

float f = src0;
if(f == 0.0f)
{
    f = FLT_MAX;
}
else
{
    if(f != 1.0)
    {
        f = 1/f;
    }
}

dest = f;

The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 2.0) because common implementations will separate mantissa and exponent.

If the source has no subscripts, the x-component is used.


rep - vs

Start a rep...endrep block.

Syntax

rep i#

where i# is an integer register that specifies the repeat count in the .x component. See Constant Integer Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rep |  | x | x | x | x | x
  • i#.x specifies the iteration count. The legal range is [0, 255]. Note that this instruction does not increment or decrement the value of i#.x.
  • i#.yzw are not used by the repeat block.
  • Repeat blocks may be nested. See Flow Control Nesting Limits.
  • Repeat blocks are allowed to be either completely inside an if* block or completely surrounding it. No straddling is allowed.
  • Using the same i# for different or nested rep instructions is fine - each loop will iterate based on the specified count.

Example

rep i2
    add r0, r0, c0
endrep


ret - vs

Return from a subroutine or a main function.

Syntax

ret

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
ret |  | x | x | x | x | x

This instruction takes the address of an instruction from the return address stack and continues execution from it. In the case of the main function, this instruction stops shader execution.

The ret instruction consumes one vertex shader instruction slot.

If a shader contains no subroutines, using ret at the end of the main program is optional.

Multiple return statements are not permitted in the main program or in any subroutine, the first return statement is treated as the end of the main program or subroutine.


rsq - vs

Computes the reciprocal square root (positive only) of the source scalar.

Syntax

rsq dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rsq | x | x | x | x | x | x

The following code fragment shows the operations performed.

float f = abs(src0);
if (f == 0)
    f = FLT_MAX
else
{
    if (f != 1.0)
        f = 1.0/(float)sqrt(f);
}

dest.z = dest.y = dest.z = dest.w = f;

The absolute value is taken before processing.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 4.0) because common implementations will separate mantissa and exponent.

If source has no subscripts, the x-component is used. The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.


setp_comp - vs

Set the predicate register.

Syntax

setp_comp dst, src0, src1

Where:

  • _comp is a per-channel comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • dst is the Predicate Register register, p0.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
setp_comp |  |  | x | x | x | x

This instruction operates as:

per channel in destination write mask
{
  dst.channel = src0.channel cmp src1.channel
}

For each channel that can be written according to the destination write mask, save the boolean result of the comparison operation between the corresponding channels of src0 and src1 (after the source modifier swizzles have been resolved).

Source registers allow arbitrary component swizzles to be specified.

The destination register allows arbitrary write masks.

The dest register must be the predicate register.

Applying the Predicate Register

Once the predicate register has been initialized with setp, it can be used to control an instruction per component. Here's the syntax:

([!]p0[.swizzle]) instruction dest, srcReg, ...

Where:

  • [!] is an optional boolean NOT
  • p0 is the predicate register
  • [.swizzle] is an optional swizzle to apply to the contents of the predicate register before using it to mask the instruction. The available swizzles are: .xyzw (default when none specified), or any replicate swizzle: .x/.r, .y/.g, .z/.b or .a/.w.
  • instruction is any aritmetic, or texture instruction. This cannot be a static or dynamic flow control instruction.
  • dest, srcReg, ... are the registers required by the instruction

Assuming the predicate register has been set up with (true, true, false, false) component values, it can be applied to this instruction:

// given r0 = 0,0,1,1
// given r1 = 1,1,0,0
setp_le p0, r0, r1
(p0) add r2, r3, r4

to perform a 2 component add.

r2.x = r3.x + r4.x
r2.y = r3.y + r4.y

The x and y components of r2 will not be written since the predicate register contained false in components z and w.

Applying the predicate register to an arithmetic or texture instruction increases its instruction slot count by 1.

The predicate register can also be applied to if pred - vs, callnz pred - vs and breakp - vs instructions. These flow control instructions do not have any increase in the instruction slot count when using the predicate register.


sge - vs

Computes the sign if the first source is greater than or equal to the second source.

Syntax

sge dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sge | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = (src0.x >= src1.x) ? 1.0f : 0.0f;
dest.y = (src0.y >= src1.y) ? 1.0f : 0.0f;
dest.z = (src0.z >= src1.z) ? 1.0f : 0.0f;
dest.w = (src0.w >= src1.w) ? 1.0f : 0.0f;


sgn - vs

Computes the sign of the input.

Syntax

sgn dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a temporary register that holds intermediate results. Following execution, contents are undefined.
  • src2 is a temporary register that holds intermediate results. Following execution, contents are undefined.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sgn |  | x | x | x | x | x

This instruction works as shown below.

for each component in src0
{
   if (src0.component < 0)
       dest.component = -1;
   else
       if (src0.component == 0)
           dest.component = 0;
       else
           dest.component = 1;
}

src1 and src2 must be different Temporary Registers.


sincos - vs

Computes sine and cosine, in radians.

Syntax

vs_2_0 and vs_2_x

sincos dst.{x|y|xy}, src0.{x|y|z|w}, src1, src2

Where:

  • dst is the destination register and has to be a Temporary Register (r#). The destination register must have exactly one of the following three masks: .x | .y | .xy.
  • src0 is a source register that provides the input angle, which must be within [-pi, +pi]. {x|y|z|w} is the required replicate swizzle.
  • src1 and src2 are source registers and must be two different Constant Float Register (c#). The values of src1 and src2 must be that of the macros D3DSINCOSCONST1 and D3DSINCOSCONST2 respectively.

vs_3_0

sincos dst.{x|y|xy}, src0.{x|y|z|w}

Where:

  • dst is a destination register and has to be a Temporary Register (r#). The destination register must have exactly one of the following three masks: .x | .y | .xy.
  • src0 is a source register that provides the input angle, which must be within [-pi, +pi]. {x|y|z|w} is the required replicate swizzle.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sincos |  | x | x | x | x | x

vs_2_0 and vs_2_x Remarks

For vs_2_0 and vs_2_x, sincos can be used with predication, but with one restriction to the swizzle of the Predicate Register (p0): only replicate swizzle (.x | .y | .z | .w) is allowed.

For vs_2_0 and vs_2_x, the instruction operates as follows: (V = the scalar value from src0 with a replicate swizzle):

  • If the write mask is .x:
    dest.x = cos( V )
dest.y is undefined when the instruction completes
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction
  • If the write mask is .y:
    dest.x is undefined when the instruction completes
dest.y = sin( V )
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction
  • If the write mask is .xy:
    dest.x = cos( V )
dest.y = sin( V )
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction

vs_3_0 Remarks

For vs_3_0, sincos can be used with predication without any restriction. See Predicate Register.

For vs_3_0, the instruction operates as follows: (V = the scalar value from src0 with a replicate swizzle)

  • If the write mask is .x:
    dest.x = cos( V )
dest.y is not touched by the instruction
dest.z is not touched by the instruction
dest.w is not touched by the instruction
  • If the write mask is .y:
    dest.x is not touched by the instruction
dest.y = sin( V )
dest.z is not touched by the instruction
dest.w is not touched by the instruction
  • If the write mask is .xy:
    dest.x = cos( V )
dest.y = sin( V )
dest.z is not touched by the instruction
dest.w is not touched by the instruction

The application can map an arbitrary angle (in radians) to the range [-pi, +pi] using the following shader pseudocode:

def c0, pi, 0.5, 2*pi, 1/(2*pi)
mad r0.x, input_angle, c0.w, c0.y
frc r0.x, r0.x
mad r0.x, r0.x, c0.z, -c0.x


slt - vs

Computes the sign if the first source is less than the second source.

Syntax

slt dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
slt | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = (src0.x < src1.x) ? 1.0f : 0.0f;
dest.y = (src0.y < src1.y) ? 1.0f : 0.0f;
dest.z = (src0.z < src1.z) ? 1.0f : 0.0f;
dest.w = (src0.w < src1.w) ? 1.0f : 0.0f;


sub - vs

Subtracts sources.

Syntax

sub dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sub | x | x | x | x | x | x

This instruction performs the subtraction shown in this formula.

dest.x = src0.x - src1.x
dest.y = src0.y - src1.y
dest.z = src0.z - src1.z
dest.w = src0.w - src1.w


texldl - vs

Sample a texture with a particular sampler. The particular mipmap level-of-detail being sampled has to be specified as the fourth component of the texture coordinate.

Syntax

texldl dst, src0, src1

Where:

  • dst is a destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample.
  • src1 identifies the source sampler register (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a control state defined by the D3DSAMPLERSTATETYPE enumeration (for example, D3DSAMP_MINFILTER).

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldl |  |  |  |  | x | x

texldl looks up the texture set at the sampler stage referenced by src1. The level-of-detail is selected from src0.w. This value can be negative, in which case the level-of-detail selected is the "zeroth one" (biggest map) with the MAGFILTER. Because src0.w is a floating point value, the fractional value is used to interpolate (if MIPFILTER is LINEAR) between two mip levels. Sampler states MIPMAPLODBIAS and MAXMIPLEVEL are honored. For more information about sampler states, see D3DSAMPLERSTATETYPE.

If a shader program samples from a sampler that does not have a texture set, 0001 is obtained in the destination register.

This is an approximation to the reference device algorithm.

LOD = src0.w + LODBIAS;
if (LOD <= 0 )
{
   LOD = 0;
   Filter = MagFilter;
   tex = Lookup( MAX(MAXMIPLEVEL, LOD), Filter );
}
else
{
   Filter = MinFilter;
   LOD = MAX( MAXMIPLEVEL, LOD);
   tex = Lookup( Floor(LOD), Filter );
   if( MipFilter == LINEAR )
   {
      tex1 = Lookup( Ceil(LOD), Filter );
      tex = (1 - frac(src0.w))*tex + frac(src0.w)*tex1;
   }
}

Restrictions:

  • The texture coordinates should not be scaled by texture size.
  • dst must be a Temporary Register (r#).
  • dst can accept a write mask. See Destination Register Masking.
  • Defaults for missing components are either 0 or 1, and depend on the texture format.
  • src1 must be a Sampler (s#). src1 may not use a negate modifier. src1 may use swizzle, which is applied after sampling before the write mask is honored. The sampler must have been declared (using dcl_samplerType - vs) at the beginning of the shader.
  • The number of coordinates required to perform the texture sample depends on how the sampler was declared. If it was declared as a cube, a three-component texture coordinate is required (.rgb). Validation enforces that coordinates provided to texldl Are sufficient for the texture dimension declared for the sampler. However, it is not guaranteed that the application actually set a texture (through the API) with dimensions equal to the dimension declared for the sampler. In such a case, the runtime will attempt to detect mismatches (possibly in debug only). Sampling a texture with fewer dimensions than are present in the texture coordinate will be allowed, and will be assumed to ignore the extra texture coordinate components. Conversely, sampling a texture with more dimensions than are present in the texture coordinate is not allowed.
  • If the src0 (texture coordinate) is a Temporary Register (r#), the components required for the lookup (described above) must have been previously written.
  • Sampling unsigned RGB textures will result in float values between 0.0 and 1.0.
  • Sampling signed textures will result in float values between -1.0 to 1.0.
  • When sampling floating point textures, Float16 means that the data will range within MAX_FLOAT16. Float32 means the maximum range of the pipeline will be used. Sampling outside of either range is undefined.
  • There is no dependent read limit.


vs

This instruction specifies the shader version number. This instruction works on all shader versions.

Syntax

vs_mainVer_subVer

Input Arguments

Input arguments contain a single main version number with a single sub version number. The allowable combinations are listed in the table below.

Main versions | Sub versions
1 | 1
2 | 0, sw (software), x (extended)
3 | 0, sw (software)

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
vs | x | x | x | x | x | x

This instruction must be the first non-comment instruction in a vertex shader.

This instruction is supported in all vertex shader versions.

Hardware accelerated versions of the software (versions without _sw in the version number), can process vertices with hardware accelearation or use software vertex processing. Software versions (versions with _sw in the version number) process vertices only with software.

Examples

This partial example declares a version 1_1 vertex shader.

vs_1_1

This partial example declares a version 2 software vertex shader.

vs_2_sw


Vertex Shader Registers

  • Registers - vs_1_1
  • Registers - vs_2_0
  • Registers - vs_2_x
  • Registers - vs_3_0
  • Vertex Shader Register Modifiers


Vertex Shader Register Modifiers

  • Vertex Shader Source Register Modifiers
  • Source Register Swizzling
  • Destination Register Masking


Vertex Shader Source Register Modifiers

Source modifiers can be applied to modify the data read from a source register before the data is used by the instruction.

Negate

Negate the contents of the source register.

Component modifier | Description
- r | Source negation

The negate modifier cannot be used on second source register of these instructions: m3x2 - vs, m3x3 - vs, m3x4 - vs, m4x3 - vs, m4x4 - vs.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
- | x | x | x | x | x | x

Absolute Value

Take the absolute value of the register.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  |  |  |  | x | x

If any version 3 shader reads from one or more constant float registers (c#), one of the following must be true.

  • All of the constant floating-point registers must use the abs modifier.
  • None of the constant floating-point registers can use the abs modifier.


Source Register Swizzling

Before an instruction runs, the data in a source register is copied to a temporary register. Swizzling refers to the ability to copy any source register component to any temporary register component. Swizzling does not affect the source register data.

Component Swizzling

As shown in the following table, swizzling can be applied to the individual components of the source register data (where r is one of the valid vertex shader input Registers - vs_1_1).

Component modifier | Description
r.[xyzw][xyzw][xyzw][xyzw] | Source swizzle
  • All four components are always copied. If fewer than four components are specified, the last component is repeated (xy means .xyyy). If no components are specified, x is repeated (.xxxx).
  • The components can appear in any order. v0.ywx results in v0.ywxx.
  • The rgba components can be used respectively for xyzw (r for x, g for b, etc.).
  • These instructions implement source-register single component swizzles: exp, expp, log, logp, pow, rcp, rsq. The result of these instructions is copied to all four destination register components.

Swizzling cannot be used on the m3x2 - vs, m3x3 - vs, m4x3 - vs, and m4x4 - vs instructions.


Destination Register Masking

Masking specifies which components of the destination register will be updated with the result of an instruction. Texture registers have one set of rules and nontexture registers have another set of rules.

  • dx9_graphics_reference_asm_vs_registers_modifiers_masking - This section contains rules for applying masks to destination registers.
  • Texture_Register_Masks - Texture registers have some unique rules.

Destination Register Masking

As shown in the following table, masking (where r is one of the valid vertex shader Vertex Shader Registers) can be applied to the individual components of the vector data.

Component modifier | Description
r.{x}{y}{z}{w} | Destination mask
  • In general, specifying destination register write masks is good coding style. It makes code easier to read and maintain.
  • Any combination of components may be specified (including none) as long as x precedes y, y precedes z, and z precedes w.
  • The oPts and oFog output registers must use only one mask.
  • Certain instructions require the destination register to use a single write mask: exp, expp, log, logp, pow, rcp, and rsq.
  • In version 1.0, the frc instruction required one of the following mask combinations: .x or .y or .xy. Version 2.0 has no mask restriction.
  • sincos requires one of the following mask combinations: .x or .y or .xyz.
  • m3x2 requires the .xy write mask.
  • m3x3 and m4x3 require the .xyz write mask.
  • m3x4 and m4x4 require either the .xyz write mask or the default write mask (xyzw).

Texture Register Masks

The validation rules for using modifiers on texture coordinate registers are tighter than the validation rules for other registers.

  • If oTn is written, all previous registers (oTn-1 ~ oT0) have to be written as well.
  • The "combined" write mask for any oT# register must be exactly one of the following:
    • .x
    • .xy
    • .xyz
    • .xyzw (which is equivalent to not using any component modifiers)

For example, a vertex shader can output to texture registers in separate instructions.

    oT1.y
    oT0.y
    oT2
    oT0.xz
    oT1.x

Or, the instructions can be combined.

    oT0.xyz
    oT1.xy
    oT2.xyzw

These restrictions apply only to the texture coordinate registers.


Registers - vs_1_1

This section contains reference information for the input and output registers implemented by vertex shader version 1_1.

Input Registers

Register | Name | Count | R/W | # Read ports | # Reads / inst | Dimension | RelAddr | Defaults | Requires DCL
a0 | Address Register | 1 | R/W | 1 | Unlimited | See note 3 | No | None | No
c# | Constant Float Register | See note 2 | R | 1 | Unlimited | 4 | a0.x | (0, 0, 0, 0) | No
v# | Input Register | 16 | R | 1 | Unlimited | 4 | No | See note 1 | Yes
r# | Temporary Register | 12 | R/W | 3 | Unlimited | 4 | No | None | No

Notes:

  1. Partial (0, 0, 0, 1) - If only a subset of channels are updated, the remaining channels will default to (0, 0, 0, 1).
  2. Equal to D3DCAPS9.MaxVertexShaderConst (at least 96 for vs_1_1).
  3. Only .x channel is available.

Output Registers

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oPos | Position Register | 1 | W | 4 | No | None | No
oFog | Fog Register | 1 | W | 1 | No | None | No
oPts | Point Size Register | 1 | W | 1 | No | None | No
oD# | Color Register; See note 1 | 2 | W | 4 | No | None | No
oT# | Texture Coordinate Register | 8 | W | 4 | No | None | No

Notes:

  1. oD0 is the diffuse color output; oD1 is the specular color output.


Registers - vs_2_0

This section contains reference information for the input and output registers implemented by vertex shader version 2_0.

Input Registers

Register | Name | Count | R/W | # Read ports | # Reads / inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Register | 16 | R | 1 | Unlimited | 4 | No | See note 1 | Yes
r# | Temporary Register | 12 | R/W | 3 | Unlimited | 4 | No | None | No
c# | Constant Float Register | See note 2 | R | 1 | 2 | 4 | a0 / aL | (0, 0, 0, 0) | No
a0 | Address Register | 1 | R/W | 1 | 2 | 4 | No | None | No
b# | Constant Boolean Register | 16 | R | 1 | 1 | 1 | No | FALSE | No
i# | Constant Integer Register | 16 | R | 1 | 1 | 4 | No | (0, 0, 0, 0) | No
aL | Loop Counter Register | 1 | R | 1 | 2 | 1 | No | None | No

Notes:

  1. Partial (0, 0, 0, 1) - If only a subset of channels are updated, the remaining channels will default to (0, 0, 0, 1).
  2. Equal to D3DCAPS9.MaxVertexShaderConst (at least 256 for vs_2_0).

Output Registers

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oPos | Position Register | 1 | W | 4 | No | None | No
oFog | Fog Register | 1 | W | 1 | No | None | No
oPts | Point Size Register | 1 | W | 1 | No | None | No
oD# | Color Register; See note 1 | 2 | W | 4 | No | None | No
oT# | Texture Coordinate Register | 8 | W | 4 | No | None | No

Notes:

  1. oD0 is the diffuse color output; oD1 is the specular color output.


Registers - vs_2_x

This section contains reference information for the input and output registers implemented by vertex shader version 2_x.

Input Registers

Register | Name | Count | R/W | # Read ports | # Reads / inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Register | 16 | R | 1 | Unlimited | 4 | No | See note 1 | Yes
r# | Temporary Register | See note 2 | R/W | 3 | Unlimited | 4 | No | None | No
c# | Constant Float Register | See note 3 | R | 1 | 2 | 4 | a0 / aL | (0, 0, 0, 0) | No
a0 | Address Register | 1 | R/W | 1 | 2 | 4 | No | None | No
b# | Constant Boolean Register | 16 | R | 1 | 1 | 1 | No | FALSE | No
i# | Constant Integer Register | 16 | R | 1 | 1 | 4 | No | (0, 0, 0, 0) | No
aL | Loop Counter Register | 1 | R | 1 | 2 | 1 | No | None | No
p0 | Predicate Register | 1 | R/W | 1 | 1 | 4 | No | None | No

Notes:

  1. Partial (0, 0, 0, 1) - If only a subset of channels are updated, the remaining channels will default to (0, 0, 0, 1).
  2. Equal to D3DCAPS9.VS20Caps.NumTemps (at least 12 for vs_2_x).
  3. Equal to D3DCAPS9.MaxVertexShaderConst (at least 256 for vs_2_x).

Output Registers

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oPos | Position Register | 1 | W | 4 | No | None | No
oFog | Fog Register | 1 | W | 1 | No | None | No
oPts | Point Size Register | 1 | W | 1 | No | None | No
oD# | Color Register; See note 1 | 2 | W | 4 | No | None | No
oT# | Texture Coordinate Register | 8 | W | 4 | No | None | No

Notes:

  1. oD0 is the diffuse color output; oD1 is the specular color output.


Registers - vs_3_0

This section contains reference information for the input and output registers implemented by vertex shader version 3_0.

Input Registers

Register | Name | Count | R/W | # Read ports | # Reads / inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Register | 16 | R | 1 | Unlimited | 4 | No | See note 1 | Yes
r# | Temporary Register | 32 | R/W | 3 | Unlimited | 4 | No | None | No
c# | Constant Float Register | See note 2 | R | 1 | Unlimited | 4 | a0 / aL | (0, 0, 0, 0) | No
a0 | Address Register | 1 | R/W | 1 | Unlimited | 4 | No | None | No
b# | Constant Boolean Register | 16 | R | 1 | 1 | 1 | No | FALSE | No
i# | Constant Integer Register | 16 | R | 1 | 1 | 4 | No | (0, 0, 0, 0) | No
aL | Loop Counter Register | 1 | R | 1 | Unlimited | 1 | No | None | No
p0 | Predicate Register | 1 | R/W | 1 | 1 | 4 | no | none | no
s# | Sampler | 4 | R | 1 | 1 | 4 | No | See note 3 | Yes

Notes:

  1. Partial (0, 0, 0, 1) - If only a subset of channels are updated, the remaining channels will default to (0, 0, 0, 1).
  2. Equal to D3DCAPS9.MaxVertexShaderConst (at least 256 for vs_3_0).
  3. Defaults for sampler lookup exist, but values depend on texture format.

Output Registers

Output registers have been collapsed into 12 o# (output) registers. These can be used for anything the user wants to interpolate for the pixel shader: texture coordinates, colors, fog, etc.

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
o# | Output Register | 12 | W | 4 | aL | None | Yes


Relative Addressing

The [ ] syntax can be used only in register types that can be relatively addressed in certain shader models. The supported forms of [ ] syntax are listed as follows:

Where:

  • "R" denotes any register type that can be relatively addressed.
  • "A" denotes any register that can be used as an index to relatively address other registers.
  • n0 - ni, m0 - mj, and k are integers >= 0.
[ ] syntax | Effective index | Examples
R[ A + m0 + ... + mj ] | A + m0 + ... + mj | c[ a0.x + 3 + 7 ]
R[ k ] ( = Rk ) | k | c[ 10 ] ( = c10 )
R[ A ] | A | c[ a0.y ]
Rk[ n0 + ... + ni + A + m0 + ... + mj ] | A + k + n0 + ... + ni + m0 + ... + mj | c8[ 3 + 2 + a0.w + 5 + 6 + 1 ]
R[ n0 + ... + ni + A + m0 + ... + mj ] | A + n0 + ... + ni + m0 + ... + mj | c[ 2 + 1 + aL + 3 + 4 + 5 ]
Rk[ A ] | A + k | c12[ aL ], c0[ a0.z ]
Rk[ A + m0 + ... + mj ] | A + k + m0 + ... + mj | v1[ aL + 4 + 8 ]
R[ n0 + ... + ni + A ] | A + n0 + ... + ni | o[ 3 + 1 + aL ]
Rk[ n0 + ... + ni + A ] | A + k + n0 + ... + ni | o1[ 2 + 1 + 3 + aL ]

The registers are available in the following versions:

Register type | Vertex Shader Versions
a0 | All
aL | vs_2_0 and higher
cn | vs_1_1 and higher
on | vs_3_0


Address Register

The a0 register is an address register. A single register is available in version vs_1_1. The address register, designated as a0.x in vs_1_1, can be used as a signed integer offset for relative addressing into the constant register file. For versions vs_2_0 and above, all four components (.x, .y, .z, .w) are available for relative addressing.

c[a0.x + n]

The address register cannot be read by a vertex shader, it can only be used for relative addressing of a constant register. Reading values outside of the legal range will return (0.0, 0.0, 0.0, 0.0). The address register can only be a destination for the mov - vs instruction. If a floating-point number is moved into an integer register, a round-to-nearest conversion happens.

All shaders must initialize the address register before using it. For version vs_2_0 and above, the mova - vs instruction can move a floating-point value to an address register.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Address Register | x | x | x | x | x | x


Constant Float Register

Vertex shader input register for a four component floating-point constant. Set a constant register with either def - vs or IDirect3DDevice9::SetVertexShaderConstantF.

The constant register file is read-only from the perspective of the vertex shader. Any single instruction may access only one constant register. However, each source in that instruction may independently swizzle and negate that vector as it is read.

The behavior of shader constants has changed between Direct3D 8 and Direct3D 9.

  • For Direct3D 9, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the APIs SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For Direct3D 8, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.

A constant register is designated as either absolute or relative:

c[n]           ; absolute
c[a0.x + n]    ; relative - supported only in version 1_1

The constant register can be read, therefore, either by using an absolute index or with a relative index from an address register. Reads from out-of-range registers return (0.0, 0.0, 0.0, 0.0).

Examples

Here is an example declaring two floating-point constants within a shader.

def c40, 0.0f,0.0f,0.0f,0.0f;

These constants are loaded every time IDirect3DDevice9::SetVertexShader is called.

Here is an example using the API.

    // Set up the vertex shader constants.
    {
        D3DXMATRIXA16 mat;
        D3DXMatrixMultiply( &mat, &m_matView, &m_matProj );
        D3DXMatrixTranspose( &mat, &mat );

        D3DXVECTOR4 vA( sinf(m_fTime)*15.0f, 0.0f, 0.5f, 1.0f );
        D3DXVECTOR4 vD( D3DX_PI, 1.0f/(2.0f*D3DX_PI), 2.0f*D3DX_PI, 0.05f );

        // Taylor series coefficients for sin and cos.
        D3DXVECTOR4 vSin( 1.0f, -1.0f/6.0f, 1.0f/120.0f, -1.0f/5040.0f );
        D3DXVECTOR4 vCos( 1.0f, -1.0f/2.0f, 1.0f/ 24.0f, -1.0f/ 720.0f );

        m_pd3dDevice->SetVertexShaderConstantF(  0, (float*)&mat,  4 );
        m_pd3dDevice->SetVertexShaderConstantF(  4, (float*)&vA,   1 );
        m_pd3dDevice->SetVertexShaderConstantF(  7, (float*)&vD,   1 );
        m_pd3dDevice->SetVertexShaderConstantF( 10, (float*)&vSin, 1 );
        m_pd3dDevice->SetVertexShaderConstantF( 11, (float*)&vCos, 1 );
    }

If you are setting constant values with the API, there is no shader declaration required.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Constant Register | x | x | x | x | x | x


Constant Integer Register

Constant integer registers are used only by loop - vs and rep - vs.

They can be set using defi - vs or IDirect3DDevice9::SetVertexShaderConstantI.

When used as an argument to the loop - vs instruction:

  • .x is the iteration count. (rep - vs uses only this component).
  • .y is the initial value for the loop counter.
  • .z is the increment step for the loop counter.

The behavior of shader constants has changed between Direct3D 8 and Direct3D 9.

  • For Direct3D 9, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the APIs SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For Direct3D 8, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.


Constant Boolean Register

This register is a collection of bits used in static flow control instructions (for example, if bool - vs - else - vs - endif - vs). There are 16 of them, therefore, a shader can have 16 independent branch conditions. They can be set using defb - vs or IDirect3DDevice9::SetVertexShaderConstantI.

The behavior of shader constants has changed between Direct3D 8 and Direct3D 9.

  • For Direct3D 9, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the APIs SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For Direct3D 8, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.


Color Register

These vertex shader output registers contain a color value.

Register | Description
oD0 | diffuse color register.
oD1 | specular color register.

The oD0 value is interpolated and is written to the pixel shader color register 0 (v0). The oD1 value is interpolated and written to the pixel shader color register 1 (v1). For more information about pixel shader color registers, see the pixel shader Input Color Register page.

Remarks

Example

min oD0, r0, c1.x


Fog Register

This vertex shader output register contains a per-vertex fog color.

Remarks

A register consists of properties that determine how each register behaves.

Property | Description
Name | oFog
Count | One vector, of which only one component can be used and must be specified by the component mask
I/O permissions | Write-only.

The output fog value registers. The value is the fog factor to be interpolated and then routed to the fog table. Only the scalar x-component of the fog is used.


Input Register

Vertex shader input register.

Data from each vertex (using one or more input vertex streams) is loaded into the vertex input registers before the vertex shader is run. The input registers consist of 16 four-component floating-point vectors, designated as v0 through v15. These registers are read-only. An input register is bound to vertex data through a vertex declaration.

The following register properties control how each register behaves:

Property | Description
Name | v[n] - n is an optional register number. 0 is the default value used, if it is omitted.
Count | A maximum of 16 registers, v0 - v15.
I/O permissions | Read-only. This register cannot be written by the API or within the shader.
Read ports | 1. This is the number of times a register can be read within a single instruction. See below.

Any single instruction can access only one vertex input register. However, each source in the instruction can independently swizzle and negate that vector as it is read.

Example

Here is an example using a vertex declaration to bind 2D vertex position data to register v0.

The vertex declaration belongs in the application:

D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
      D3DDECL_END()
};

Here is the corresponding vertex shader declaration:

dcl_position v0

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Position Register | x | x | x | x | x | x


Loop Counter Register

The only register in this bank is the current loop counter (aL) register. It automatically gets incremented in each execution of the loop - vs...endloop - vs block. So it can be used in the block for relative addressing if needed and is invalid to use it outside the loop.


Output Registers

  • Vertex Color Register
  • Fog Register
  • Position_Register
  • Point_Size_Register
  • Texture_Coordinate_Register

Register names are preceded by a lowercase letter o, indicating that the output registers are write-only.

Vertex Color Register - oD0, oD1

oD0 is the diffuse color register. oD1 is the specular color register. The oD0 value is interpolated and is written to the input color register 0 (v0) of the pixel shader. The oD1 value is interpolated and written to the input color register 1 (v1) of the pixel shader. For more information about pixel shader color registers, see Registers.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Vertex Color Register | x | x | x | x |  |

Fog Register - oFog

The output fog value registers. The value is the fog factor to be interpolated and then routed to the fog table. Only the scalar x-component of the fog is used. Values are clamped between zero and one before passing to the rasterizer.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Fog Register | x | x | x | x |  |

Position Register - oPos

The output position registers. The value is the position in homogeneous clipping space. This value must be written by the vertex shader.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Position Register | x | x | x | x |  |

Point Size Register - oPts

The output point-size registers. Only the scalar x-component of the point size is used.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Point Size Register | x | x | x | x |  |

Texture Coordinate Register - oT0 to oT7

The output texture coordinates registers. Specifically, these are an array of output data registers that are iterated and used as texture coordinates by the texture sampling stages routing data to the pixel shader.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Texture Coordinate Register | x | x | x | x |  |

When writing to a texture coordinate register, it is recommended to pass only as many floating point values as the dimension of the corresponding texture map. Control the values passed with a modifier. For example, use .xy for a 2D texture map.

When texture projection is enabled for a texture stage, all four floating point values must be written to the corresponding texture register.

Any of the D3DTTFF* texture transform flags should be zero when the programmable pipeline is being used.

Texture Coordinate Range

Object vertex data supplies input texture coordinates. Objects that do not used tiled textures commonly have texture coordinates in the range [0,1]. Objects that use tiled textures, such as terrain, typically have texture coordinates that range from [-?,+?] where ? can be a large floating point number.

Texture coordinate interpolation is performed on vertex data for rasterization. During rasterization, texture coordinates are interpolated between object vertices, modified by texture wrapping and scaled by the texture size (also taking into account texture address mode) to produce an integer index. The index is then used to perform a texture lookup. MaxTextureRepeat can be used to determine how many times a texture can be tiled.

If texture coordinates are read directly into a pixel shader (using texcoord or texcrd), the texture coordinate range depends on the instruction and the pixel shader version.


Point Size Register

This vertex shader output register contains per-vertex point size data.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Point Size Register | x | x | x | x | x | x

A register consists of properties that determine how each register behaves.

Property | Description
Name | oPts
Count | 1 vector, of which of only 1 component can be used and must be specified by the component mask.
I/O permissions | Write-only.

Only the scalar x-component of the point size is used.


Position Register

This vertex shader output register contains per-vertex position data.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Position Register | x | x | x | x | x | x

A register consists of properties that determine how each register behaves.

Property | Description
Name | oPos
Count | 1 vector
I/O permissions | Write-only.

The value is the position in homogeneous clipping space. This value must be written by the vertex shader.

Example

    dcl_position v0

    def c40, 0.0f,0.0f,0.0f,0.0f;
    // transform into projection space
    m4x4 r0,v0,c8
    max r0.z,c40.z,r0.z //clamp to 0
    max r0.w,c12.x,r0.w //clamp to near clip plane
    mov oPos,r0


Predicate Register

This vertex shader output register contains a per-channel Boolean value.

Remarks

A predicate register is supported by the following versions.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
predicate register |  |  |  | x | x | x

Here are the register properties.

Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
Predicate(p) | 1 | R/W | 1 | 1 | 4 | N/A | None | N

The predicate register can be modified with setp_comp - vs. There are no default values for this register, an application needs to set the register before it is used.


Sampler

A sampler is a input pseudo-register for a vertex shader, which is used to identify the sampling stage. There are four vertex shader samplers: s0 to s3. Four texture surfaces can be read in a single shader pass.

Samplers are pseudo registers because you cannot directly read or write to them.

A sampling unit corresponds to the texture sampling stage, encapsulating the sampling-specific state provided by IDirect3DDevice9::SetSamplerState. Each sampler uniquely identifies a single texture surface, which is set to the corresponding sampler using the IDirect3DDevice9::SetTexture. However, the same texture surface can be set at multiple samplers.

At draw time, a texture cannot be simultaneously set as a render target and a texture at a stage.

Because there are four samplers, up to four texture surfaces can be read from in a single shader pass. A sampler might appear as the only argument in the texture load instruction: texldl - vs.

In vs_3_0, if a sampler is used, it needs to be declared at the beginning of the shader program using the dcl_samplerType - vs instruction.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Sampler |  |  |  |  | x | x

See Also

Vertex Textures in vs_3_0 (Direct3D 9)


Temporary Register

A vertex shader temporary register is used to hold intermediate results.

A temporary register must be initialized before it is used. Each temporary register has single-write and triple-read access. This means that a single shader instruction can use as many as three temporary registers as inputs.

Values in a temporary register that remain from preceeding invocations of the vertex shader cannot be used.

A register consists of properties that determine how each register behaves.

Property | Description
Name | r[n]. n is an optional register number. The default is 0, and is the value used if no value is specified.
Count | A maximum of 12 registers.
I/O permissions | Read/write. This register can be read or written by the API or by the shader.
Read ports | The number of times a register can be read within a single instruction is 3. A temporary register is the only register that can be read and written more than once in a single instruction.

Each temporary register has single-write and triple-read access. Therefore, an instruction can have as many as three temporary registers in its set of input source operands.

No values in a temporary register that remain from preceding invocations of the vertex shader can be used. Vertex shaders that read a value from a temporary register before writing to it will fail the Direct3D API call to create the vertex shader.

Example

Here is an example using a temporary register:

def c4, 0,0,0,1
...
// Decompress position
mov r0.x, v0.x
mov r0.y, c4.w       // 1
mov r0.z, v0.y
mov r0.w, c4.w       // 1

// Compute theta from distance and time
mov r4.xz, r0        // xz

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Temporary Register | x | x | x | x | x | x


Texture Coordinate Register

This vertex shader output register contains per-vertex texture coordinates.

A register consists of properties that determine how each register behaves.

Property | Description
Name | oT0 - oT7
Count | Eight vectors
I/O permissions | Write-only

The output texture coordinates registers are an array of output data registers. The register data is iterated and used as texture coordinates by the texture sampling stages to supply data to the pixel shader.

When writing to a texture coordinate register, it is recommended that you pass only as many floating point values as the dimension of the corresponding texture map. Control the values that are passed with a modifier. For example, use .xy for a 2D texture map.

The fixed function vertex pipeline flags, D3DTEXTURETRANSFORMFLAGS (D3DTTFF_COUNT1, D3DTTFF_COUNT2, D3DTTFF_COUNT3, D3DTTFF_COUNT4), should be set to zero if you are using a programmable vertex shader.

Object vertex data supplies input texture coordinates. Objects that do not use tiled textures commonly have texture coordinates in the range [0,1]. Objects that use tiled textures, such as terrain, typically have texture coordinates that range from [-n,+n] where n can be any floating point number.

Texture coordinate interpolation is performed on vertex data for rasterization. During rasterization, texture coordinates are interpolated between object vertices, modified by texture wrapping, and scaled by the texture size (also taking into account texture addressing modes) to produce an integer index. The index is then used to perform a texture lookup. Use the MaxTextureRepeat value in D3DCAPS9 to determine how many times a texture can be tiled.

Example

Declare the texture coordinate register.

dcl_texcoord v7

Copy the per-vertex texture coordinates to the output register.

mov oT0, v7

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Texture Coordinate Register | x | x | x | x | x | x


Pixel Shaders

  • ps_1_1, ps_1_2, ps_1_3, ps_1_4
  • ps_2_0
  • ps_2_x
  • ps_3_0
  • Registers
  • Pixel Shader Instructions
  • Pixel Shader Differences


ps_1_1, ps_1_2, ps_1_3, ps_1_4

The pixel shader assembler is made up of a set of instructions that operate on pixel data contained in registers. Operations are expressed as instructions comprised of an operator and one or more operands. Instructions use registers to transfer data in and out of the pixel shader ALU. Registers can also be used by some instructions to hold temporary results.

Instructions

There are two main categories of pixel shader instructions: arithmetic instructions and texture addressing instructions. Arithmetic instructions modify color data. Texture addressing operations process texture coordinate data and in most cases, sample a texture. Pixel shader instructions are run on a per-pixel basis; that is, they have no knowledge of other pixels in the pipeline.

Texture addressing instructions each consume one slot, but arithmetic instructions can be paired to enable both color components (RGB) and an alpha component instruction in a single slot.

ps_1_1, ps_1_2, ps_1_3, ps_1_4 Instructions contains a list of the available instructions.

When multisampling is enabled, pixel shaders only get run once per pixel, not once for every subpixel. Multisampling only increases the resolution of polygon edges, as well as depth and stencil tests. For example, if 3x3 multisampling is enabled, and a triangle being rasterized is found to cover five of the nine subpixels for a particular pixel, the pixel shader gets run once and the same color result is applied to all five subpixels.

Registers

ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers lists the different registers used by the shader ALU.

Modifiers

Modifiers for ps_1_X can be used to change the functionality of an instruction, or the data read from or written to a register.

Direct3D 9 requires intermediate computations to maintain at least 8-bit precision for all surface formats. Both higher precision (12-bit) for in-stage math, and saturation to 8-bits between texture stages are recommended. No modifiable rounding modes or exceptions are supported. Multiplication should be supported with a round-to-nearest precision to keep precision loss to a minimum.

Sampler Count

The number of texture samplers available is:

  • For ps_1_0 - ps_1_3, the maximum is 4.
  • For ps_1_4, the maximum is 6.


ps_2_0

A programmable pixel shader is made up of a set of instructions that operate on pixel data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • ps_2_0 Instructions contains a list of the available instructions.
  • ps_2_0 Registers lists the different types of registers used by the vertex shader ALU.
  • Modifiers Are used to modify the way an instruction works.
  • Destination Register Write Mask determines what components of the destination register get written.
  • Pixel Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.

Instruction Count

Shaders have restrictions for maximum instuction counts. Total Instruction slots: 96 (64 arithmetic and 32 texture).

Sampler Count

The number of texture samplers available is 16.


ps_2_x

A programmable pixel shader is made up of a set of instructions that operate on pixel data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • ps_2_x Instructions contains a list of the available instructions.
  • ps_2_x Registers lists the different types of registers used by the vertex shader ALU.
  • Modifiers Are used to modify the way an instruction works.
  • Destination Register Write Mask determines what components of the destination register get written.
  • Pixel Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.

Dynamic Flow Control

DynamicFlowControlDepth represents the nesting depth of dynamic flow control instructions: if, if_comp, if_pred, break - ps, and break_comp - ps. The value is equal to the nesting depth of the if_comp block. If this cap is zero, the device does not support dynamic flow control instructions.

Number of Temporary Registers

The number of temporary registers supported by the device. The range is from 12 to 32.

Static Flow Control Nesting Depth

StaticFlowControlDepth represents the nesting depth of two types of static flow control instructions: loop /rep And call /callnz. loop /rep instructions can be nested up to StaticFlowControlDepth deep. Independently, call /callnz instructions can be nested up to StaticFlowControlDepth deep.

Number of Instruction Slots

The number of instruction slots can range from 96 to a maximum of 512, and is specified by the MaxPixelShaderInstructionSlots. The total number of instructions that can run is defined by MaxPixelShaderInstructionsExecuted. This can be larger than the number of instruction slots due to looping and subroutine calls.

Arbitrary Swizzle

If D3DD3DPSHADERCAPS2_0_ARBITRARYSWIZZLE is set, arbitrary swizzle is supported. See Source Register Swizzling.

Gradient Instructions

If D3DD3DPSHADERCAPS2_0_GRADIENTINSTRUCTIONS is set, gradient instructions are supported. See dsx - ps, dsy - ps, and texldd - ps.

Predication

If D3DD3DPSHADERCAPS2_0_PREDICATION is set, instruction predication is supported. See Predicate Register.

Dependent Read Limit

If D3DD3DPSHADERCAPS2_0_NODEPENDENTREADLIMIT is set, there are no dependent read limits.

Texture Instruction Limit

If D3DD3DPSHADERCAPS2_0_NOTEXINSTRUCTIONLIMIT is set, there is no limit on texture instructions.

Sampler Count

The number of texture samplers available is 16.


ps_3_0

A programmable pixel shader is made up of a set of instructions that operate on pixel data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • ps_3_0 Instructions contains a list of the available instructions.
  • ps_3_0 Registers lists the different types of registers used by the pixel shader ALU.
  • Modifiers Are used to modify the way an instruction works.
  • Destination Register Write Mask determines what components of the destination register get written.
  • Pixel Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.

New Features

Add a face register. Add a position register. Color registers (v#) are now fully floating point and the texture coordinate registers (t#) have been consolidated. Input declarations take the usage names, and multiple usages are permitted for components of a given register.

Dynamic Flow Control

The device supports dynamic flow control (if bool - ps, break - ps, and break_comp - ps). The depth of nesting ranges from 0 to 24.

Number of Temporary Registers

The number of temporary registers supported is 32.

Static Flow Control Nesting Depth

The call - ps/callnz /call_pred can be nested to a maximum depth of 4. Independently, loop - ps/rep - ps instructions can be nested to a maximum depth of 4.

Arbitrary Swizzle

Arbitrary swizzle is supported. See Source Register Swizzling.

Gradient Instructions

Gradient instructions are supported. See dsx - ps, dsy - ps, and texldd - ps.

Predication

Instruction predication is supported. See Predicate Register.

Dependent Read Limit

There are no dependent read limits.

Texture Instruction Limit

There is no limit on texture instructions.

Instruction Count

Each pixel shader is allowed anywhere from 512 up to the number of slots in MaxPixelShader30InstructionSlots (not more than 32768). The number of instructions run can be much higher because of the looping support. MaxPShaderInstructionsExecuted should be at least 2^16.

Sampler Count

The number of texture samplers available is 16.

Device Caps

If ps_3_0 is supported, the following caps are supported in hardware (at a minimum):

Cap | Value
MaxTextureWidth, MaxTextureHeight | 4K each
MaxTextureRepeat | 8K
MaxAnisotropy | 16
PixelShaderVersion | 3_0
MaxPixelShader30InstructionSlots | 512
The following primitive caps are set: | D3DPMISCCAPS_BLENDOP, D3DPMISCCAPS_CLIPPLANESCALEDPOINTS, D3DPMISCCAPS_CLIPTLVERTS, D3DPMISCCAPS_CULLCCW, D3DPMISCCAPS_CULLCW, D3DPMISCCAPS_CULLNONE, D3DPMISCCAPS_FOGINFVF, D3DPMISCCAPS_MASKZ
The following raster caps are set: | D3DPRASTERCAPS_MIPMAPLODBIAS, D3DPRASTERCAPS_ANISOTROPY, D3DPRASTERCAPS_COLORPERSPECTIVE, D3DPRASTERCAPS_SCISSORTEST in D3DCAPS9
Full support for depth bias including: | D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS, D3DPRASTERCAPS_DEPTHBIAS
Full set of comparisons for depth and alpha test including: | All the D3DPCMPCAPS in D3DCAPS9.
Source blending modes | All blending modes are supported as a source (except D3DPBLENDCAPS_SRCALPHASAT, D3DPBLENDCAPS_BOTHSRCALPHA, and D3DPBLENDCAPS_BOTHINVSRCALPHA).
The following texture caps are supported: | D3DPTEXTURECAPS_CUBEMAP, D3DPTEXTURECAPS_MIPCUBEMAP, D3DPTEXTURECAPS_MIPMAP, D3DPTEXTURECAPS_MIPVOLUMEMAP, D3DPTEXTURECAPS_PERSPECTIVE, D3DPTEXTURECAPS_PROJECTED, D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE, D3DPTEXTURECAPS_VOLUMEMAP
The following are supported on texture filter caps, volume texture filter caps and cube texture filter caps: | D3DPTFILTERCAPS_MINFPOINT, D3DPTFILTERCAPS_MINFLINEAR, D3DPTFILTERCAPS_MINFANISOTROPIC (This is not required for VolumeTextureFilterCaps and CubeTextureFilterCaps ), D3DPTFILTERCAPS_MIPFPOINT, D3DPTFILTERCAPS_MIPFLINEAR, D3DPTFILTERCAPS_MAGFPOINT, D3DPTFILTERCAPS_MAGFLINEAR
The following texture address modes are supported at vertex and pixel stages: | D3DPTADDRESSCAPS_WRAP, D3DPTADDRESSCAPS_MIRROR, D3DPTADDRESSCAPS_CLAMP, D3DPTADDRESSCAPS_BORDER, D3DPTADDRESSCAPS_INDEPENDENTUV, D3DPTADDRESSCAPS_MIRRORONCE
All the pixel shader caps are supported. | DynamicFlowControlDepth = 24, NumTemps = 32, StaticFlowControlDepth = 4, NumInstructionSlots = 512. The following features are supported: predication, arbitrary swizzles, and gradient instructions. There is no dependent-read limit, and no limit on the mixture of texture and math instructions.
All the stencil operations are supported. This includes two sided stencil. | See D3DSTENCILOP
Device support point size per vertex | D3DFVFCAPS_PSIZE in D3DCAPS9
Non-power of 2 texture support. | Either full support or conditional non-pow-2 support; device should not have the square texture only limitation as in D3DPTEXTURECAPS_SQUAREONLY.
If the device supports multiple rendertargets, the following caps are supported: | D3DPMISCCAPS_INDEPENDENTWRITEMASKS, D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING
If vs_3_0 is supported | MaxUserClipPlanes in D3DCAPS9 is 6


Pixel Shader Differences

Instruction Slots

Each version supports a different number of maximum instruction slots.

Version | Maximum number of instruction slots
ps_1_1 | 4 texture + 8 arithmetic
ps_1_2 | 4 texture + 8 arithmetic
ps_1_3 | 4 texture + 8 arithmetic
ps_1_4 | 6 texture + 8 arithmetic per phase
ps_2_0 | 32 texture + 64 arithmetic
ps_2_x | 96 minimum, and up to the number of slots in D3DCAPS9.D3DPSHADERCAPS2_0.NumInstructionSlots. See D3DPSHADERCAPS2_0.
ps_3_0 | 512 minimum, and up to the number of slots in D3DCAPS9.MaxPixelShader30InstructionSlots. See D3DPSHADERCAPS2_0.

For information about the limitations of software shaders, see Software Shaders.

Flow Control Nesting Limits

  • See Flow Control Limitations.

ps_1_x Features

New instructions:

See ps_1_1, ps_1_2, ps_1_3, ps_1_4 Instructions.

New registers:

See ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers.

ps_2_0 Features

New features:

  • Three new swizzles - .yzxw, .zxyw, .wzyx
  • Number of Temporary Register (r#) increased to 12
  • Number of Constant Float Register registers (c#) increased to 32
  • Number of Texture Coordinate Registers (t#) increased to 8

New instructions:

  • Setup instructions - dcl - ps, dcl_samplerType - ps
  • Arithmetic instructions - abs - ps, crs - ps, dp2add - ps, exp - ps, frc - ps, log - ps, m3x2 - ps, m3x3 - ps, m3x4 - ps, m4x3 - ps, m4x4 - ps, max - ps, min - ps, nrm - ps, pow - ps, rcp - ps, rsq - ps, sincos - ps
  • Texture instructions - texld - ps_2_0 and up (different syntax), texldb - ps, texldp - ps

New registers:

  • Sampler (s#)

ps_2_x Features

New features (See D3DPSHADERCAPS2_0.):

  • Dynamic flow control
  • Static flow control
  • Nesting for dynamic and static flow control instructions
  • Number of Temporary Registers (r#) increased
  • Arbitrary source swizzle
  • Gradient instructions
  • Predication
  • No dependent texture read limit
  • No texture instruction limit

New instructions:

  • Static flow control instructions - if bool - ps, call - ps, callnz bool - ps, else - ps, endif - ps, rep - ps, endrep - ps, label - ps, ret - ps
  • Dynamic flow control instructions - break - ps, break_comp - ps, breakp - ps, callnz pred - ps, if_comp - ps, if pred - ps, setp_comp - ps
  • Arithmetic instructions - dsx - ps, dsy - ps
  • Texture instruction - texldd - ps

New registers:

  • Predicate Register (p0)

ps_3_0 Features

New features:

  • Consolidated 10 Input Registers (v#)
  • Indexable Constant Float Registers (c#) with the Loop Counter Register (aL)
  • Number of Temporary Registers (r#) increased to 32
  • Number of Constant Float Registers (c#) increased to 224

New instructions:

  • Setup instruction - dcl_usage - ps
  • Static flow instructions - loop - ps, endloop - ps
  • Arithmetic instruction - sincos - ps (new syntax)
  • Texture instruction - texldl - ps

New registers:

  • Input Register (v#)
  • Position Register (vPos)
  • Face Register (vFace)


Pixel Shader Instructions

  • ps_1_1, ps_1_2, ps_1_3, ps_1_4 Instructions
  • ps_2_0 Instructions
  • ps_2_x Instructions
  • ps_3_0 Instructions
  • Modifiers for ps_1_X
  • Flow Control Limitations


ps_1_1, ps_1_2, ps_1_3, ps_1_4 Instructions

This section contains reference information for the pixel shader version 1_X instructions.

There are several types of pixel shader instructions, as shown in the following table.

Instruction Set

Version |  | Instruction slots | 1_1 | 1_2 | 1_3 | 1_4
ps | Version number | 0 | x | x | x | x
Constant instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
def - ps | Define constants | 0 | x | x | x | x
Phase instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
phase - ps | Transition between phase 1 and phase 2 | 0 |  |  |  | x
Arithmetic instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
add - ps | Add two vectors | 1 | x | x | x | x
bem - ps | Apply a fake bump environment-map transform | 2 |  |  |  | x
cmp - ps | Compare source to 0 | 11 |  | x | x | x
cnd - ps | Compare source to 0.5 | 1 | x | x | x | x
dp3 - ps | Three-component dot product | 1 | x | x | x | x
dp4 - ps | Four-component dot product | 11 |  | x | x | x
lrp - ps | Linear interpolate | 1 | x | x | x | x
mad - ps | Multiply and add | 1 | x | x | x | x
mov - ps | Move | 1 | x | x | x | x
mul - ps | Multiply | 1 | x | x | x | x
nop - ps | No operation | 0 | x | x | x | x
sub - ps | Subtract | 1 | x | x | x | x
Texture instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
tex - ps | Sample a texture | 1 | x | x | x |
texbem - ps | Apply a fake bump environment-map transform | 1 | x | x | x |
texbeml - ps | Apply a fake bump environment-map transform with luminance correction | 1+12 | x | x | x |
texcoord - ps | Interpret texture coordinate data as color data | 1 | x | x | x |
texcrd - ps | Copy texture coordinate data as color data | 1 |  |  |  | x
texdepth - ps | Calculate depth values | 1 |  |  |  | x
texdp3 - ps | Three-component dot product between texture data and the texture coordinates | 1 |  | x | x |
texdp3tex - ps | Three-component dot product and 1D texture lookup | 1 |  | x | x |
texkill - ps | Cancels rendering of pixels based on a comparison | 1 | x | x | x | x
texld - ps_1_4 | Sample a texture | 1 |  |  |  | x
texm3x2depth - ps | Calculate per-pixel depth values | 1 |  |  | x |
texm3x2pad - ps | First row matrix multiply of a two-row matrix multiply | 1 | x | x | x |
texm3x2tex - ps | Final row matrix multiply of a two-row matrix multiply | 1 | x | x | x |
texm3x3 - ps | 3x3 matrix multiply | 1 |  | x | x |
texm3x3pad - ps | First or second row multiply of a three-row matrix multiply | 1 | x | x | x |
texm3x3spec - ps | Final row multiply of a three-row matrix multiply | 1 | x | x | x |
texm3x3tex - ps | Texture look up using a 3x3 matrix multiply | 1 | x | x | x |
texm3x3vspec - ps | Texture look up using a 3x3 matrix multiply, with non-constant eye-ray vector | 1 | x | x | x |
texreg2ar - ps | Sample a texture using the alpha and red components | 1 | x | x | x |
texreg2gb - ps | Sample a texture using the green and blue components | 1 | x | x | x |
texreg2rgb - ps | Sample a texture using the red, green and blue components | 1 |  | x | x |
  1. 1 slot in ps_1_4; 2 slots in ps_1_2 and ps_1_3
  2. 1 + 1 = 1 arithmetic instruction + 1 texture instruction


ps_2_0 Instructions

This section contains reference information for the pixel shader version 2_0 instructions.

There are several types of pixel shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - A pixel shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Texture - These instructions are used to load and sample texture data, and to modify texture coordinates.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Texture | New
abs - ps | Absolute value | 1 |  | x |  | x
add - ps | Add two vectors | 1 |  | x |  |
cmp - ps | Compare source to 0 | 1 |  | x |  |
crs - ps | Cross product | 2 |  | x |  | x
dcl_samplerType - ps | Declare the texture dimension for a sampler | 0 | x |  |  | x
dcl - ps | Declare the association between vertex shader output registers and pixel shader input registers. | 0 | x |  |  | x
def - ps | Define constants | 0 | x |  |  |
dp2add - ps | 2D dot product and add | 2 |  | x |  | x
dp3 - ps | 3D dot product | 1 |  | x |  |
dp4 - ps | 4D dot product | 1 |  | x |  |
exp - ps | Full precision 2x | 1 |  | x |  | x
frc - ps | Fractional component | 1 |  | x |  | x
log - ps | Full precision log2(x) | 1 |  | x |  | x
lrp - ps | Linear interpolate | 2 |  | x |  |
m3x2 - ps | 3x2 multiply | 2 |  | x |  | x
m3x3 - ps | 3x3 multiply | 3 |  | x |  | x
m3x4 - ps | 3x4 multiply | 4 |  | x |  | x
m4x3 - ps | 4x3 multiply | 3 |  | x |  | x
m4x4 - ps | 4x4 multiply | 4 |  | x |  | x
mad - ps | Multiply and add | 1 |  | x |  |
max - ps | Maximum | 1 |  | x |  | x
min - ps | Minimum | 1 |  | x |  | x
mov - ps | Move | 1 |  | x |  |
mul - ps | Multiply | 1 |  | x |  |
nop - ps | No operation | 1 |  | x |  |
nrm - ps | Normalize | 3 |  | x |  | x
pow - ps | xy | 3 |  | x |  | x
ps | Version | 0 | x |  |  |
rcp - ps | Reciprocal | 1 |  | x |  | x
rsq - ps | Reciprocal square root | 1 |  | x |  | x
sincos - ps | Sine and cosine | 8 |  | x |  | x
sub - ps | Subtract | 1 |  | x |  |
texkill - ps | Kill pixel render | 1 |  |  | x |
texld - ps_2_0 and up | Sample a texture | 1 |  |  | x | x
texldb - ps | Texture sampling with level-of-detail bias from w-component | 1 |  |  | x | x
texldp - ps | Texture sampling with projective divide by w-component | 1 |  |  | x | x


ps_2_x Instructions

This section contains reference information for the pixel shader version 2_x instructions.

There are several types of pixel shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - A pixel shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Texture - These instructions are used to load and sample texture data, and to modify texture coordinates.
  • Flow control - These instructions provide static and dynamic flow control to the execution of instructions.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Texture | Flow control | New
abs - ps | Absolute value | 1 |  | x |  |  |
add - ps | Add two vectors | 1 |  | x |  |  |
break - ps | Break out of a rep...endrep block | 1 |  |  |  | x | x
break_comp - ps | Conditionally break out of a rep...endrep block, with a comparison | 3 |  |  |  | x | x
breakp - ps | Break out of a rep...endrep block, based on a predicate | 3 |  |  |  | x | x
call - ps | Call a subroutine | 2 |  |  |  | x | x
callnz bool - ps | Call a subroutine if a boolean register is not zero | 3 |  |  |  | x | x
callnz pred - ps | Call a subroutine if a predicate register is not zero | 3 |  |  |  | x | x
cmp - ps | Compare source to 0 | 1 |  | x |  |  |
crs - ps | Cross product | 2 |  | x |  |  |
dcl_samplerType - ps | Declare the texture dimension for a sampler | 0 | x |  |  |  |
dcl - ps | Declare the association between vertex shader output registers and pixel shader input registers. | 0 | x |  |  |  |
def - ps | Define constants | 0 | x |  |  |  |
defb - ps | Define a Boolean constant | 0 | x |  |  |  | x
defi - ps | Define an integer constant | 0 | x |  |  |  | x
dp2add - ps | 2D dot product and add | 2 |  | x |  |  |
dp3 - ps | 3D dot product | 1 |  | x |  |  |
dp4 - ps | 4D dot product | 1 |  | x |  |  |
dsx - ps | Rate of change in the x-direction | 2 |  | x |  |  | x
dsy - ps | Rate of change in the y direction | 2 |  | x |  |  | x
else - ps | Begin an else - ps block | 1 |  |  |  | x | x
endif - ps | End an if...else - ps block | 1 |  |  |  | x | x
endrep - ps | End of a repeat block | 2 |  |  |  | x | x
exp - ps | Full precision 2x | 1 |  | x |  |  |
frc - ps | Fractional component | 1 |  | x |  |  |
if bool - ps | Begin an if block | 3 |  |  |  | x | x
if_comp - ps | Begin an if block with a comparison | 3 |  |  |  | x | x
if pred - ps | Begin an if block with predication | 3 |  |  |  | x | x
label - ps | Label | 0 |  |  |  | x | x
log - ps | Full precision log2(x) | 1 |  | x |  |  |
lrp - ps | Linear interpolate | 2 |  | x |  |  |
m3x2 - ps | 3x2 multiply | 2 |  | x |  |  |
m3x3 - ps | 3x3 multiply | 3 |  | x |  |  |
m3x4 - ps | 3x4 multiply | 4 |  | x |  |  |
m4x3 - ps | 4x3 multiply | 3 |  | x |  |  |
m4x4 - ps | 4x4 multiply | 4 |  | x |  |  |
mad - ps | Multiply and add | 1 |  | x |  |  |
max - ps | Maximum | 1 |  | x |  |  |
min - ps | Minimum | 1 |  | x |  |  |
mov - ps | Move | 1 |  | x |  |  |
mul - ps | Multiply | 1 |  | x |  |  |
nop - ps | No operation | 1 |  | x |  |  |
nrm - ps | Normalize | 3 |  | x |  |  |
pow - ps | xy | 3 |  | x |  |  |
ps | Version | 0 | x |  |  |  |
rcp - ps | Reciprocal | 1 |  | x |  |  |
rep - ps | Repeat | 3 |  |  |  | x | x
ret - ps | End of a subroutine | 1 |  |  |  | x | x
rsq - ps | Reciprocal square root | 1 |  | x |  |  |
setp_comp | Set the predicate register | 1 |  |  |  | x | x
sincos - ps | Sine and cosine | 8 |  | x |  |  |
sub - ps | Subtract | 1 |  | x |  |  |
texkill - ps | Kill pixel render | See note 1 |  |  | x |  |
texld - ps_2_0 and up | Sample a texture | See note 2 |  |  | x |  |
texldb - ps | Texture sampling with level-of-detail bias from w-component | See note 3 |  |  | x |  |
texldd - ps | Texture sampling with user-provided gradients | 3 |  |  | x |  | x
texldp - ps | Texture sampling with projective divide by w-component | See note 4 |  |  | x |  |

Notes:

  1. If D3DD3DPSHADERCAPS2_0_NOTEXINSTRUCTIONLIMIT is set, slots = 2; otherwise slots = 1.
  2. If D3DD3DPSHADERCAPS2_0_NOTEXINSTRUCTIONLIMIT is set and the texture is a cube map, slots = 4; otherwise slot = 1.
  3. If D3DD3DPSHADERCAPS2_0_NOTEXINSTRUCTIONLIMIT is set, slots = 6; otherwise slots = 1.
  4. If D3DD3DPSHADERCAPS2_0_NOTEXINSTRUCTIONLIMIT is not set, slots = 1; otherwise:
    • if D3DD3DPSHADERCAPS2_0_NOTEXINSTRUCTIONLIMIT is set and the texture is a cube map, slots = 4.
    • if D3DD3DPSHADERCAPS2_0_NOTEXINSTRUCTIONLIMIT is set and the texture is not a cube map, slots = 3.


ps_3_0 Instructions

This section contains reference information for the pixel shader version 3_0 instructions.

There are several types of pixel shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - A pixel shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Texture - These instructions are used to load and sample texture data, and to modify texture coordinates.
  • Flow control - These instructions provide static and dynamic flow control to the execution of instructions.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Texture | Flow control | New
abs - ps | Absolute value | 1 |  | x |  |  |
add - ps | Add two vectors | 1 |  | x |  |  |
break - ps | Break out of a loop - ps...endloop - ps or rep...endrep block | 1 |  |  |  | x |
break_comp - ps | Conditionally break out of a loop - ps...endloop - ps or rep...endrep block, with a comparison | 3 |  |  |  | x |
breakp - ps | Break out of a loop - ps...endloop - ps or rep...endrep block, based on a predicate | 3 |  |  |  | x |
call - ps | Call a subroutine | 2 |  |  |  | x |
callnz bool - ps | Call a subroutine if a boolean register is not zero | 3 |  |  |  | x |
callnz pred - ps | Call a subroutine if a predicate register is not zero | 3 |  |  |  | x |
cmp - ps | Compare source to 0 | 1 |  | x |  |  |
crs - ps | Cross product | 2 |  | x |  |  |
dcl_samplerType - ps | Declare the texture dimension for a sampler | 0 | x |  |  |  |
dcl_usage - ps | Declare input and output registers | 0 | x |  |  |  | x
def - ps | Define constants | 0 | x |  |  |  |
defb - ps | Define a Boolean constant | 0 | x |  |  |  |
defi - ps | Define an integer constant | 0 | x |  |  |  |
dp2add - ps | 2D dot product and add | 2 |  | x |  |  |
dp3 - ps | 3D dot product | 1 |  | x |  |  |
dp4 - ps | 4D dot product | 1 |  | x |  |  |
dsx - ps | Rate of change in the x-direction | 2 |  | x |  |  |
dsy - ps | Rate of change in the y direction | 2 |  | x |  |  |
else - ps | Begin an else - ps block | 1 |  |  |  | x |
endif - ps | End an if...else - ps block | 1 |  |  |  | x |
endloop - ps | endloop - ps | 2 |  |  |  | x | x
endrep - ps | End of a repeat block | 2 |  |  |  | x |
exp - ps | Full precision 2x | 1 |  | x |  |  |
frc - ps | Fractional component | 1 |  | x |  |  |
if bool - ps | Begin an if block | 3 |  |  |  | x |
if_comp - ps | Begin an if block with a comparison | 3 |  |  |  | x |
if pred - ps | Begin an if block with predication | 3 |  |  |  | x |
label - ps | Label | 0 |  |  |  | x |
log - ps | Full precision log2(x) | 1 |  | x |  |  |
loop - ps | Loop | 3 |  |  |  | x | x
lrp - ps | Linear interpolate | 2 |  | x |  |  |
m3x2 - ps | 3x2 multiply | 2 |  | x |  |  |
m3x3 - ps | 3x3 multiply | 3 |  | x |  |  |
m3x4 - ps | 3x4 multiply | 4 |  | x |  |  |
m4x3 - ps | 4x3 multiply | 3 |  | x |  |  |
m4x4 - ps | 4x4 multiply | 4 |  | x |  |  |
mad - ps | Multiply and add | 1 |  | x |  |  |
max - ps | Maximum | 1 |  | x |  |  |
min - ps | Minimum | 1 |  | x |  |  |
mov - ps | Move | 1 |  | x |  |  |
mul - ps | Multiply | 1 |  | x |  |  |
nop - ps | No operation | 1 |  | x |  |  |
nrm - ps | Normalize | 3 |  | x |  |  |
pow - ps | xy | 3 |  | x |  |  |
ps | Version | 0 | x |  |  |  |
rcp - ps | Reciprocal | 1 |  | x |  |  |
rep - ps | Repeat | 3 |  |  |  | x |
ret - ps | End of a subroutine | 1 |  |  |  | x |
rsq - ps | Reciprocal square root | 1 |  | x |  |  |
setp_comp | Set the predicate register | 1 |  |  |  | x |
sincos - ps | Sine and cosine | 8 |  | x |  |  |
sub - ps | Subtract | 1 |  | x |  |  |
texkill - ps | Kill pixel render | 2 |  |  | x |  |
texld - ps_2_0 and up | Sample a texture | See note 1 |  |  | x |  |
texldb - ps | Texture sampling with level-of-detail bias from w-component | 6 |  |  | x |  |
texldl - ps | Texture sampling with level-of-detail from w-component | See note 2 |  |  | x |  | x
texldd - ps | Texture sampling with user-provided gradients | 3 |  |  | x |  |
texldp - ps | Texture sampling with projective divide by w-component | See note 3 |  |  | x |  |

Notes:

  1. If the texture is a cube map, slots = 4; otherwise slots = 1.
  2. If the texture is a cube map, slots = 5; otherwise slots = 2.
  3. If the texture is a cube map, slots = 4; otherwise slots = 3.


Modifiers for ps_1_X

Instruction modifiers affect the result of the instruction before it is written into the destination register. For instance, use them to multiply or divide the result by a factor of two, or to clamp the result between zero and one. Instruction modifiers are applied after the instruction runs but before writing the result to the destination register.

A list of the modifiers is shown below.

Modifier | Description | Syntax | Version |
 |  |  | 1_1 | 1_2 | 1_3 | 1_4
_x2 | Multiply by 2 | instruction_x2 | X | X | X | X
_x4 | Multiply by 4 | instruction_x4 | X | X | X | X
_x8 | Multiply by 8 | instruction_x8 |  |  |  | X
_d2 | Divide by 2 | instruction_d2 | X | X | X | X
_d4 | Divide by 4 | instruction_d4 |  |  |  | X
_d8 | Divide by 8 | instruction_d8 |  |  |  | X
_sat | Saturate (clamp from 0 and 1) | instruction_sat | X | X | X | X
  • The multiply modifier multiplies the register data by a power of two after it is read. This is the same as a shift left.
  • The divide modifier divides the register data by a power of two after it is read. This is the same as a shift right.
  • The saturate modifier clamps the range of register values from zero to one.

Instruction modifiers can be used on arithmetic instructions. They may not be used on texture address instructions.

Multiply modifier

This example loads the destination register (dest) with the sum of the two colors in the source operands (src0 and src1) and multiplies the result by two.

add_x2 dest, src0, src1

This example combines two instruction modifiers. First, two colors in the source operands (src0 and src1) are added. The result is then multiplied by two, and clamped between 0.0 to 1.0 for each component. The result is saved in the destination register.

add_x2_sat dest, src0, src1

Divide modifier

This example loads the destination register (dest) with the sum of the two colors in the source operands (src0 and src1) and divides the result by two.

add_d2 dest, src0, src1

Saturate modifier

For arithmetic instructions, the saturation modifier clamps the result of this instruction into the range 0.0 to 1.0 for each component. The following example shows how to use this instruction modifier.

dp3_sat r0, t0_bx2, v0_bx2    ; t0 is bump, v0 is light direction

This operation occurs after any multiply or divide instruction modifier. _sat is most often used to clamp dot product results. However, it also enables consistent emulation of multipass methods where the frame buffer is always in the range 0 to 1, and of DirectX 6 and 7.0 multitexture syntax, in which saturation is defined to occur at every stage.

This example loads the destination register (dest) with the sum of the two colors in the source operands (src0 and src1), and clamps the result into the range 0.0 to 1.0 for each component.

add_sat dest, src0, src1

This example combines two instruction modifiers. First, two colors in the source operands (src0 and src1) are added. The result is multiplied by two and clamped between 0.0 to 1.0 for each component. The result is saved in the destination register.

add_x2_sat dest, src0, src1


Modifiers for ps_2_0 and Above

Instruction modifiers affect the result of the instruction before it is written into the destination register.

This section contains reference information for the instruction modifiers implemented by pixel shader version 2_0 and above.

Name | Syntax | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
Centroid | _centroid | x | x | x | x | x
Partial_Precision | _pp | x | x | x | x | x
Saturate | _sat | x | x | x | x | x

Centroid

The centroid modifier is an optional modifier that clamps attribute interpolation within the range of the primitive when a multisample pixel center is not covered by the primitive. This can be seen in Centroid Sampling.

You can apply the centroid modifier to an assembly instruction as shown here:

dcl_texcoord0_centroid v0

You can also apply the centroid modifier to a semantic as shown here:

float4 TexturePointCentroidPS( float4 TexCoord : TEXCOORD0_centroid ) : COLOR0
{
    return tex2D( PointSampler, TexCoord );
}

In addition, any Input Color Register (v#) declared with a color semantic will automatically have centroid applied. Gradients computed from attributes that are centroid sampled are not guaranteed to be accurate.

Partial Precision

The partial precision instruction modifier (_pp) indicates areas where partial precision is acceptable, provided that the underlying implementation supports it. Implementations are always free to ignore the modifier and perform the affected operations in full precision.

The _pp modifier can occur in two contexts:

  • On a texture coordinate declaration to enable passing texture coordinates to the pixel shader in partial-precision form. This allows, for example, the use of texture coordinates to relay color data to the pixel shader, which may be faster with partial precision than with full precision in some implementations. In the absence of this modifier, texture coordinates must be passed in full precision.
  • On any instruction including texture load instructions. This indicates that the implementation is allowed to execute the instruction with partial precision and store a partial precision result. In the absence of an explicit modifier, the instruction must be performed at full precision (regardless of the input precision).

Examples:

dcl_texcoord0_pp t1
cmp_pp r0, r1, r2, r3

Saturate

The saturate instruction modifier (_sat) saturates (or clamps) the instruction result to the range [0, 1] before writing to the destination register.

The _sat instruction modifier can be used with any instruction except frc - ps, sincos - ps, and any tex* instructions.

For ps_2_0, ps_2_x, and ps_2_sw, the _sat instruction modifier cannot be used with instructions writing to any output registers (Output Color Register or Output Depth Register). This restriction does not apply to ps_3_0 and above.

Example:

dp3_sat r0, v0, c1


Flow Control Limitations

Pixel shader flow control instructions have limits affecting how many levels of nesting can be included in the instructions. In addition, there are some limitations for implementing per-pixel flow control with gradient instructions.

  • Pixel Shader Instruction Depth Counts
  • Interaction of Per-Pixel Flow Control With Screen Gradients

Pixel Shader Instruction Depth Counts

ps_2_0 does not support flow control. The limitations for the other pixel shader versions are listed below.

Instruction Depth Count for ps_2_x

Each instruction counts against one or more nesting depth limits. The following table lists the depth count that each instruction adds or subtracts from the existing depth.

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting
if bool - ps | 1 | 0 | 0 | 0
if_comp - ps | 0 | 1 | 0 | 0
if pred - ps | 0 | 1 | 0 | 0
else - ps | 0 | 0 | 0 | 0
endif - ps | -1(if bool - ps) | -1(if pred - ps or if_comp - ps) | 0 | 0
rep - ps | 0 | 0 | 1 | 0
endrep - ps | 0 | 0 | -1 | 0
break - ps | 0 | 0 | 0 | 0
break_comp - ps | 0 | 1, -1 | 0 | 0
breakp - ps | 0 | 0 | 0 | 0
call - ps | 0 | 0 | 0 | 1
callnz bool - ps | 0 | 0 | 0 | 1
callnz pred - ps | 0 | 1 | 0 | 1
ret - ps | 0 | -1(callnz pred - ps) | 0 | -1
setp_comp - ps | 0 | 0 | 0 | 0

Nesting Depth

Nesting depth defines the number of instructions can be called from inside of each other. Each type of instruction has one or more nesting limits as indicated in the following table.

Instruction Type | Maximum
Static nesting | 24 if (D3DCAPS9.D3DPSHADERCAPS2_0.StaticFlowControlDepth > 0); 0 otherwise
Dynamic nesting | 0 to 24, see D3DCAPS9.D3DPSHADERCAPS2_0.DynamicFlowControlDepth
rep nesting | 0 to 4, see D3DCAPS9.D3DPSHADERCAPS2_0.StaticFlowControlDepth
call nesting | 0 to 4, see D3DCAPS9.D3DPSHADERCAPS2_0.StaticFlowControlDepth (independent of rep limit)

Instruction Depth Count for ps_2_sw

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth.

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting
if bool - ps | 1 | 0 | 0 | 0
if pred - ps | 0 | 1 | 0 | 0
if_comp - ps | 0 | 1 | 0 | 0
else - ps | 0 | 0 | 0 | 0
endif - ps | -1(if bool - ps) | -1(if pred - ps or if_comp - ps) | 0 | 0
rep - ps | 0 | 0 | 1 | 0
endrep - ps | 0 | 0 | -1 | 0
loop - ps | n/a | n/a | n/a | n/a
endloop - ps | n/a | n/a | n/a | n/a
break - ps | 0 | 0 | 0 | 0
break_comp - ps | 0 | 1, -1 | 0 | 0
breakp - ps | 0 | 0 | 0 | 0
call - ps | 0 | 0 | 0 | 1
callnz bool - ps | 0 | 0 | 0 | 1
callnz pred - ps | 0 | 1 | 0 | 1
ret - ps | 0 | -1(callnz pred - ps) | 0 | -1
setp_comp - ps | 0 | 0 | 0 | 0

Nesting Depth

Nesting depth defines the number of instructions that can be called from inside of each other. Each type of instruction has one or more nesting limits as indicated in the following table.

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
rep nesting | 4
call nesting | 4

Instruction Depth Count for ps_3_0

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth.

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting
if bool - ps | 1 | 0 | 0 | 0
if pred - ps | 0 | 1 | 0 | 0
if_comp - ps | 0 | 1 | 0 | 0
else - ps | 0 | 0 | 0 | 0
endif - ps | -1(if bool - ps) | -1(if pred - ps or if_comp - ps) | 0 | 0
rep - ps | 0 | 0 | 1 | 0
endrep - ps | 0 | 0 | -1 | 0
loop - ps | 0 | 0 | 1 | 0
endloop - ps | 0 | 0 | -1 | 0
break - ps | 0 | 0 | 0 | 0
break_comp - ps | 0 | 1, -1 | 0 | 0
breakp - ps | 0 | 0 | 0 | 0
call - ps | 0 | 0 | 0 | 1
callnz bool - ps | 0 | 0 | 0 | 1
callnz pred - ps | 0 | 1 | 0 | 1
ret - ps | 0 | -1(callnz pred - ps) | 0 | -1
setp_comp - ps | 0 | 0 | 0 | 0

Nesting Depth

Nesting depth defines the number of instructions that can be called from inside of each other. Each type of instruction has one or more nesting limits as indicated in the following table.

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
loop/rep nesting | 4
call nesting | 4

Instruction Depth Count for ps_3_sw

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth.

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting
if bool - ps | 1 | 0 | 0 | 0
if pred - ps | 0 | 1 | 0 | 0
if_comp - ps | 0 | 1 | 0 | 0
else - ps | 0 | 0 | 0 | 0
endif - ps | -1(if bool - ps) | -1(if pred - ps or if_comp - ps) | 0 | 0
rep - ps | 0 | 0 | 1 | 0
endrep - ps | 0 | 0 | -1 | 0
loop - ps | 0 | 0 | 1 | 0
endloop - ps | 0 | 0 | -1 | 0
break - ps | 0 | 0 | 0 | 0
break_comp - ps | 0 | 1, -1 | 0 | 0
breakp - ps | 0 | 0 | 0 | 0
call - ps | 0 | 0 | 0 | 1
callnz bool - ps | 0 | 0 | 0 | 1
callnz pred - ps | 0 | 1 | 0 | 1
ret - ps | 0 | -1(callnz pred - ps) | 0 | -1
setp_comp - ps | 0 | 0 | 0 | 0

Nesting Depth

Nesting depth defines the number of instructions that can be called from inside of each other. Each type of instruction has one or more nesting limits as indicated in the following table.

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
loop/rep nesting | 4
call nesting | 4

Interaction of Per-Pixel Flow Control With Screen Gradients

The pixel shader instruction set includes several instructions that produce or use gradients of quantities with respect to screen space x and y. The most common use for gradients is to compute level-of-detail calculations for texture sampling, and in the case of anisotropic filtering, selecting samples along the axis of anisotropy. Typically, hardware implementations run the pixel shader on multiple pixels simultaneously (such as a 2x2 grid), so that gradients of quantities computed in the shader can be reasonably approximated as deltas of the values at the same point of execution in adjacent pixels.

When flow control is present in a shader, the result of a gradient calculation requested inside a given branch path is ambiguous when adjacent pixels may execute separate flow control paths. Therefore, it is deemed illegal to use any pixel shader operation that requests a gradient calculation to occur at a location that is inside a flow control construct which could vary across pixels for a given primitive being rasterized.

All pixel shader instructions are partitioned into those operations that are permitted and into those that are not permitted inside of flow control:

  • Scenario A: Operations that are not permitted inside flow control that could vary across the pixels in a primitive. These include the operations listed in the following table.
    Instruction | Is Permitted in Flow Control when:
    texld - ps_2_0 and up, texldb - ps and texldp - ps | A temporary register is used for the texture coordinate.
    dsx - ps and dsy - ps | A temporary register is used for the operand.
  • Scenario B: Operations that are permitted anywhere. These include the operations listed in the following table.
    Instruction | Is Permitted Anywhere when:
    texld - ps_2_0 and up, texldb - ps and texldp - ps | A read-only quantity is used for the texture coordinate (may vary per-pixel, such as interpolated texture coordinates).
    dsx - ps and dsy - ps | A read-only quantity is used for the input operand (may vary per-pixel, such as interpolated texture coordinates).
    texldl - ps | The user provides level-of-detail as an argument, so there are no gradients, and thus no issue with flow control.
    texldd - ps | The user provides gradients as input arguments, so there is no issue with flow control.

These restrictions are strictly enforced in shader validation. Scenarios having a branch condition that looks like it would branch consistently across a primitive, even though an operand in the condition expression is a pixel-shader-computed quantity, nevertheless still fall into scenario A and are not permitted. Similarly, scenarios where gradients are requested on some shader-computed quantity x from inside dynamic flow control, yet where it appears that x is not modified across any of the branches, nevertheless still fall into scenario A and are not permitted.

Predication is included in these restrictions on flow control, so that implementations remain free to trivially interchange the implementation of branch instructions with predicated instructions.

The user can use instructions from scenarios A and B together. For example, suppose the user needs an anisotropic texture sample given a shader computed texture coordinate; however, the texture load is only needed for pixels satisfying some per-pixel condition. To meet these requirements, the user can compute the texture coordinate for all pixels, outside per-pixel varying flow control, immediately computing gradients using dsx - ps and dsy - ps instructions. Then, within a per-pixel if bool - ps/endif - ps block, the user can use texldd - ps (texture load with user provided gradients), passing the precalculated gradients. Another way to describe this usage pattern is that, while all pixels in the primitive had to compute the texture coordinates and be involved with gradient calculation, only the pixels that needed to sample a texture actually did so.

Regardless of these rules, the burden is still on the user to ensure that before computing any gradient (or performing a texture sample that implicitly computes a gradient), the register containing the source data must have been initialized for all execution paths beforehand. Initialization of temporary registers is not validated or enforced in general.


abs - ps

Computes absolute value.

Syntax

abs dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  |  |  |  | x | x | x | x | x

This instruction works as shown here.

dest.x = abs(src.x)
dest.y = abs(src.y)
dest.z = abs(src.z)
dest.w = abs(src.w)

Instruction Information

Minimum operating system Windows 98


add - ps

Adds two vectors.

Syntax

add dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
add | x | x | x | x | x | x | x | x | x

The following code snippet shows the operations performed.

dest.x = src0.x + src1.x;
dest.y = src0.y + src1.y;
dest.z = src0.z + src1.z;
dest.w = src0.w + src1.w;

Instruction Information

Minimum operating system Windows 98


bem - ps

Apply a fake bump environment-map transform.

Syntax

bem dst.rg, src0, src1

where

  • dst.rg dst is the destination register. The red and green component write mask must be used.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
bem |  |  |  | x |  |  |  |  |

This instruction performs the following calculation.

(Given n == dest register #)
dest.r = src0.r + D3DTSS_BUMPENVMAT00(stage n) * src1.r
                + D3DTSS_BUMPENVMAT10(stage n) * src1.g

dest.g = src0.g + D3DTSS_BUMPENVMAT01(stage n) * src1.r
                + D3DTSS_BUMPENVMAT11(stage n) * src1.g

Rules for using bem:

  1. bem must appear in the first phase of a shader (that is, before a phase marker).
  2. bem consumes two arithmetic instruction slots.
  3. Only one use of this instruction is allowed per shader.
  4. Destination writemask must be .rg /.xy.
  5. This instruction cannot be co-issued.
  6. Aside from the restriction that destination write mask be .rg, modifiers on source src0, src1, and instruction modifiers are unconstrained.

Instruction Information

Minimum operating system Windows 98


break - ps

Break out of the current loop at the nearest endloop - ps or endrep - ps.

Syntax

break

Remarks

This instruction is supported in the following versions.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break |  |  |  |  |  | x | x | x | x
Minimum operating system Windows 98


break_comp - ps

Break out of the current loop at the nearest endloop - ps or endrep - ps, based on a per-component comparison.

Syntax

break_comp src0, src1

Where:

  • _comp is a scalar (or single) comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required if selecting a single component.
  • src1 is a source register. Replicate swizzle is required if selecting a single component.

Remarks

This instruction is supported in the following versions.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break_comp |  |  |  |  |  | x | x | x | x

When the comparison is true, it breaks out of the current loop, as shown.

if (!(src0 comparison src1))
   jump to the corresponding endloop or endrep instruction;


breakp - ps

Conditionally break out of the current loop at the nearest endloop - ps or endrep - ps. Use one of the components of the predicate register as a condition to determine whether or not to perform the instruction.

Syntax

breakp [!]p0.{x|y|z|w}

Where:

  • [!] is an optional negate modifier.
  • p0 is the Predicate Register.
  • {x|y|z|w} is the required replicate swizzle on p0.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
breakp |  |  |  |  |  | x | x | x | x


call - ps

Performs a function call to the instruction marked with the provided label.

Syntax

call l#

Where:

  • l# is a label - ps marking the beginning of the subroutine to be called.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
call |  |  |  |  |  | x | x | x | x

This instruction does the following:

  1. Push address of the next instruction to the return address stack.
  2. Continue execution from the instruction marked by the label.


callnz bool - ps

Call if not zero. Performs a conditional call to the instruction marked by the label index.

Syntax

callnz l#, [!]b#

Where:

  • l# is a label - ps marking the beginning of the subroutine to be called.
  • [!] is an optional negate modifier.
  • b# identifies a Constant Boolean Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz bool |  |  |  |  |  | x | x | x | x

This instruction does the following:

if (specified Boolean register is not zero)
{
    Push address of the next instruction to the return address stack
    Continue execution from the instruction marked by the label
}


callnz pred - ps

Call with a predicate, if not zero. Performs a conditional call to the instruction marked by the label index. Predication uses a Boolean value to determine whether of not to perform the instruction.

Syntax

callnz l#, [!]p0.{x|y|z|w}

Where:

  • where l# is a label - ps marking the beginning of the subroutine to be called.
  • [!] is an optional negate modifier.
  • p0 is the predicate register. See Predicate Register.
  • {x|y|z|w} is the required replicate swizzle on p0.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz pred |  |  |  |  |  | x | x | x | x

This instruction does the following:

if (specified register component is not zero)
{
    Push address of the next instruction to the return address stack
    Continue execution from the instruction marked by the label
}


cmp - ps

Choose src1 if src0 >= 0. Otherwise, choose src2. The comparison is done per channel.

Syntax

cmp dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
cmp |  | x | x | x | x | x | x | x | x

There are a few additional limitations for versions 1_2 and 1_3:

  • Each shader can use up to a maximum of three cmp instructions.
  • The destination register cannot be the same as any of the source registers.

This example does a four-channel comparison.

ps_1_4
def c0, -0.6, 0.6, 0, 0.6
def c1  0,0,0,0
def c2  1,1,1,1

mov r1, c1
mov r2, c2

cmp r0, c0, r1, r2   // r0 is assigned 1,0,0,0 based on the following:

// r0.x = c2.x because c0.x < 0
// r0.y = c1.y because c0.y >= 0
// r0.z = c1.z because c0.z >= 0
// r0.w = c1.w because c0.w >= 0


cnd - ps

Conditionally chooses between src1 and src2, based on the comparison src0 > 0.5.

Syntax

cnd dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
cnd | x | x | x | x |  |  |  |  |

For versions 1_1 to 1_3, src0 must be r0.a.

// Version 1_1 to 1_3
if (r0.a > 0.5)
  dest = src1
else
  dest = src2

Version 1_4 compares each channel separately.

for each component in src0
{
   if (src0.component > 0.5)
     dest.component = src1.component
   else
     dest.component = src2.component
}

These examples show a four-channel comparison done in a version 1_4 shader, as well as a single-channel comparison possible in a version 1_1 shader.

ps_1_4
def c0, -0.5, 0.5, 0, 0.6
def c1,  0,0,0,0
def c2,  1,1,1,1

cnd r1, c0, c1, c2   // r0 contains 1,1,1,0 because
// r1.x = c2.x because c0.x <= 0.5
// r1.y = c2.y because c0.y <= 0.5
// r1.z = c2.z because c0.z <= 0.5
// r1.w = c1.w because c0.w >  0.5

Version 1_1 to 1_3 compares against the replicated alpha channel of r0 only.

ps_1_1
def c0, -0.5, 0.5, 0, 0.6
def c1,  0,0,0,0
def c2,  1,1,1,1
mov r0, c0
cnd r1, r0.a, c1, c2   // r1 gets assigned 0,0,0,0 because
                       // r0.a > 0.5, therefore r1.xyzw = c1.xyzw

This example compares two values, A and B. The example assumes A is loaded into v0 and B is loaded into v1. Both A and B must be in the range of -1 to +1, and since the color registers (vn) are defined to be between 0 and 1, the restriction happens to be satisfied in this example.

ps_1_1                // Version instruction
sub r0, v0, v1_bias   // r0 = A - (B - 0.5)
cnd r0, r0.a, c0, c1  // r0 = ( A > B ? c0 : c1 )

// r0 = c0 if A > B, otherwise, r0 = c1


crs - ps

Computes a cross product using the right-hand rule.

Syntax

crs dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
crs |  |  |  |  | x | x | x | x | x

This instruction works as shown here.

dest.x = src0.y * src1.z - src0.z * src1.y;
dest.y = src0.z * src1.x - src0.x * src1.z;
dest.z = src0.x * src1.y - src0.y * src1.x;

Some restrictions on use:

  • src0 cannot be the same register as dest.
  • src1 cannot be the same register as dest.
  • src0 cannot have any swizzle other than the default swizzle (.xyzw).
  • src1 cannot have any swizzle other than the default swizzle (.xyzw).
  • dest has to have exactly one of the following seven masks: .x | .y | .z | .xy | .xz | .yz | .xyz.
  • dest must be a temporary register.
  • dest must not be the same register as src0 or src1


dcl - ps

Declare a pixel shader input register.

Syntax

dcl[_pp] dest[.mask]

Where:

  • [_pp] is optional partial precision. See Partial Precision.
  • dest is a destination register. It must be either a Input Color Register (vn), or an Texture Coordinate Register (tn).
  • [.mask] is an optional write mask that controls which components of the destination register that can be written to. See Destination Register Write Mask.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl |  |  |  |  | x | x | x | x | x

All dcl instructions must appear before the first executable instruction.


dcl_samplerType - ps

Declare a pixel shader sampler.

Syntax

dcl_samplerType s#

where:

  • _samplerType defines the sampler data type. This determines how many coordinates are required by each texture coordinate when sampling. The following texture coordinate dimensions are defined.
    • _2d
    • _cube
    • _volume
  • s# identifies a sampler where s is an abbreviation for the sampler, and # is the sampler number. Samplers are pseudo registers because you cannot directly read or write to them.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_samplerType |  |  |  |  | x | x | x | x | x

All dcl_samplerType instructions must appear before the first executable instruction.

Example

dcl_cube t0.rgb;  // Define a 3D texture map.

add r0, r0, t0;   // Perturb texture coordinates.
texld r0, s0, r0; // Load r0 with a color sampled from stage0
                  //   at perturbed texture coordinates r0.
                  // This is a dependent texture read.


dcl_usage - ps

Declare the association between vertex shader output and pixel shader input.

Syntax

dcl_semantics [_centroid] dst[.write_mask]

Where:

  • _semantics: Identifies the intended data usage, and may be any of the values in D3DDECLUSAGE (without the D3DDECLUSAGE_ prefix). Additionally, an integer index can be appended to the semantic to distinguish parameters that use similar semantics.
  • [_Centroid] is an optional instruction modifier. It is is supported on dcl_usage instructions that declare the input registers and on texture lookup instructions. The centroid is appended with no space.
  • dst: destination register. See ps_3_0 Registers.
  • write_mask: The same output register may be declared multiple times, each time with a unique write mask (so different semantics can be applied to individual components). However, the same semantic cannot be used multiple times in a declaration. This means that vectors must be four components or less, and cannot go across four-component register boundaries (individual output registers). When the _psize semantic is used, it should have a full write mask because it is considered a scalar. When the _position semantic is used, it should have full write mask because all four components have to be written.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_usage |  |  |  |  |  |  |  | x | x

All dcl_usage instructions must appear before the first executable instruction.

Declaration Examples

ps_3_0

; Declaring inputs
dcl_normal      v0.xyz
dcl_blendweight v0.w ; Must be same reg# as normal, matching vshader packing
dcl_texcoord1   v1.y ; Mask can be any subset of mask from vshader semantic
dcl_texcoord0   v1.zw; Has to be same reg# as texcoord1, to match vshader

; Declaring samplers
dcl_2d s0
dcl_2d s1

def c0, 0, 0, 0, 0

mov r0.x, v1.y ; texcoord1
mov r0.y, c0
texld r0, r0, s0

texld r1, v1.zw, s1
...
(output regs in ps_3_0 are same as ps_2_0: oC0-oC3, oDepth)

See Also

Antialias Sample


def - ps

Defines pixel shader floating-point constants.

Syntax

def dst, fVvalue1, fValue2, fValue3, fValue4

Where:

  • dst is the destination register.
  • fValue1 to fValue4 are floating-point values..

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
def | x | x | x | x | x | x | x | x | x

There are two ways to set a floating-point constant in a pixel shader.

  1. Use def to define the constant directly inside a shader.
  2. Use the API to set a constant with IDirect3DDevice9::SetPixelShaderConstantF.

def defines a shader constant whose value is loaded any time a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the API method.

  • Must appear before the first arithmetic or addressing instruction in shader.
  • Can be intermixed with dcl - ps instructions (which are the other type of instruction that resides at the beginning of a shader).
  • dst register must be a constant register.
  • Write mask must be full (default).
  • If a constant register is defined multiple times in a shader, the last one persists.


defb - ps

Defines a boolean constant value, which should be loaded any time a shader is set to a device.

Syntax

defb dest, booleanValue

where

  • dst is the destination register.
  • booleanValue is a single boolean value, either true or false.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defb |  |  |  |  |  | x | x | x | x

The defb instruction defines a boolean shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the API method SetPixelShaderConstantB.

There are two ways to set a booleanconstant in a shader.

  1. Use defb to define the constant directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantB to set a Boolean constant.

See Also

def - ps, defi - ps


defi - ps

Defines an integer constant value, which should be loaded any time a shader is set to a device.

Syntax

defi dst, integerValue
  • dst is the destination register.
  • integerValue is a constant integer value.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defi |  |  |  |  |  | x | x | x | x

The defi instruction defines a shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the API method SetPixelShaderConstantB.

There are two ways to set a constant in a shader.

  1. Use defi to define the constant directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantB to set a Boolean constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantF to set a floating-point constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantI to set an integer constant.


dp2add - ps

Performs a 2D dot product and a scalar addition.

Syntax

dp2add dst, src0, src1, src2.{x|y|z|w}

Where:

  • dst is a destination register.
  • src0, src1, and src2 are three source registers.
  • {x|y|z|w} is the required replicate swizzle on src2.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp2add |  |  |  |  | x | x | x | x | x

The scalar value for add is chosen by the replicate swizzle on src2.

The following code snippet shows the operations performed.

dest = src0.r * src1.r + src0.g * src1.g + src2.replicate_swizzle
// The scalar result is replicated to the write mask components


dp3 - ps

Computes the three-component dot product of the source registers.

Syntax

dp3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp3 | x | x | x | x | x | x | x | x | x

The following code snippet shows the operations performed:

dest.x = dest.y = dest.z = dest.w =
  (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);

This instruction runs in the vector pipeline, always writing out to the color channels. For version 1_4, this instruction still uses the vector pipeline but may write to any channel.

An instruction with a destination register .rgb (.xyz) write mask may be co-issued with dp3 As shown below.

dp3 r0.rgb, t0, v0            // Copy scalar result to color components
+mov r2.a, t0                 // Copy alpha component from t0 in parallel

The dp3 instruction can be modified using the Source Register Signed Scaling input argument modifier (_bx2) applied to its input arguments if they are not already expanded to signed dynamic range. For a lighting shader, the saturate instruction modifier (_sat) is often used to clamp the negative values to black, as shown in the following example.

dp3_sat r0, t0_bx2, v0_bx2    // t0 is a bump map, v0 contains the light direction


dp4 - ps

Computes the four-component dot product of the source registers.

Syntax

dp4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp4 |  | x | x | x | x | x | x | x | x

The following code snippet shows the operations performed:

dest.x = dest.y = dest.z = dest.w =
    (src0.x * src1.x) + (src0.y * src1.y) +
    (src0.z * src1.z) + (src0.w * src1.w);

Limitations for ps_1_2 and ps_1_3:

  • Each shader can use up to a maximum of four dp4 instructions.
  • Each dp4 instruction counts as two arithmetic instructions.

Limitations for 1_X versions:

  • This instruction cannot be co-issued because dp4 runs in both the vector and alpha pipeline.


dsx - ps

Compute the rate of change in the render target's x-direction.

Syntax

dsx dst, src

Where:

  • dst is a destination register.
  • src is an input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dsx |  |  |  |  |  | x | x | x | x

The rate of change computed from the source register is an approximation on the contents of the same register in adjacent pixel(s) running the pixel shader in lock-step with the current pixel.

The dsx And dsy instructions compute their result by looking at the current contents of the source register (per component) for the various pixels in the local area executing in the lock-step. The exact formula used to compute the gradient varies depending on the hardware but should be consistent with the way the hardware does the same operations as part of the level-of-detail calculation process for texture sampling.

See Also

texldd - ps


dsy - ps

Compute the rate of change in the render target's y-direction.

Syntax

dsy dst, src

Where:

  • dst is a destination register.
  • src is an input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dsy |  |  |  |  |  | x | x | x | x

The rate of change computed from the source register is an approximation on the contents of the same register in adjacent pixel(s) running the pixel shader in lock-step with the current pixel.

The dsx And dsy instructions compute their result by looking at the current contents of the source register (per component) for the various pixels in the local area executing in the lock-step. The exact formula used to compute the gradient varies depending on the hardware but should be consistent with the way the hardware does the same operations as part of the level-of-detail calculation process for texture sampling.

See Also

texldd - ps


else - ps

Start of an else block.

Syntax

else

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
else |  |  |  |  |  | x | x | x | x

If the condition in the corresponding if statement is true, the code enclosed by the if statement and the matching else is run.

See Also

if bool - ps, endif - ps


endif - ps

Marks the end of an if...else block.

Syntax

endif

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endif |  |  |  |  |  | x | x | x | x

See Also

if bool - ps, else - ps


endloop - ps

End of a loop - ps...endloop block.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endloop |  |  |  |  |  |  |  | x | x

endloop must follow the last instruction of a loop - ps block.

Example

loop aL, i3
    add r1, r0, c2[ aL ]
endloop


endrep - ps

End a rep - ps...endrep block.

Syntax

endrep

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endrep |  |  |  |  |  | x | x | x | x

Example

rep i2
    add r0, r0, c0
endrep


exp - ps

Provides full precision exponential 2x.

Syntax

exp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle; that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified. See Source Register Swizzling.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
exp |  |  |  |  | x | x | x | x | x

The following code snippet shows the operations performed:

dest.x = dest.y = dest.z = dest.w = (float)pow(2, src.replicateSwizzleComponent);


frc - ps

Returns the fractional portion of each input component.

Syntax

frc dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
frc |  |  |  |  | x | x | x | x | x

The following code snippet shows conceptually how the instruction operates.

dest.x = src.x - (float)floor(src.x);
dest.y = src.y - (float)floor(src.y);
dest.z = src.z - (float)floor(src.z);
dest.w = src.w - (float)floor(src.w);

The floor function converts the argument passed in to the greatest integer that is less than (or equal to) the argument. This is converted to a float and then subtracted fom the original value. The resulting fractional value ranges from 0.0 through 1.0.


if bool - ps

Start of an if block.

Syntax

if bool

Where:

  • bool is a bool (Boolean) register number. See Constant Boolean Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if bool |  |  |  |  |  | x | x | x | x

If the source Boolean register in the if statement is true, the code enclosed by the if statement and the matching endif - ps or else - ps is executed. Otherwise, the code enclosed by the else - ps...endif - ps statements is executed. This instruction consumes one instruction slot.

An if block can be nested.

An if block cannot straddle a loop block.

An if block can be followed by a statement block, and/or an else - ps instruction, and/or an endif - ps instruction.

Example

This instruction provides conditional static flow control.

defb b3, true

if b3
// Instructions to run if b3 is nonzero
else
// Instructions to run otherwise
endif

See Also

else - ps, endif - ps


if_comp - ps

Start an if bool - ps...else - ps...endif - ps block, with a condition based on values that could be computed in a shader. This instruction is used to skip a block of code, based on a condition.

Syntax

if_comp src0, src1

Where:

  • _comp is a comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required to select a component.
  • src1 is a source register. Replicate swizzle is required to select a component.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if_comp |  |  |  |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a condition.

if (src0 comparison src1)
   jump to the corresponding else or endif instruction;

Be careful using the equals and not equals comparison modes on floating point numbers. Because rounding occurs during during floating point calculations, the comparison can be done against an epsilon value (small nonzero number) to avoid errors.

Restrictions include:

  • if_comp...else - ps...endif - ps blocks (along with the predicated if blocks) can be nested up to 24 layers deep.
  • src0 and src1 registers require a replicate swizzle.
  • if_comp blocks must end with an else - vs or endif - vs instruction.
  • if_comp...else - ps...endif - ps blocks cannot straddle a loop block. The if_comp block must be completely inside or outside the loop block.

Example

This instruction provides conditional dynamic flow control.

if_lt r3.x, r4.y
// Instructions to run if r3.x < r4.y

else
// Instructions to run otherwise

endif


if pred - ps

Start of an if bool - ps...else - ps...endif - ps block, with the condition taken from the content of the predicate register.

Syntax

if [!]pred.replicateSwizzle

Where:

  • [!] is an optional NOT modifier. This modifies the value in the predicate register.
  • pred is the Predicate Register.
  • replicateSwizzle is a single component that is copied (or replicated) to all four components (swizzled). Valid components are: [x, y, z, w] or [r, g, b, a].

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if_pred |  |  |  |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a channel of the predicate register. Each if_pred block must end with an else - ps or endif - ps instruction.

Restrictions include:

if_pred blocks can be nested. This counts to the total dynamic nesting depth along with if_comp blocks.

An if_pred block cannot straddle a loop block; it should either be completely inside it or surround it.


label - ps

Mark the next instruction as having a label index.

Syntax

label l#

where # identifies the label number.

For ps_2_x, the label number must be between between 0 and 15.

For ps_2_sw, ps_3_0, and ps_3_sw, the label number must be between between 0 and 2047.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
label |  |  |  |  |  | x | x | x | x

This instruction defines a label located at the next shader instruction. The label instruction can only be present directly after a ret instruction (which defines the end of the previous subroutine or main program).


loop - ps

Starts a loop...endloop - ps block.

Syntax

loop aL, i#

Where:

  • aL is the Loop Counter Register holding the current loop count.
  • i# is a Constant Integer Register. See remarks.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
loop |  |  |  |  |  |  |  | x | x
  • The Loop Counter Register (aL) holds the current loop count and can be used for relative addressing into Input Color Register (v#) inside the loop block.
  • i#.x specifies the iteration count. The legal range is [0, 255]. Note that this instruction does not increment or decrement the value of i#.x.
  • i#.y specifies the initial value of the Loop Counter Register (aL) register. The legal range is [0, 255]. Note that this instruction does not increment or decrement the value of i#.y.
  • i#.z specifies the step/stride size. The legal range is [-128, 127].
  • i#.w is not used by the loop block and has to be 0.
  • Loop blocks may be nested. See Flow Control Limitations.
  • When nested, the value of the Loop Counter Register (aL) refers to the immediate enclosing loop block.
  • Loop blocks are allowed to be either completely inside an if* block or completely surrounding it. No straddling is allowed.

Example

loop aL, i3
    add r1, r0, v2[ aL ]
endloop


log - ps

Full precision log2(x).

Syntax

log dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle; that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
log |  |  |  |  | x | x | x | x | x

The following code snippet shows the operations performed.

float v = abs(src);
if (v != 0)
{
    dest.x = dest.y = dest.z = dest.w =
        (float)(log(v)/log(2));
}
else
{
    dest.x = dest.y = dest.z = dest.w = -FLT_MAX;
}

This instruction accepts a scalar source whose sign bit is ignored. The result is replicated to all four channels.


lrp - ps

Interpolates linearly between the second and third source registers by a proportion specified in the first source register.

Syntax

lrp dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
lrp | x | x | x | x | x | x | x | x | x

This instruction performs the linear interpolation based on the following formula.

dest = src0 * src1 + (1-src0) * src2
// which is the same as
dest = src2 + src0 * (src1 - src2)


m3x2 - ps

Multiplies a 3-component vector by a 3x2 matrix.

Syntax

m3x2 dst, src0, src1

where

  • dst is the destination register. Result is a 2-component vector.
  • src0 is a source register representing a 3-component vector.
  • src1 is a source register representing a 3x2 matrix, which corresponds to the first of 2 consecutive registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x2 |  |  |  |  | x | x | x | x | x

The xy mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following equations show how the instruction operates:

dest.x = (src0.x*src1.x) + (src0.y*src1.y) + (src0.z*src1.z);
dest.y = (src0.x*src2.x) + (src0.y*src2.y) + (src0.z*src2.z);

The input vector is in register src0. The input 3x2 matrix is in register src1 and the next higher register in the same register file, as shown in the following expansion. A 2D result is produced, leaving the other elements of the destination register (dest.z and dest.w) unaffected.

This operation is commonly used for 2D transforms. This instruction is implemented as a pair of dot products as shown here.

m3x2   r0.xy, r1, c0   which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1

Swizzle and negate modifiers are invalid for the src1 register. The dst and src0 register, or any of src1+i registers, cannot be the same.


m3x3 - ps

Multiplies a 3-component vector by a 3x3 matrix.

Syntax

m3x3 dst, src0, src1

where

  • dst is the destination register. Result is a 3-component vector.
  • src0 is a source register representing a 3-component vector.
  • src1 is a source register representing a 3x3 matrix, which corresponds to the first of 3 consecutive registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x3 |  |  |  |  | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code snippet shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z);

The input vector is in register src0. The input 3x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming normal vectors during lighting computations. This instruction is implemented as a set of dot products as shown below.

m3x3 r0.xyz, r1, c0  which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1
dp3   r0.z, r1, c2


m3x4 - ps

Multiplies a 3-component vector by a 3x4 matrix.

Syntax

m3x4 dst, src0, src1

where

  • dst is the destination register. Result is a 4-component vector.
  • src0 is a source register representing a 3-component vector.
  • src1 is a source register representing a 3x4 matrix, which corresponds to the first of 4 consecutive registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x4 |  |  |  |  | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code snippet shows the operations performed.

dest.x = (src0.x*src1.x) + (src0.y*src1.y) + (src0.z*src1.z);
dest.y = (src0.x*src2.x) + (src0.y*src2.y) + (src0.z*src2.z);
dest.z = (src0.x*src3.x) + (src0.y*src3.y) + (src0.z*src3.z);
dest.w = (src0.x*src4.x) + (src0.y*src4.y) + (src0.z*src4.z);

The input vector is in register src0. The input 3x4 matrix is in register src1, and the next two higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position vector by a matrix that has a projective effect but applies no translation. This instruction is implemented as a pair of dot products as shown here.

m3x4   r0.xyzw, r1, c0   will be expanded to:

dp3 r0.x, r1, c0
dp3 r0.y, r1, c1
dp3 r0.z, r1, c2
dp3 r0.w, r1, c3


m4x3 - ps

Multiplies a 4-component vector by a 4x3 matrix.

Syntax

m4x3 dst, src0, src1

where

  • dst is the destination register. Result is a 3-component vector.
  • src0 is a source register representing a 4-component vector.
  • src1 is a source register representing a 4x3 matrix, which corresponds to the first of 3 consecutive registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x3 |  |  |  |  | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

The following code snippet shows the operations performed.

dest.x = (src0.x*src1.x) + (src0.y*src1.y) + (src0.z*src1.z) + (src0.w*src1.w);
dest.y = (src0.x*src2.x) + (src0.y*src2.y) + (src0.z*src2.z) + (src0.w*src2.w);
dest.z = (src0.x*src3.x) + (src0.y*src3.y) + (src0.z*src3.z) + (src0.w*src3.w);

The input vector is in register src0. The input 4x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming a position vector by a matrix that has no projective effect, such as occurs in model-space transformations. This instruction is implemented as a set of dot products as shown below.

m4x3   r0.xyz, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2

Swizzle and negate modifiers are invalid for the src1 register. The dst and src0 register cannot be the same.


m4x4 - ps

Multiplies a 4-component vector by a 4x4 matrix.

Syntax

m4x4 dst, src0, src1

where

  • dst is the destination register. Result is a 4-component vector.
  • src0 is a source register representing a 4-component vector.
  • src1 is a source register representing a 4x4 matrix, which corresponds to the first of 4 consecutive registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x4 |  |  |  |  | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

Swizzle and negate modifiers are invalid for the src0 register. The dst and src0 registers cannot be the same.

The following code snippet shows the operations performed.

dest.x = (src0.x*src1.x) + (src0.y*src1.y) + (src0.z*src1.z) + (src0.w*src1.w);
dest.y = (src0.x*src2.x) + (src0.y*src2.y) + (src0.z*src2.z) + (src0.w*src2.w);
dest.z = (src0.x*src3.x) + (src0.y*src3.y) + (src0.z*src3.z) + (src0.w*src3.w);
dest.w = (src0.x*src4.x) + (src0.y*src4.y) + (src0.z*src4.z) + (src0.w*src4.w);

The input vector is in register src0. The input 4x4 matrix is in register src1, and the next three higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position by a projection matrix. This instruction is implemented as a set of dot products as shown here.

m4x4   r0.xyzw, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2
dp4   r0.w, r1, c3


mad - ps

Multiply and add instruction. Sets the destination register to (src0 * src1) + src2.

Syntax

mad dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mad | x | x | x | x | x | x | x | x | x

The following code snippet shows the operations performed.

dest.x = src0.x * src1.x + src2.x;
dest.y = src0.y * src1.y + src2.y;
dest.z = src0.z * src1.z + src2.z;
dest.w = src0.w * src1.w + src2.w;


mov - ps

Move data between registers.

Syntax

mov dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mov | x | x | x | x | x | x | x | x | x


mul - ps

Multiplies sources into the destination.

Syntax

mul dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mul | x | x | x | x | x | x | x | x | x

The following code snippet shows the operations performed.

dest.x = src0.x * src1.x;
dest.y = src0.y * src1.y;
dest.z = src0.z * src1.z;
dest.w = src0.w * src1.w;


max - ps

Calculates the maximum of the sources.

Syntax

max dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
max |  |  |  |  | x | x | x | x | x

The following code snippet shows the operations performed.

dest.x=(src0.x >= src1.x) ? src0.x : src1.x;
dest.y=(src0.y >= src1.y) ? src0.y : src1.y;
dest.z=(src0.z >= src1.z) ? src0.z : src1.z;
dest.w=(src0.w >= src1.w) ? src0.w : src1.w;


min - ps

Calculates the minimum of the sources.

Syntax

min dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
min |  |  |  |  | x | x | x | x | x

The following code snippet shows the operations performed.

dest.x=(src0.x < src1.x) ? src0.x : src1.x;
dest.y=(src0.y < src1.y) ? src0.y : src1.y;
dest.z=(src0.z < src1.z) ? src0.z : src1.z;
dest.w=(src0.w < src1.w) ? src0.w : src1.w;


nrm - ps

Normalize a 3D vector.

Syntax

nrm dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nrm |  |  |  |  | x | x | x | x | x

This instruction works conceptually as shown here.

squareRootOfTheSum = (src0.x*src0.x + src0.y*src0.y + src0.z*src0.z)1/2;
dest.x = src0.x * (1 / squareRootOfTheSum);
dest.y = src0.y * (1 / squareRootOfTheSum);
dest.z = src0.z * (1 / squareRootOfTheSum);
dest.w = src0.w * (1 / squareRootOfTheSum);

The dest and src registers cannot be the same. The dest register must be a temporary register.

This instruction performs the linear interpolation based on the following formula.

float f = src0.x*src0.x + src0.y*src0.y + src0.z*src0.z;
if (f != 0)
    f = (float)(1/sqrt(f));
else
    f = FLT_MAX;

dest.x = src0.x*f;
dest.y = src0.y*f;
dest.z = src0.z*f;
dest.w = src0.w*f;


nop - ps

No operation is performed.

Syntax

nop

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nop | x | x | x | x | x | x | x | x | x

This instruction performs a no-op, or no operation. The syntax for calling it is as follows:

nop


phase - ps

The phase instruction marks the transition between phase 1 and phase 2. If no phase instruction is present, the entire shader runs as if it is a phase 2 shader.

This instruction applies to version 1_4 only.

Syntax

phase

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
phase |  |  |  | x |  |  |  |  |

Shader instructions that occur before the phase instruction are phase 1 instructions. All other instructions are phase 2 instructions. By having two phases for instructions, the maximum number of instructions per shader is increased.

The unfortunate side-effect of the phase transition is that the alpha component of temporary registers do not persist across the transition. In other words, the alpha component must be reinitialized after the phase instruction.

Example

This example shows how to group instructions as phase 1 or phase 2 instructions within a shader.

The phase instruction is also commonly called the phase marker because it marks the transition between phase 1 and 2 instructions. In a version 1_4 pixel shader, if the phase marker is not present, the shader is run as if it is running in phase 2. This is important because there are differences between phase 1 and 2 instructions and register availability. The differences are noted throughout the reference section.

ps_1_4
  // Add phase 1 instructions here

phase
  // Add phase 2 instructions here


pow - ps

Full precision abs(src0)src1.

Syntax

pow dst, src0, src1

where

  • dst is the destination register.
  • src0 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.
  • src1 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
pow |  |  |  |  | x | x | x | x | x

This instruction works as follows:

dest.x = dest.y = dest.z = dest.w = [abs(src0)]src1;

This is a scalar instruction, therefore the source registers should have replicate swizzles to indicate which channels are used.

The input power (src1) must be a scalar.

The scalar result is replicated to all four output channels.

This instruction could be expanded as exp(src1 * log(src0)).

The dst register should be a temporary register, and should not be the same register as src1.


ps

This instruction specifies the shader version number and works on all shader versions.

Syntax

ps_mainVer_subVer

Input Arguments

Input arguments contain a single main version number with a single sub version number. The allowable combinations are listed in the table below.

Main versions | Sub versions
1 | 1, 2, 3, 4
2 | 0, x (extended), sw (software)
3 | 0, sw (software)

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
ps | x | x | x | x | x | x | x | x | x

This instruction must be the first non-comment instruction in a pixel shader.

Hardware accelerated versions of the software (versions without _sw in the version number), can process vertices with hardware accelearation or use software vertex processing. Software versions (versions with _sw in the version number) process vertices only with software.

Examples

This partial example declares a version 1_1 pixel shader.

ps_1_1

This partial example declares a version 1_4 pixel shader.

ps_1_4


rcp - ps

Computes the reciprocal of the source scalar.

Syntax

rcp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rcp |  |  |  |  | x | x | x | x | x

The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.

The scalar result is replicated to all channels in the destination write mask.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 2.0) because common implementations will separate mantissa and exponent.


rep - ps

Start a rep...endrep - ps block.

Syntax

rep i#

where i# is an integer register that specifies the repeat count in the .x component. See Constant Integer Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rep |  |  |  |  |  | x | x | x | x
  • i#.x specifies the iteration count. The legal range is [0, 255]. Note that this instruction does not increment or decrement the value of i#.x.
  • i#.yzw are not used by the repeat block.
  • Repeat blocks may be nested. See Flow Control Limitations.
  • Repeat blocks are allowed to be either completely inside an if* block or completely surrounding it. No straddling is allowed.
  • Using the same i# for different or nested rep instructions is fine - each loop will iterate based on the specified count.

Example

rep i2
    add r0, r0, c0
endrep


ret - ps

Takes the address of an instruction from the return address stack and continues execution from it. In the case of the main function, this instruction stops shader execution.

Syntax

ret

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
ret |  |  |  |  |  | x | x | x | x

This instruction takes the address of an instruction from the return address stack and continues execution from it. In the case of the main function, this instruction stops shader execution.

The ret instruction consumes one vertex shader instruction slot.

If a shader contains no subroutines, using ret at the end of the main program is optional.

Multiple return statements are not permitted in the main program or in any subroutine, the first return statement is treated as the end of the main program or subroutine.


rsq - ps

Computes the reciprocal square root (positive only) of the source scalar.

Syntax

rsq dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rsq |  |  |  |  | x | x | x | x | x

The absolute value is taken before processing.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 4.0) because common implementations will separate mantissa and exponent.

The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.


setp_comp - ps

Set the predicate register.

Syntax

setp_comp dst, src0, src1

Where:

  • _comp is a per-channel comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • dst is the Predicate Register register, p0.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
setp_comp |  |  |  |  |  | x | x | x | x

This instruction operates as:

per channel in destination write mask
{
  dst.channel = src0.channel cmp src1.channel
}

For each channel that can be written according to the destination write mask, save the boolean result of the comparison operation between the corresponding channels of src0 and src1 (after the source modifier swizzles have been resolved).

Source registers allow arbitrary component swizzles to be specified.

The destination register allows arbitrary write masks.

The dst register must be the predicate register.

Applying the Predicate Register

Once the predicate register has been initialized with setp_comp, it can be used to control an instruction per component. Here's the syntax:

([!]p0[.swizzle]) instruction dest, src0, ...

Where:

  • [!] is an optional boolean NOT
  • p0 is the predicate register
  • [.swizzle] is an optional swizzle to apply to the contents of the predicate register before using it to mask the instruction. The available swizzles are: .xyzw (default when none specified), or any replicate swizzle: .x/.r, .y/.g, .z/.b or .a/.w.
  • instruction is any aritmetic, or texture instruction. This cannot be a static or dynamic flow control instruction.
  • dest, src0, ... are the registers required by the instruction

Assuming the predicate register has been set up with (true, true, false, false) component values, it can be applied to this instruction:

(p0) add r1, r2, r3

to perform a 2 component add.

r1.x = r2.x + r3.x
r1.y = r2.y + r3.y

The z and w components of r1 will not be written since the predicate register contained false in components z and w.

Applying the predicate register to an arithmetic or texture instruction increases its instruction slot count by 1.

The predicate register can also be applied to if pred - ps, callnz pred - ps and breakp - ps instructions. These flow control instructions do not have any increase in the instruction slot count when using the predicate register.


sincos - ps

Computes sine and cosine, in radians.

Syntax

ps_2_0 and ps_2_x

sincos dst.{x|y|xy}, src0.{x|y|z|w}, src1, src2

Where:

  • dst is the destination register and has to be a Temporary Register (r#). The destination register must have exactly one of the following three masks: .x | .y | .xy.
  • src0 is a source register that provides the input angle, which must be within [-pi, +pi]. {x|y|z|w} is the required replicate swizzle.
  • src1 and src2 are source registers and must be two different Constant Float Registers (c#). The values of src1 and src2 must be that of the macros D3DSINCOSCONST1 and D3DSINCOSCONST2 respectively.

ps_3_0

sincos dst.{x|y|xy}, src0.{x|y|z|w}

Where:

  • dst is a destination register and has to be a Temporary Register (r#). The destination register must have exactly one of the following three masks: .x | .y | .xy.
  • src0 is a source register that provides the input angle, which must be within [-pi, +pi]. {x|y|z|w} is the required replicate swizzle.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sincos |  |  |  |  | x | x | x | x | x

ps_2_0 and ps_2_x

For ps_2_0 and ps_2_x, sincos can be used with predication, but with one restriction to the swizzle of the Predicate Register (p0): only replicate swizzle (.x | .y | .z | .w) is allowed.

For ps_2_0 and ps_2_x, the instruction operates as follows (V = the scalar value from src0 with a replicate swizzle):

  • If the write mask is .x:
    dest.x = cos(V)
dest.y is undefined when the instruction completes
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction
  • If the write mask is .y:
    dest.x is undefined when the instruction completes
dest.y = sin(V)
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction
  • If the write mask is .xy:
    dest.x = cos(V)
dest.y = sin(V)
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction

ps_3_0

For ps_3_0, sincos can be used with predication without any restriction. See Predicate Register.

For ps_3_0, the instruction operates as follows (V = the scalar value from src0 with a replicate swizzle):

  • If the write mask is .x:
    dest.x = cos(V)
dest.y is not touched by the instruction
dest.z is not touched by the instruction
dest.w is not touched by the instruction
  • If the write mask is .y:
    dest.x is not touched by the instruction
dest.y = sin(V)
dest.z is not touched by the instruction
dest.w is not touched by the instruction
  • If the write mask is .xy:
    dest.x = cos(V)
dest.y = sin(V)
dest.z is not touched by the instruction
dest.w is not touched by the instruction

The application can map an arbitrary angle (in radians) to the range [-pi, +pi] using the following shader pseudocode:

def c0, pi, 0.5, 2*pi, 1/(2*pi)
mad r0.x, input_angle, c0.w, c0.y
frc r0.x, r0.x
mad r0.x, r0.x, c0.z, -c0.x


sub - ps

Subtracts sources.

Syntax

sub dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sub | x | x | x | x | x | x | x | x | x

This instruction performs the subtraction shown in this formula.

dest = src0 - src1


tex - ps

Loads the destination register with color data (RGBA) sampled from a texture. The texture must be bound to a particular texture stage (n) using IDirect3DDevice9::SetTexture. Texture sampling is controlled by IDirect3DDevice9::SetSamplerState.

Syntax

tex dst

where

  • dst is the destination register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
tex | x | x | x |  |  |  |  |  |

The destination register number specifies the texture stage number.

Texture sampling uses texture coordinates to look up, or sample, a color value at the specified (u,v,w,q) coordinates while taking into account the texture stage state attributes.

The texture coordinate data is interpolated from the vertex texture coordinate data and is associated with a specific texture stage. The default association is a one-to-one mapping between texture stage number and texture coordinate declaration order. This means that the first set of texture coordinates defined in the vertex format are by default associated with texture stage 0.

Texture coordinates may be associated with any stage using two techniques. When using a fixed function vertex shader or the fixed function pipeline, the texture stage state flag TSS_TEXCOORDINDEX can be used in IDirect3DDevice9::SetTextureStageState to associate coordinates to a stage. Otherwise, the texture coordinates are output by the vertex shader oTn registers when using a programmable vertex shader.


texbem - ps

Apply a fake bump environment-map transform. This is accomplished by modifying the texture address data of the destination register, using address perturbation data (du,dv), and a 2D bump environment matrix.

Syntax

texbem dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texbem | x | x | x |  |  |  |  |  |

The red and green color data in the src register is interpreted as the perturbation data (du,dv).

This instruction transforms red and green components in the source register using the 2D bump environment-mapping matrix. The result is added to the texture coordinate set corresponding to the destination register number, and is used to sample the current texture stage.

This operation always interprets du and dv as signed quantities. For versions 1_0 and 1_1, the Source Register Signed Scaling input modifier (_bx2) is not permitted on the input argument.

This instruction produces defined results when input textures contain signed format data. Mixed format data works only if the first two channels contain signed data. For more information about surface formats, see D3DFORMAT.

This can be used for a variety of techniques based on address perturbation, including fake per-pixel environment mapping and diffuse lighting (bump mapping).

When using this instruction, texture registers must follow the following sequence.

// The texture assigned to stage t(n) contains the (du,dv) data
// The texture assigned to stage t(m) is sampled
tex     t(n)
texbem  t(m),  t(n)      where m > n

The calculations done within the instruction are shown below.

// 1. New values for texture addresses (u',v') are calculated
// 2. Sample the texture using (u',v')

u' = TextureCoordinates(stage m)u +
      D3DTSS_BUMPENVMAT00(stage m)*t(n)R +
      D3DTSS_BUMPENVMAT10(stage m)*t(n)G

v' = TextureCoordinates(stage m)v +
      D3DTSS_BUMPENVMAT01(stage m)*t(n)R +
      D3DTSS_BUMPENVMAT11(stage m)*t(n)G

t(m)RGBA = TextureSample(stage m)
// using (u',v') as coordinates

Register data that has been read by a texbem - ps or texbeml - ps instruction cannot be read later, except by another texbem - ps or texbeml - ps.

// This example demonstrates the validation error caused by t0 being reread:
ps_1_1
tex t0
texbem t1, t0
add r0, t1, t0

(Instruction Error) (Statement 4) Register data that has been read by
texbem or texbeml instruction cannot be read by other instructions

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0              ; Define t0 to get a 2-tuple DuDv
texbem t1, t0       ; Compute (u',v')
                    ; Sample t1 using (u',v')
mov r0, t1          ; Output result

texbem requires the following textures in the following texture stages.

  • Stage 0 is assigned a bump map with (du, dv) perturbation data.
  • Stage 1 uses a texture map with color data.
  • This instruction sets the matrix data on the texture stage that is sampled.
  • This is different from the functionality of the fixed function pipeline where the perturbation data and the matrices occupy the same texture stage.


texbeml - ps

Apply a fake bump environment-map transform with luminance correction. This is accomplished by modifying the texture address data of the destination register, using address perturbation data (du,dv), a 2D bump environment matrix, and luminance.

Syntax

texbeml dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texbeml | x | x | x |  |  |  |  |  |

The red and green color data in the src register is interpreted as the perturbation data (du,dv). The blue color data in the src register is interpreted as the luminance data.

This instruction transforms the red and green components in the source register using the 2D bump environment mapping matrix. The result is added to the texture coordinate set corresponding to the destination register number. A luminance correction is applied using the luminance value and the bias texture stage values. The result is used to sample the current texture stage.

This can be used for a variety of techniques based on address perturbation such as fake per-pixel environment mapping.

This operation always interprets du and dv as signed quantities. For versions 1_0 and 1_1, the Source Register Signed Scaling input modifier (_bx2) is not permitted on the input argument.

This instruction produces defined results when input textures contain mixed format data. For more information about surface formats, see D3DFORMAT.

// When using this instruction, texture registers must follow
//   the following sequence:
// The texture assigned to stage tn contains the (du,dv) data
// The texture assigned to stage t(m) is sampled
tex     t(n)
texbeml t(m),  t(n)      where m > n

This example shows the calculations done within the instruction.

// 1. New values for texture addresses (u',v') are calculated
// 2. Sample the texture using (u',v')
// 3. Luminance correction is applied

u' = TextureCoordinates(stage m)u +
    D3DTSS_BUMPENVMAT00(stage m)*t(n)R +
    D3DTSS_BUMPENVMAT10(stage m)*t(n)G

v' = TextureCoordinates(stage m)v +
    D3DTSS_BUMPENVMAT01(stage m)*t(n)R +
    D3DTSS_BUMPENVMAT11(stage m)*t(n)G

t(m)RGBA = TextureSample(stage m) using (u',v') as coordinates

t(m)RGBA = t(m)RGBA*
    [(t(n)B * D3DTSS_BUMPENVLSCALE(stage m)) +
        D3DTSS_BUMPENVLOFFSET(stage m)]

Register data that has been read by a texbem or texbeml instruction cannot be read later, except by another texbem or texbeml.

// This example demonstrates the validation error caused by
//   t0 being reread
ps_1_1
tex t0
texbem t1, t0
add r0, t1, t0

(Instruction Error) (Statement 4) Register data that has been read by
texbem or texbeml instruction cannot be read by other instructions

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0              ; Define t0 to get a 2-tuple DuDv
texbeml t1, t0      ; Compute (u',v')
                    ; Apply luminance correction
                    ; Sample t1 using (u',v')
mov r0, t1          ; Output result

This example requires the following textures in the following texture stages.

  • Stage 0 is assigned a bump map with (du, dv) perturbation data.
  • Stage 1 is assigned a texture map with color data.
  • texbeml sets the matrix data on the texture stage that is sampled. This is different from the functionality of the fixed function pipeline where the perturbation data and the matrices occupy the same texture stage.


texcoord - ps

Interprets texture coordinate data (UVW1) as color data (RGBA).

Syntax

texcoord dst

where

  • dst is the destination register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texcoord | x | x | x |  |  |  |  |  |

This instruction interprets the texture coordinate set (UVW1) corresponding to the destination register number as color data (RGBA). If the texture coordinate set contains fewer than three components, the missing components are set to 0. The fourth component is always set to 1. All values are clamped between 0 and 1.

The advantage of texcoord is that it provides a way to pass vertex data interpolated at high precision directly into the pixel shader. However, when the data is written into the destination register, some precision will be lost, depending on the number of bits used by the hardware for registers.

No texture is sampled by this instruction. Only texture coordinates set on this texture stage are relevant.

Any texture data (such as position, normal, and light source direction) can be mapped by a vertex shader into a texture coordinate. This is done by associating a texture with a texture register using ID3DXBaseEffect::SetTexture and by specifying how the texture sampling is done using IDirect3DDevice9::SetTextureStageState. If the fixed function pipeline is used, be sure to supply the TSS_TEXCOORDINDEX flag.

This instruction is used as follows:

texcoord tn

An Texture Coordinate Register (tn) contains four color values (RGBA). The data can also be thought of as vector data (xyzw). texcoord will retrieve three of these values (xyz) from texture coordinate set x, and the fourth component (w) is set to 1. The texture address is copied from the texture coordinate set n. The result is clamped between 0 and 1.

This example is for illustration only. The C code accompanying the shader has not been optimized for performance.

Here is an example shader using texcoord.

ps_1_1        ; version instruction
texcoord t0   ; declare t0 hold texture coordinates,
              ; which represent rgba values in this example
mov r0, t0    ; move the color in t0 to output register r0

The rendered output from the pixel shader is shown below. The (u,v,w,1) coordinate values map to the (rgb) channels. The alpha channel is set to 1. At the corners of the image, coordinate (0,0,0,1) is interpreted as black; (1,0,0,1) is red; (0,1,0,1) is green; and (1,1,0,1) contains green and red, producing yellow.

Texture coordinate data

Additional code is required to use this shader and an example scenario is shown below.

// This code creates the shader from a file. The contents of
// the shader file can also be supplied as a text string.
LPD3DXBUFFER        pCode;

// Assemble the vertex shader from the file
D3DXAssembleShaderFromFile(strPShaderPath, 0, NULL, &pCode, NULL);
m_pd3dDevice->CreatePixelShader((DWORD*)pCode->GetBufferPointer(),
                   &m_hPixelShader);
pCode->Release();

// This code defines the object vertex data
struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    FLOAT tu1, tv1;
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_TEX1|TEXCOORD2(0))

static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z     u1    v1
    { -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, },
    { +1.0f, -1.0f, 0.0f, 1.0f, 0.0f, },
    { +1.0f, +1.0f, 0.0f, 1.0f, 1.0f, },
    { -1.0f, +1.0f, 0.0f, 0.0f, 1.0f, },
};


texcrd - ps

Copies texture coordinate data from the source texture coordinate iterator register as color data in the destination register.

Syntax

texcrd dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texcrd |  |  |  | x |  |  |  |  |

This instruction interprets coordinate data as color data (RGBA).

No texture is sampled by this instruction. Only texture coordinates set on this texture stage are relevant.

When using texcrd, keep in mind the following detail about how data is copied from the source register to the destination register. The source texture coordinate register (t#) holds data in the range [-D3DCAPS9.MaxTextureRepeat, D3DCAPS9.MaxTextureRepeat], while the destination register (r#) can hold data only in the (likely smaller) range [-D3DCAPS9.PixelShader1xMaxValue, D3DCAPS9.PixelShader1xMaxValue]. Note that for pixel shader version 1_4, D3DCAPS9.PixelShader1xMaxValue must be a minimum of eight. The texcrd instruction, in the process of clamping source data that is out of range of the destination register, is likely to behave differently on different hardware. The first pixel shader version 1_4 hardware on the market will perform a special clamp for values outside of range. This clamp is designed to produce a number that can fit into the destination register, but also to preserve texture addressing behavior for out-of-range data (see D3DTEXTUREADDRESS) if the data were to be subsequently used for texture sampling. However, new hardware from different manufacturers might not exhibit this behavior and might just chop data to fit the destination register range. Therefore, the safest course of action when using pixel shader version 1_4 texcrd is to supply texture coordinate data only into the pixel shader that is already within the range [-8,8] so that you do not rely on the way hardware clamps.

Unlike texcoord_, texcrd does not clamp values between 0 and 1.

Rules for using texcrd :

  1. The same .xyz or .xyw modifier must be applied to every read of an individual t(n) register within a texcrd or texld instruction.
  2. The fourth channel result of texcrd is unset/undefined in all cases.
  3. The third channel is unset/undefined for the xyw_dw case.

Examples

The complete set of allowed syntax for texcrd, taking into account all valid source modifier/selector and destination write mask combinations, is shown below. Note that the .rgba and .xyzw notation can be used interchangeably.

Copies first three channels of texture coordinate iterator register, t(n), into r(m). The fourth channel of r(m) is uninitialized.

texcrd  r(m).rgb, t(n).xyz

// Produces the same result as the previous instruction
texcrd  r(m).rgb, t(n)

Puts first, second, and fourth components of t(n) into first three channels of r(m). The fourth channel of r(m) is uninitialized.

texcrd  r(m).rgb, t(n).xyw

Here is a projective divide example using the _dw modifier.

This example copies x/w and y/w from t(n) into the first two channels of r(m). The third and fourth channels of r(m) are uninitialized. Any data previously written to the third channel of r(m) will be lost. Data in the fourth channel of r(m) is lost due to the phase marker. For version 1_4, the D3DTTFF_PROJECTED flag is ignored.

texcrd  r(m).rg,  t(n)_dw.xyw


texdepth - ps

Calculate depth values to be used in the depth buffer comparison test for this pixel.

Syntax

texdepth dst

where

  • dst is the destination register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texdepth |  |  |  | x |  |  |  |  |

This instruction uses r5.r / r5.g in the depth buffer comparison test for this pixel. The data in the blue and alpha channels is ignored. If r5.g = 0, the result of r5.r / r5.g = 1.0.

Temporary register r5 is the only register that this instruction can use.

After executing this instruction, temporary register r5 is unavailable for additional use in the shader.

When multisampling, using this instruction eliminates most of the benefit of the higher resolution depth buffer. Because the pixel shader runs once per pixel, the single depth value output by texm3x2depth - ps or texdepth will be used for each of the subpixel depth comparison tests.

Examples

Here is an example using texdepth.

ps_1_4
texld  r0, t0        // Sample texture from texture stage 0 (dest
                     //   register number) into r0
                     // Use texture coordinate data from t0
texcrd r1.rgb, t1    // Load a second set of texture coordinate data into r1
add    r5.rg, r0, r1 // Add the two sets of texture coordinate data
phase                // Phase marker, required when using texdepth instruction
texdepth  r5         // Calculate pixel depth as r5.r / r5.g
                     // Do other color calculations with shader output r0


texdp3 - ps

Performs a three-component dot product between data in the texture register number and the texture coordinate set corresponding to the destination register number.

Syntax

texdp3 dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texdp3 |  | x | x |  |  |  |  |  |

Texture registers must use the following sequence.

tex    t(n)        // Define tn as a standard 3-vector (tn must be
                   //   defined in some way before texdp3 uses it)
texdp3 t(m), t(n)  // where m > n
                   // Perform a three-component dot product between tn and
                   //   the texture coordinate set m. The scalar result is
                   //   replicated to all components of t(m)

Here is more detail about how the dot product is accomplished.

The texdp3 instruction performs a three-component dot product and replicates it to all four color channels.

t(m)RGBA = TextureCoordinates(stage m)UVW • t(n)RGB


texdp3tex - ps

Performs a three-component dot product and uses the result to do a 1D texture lookup.

Syntax

texdp3tex dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texdp3tex |  | x | x |  |  |  |  |  |

Texture registers must use the following sequence.

tex       t(n)        // Define tn as a standard 3-vector (tn must be
                      // defined in some way before texdp3tex uses it)
texdp3tex t(m), t(n)  // where m > n
                      // Perform a three-component dot product between t(n) and
                      // the texture coordinate set m. Use the scalar result to
                      // do a 1D texture lookup at texturestage m and place
                      // the result in t(m)

Here is more detail about how the dot product and texture lookup are done.

The texdp3tex instruction performs a three-component dot product.

u' = TextureCoordinates(stage m)UVW • t(n)RGB

The result is used to sample the texture at texture stage m by performing a 1D lookup.

t(m)RGBA = TextureSample(stage m)RGBA using (u',0,0) as coordinates


texkill - ps

Cancels rendering of the current pixel if any of the first three components (UVW) of the texture coordinates is less than zero.

Syntax

texkill src

where

  • src is a source register

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texkill | x | x | x | x | x | x | x | x | x

This instruction corresponds to the HLSL's clip function.

texkill does not sample any texture. It operates on the first three components of the texture coordinates given by the source register number. For ps_1_4, texkill operates on the data in the first three components of the source register.

You can use this instruction to implement arbitrary clip planes in the rasterizer.

When using vertex shaders, the application is responsible for applying the perspective transform. This can cause problems for the arbitrary clipping planes because if it contains anisomorphic scale factors, the clip planes need to be transformed as well. Therefore, it is best to provide an unprojected vertex position to use in the arbitrary clipper, which is the texture coordinate set identified by the texkill operator.

This instruction is used as follows:

texkill tn

// The pixel masking is accomplished as follows:
if ( the x,y,z components of TextureCoordinates(stage n)UVWQ< 0 )
cancel pixel render

For pixel shader 1_1, 1_2, and 1_3, texkill operates on the texture coordinate set given by the source register number. In version 1_4, however, texkill operates on the data contained in the Texture Coordinate Register (tn) or in the temporary register (rn) that has been specified as the source.

When multisampling is enabled, any antialiasing effect achieved on polygon edges due to multisampling will not be achieved along any edge that has been generated by texkill. The pixel shader runs once per pixel.

This example is for illustration only.

This example masks out pixels that have negative texture coordinates. The pixel colors are interpolated from vertex colors provided in the vertex data.

ps_1_1       // Version instruction
texkill t0   // Mask out pixel using texture coordinates from stage 0
mov r0, v0   // Move the diffuse color in v0 to r0

// The rendered output from the pixel shader is shown below

The texture coordinates range from -0.5 to 0.5 in u, and 0.0 to 1.0 in v. This instruction causes the negative u values get masked out. The first image shows the vertex color applied to the quad without the texkill instruction applied. The second image shows the result of the texkill instruction. The pixel colors from the texture coordinates below 0 (where x goes from -0.5 to 0.0) are masked out. The background color (white) is used where the pixel color is masked.

Vertex color applied to the quad without the texkill instruction Output with the texkill instruction applied

The texture coordinate data is declared in the vertex data declaration in this example.

struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    DWORD color;
    FLOAT tu1, tv1;
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1|D3DTEXCOORD2(0))

static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z    color         u1,    v1
    { -1.0f, -1.0f, 0.0f, 0xffff0000, -0.5f,  1.0f, },
    {  1.0f, -1.0f, 0.0f, 0xff00ff00,  0.5f,  1.0f, },
    {  1.0f,  1.0f, 0.0f, 0xff0000ff,  0.5f,  0.0f, },
    { -1.0f,  1.0f, 0.0f, 0xffffffff, -0.5f,  0.0f, },

};


texld - ps_1_4

Loads the destination register with color data (RGBA) sampled using the contents of the source register as texture coordinates. The sampled texture is the texture associated with the destination register number.

texld dst, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dst | Destination register |  |  |  | x | 1_4
src | Source register |  |  | x |  | 1_4 phase 1
 |  |  |  | x | x | 1_4 phase

When using r(n) as a source register, the first three components (XYZ) must have been initialized in the previous phase of the shader.

To learn more about registers, see ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers.

Remarks

This instruction samples the texture in the texture stage associated with the destination register number. The texture is sampled using texture coordinate data from the source register.

The syntax for the texld and texcrd instructions expose support for a projective divide with a Texture Register Modifier. For pixel shader version 1.4, the D3DTTFF_PROJECTED texture transform flag is always ignored.

Rules for using texld:

  1. The same .xyz or .xyw modifier must be applied to every read of an individual t(n) register within both texcrd or texld instructions. If .xyw is being used on t(n) register reads, this can be mixed with other reads of the same t(n) register using .xyw_dw.
  2. The _dz source modifier is only valid on texld with r(n) source register (thus phase 2 only).
  3. The _dz source modifier may be used no more than two times per shader.
Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texld |  |  |  | x |  |  |  |  |

Examples

The texld instruction offers some control over which components of the source texture coordinate data are used. The complete set of allowed syntax for texld follows, and includes all valid source register modifiers, selectors, and write mask combinations.

texld  r(m), t(n).xyz
// Uses xyz from t(n) to sample 1D, 2D, or 3D texture

texld  r(m), t(n)
// Same as previous

texld  r(m), t(n).xyw
// Uses xyw (skipping z) from t(n) to sample 1D, 2D or 3D texture

texld  r(m), t(n)_dw.xyw
// Samples 1D or 2D texture at x/w, y/w from t(n). The result
// is undefined for a cube-map lookup.

texld  r(m), r(n).xyz
// Samples 1D, 2D, or 3D texture at xyz from r(m)
// This is possible in the second phase of the shader

texld  r(m), r(n)
// Same as previous

texld  r(m), r(n)_dz.xyz
// Samples 1D or 2D texture at x/z, y/z from r(m)
// Possible only in second phase
// The result is undefined for a cube-map lookup

texld  r(n), r(n)_dz
// Same as previous


texld - ps_2_0 and up

Sample a texture at a particular sampler, using provided texture coordinates. This instruction is different from the texld - ps_1_4 instruction used in pixel shader version 1_4.

Syntax

texld dst, src0, src1

Where:

  • dst is a destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample.
  • src1 identifies the Sampler (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a sampler state defined by D3DSAMPLERSTATETYPE.

ps_2_0 and ps_2_x

dst must be a Temporary Register (r#) and only .xyzw mask (default mask) is allowed.

src0 must be either a Texture Coordinate Register (t#) or a Temporary Register (r#), with no modifier or swizzle.

src1 must be a Sampler (s#), with no modifier or swizzle.

If the D3DD3DPSHADERCAPS2_0_NODEPENDENTREADLIMIT cap bit is not set (in D3DPSHADERCAPS2_0), a given texture instruction (texld, texldp, texldb - ps, texldd ) may be dependent upon, at most, third order. A first-order dependent texture instruction is a texture instruction in which either:

  • src0 is a Temporary Register (r#).
  • dst was previously written, now being written again.

A second-order dependent texture instruction is defined as a texture instruction that reads or writes to a Temporary Register (r#) whose contents, before executing the texture instruction, depend (perhaps indirectly) on the outcome of a first-order dependent texture instruction. An (n)th-order dependent texture instruction derives from an (n - 1)th-order texture instruction.

ps_3_0

src1 must be a Sampler (s#), with no modifier. Swizzle is allowed on src0 or src1. The swizzle is applied to the texture coordintates before texture lookup.

Remarks

This instruction is supported in the following versions:

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texld |  |  |  |  | x | x | x | x | x

The number of coordinates required for src0 to perform the texture sample depends on how src1 was declared, plus the .w component. Sampler types are declared with dcl_samplerType - ps. If src1 is declared as a 2D sampler, then src0 must contain .xy coordinates; if src1 is declared as either a cube sampler or a volume sampler, then src0 must contain .xyz coordinates. Sampling a texture with fewer dimensions than are present in the texture coordinate is allowed since the extra texture coordinate component(s) are ignored.

If the source texture contains fewer than four components, defaults are placed in the missing components. Defaults depend on the texture format as shown in the following table:

Texture Format | Default Values
D3DFMT_R5G6B5, D3DFMT_R8G8B8, D3DFMT_L8, D3DFMT_L16, D3DFMT_R3G3B2, D3DFMT_CxV8U8, D3DFMT_L6V5U5 | A = 1.0
D3DFMT_V8U8, D3DFMT_V16U16, D3DFMT_G16R16, D3DFMT_G16R16F, D3DFMT_G32R32F | B = A = 1.0
D3DFMT_A8 | R = G = B = 0.0
D3DFMT_R16F, D3DFMT_R32F | G = B = A = 1.0
All depth/stencil formats | R = B = 0.0, A = 1.0


texldb - ps

Biased texture load instruction. This instruction uses the fourth element (.a or .w) to bias the texture-sampling level-of-detail just before sampling.

Syntax

texldb dst, src0, src1

Where:

  • dst is the destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample. See Texture Coordinate Register.
  • src1 identifies the Sampler (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a sampler state defined by D3DSAMPLERSTATETYPE.

For the restrictions when using texldb, see the texld - ps_2_0 and up instruction.

ps_2_0 and ps_2_x

dst must be a Temporary Register (r#) and only .xyzw mask (default mask) is allowed.

src0 must be either a Texture Coordinate Register (t#) or a Temporary Register (r#), with no modifier or swizzle.

src1 must be a Sampler (s#), with no modifier or swizzle.

If the D3DD3DPSHADERCAPS2_0_NODEPENDENTREADLIMIT cap bit is not set (in D3DPSHADERCAPS2_0), a given texture instruction (texld, texldp, texldb, texldd) may be dependent upon, at most, third order. A first-order dependent texture instruction is a texture instruction in which either:

  • src0 is a Temporary Register (r#).
  • dst was previously written, now being written again.

A second-order dependent texture instruction is defined as a texture instruction that reads or writes to a Temporary Register (r#) whose contents, before executing the texture instruction, depend (perhaps indirectly) on the outcome of a first-order dependent texture instruction. An (n)th-order dependent texture instruction derives from an (n - 1)th-order texture instruction.

ps_3_0

src1 must be a Sampler (s#), with no modifier. Swizzle is allowed on src1, and when applied, the texture lookup results are pre-swizzled before written to dst.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldb |  |  |  |  | x | x | x | x | x

texldb biases the mipmap level-of-detail, computed normally as part of the sample process by the (signed) value in src0.w. Positive bias values will result in smaller mipmaps being selected and vice versa. For ps_2_0 and ps_2_x, bias values can be within the range [-3.0, +3.0]. For ps_3_0, bias values can be within the range [-16.0, +15.0]. Bias values outside these ranges produce undefined results. The sampler state D3DSAMP_MIPMAPLODBIAS is still honored, and the texldb bias is added to this, but on a per-pixel basis. After the biased level-of-detail is computed, D3DSAMP_MAXMIPLEVEL is still honored and the texture sample occurs. After texldb, the contents of src0 are unaffected (unless dst is the same register).

The number of coordinates required for src0 to perform the texture sample depends on how src1 was declared, plus the .w component. Sampler types are declared with dcl_samplerType - ps. If src1 is declared as a 2D sampler, then src0 must contain .xyw coordinates; if src1 is declared as either a cube sampler or a volume sampler, then src0 must contain .xyzw coordinates. Sampling a 2D texture with .xyzw coordinates is allowed (the .z coordinate is ignored).

If the source texture contains fewer than four components, defaults are placed in the missing components. Defaults depend on the texture format as shown in the following table:

Texture Format | Default Values
D3DFMT_R5G6B5, D3DFMT_R8G8B8, D3DFMT_L8, D3DFMT_L16, D3DFMT_R3G3B2, D3DFMT_CxV8U8, D3DFMT_L6V5U5 | A = 1.0
D3DFMT_V8U8, D3DFMT_V16U16, D3DFMT_G16R16, D3DFMT_G16R16F, D3DFMT_G32R32F | B = A = 1.0
D3DFMT_A8 | R = G = B = 0.0
D3DFMT_R16F, D3DFMT_R32F | G = B = A = 1.0
All depth/stencil formats | R = B = 0.0, A = 1.0


texldd - ps

Samples a texture with additional gradient inputs.

Syntax

texldd, dst, src0, src1, src2, src3

Where:

  • dst is a destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample. See Texture Coordinate Register.
  • src1 identifies the source sampler register (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a control state defined by the D3DSAMPLERSTATETYPE enumeration (ex. D3DSAMP_MINFILTER).
  • src2 is an input source register that specifies the x gradient.
  • src3 is an input source register that specifies the y gradient.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldd |  |  |  |  |  | x * | x | x | x

* This instruction is only supported by ps_2_a. It is not supported by ps_2_b. For more information about profiles, see D3DXGetPixelShaderProfile.

This instruction samples a texture using the texture coordinates at src0, the sampler specified by src1, and the gradients DSX and DSY coming from src2 and src3. The x and y gradient values are used to select the appropriate mipmap level of the texture for sampling.

All sources support arbitrary swizzles.

All write masks are valid on the destination.


texldl - ps

Sample a texture with a particular sampler. The particular mipmap level-of-detail being sampled has to be specified as the fourth component of the texture coordinate.

Syntax

texldl dst, src0, src1

Where:

  • dst is a destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample. See Texture Coordinate Register.
  • src1 identifies the source sampler register (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a control state defined by the D3DSAMPLERSTATETYPE enumeration (for example, D3DSAMP_MINFILTER).

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldl |  |  |  |  |  |  |  | x | x

texldl looks up the texture set at the sampler stage referenced by src1. The level-of-detail is selected from src0.w. This value can be negative in which case the level-of-detail selected is the zeroth one (biggest map) with the MAGFILTER. Since src0.w is a floating point value, the fractional value is used to interpolate (if MIPFILTER is LINEAR) between two mip levels. Sampler states MIPMAPLODBIAS and MAXMIPLEVEL are honored. For more information about sampler states, see D3DSAMPLERSTATETYPE.

If a shader program samples from a sampler that does not have a texture set, then 0001 is obtained in the destination register.

The following is a rough algorithm that the reference device follows:

LOD = src0.w + LODBIAS;
if (LOD <= 0 )
{
   LOD = 0;
   Filter = MagFilter;
   tex = Lookup( MAX(MAXMIPLEVEL, LOD), Filter );
}
else
{
   Filter = MinFilter;
   LOD = MAX( MAXMIPLEVEL, LOD );
   tex = Lookup( Floor(LOD), Filter );
   if( MipFilter == LINEAR )
   {
      tex1 = Lookup( Ceil(LOD), Filter );
      tex = (1 - frac(src0.w))*tex + frac(src0.w)*tex1;
   }
}

Restrictions:

  • The texture coordinates should not be scaled by texture size.
  • dst must be a Temporary Register (r#).
  • dst can accept a writemask. See Destination Register Write Mask.
  • Defaults for missing components are either 0 or 1, and depend on the texture format.
  • src1 must be a Sampler (s#). src1 may not use a negate modifier (see Destination Register Write Mask). src1 may use swizzle (see Source Register Swizzling), which is applied after sampling, but before the write mask (see Destination Register Write Mask) is honored. The sampler must have been declared (using dcl_samplerType - ps) at the beginning of the shader.
  • The number of coordinates required to perform the texture sample depends on how the sampler was declared. If it was declared as a cube, a three-component texture coordinate is required (.rgb). Validation enforces that coordinates provided to tex_ldl Are sufficient for the texture dimension declared for the sampler. However, it is not guaranteed that the application actually sets a texture (through the API) with dimensions equal to the dimension declared for the sampler. In such a case, the runtime will attempt to detect mismatches (possibly in debug only). Sampling a texture with fewer dimensions than are present in the texture coordinate will be allowed and assumed to ignore the extra texture coordinate components. Conversely, sampling a texture with more dimensions than are present in the texture coordinate is illegal.
  • If the src0 (texture coordinate) is Temporary Register, the components required for the lookup (described above) must have been previously written.
  • Sampling unsigned RGB textures will result in float values between 0.0 and 1.0.
  • Sampling signed textures will result in float values between -1.0 to 1.0.
  • When sampling floating-point textures, Float16 means that the data will range within MAX_FLOAT16. Float32 means the maximum range of the pipeline will be used. Sampling outside of either range is undefined.
  • There is no dependent read limit.


texldp - ps

Projected texture load instruction. This instruction divides the input texture coordinate by the fourth element (.a or .w) just before sampling.

Syntax

texldp dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample. See Texture Coordinate Register.
  • src1 identifies the Sampler (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a sampler state defined by D3DSAMPLERSTATETYPE.

For the set of restrictions when using texldp, see texld.

Remarks

texldp performs projection on the coordinates read from src0 before performing the sample. Each texture coordinate is divided by src0.w, then the texture is sampled. When texldp completes, the contents of src0 are unaffected (unless dst is the same register). An alternative to using texldp is to manually perform the projection division in the shader. However, performing the division in shader code is usually slower than when performed by the texldp instruction, so avoid such additional math when possible.

The number of coordinates required for src0 to perform the texture sample depends on how src1 was declared, plus the .w component. Sampler types are declared with dcl_samplerType - ps. If src1 is declared as a 2D sampler, then src0 must contain .xyw coordinates; if src1 is declared as either a cube sampler or a volume sampler, then src0 must contain .xyzw coordinates. Sampling a 2D texture with .xyzw coordinates is allowed (the .z coordinate is ignored).

If the source texture contains fewer than four components, defaults are placed in the missing components. Defaults depend on the texture format as shown in the following table.

Texture Format | Default Values for missing components
D3DFMT_R5G6B5, D3DFMT_R8G8B8, D3DFMT_L8, D3DFMT_L16, D3DFMT_R3G3B2, D3DFMT_CxV8U8, D3DFMT_L6V5U5 | A = 1.0
D3DFMT_V8U8, D3DFMT_V16U16, D3DFMT_G16R16, D3DFMT_G16R16F, D3DFMT_G32R32F | B = A = 1.0
D3DFMT_A8 | R = G = B = 0.0
D3DFMT_R16F, D3DFMT_R32F | G = B = A = 1.0
All depth/stencil formats | R = B = 0.0, A = 1.0

This instruction is supported in the following versions:

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldp |  |  |  |  | x | x | x | x | x

ps_2_0 and ps_2_x

dst must be a Temporary Register (r#) and only .xyzw mask (default mask) is allowed.

src0 must be either a Texture Coordinate Register (t#) or a Temporary Register (r#), with no modifier or swizzle.

src1 must be a Sampler (s#), with no modifier or swizzle.

If the D3DD3DPSHADERCAPS2_0_NODEPENDENTREADLIMIT cap bit is not set (in D3DPSHADERCAPS2_0), a given texture instruction (texld, texldp, texldb - ps, texldd ) may be dependent upon, at most, third order. A first-order dependent texture instruction is a texture instruction in which either:

  • src0 is a Temporary Register (r#)
  • dst was previously written, now being written again.

A second-order dependent texture instruction is defined as a texture instruction that reads or writes to a Temporary Register (r#) whose contents, before executing the texture instruction, depend (perhaps indirectly) on the outcome of a first-order dependent texture instruction. An (n)th-order dependent texture instruction derives from an (n - 1)th-order texture instruction.

ps_3_0

For ps_3_0, src1 must be a Sampler (s#), with no modifier. Swizzle is allowed on src1, and when applied, the texture lookup results are pre-swizzled before written to dst.


texm3x2depth - ps

Calculate the depth value to be used in depth testing for this pixel.

Syntax

texm3x2depth dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x2depth |  |  | x |  |  |  |  |  |

This instruction must be used with the texm3x2pad - ps instruction.

When using these two instructions, texture registers must use the following sequence.

tex t(n)                     // Define tn as a standard 3-vector.(tn must be
                             // defined in some way before it is used
texm3x2pad   t(m),   t(n)    // Where m > n
                             // Calculate z value
texm3x2depth t(m+1), t(n)    // Calculate w value; use both z and w to
                             // find depth

The depth calculation is done after using a dot product operation to find z and w. Here is more detail about how the depth calculation is accomplished.

The texm3x2pad instruction calculates z.

z = TextureCoordinates(stage m)UVW • t(n)RGB

The texm3x2depth instruction calculates w.

w = TextureCoordinates(stage m+1)UVW • t(n)RGB

Calculate depth and store the result in t(m+1).

if (w == 0)
  t(m+1) = 1.0
else
  t(m+1) = z/w

The calculated depth is tagged to be used in the depth test for the pixel, replacing the existing depth test value for the pixel.

Be sure to clamp z/w to be in the range of (0-1). If z/w is outside this range, the result stored in the depth buffer will be undefined.

After running tex3x2depth, register t(m+1) is no longer available for use in the shader.

When multisampling, using this instruction eliminates most of the benefit of the higher resolution depth buffer. Because the pixel shader runs once per pixel, the single depth value output by texm3x2depth or texdepth - ps will be used for each of the subpixel depth comparison tests.


texm3x2pad - ps

Performs the first row multiplication of a two-row matrix multiply. This instruction must be combined with either texm3x2tex - ps or texm3x2depth - ps. Refer to either of these instructions for details on using texmpad.

Syntax

tex3x2pad dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x2pad | x | x | x |  |  |  |  |  |

This instruction cannot be used by itself.


texm3x2tex - ps

Performs the final row of a 3x2 matrix multiply and uses the result to do a texture lookup. texm3x2tex must be used in conjunction with the texm3x2pad - ps instruction.

Syntax

texm3x2tex dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x2tex | x | x | x |  |  |  |  |  |

The instruction is used as one of two instructions representing a 3x2 matrix multiply operation. This instruction must be used with the texm3x2pad - ps instruction.

When using these two instructions, texture registers must use the following sequence.

tex t(n)                      // Define tn as a standard 3-vector (tn must
                              // be defined in some way before it is used)
texm3x2pad  t(m),   t(n)      // where m > n
                              // Perform first row of matrix multiply
texm3x2tex  t(m+1), t(n)      // Perform second row of matrix multiply
                              // to get (u,v) to sample texture
                              // associated with stage m+1

Here is more detail about how the 3x2 multiply is accomplished.

The texm3x2pad instruction performs the first row of the multiply to find u'.

u' = t(n)RGB * TextureCoordinates(stage m)UVW

The texm3x2tex instruction performs the second row of the multiply to find v'.

v' = t(n)RGB * TextureCoordinates(stage m+1)UVW

The texm3x2tex instruction samples the texture on stage (m+1) with (u',v') and stores the result in t(m+1).

t(m+1)RGB = TextureSample(stage m+1)RGB using (u', v') as coordinates

Examples

Here is an example shader with the texture maps and the texture stages identified.

ps_1_1
tex t0                // Bind texture in stage 0 to register t0
texm3x2pad  t1,  t0   // First row of matrix multiply
texm3x2tex  t2,  t0   // Second row of matrix multiply to get (u,v)
                      // with which to sample texture in stage 2
mov r0, t2            // Output result

This example requires the following textures in the following texture stages.

  • Stage 0 takes a map with (x,y,z) perturbation data.
  • Stage 1 holds texture coordinates. No texture is required in the texture stage.
  • Stage 2 holds both texture coordinates as well as a 2D texture set at that texture stage.


texm3x3 - ps

Performs a 3x3 matrix multiply when used in conjunction with two texm3x3pad - ps instructions.

Syntax

texm3x3 dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3 |  | x | x |  |  |  |  |  |

This instruction is the same as the texm3x3tex - ps instruction, without the texture lookup.

This instruction is used as the final of three instructions representing a 3x3 matrix multiply operation. The 3x3 matrix is comprised of the texture coordinates of the third texture stage, and by the two preceding texture stages. Any texture assigned to any of the three texture stages is ignored.

This instruction must be used with two texm3x3pad instructions. Texture registers must follow the following sequence.

tex t(n)                 // Define tn as a standard 3-vector (tn must
                         // be defined in some way before it is used)
texm3x3pad t(m),   t(n)  // where m > n
                         // Perform first row of matrix multiply
texm3x3pad t(m+1), t(n)  // Perform second row of matrix multiply
texm3x3    t(m+2), t(n)  // Perform third row of matrix multiply to get a
                         // 3-vector result

Here is more detail about how the 3x3 multiply is accomplished.

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3tex instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

Place the result of the matrix multiply in the destination register.

t(m+2)RGBA = (u', v', w', 1)


texm3x3pad - ps

Performs the first or second row multiply of a three-row matrix multiply. This instruction must be used in combination with texm3x3 - ps, texm3x3spec - ps, texm3x3vspec - ps, or texm3x3tex - ps.

Syntax

texm3x3pad dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3pad | x | x | x |  |  |  |  |  |

This instruction cannot be used by itself.


texm3x3spec - ps

Performs a 3x3 matrix multiply and uses the result to perform a texture lookup. This can be used for specular reflection and environment mapping. texm3x3spec must be used in conjunction with two texm3x3pad - ps instructions.

Syntax

texm3x3spec dst, src0, src1

where

  • dst is the destination register.
  • src0 and src1 are source registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3spec | x | x | x |  |  |  |  |  |

This instruction performs the final row of a 3x3 matrix multiply, uses the resulting vector as a normal vector to reflect an eye-ray vector, and then uses the reflected vector to perform a texture lookup. The shader reads the eye-ray vector from a constant register. The 3x3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

The 3x3 matrix is comprised of the texture coordinates of the third texture stage and the two preceding texture stages. The resulting post reflection vector (u,v,w) is used to sample the texture on the final texture stage. Any texture assigned to the preceding two texture stages is ignored.

This instruction must be used with two texm3x3pad instructions. Texture registers must use the following sequence.

tex t(n)                      // Define tn as a standard 3-vector (tn must
                              //   be defined in some way before it is used)
texm3x3pad t(m),   t(n)       //   where m > n
                              // Perform first row of matrix multiply
texm3x3pad  t(m+1), t(n)      // Perform second row of matrix multiply
texm3x3spec t(m+2), t(n), c0  // Perform third row of matrix multiply
                              // Then do a texture lookup on the texture
                              //   associated with texture stage m+2

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3spec instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

The texm3x3spec instruction then does a reflection calculation.

(u'', v'', w'') = 2*[(N*E)/(N*N)]*N - E
// where the normal N is given by
//   N = (u', v', w')
//   and the eye-ray vector E is given by the constant register
//   E = c# (Any constant register--c0, c1, c2, etc.--can be used)

Lastly, the texm3x3spec instruction samples t(m+2) with (u'',v'',w'') and stores the result in t(m+2).

t(m+2)RGBA = TextureSample(stage m+2)RGBA using (u'', v'', w'') as coordinates

Examples

Here is an example shader with the texture maps and the texture stages identified.

ps_1_1
tex t0                    // Bind texture in stage 0 to register t0 (tn must
                          //   be defined in some way before it is used)
texm3x3pad  t1,  t0       // First row of matrix multiply
texm3x3pad  t2,  t0       // Second row of matrix multiply
texm3x3spec t3,  t0,  c#  // Third row of matrix multiply to get a 3-vector
                          // Reflect 3-vector by the eye-ray vector in c#
                          // Use reflected vector to lookup texture in
                          //   stage 3
mov r0, t3                // Output the result

This example requires the following texture stage setup.

  • Stage 0 is assigned a texture map with normal data. This is often referred to as a bump map. The data is (XYZ) normals for each texel. Texture coordinates at stage n defines where to sample this normal map.
  • Texture coordinate set m is assigned to row 1 of the 3x3 matrix. Any texture assigned to stage m is ignored.
  • Texture coordinate set m+1 is assigned to row 2 of the 3x3 matrix. Any texture assigned to stage m+1 is ignored.
  • Texture coordinate set m+2 is assigned to row 3 of the 3x3 matrix. Stage m+2 is assigned a volume or cube texture map. The texture provides color data (RGBA).
  • The eye-ray vector E is given by a constant register E = c#.


texm3x3tex - ps

Performs a 3x3 matrix multiply and uses the result to do a texture lookup. texm3x3tex must be used with two texm3x3pad - ps instructions.

Syntax

texm3x3tex dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3tex | x | x | x |  |  |  |  |  |

This instruction is used as the final of three instructions representing a 3x3 matrix multiply operation, followed by a texture lookup. The 3x3 matrix is comprised of the texture coordinates of the third texture stage and the two preceding texture stages. The resulting three-component vector (u,v,w) is used to sample the texture in stage 3. Any texture assigned to the preceding two texture stages is ignored. The 3x3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

This instruction must be used with the texm3x3pad instruction. Texture registers must use the following sequence.

tex t(n)                 // Define tn as a standard 3-vector (tn must
                         //   be defined in some way before it is used)
texm3x3pad t(m),   t(n)  //   where m > n
                         // Perform first row of matrix multiply
texm3x3pad t(m+1), t(n)  // Perform second row of matrix multiply
texm3x3tex t(m+2), t(n)  // Perform third row of matrix multiply to get a
                         //   3-vector with which to sample texture
                         //   associated with texture stage m+2

Here is more detail about how the 3x3 multiply is accomplished.

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3spec instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

Lastly, the texm3x3tex instruction samples t(m+2) with (u',v',w') and stores the result in t(m+2).

t(m+2)RGBA = TextureSample(stage m+2)RGBA using (u', v', w') as coordinates.

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0                // Bind texture in stage 0 to register t0
texm3x3pad  t1,  t0   // First row of matrix multiply
texm3x3pad  t2,  t0   // Second row of matrix multiply
texm3x3tex  t3,  t0   // Third row of matrix multiply to get a
                      // 3-vector with which to sample texture at
mov r0, t3            // stage 3 output result

This example requires the following texture stage setup.

  • Stage 0 is assigned a texture map with normal data. This is often referred to as a bump map. The data is (XYZ) normals for each texel. Texture coordinate set 0 defines how to sample this normal map.
  • Texture coordinate set 1 is assigned to row 1 of the 3x3 matrix. Any texture assigned to stage 1 is ignored.
  • Texture coordinate set 2 is assigned to row 2 of the 3x3 matrix. Any texture assigned to stage 2 is ignored.
  • Texture coordinate set 3 is assigned to row 3 of the 3x3 matrix. A volume or cube texture should be set to stage 3 for lookup by the transformed 3D vector.


texm3x3vspec - ps

Performs a 3x3 matrix multiply and uses the result to perform a texture lookup. This can be used for specular reflection and environment mapping where the eye-ray vector is not constant. texm3x3vspec must be used in conjunction with two texm3x3pad - ps instructions. If the eye-ray vector is constant, the texm3x3spec - ps instruction will perform the same matrix multiply and texture lookup.

Syntax

texm3x3vspec dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3vspec | x | x | x |  |  |  |  |  |

This instruction performs the final row of a 3x3 matrix multiply operation, interprets the resulting vector as a normal vector to reflect an eye-ray vector, and then uses the reflected vector as a texture address for a texture lookup. It works just like texm3x3spec - ps, except that the eye-ray vector is taken from the fourth component of the texture coordinates. The 3x3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

The 3x3 matrix is comprised of the texture coordinates of the third texture stage and the two preceding texture stages. The resulting post-reflection vector (UVW) is used to sample the texture in stage 3. Any texture assigned to the preceding two texture stages is ignored.

This instruction must be used with the texm3x3pad instruction. Texture registers must use the following sequence.

tex t(n)                    // Define tn as a standard 3-vector (tn must
                            //   be defined in some way before it is used)
texm3x3pad   t(m),   t(n)   // where m > n
                            // Perform first row of matrix multiply
texm3x3pad   t(m+1), t(n)   // Perform second row of matrix multiply
texm3x3vspec t(m+2), t(n)   // Perform third row of matrix multiply
                            // Then do a texture lookup on the texture
                            // associated with texture stage m+2

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3spec instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

The texm3x3vspec instruction also does a reflection calculation.

(u'', v'', w'') = 2*[(N*E)/(N*N)]*N - E
// where the normal N is given by
// N = (u', v', w')
// and the eye-ray vector E is given by
// E = (TextureCoordinates(stage m)Q,
//      TextureCoordinates(stage m+1)Q,
//      TextureCoordinates(stage m+2)Q)

Lastly, the texm3x3vspec instruction samples t(m+2) with (u'',v'',w'')and stores the result in t(m+2).

t(m+2)RGBA = TextureSample(stage m+2)RGBA
  using (u'', v'', w'') as coordinates

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0                // Bind texture in stage 0 to register t0
texm3x3pad   t1,  t0  // First row of matrix multiply
texm3x3pad   t2,  t0  // Second row of matrix multiply
texm3x3vspec t3,  t0  // Third row of matrix multiply to get a 3-vector
                      // Reflect 3-vector by the eye-ray vector
                      // Use reflected vector to do a texture lookup
                      //   at stage 3
mov r0, t3            // Output the result

This example requires the following texture stage setup.

  • Stage 0 is assigned a texture map with normal data. This is often referred to as a bump map. The data is (XYZ) normals for each texel. Texture coordinates at stage n defines how to sample this normal map.
  • Texture coordinate set m is assigned to row 1 of the 3x3 matrix. Any texture assigned to stage m is ignored.
  • Texture coordinate set m+1 is assigned to row 2 of the 3x3 matrix. Any texture assigned to stage m+1 is ignored.
  • Texture coordinate set m+2 is assigned to row 3 of the 3x3 matrix. Stage m+2 is assigned a volume or cube texture map. The texture provides color data (RGBA).
  • The eye-ray vector E is passed into the instruction in the fourth component (q) of the texture coordinate data at stages m, m+1, and m+2.


texreg2ar - ps

Interprets the alpha and red color components of the source register as texture address data (u,v) to sample the texture at the stage corresponding to the destination register number. The result is stored in the destination register.

Syntax

texreg2ar dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texreg2ar | x | x | x |  |  |  |  |  |

This instruction is useful for color-space remapping operations.

Here is an example of the sequence the instruction follows.

tex t(n)
texreg2ar t(m), t(n)     where m > n

// The first instruction loads the texture color (RGBA)
// into register tn
tex tn
// The second instruction remaps the color
t(m)RGBA = TextureSample(stage m)RGBA using t(n)AR as coordinates

_bx2 cannot be used on the src register for texreg2ar or texreg2gb - ps instructions.

For this instruction, the source register must use unsigned data. Use of signed or mixed data in the source register will produce undefined results. For more information, see D3DFORMAT.


texreg2gb - ps

Interprets the green and blue color components of the source register as texture address data to sample the texture at the stage corresponding to the destination register number.

Syntax

texreg2gb dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texreg2gb |  | x | x |  |  |  |  |  |

This instruction is useful for color-space remapping operations.

Here is an example of the sequence the instruction follows.

// Here is an example of the sequence the instruction follows
tex t(n)
texreg2gb t(m), t(n)     where m > n

// The first instruction loads the texture color (RGBA)
// into register tn
tex tn

// The second instruction remaps the color
t(m)RGBA = TextureSample(stage m)RGBA using t(n)GB as coordinates

_bx2 cannot be used on the src register for texreg2ar - ps or texreg2gb instructions.

For this instruction, the source register must use unsigned data. Use of signed or mixed data in the source register will produce undefined results. For more information, see D3DFORMAT.


texreg2rgb - ps

Interprets the red, green, and blue (RGB) color components of the source register as texture address data in order to sample the texture at the stage corresponding to the destination register number. The result is stored in the destination register.

Syntax

texreg2rgb dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texreg2rgb |  | x | x |  |  |  |  |  |

This instruction is useful for color-space remapping operations. It supports two-dimensional (2D) and three-dimensional (3D) coordinates. It can be used just like the texreg2ar - ps or texreg2gb - ps to remap 2D data. However, this instruction also supports 3D data so it can be used with cube maps and 3D volume textures.

Here is an example of the sequence the instruction follows.

tex t(n)
texreg2rgb t(m), t(n)     where m > n

Here is more detail about how the remapping is accomplished.

// The first instruction loads the texture color (RGBA) into register tn
tex tn

// The second instruction remaps the color
t(m)RGB = TextureSample(stage m)RGB using t(n)RGB as coordinates.


Registers

  • ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers
  • ps_2_0 Registers
  • ps_2_x Registers
  • ps_3_0 Registers


Pixel Shader Register Modifiers

Source Register Modifiers:

  • Source Register Bias
  • Source Register Invert
  • Source Register Negate
  • Source Register Swizzling
  • Source Register Scale x 2
  • Source Register Signed Scaling
  • Destination Register Write Mask

Destination Register Modifiers:

  • Destination Register Write Mask


Pixel Shader Source Register Modifiers

Use source register modifiers to change the value read from a register before an instruction runs. The contents of a source register are left unchanged. Modifiers are useful for adjusting the range of register data in preparation for the instruction. A set of modifiers called selectors copies or replicates the data from a single channel (r,g,b,a) into the other channels.

ps_1_1 - ps_1_4

This table identifies the versions that support each modifier:

Source register modifiers | Syntax | Version |  |  |
 |  | 1_1 | 1_2 | 1_3 | 1_4
bias | register_bias | X | X | X | X
invert | 1 - register | X | X | X | X
negate | - register | X | X | X | X
scale by 2 | register_x2 |  |  |  | X
signed scaling | register_bx2 | X | X | X | X
texld and texcrd modifiers | register_d* | X | X | X | X
source register swizzling | register.xyzw | X | X | X | X

Source register modifiers can be used only on arithmetic instructions. They cannot be used on texture address instructions. The exception to this is the scale by 2 modifier. For version 1_1, signed scale can be used on the source argument of any texm* instruction. For version 1_2 or 1_3, signed scale can be used on the source argument of any texture address instruction.

Some modifier specific restrictions:

  • Negate can be combined with either the bias, signed scaling, or scalex2 modifier. When combined, negate is run last.
  • Invert cannot be combined with any other modifier.
  • Invert, negate, bias, signed scaling, and scalex2 can be combined with any of the selectors.
  • Source register modifiers should not be used on constant registers because they will cause undefined results. For version 1_4, modifiers on constants are not allowed and will fail validation.

ps_2_0 and Above

For version ps_2_0 and up, the number of modifiers has been simplified.

Negate

Negate the contents of the source register.

Component modifier | Description
- r | Source negation

The negate modifier cannot be used on second source register of these instructions: m3x2 - ps, m3x3 - ps, m3x4 - ps, m4x3 - ps, and m4x4 - ps.

Pixel shader versions | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
- | x | x | x | x | x

Absolute Value

Take the absolute value of the register.

Pixel shader versions | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  |  |  | x | x

If any version 3 shader reads from one or more constant float registers (c#), one of the following must be true.

  • All of the constant floating-point registers must use the abs modifier.
  • None of the constant floating-point registers can use the abs modifier.


Source Register Bias

Subtract 0.5 from all components.

Registers

Source register. For more about register types, see ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register. The bias is applied to all four color channels (RGBA) as follows:

output = (input - 0.5)

The effect is to modify data that was in the range 0 to 1 to be in the range -0.5 to 0.5. Applying bias to data outside this range may produce undefined results.

Note This modifier is mutually exclusive with Source Register Invert, so it cannot be applied to the same register.

This modifier is for use with the arithmetic instructions.

Example

This example performs the same operation as D3DTOP_ADDSIGNED in DirectX 6.0 and 7.0 multiple texture syntax.

add r0, r0, t0_bias; Shift down by 0.5.


Source Register Invert

Performs a (1 - value) calculation for each channel of the specified register.

Syntax

1 - register

Registers

Source Register. For more about register types, see ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register. The invert operation is applied to all four color channels (RGBA).

This modifier can be used only with arithmetic instructions. In addition, this modifier cannot be combined with the other Destination Register Write Mask.

Example

This example uses inversion to generate the complement of register r1.

mul r0, r0, 1-r1;


Source Register Negate

Performs a negate (y = -x), on all register components.

Syntax

- register

Registers

Source Register. For more about register types, see ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register. The negate operation is applied to all four color channels (RGBA).

This operation is performed after any other modifiers present on the same argument.

This modifier is mutually exclusive with Source Register Invert so it cannot be applied to the same register.

This modifier is for use only with arithmetic instructions.

Example

The following example shows how to use this modifier.

mul r0, r0, -v1;


Source Register Scale x 2

Multiply the value by two before using it in the instruction.

Syntax

register_x2

Register

Source register. For more about register types, see ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register.

This modifier is mutually exclusive with Source Register Invert, so it cannot be applied to the same register.

This modifier is only available to arithmetic instructions in version 1_4.

Example

This example samples a texture, converts data to the range of -1 to +1, and calculates a dot product.

mul r0, r0, r1_x2;


Source Register Signed Scaling

Subtracts 0.5 from each channel and scales the result by 2.0. The name bx2 comes from bias and scale-times-two, which is the operation it performs.

Syntax

source register_bx2

Register

Source Register. For more about register types, see ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers.

Remarks

This operation is commonly used to expand data from [0.0 to 1.0] to [-1.0 to 1.0]. This modifier is designed for use with the arithmetic instructions. This modifier is commonly used on inputs to the dot product instruction (dp3 - ps). Using _bx2 on data outside the range 0 to 1 may produce undefined results.

The signed scaling operation is applied to the data read from the register before the next instruction is run. The operation is applied to all four color channels (RGBA) as follows:

y = 2(x - 0.5)

The contents of the register are not changed. The modifier is applied only to the data read from the register.

This modifier is mutually exclusive with Source Register Invert so it cannot be applied to the same register.

Version information:

  • For ps_1_0 and ps_1_1, you can use _bx2 on any source register for texture instructions of the form texm3x2* and texm3x3*. _bx2 cannot be used on any of the other texture instructions such as texreg2ar - ps or texreg2gb - ps.
  • For ps_1_2 and ps_1_3, you can use _bx2 on any source register for any tex* instruction except: texreg2ar - ps, texreg2gb - ps, texbem - ps or texbeml - ps.

Example

This example samples a texture, converts data to the range of -1 to +1, and calculates a dot product.

tex t0                        ; Read a texture color.
dp3_sat r0, t0_bx2, v0_bx2    ; Calculate a dot product.


ps_1_4 Source Register Modifiers for texld and texcrd

Two pixel shader version 1_4 texture address instructions, texld - ps_1_4 and texcrd - ps, have custom syntax. These instructions support their own set of source register modifiers, source register selectors, and destination-register write masks, as shown here.

Source Register Modifiers for texld and texcrd

These modifiers provide projective divide functionality by dividing the x and y values by either the z or w values.

Source register modifiers | Description | Syntax
_dz | Divide x,y components by z | register_dz
_db | Divide x,y components by z | register_db
_dw | Divide x,y components by w | register_dw
_da | Divide x,y components by w | register_da

Remarks

The _dz or _db modifier does the following:

x' = x/z ( x' = 1.0 if z == 0)
y' = y/z ( y' = 1.0 if z == 0)
z' is undefined
w' is undefined

The _dw or _da modifier does the following:

x' = x/w ( x' = 1.0 if w == 0)
y' = y/w ( y' = 1.0 if w == 0)
z' is undefined
w' is undefined


Source Register Swizzling

Swizzling refers to the ability to copy any source register component to any temporary register component. Swizzling does not affect the source register data. Before an instruction runs, the data in a source register is copied to a temporary register.

Source Swizzling

Source swizzle allows individual component of a source register to take on the value of any of the four components of the same source register before the register is read for computation.

For example, the .zxxy swizzle means:

  • .x component will take on the value of .z component
  • .y component will take on the value of .x component
  • .z component will take on the value of .x component
  • .w component will take on the value of .y component

The components can appear in any order. If fewer than four components are specified, the last component is repeated. For example:

.xy  = .xyyy
.wzx = .wzxx
.z   = .zzzz

If no component is specified, no swizzling is applied.

Some instructions have restrictions for source swizzle. They are listed in the respected instruction reference pages.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
.x |  |  |  | x | x | x | x | x | x
.y |  |  |  | x | x | x | x | x | x
.z | x* | x* | x* | x | x | x | x | x | x
.w | x | x | x | x | x | x | x | x | x
.xyzw (default) | x | x | x | x | x | x | x | x | x
.yzxw |  |  |  |  | x | x | x | x | x
.zxyw |  |  |  |  | x | x | x | x | x
.wzyx |  |  |  |  | x | x | x | x | x
arbitrary swizzle |  |  |  |  |  | x | x | x | x

* Only available if destination write mask is .w (.a).

Arbitrary Swizzle

Swizzles can be applied to source registers in an arbitrary order; that is, any source register can take any component mask, in any order.

Replicate Swizzle

Replicate swizzle copies one component to another. This is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

See Also

ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers, ps_2_0 Registers, ps_2_x Registers, ps_3_0 Registers


Destination Register Write Mask

A write mask controls which components of a destination register are written after an instruction is completed. An output write mask is allowed as long as the components are in the order of .rgba or .xyzw. That is, .rba and .xw are valid masks. Texture registers have one set of rules and non-texture registers have another set of rules.

Syntax

dst.writemask

where

  • dst is a destination register.
  • writemask is a sequence of masks from either set: (x,y,z,w) or (red, green, blue, alpha).

Remarks

The following destination write masks are available.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
.xyzw (default) | x | x | x | x | x | x | x | x | x
.xyz | x | x | x | x | x | x | x | x | x
.w | x | x | x | x | x | x | x | x | x
arbitrary mask |  |  |  | x | x | x | x | x | x

The arbitrary mask allows any set of channels to be combined to produce a mask. The channels must be listed in the order r, g, b, a - for example, register.rba, which updates the red, blue, and alpha channels of the destination. The arbitrary mask is available in version 1_4 or higher.

If no destination write mask is specified, the destination write mask defaults to the rgba case. In other words, all channels in the destination register are updated.

For versions 1_0 to 1_3, the dp3 - ps dp3 arithmetic instruction can use only the .rgb or .rgba output write masks.

Destination register write masks are supported for arithmetic operations only. They cannot be used on texture addressing instructions, with the exception of the version 1_4 instructions, texcrd - ps and texld - ps_2_0 and up.

The default is to write all four color channels.

// All four color channels can be written by explicitly listing them.
mul r0.rgba, t0, v0

// Or, the default mask can be used to write all four channels.
mul r0, t0, v0

The alpha write mask is also referred to as the scalar write mask, because it uses the scalar pipeline.

add r0.a, t1, v1

So this instruction effectively puts the sum of the alpha component of t1 and the alpha component of v1 into r0.a.

The color write mask is used to control writing to the color channels.

// The color write mask is also referred to as the vector write mask,
//   because it uses the vector pipeline.
mul r0.rgb, t0, v0

For version 1_4, destination write masks can be used in any combination as long as the masks are ordered r,g,b,a.

// This example updates the red, blue, and alpha channels.
mov r0.rba, r1

A co-issued instruction allows two potentially different instructions to be issued simultaneously. This is accomplished by executing the instructions in the alpha pipeline and the RGB pipeline.

  mul r0.rgb, t0, v0
+ add r1.a,   t1, c1

The advantage of pairing instructions this way is that it allows different operations to be performed in the vector and scalar pipeline in parallel.

These vertex shader output registers are restricted to the following write masks:

Register Type | Required Write Mask
oFog | no explicit write mask is allowed on this scalar register
oPts | no explicit write mask is allowed on this scalar register
oPos | .xyzw(which is the default)
oT# | combined mask: .x | .xy | .xyz | .xyzw (which is the default)


ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers

Pixel shaders depend on registers to get vertex data, to output pixel data, to hold temporary results during calculations and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 1_X.

Registers hold data for use by the pixel shader. Registers are fully described in the following sections.

  • Register Types describes the four types of registers available and their purposes.
  • Read Port Limit details the restrictions on using multiple registers in a single instruction.
  • Read only Read Write describes which registers can be used for reading, writing, or both.
  • Range details the range of the component data.

Register Types

 |  | Versions |  |  |
Name | Type | 1_1 | 1_2 | 1_3 | 1_4
c# | Constant register | 8 | 8 | 8 | 8
r# | Temporary register | 2 | 2 | 2 | 6
t# | Texture register | 4 | 4 | 4 | 6
v# | Color register | 2 | 2 | 2 | 2 in phase 2
  • Constant registers contain constant data. Data can be loaded into a constant register using IDirect3DDevice9::SetPixelShaderConstantF or it can be defined using def - ps. Constant registers are not usable by texture address instructions. The only exception is the texm3x3spec - ps instruction, which uses a constant register to supply an eye-ray vector.
  • Temporary registers are used to store intermediate results. r0 additionally serves as the pixel shader output. The value in r0 at the end of the shader is the pixel color for the shader.

    Shader validation will fail IDirect3DDevice9::CreatePixelShader on any shader that attempts to read from a temporary register that has not been written by a previous instruction. D3DXAssembleShader will fail similarly, assuming validation is enabled (do not use D3DXSHADER_SKIPVALIDATION).

  • Texture registers

    For pixel shader version 1_1 to 1_3, texture registers contain texture data or texture coordinates. Texture data is loaded into a texture register when a texture is sampled. Texture sampling uses texture coordinates to look up, or sample, a color value at the specified (u,v,w,q) coordinates while taking into account the texture stage state attributes. The texture coordinate data is interpolated from the vertex texture coordinate data and is associated with a specific texture stage. There is a default one-to-one association between texture stage number and texture coordinate declaration order. By default, the first set of texture coordinates defined in the vertex format is associated with texture stage 0.

    For these pixel shader versions, texture registers behave just like temporary registers when used by arithmetic instructions.

    For pixel shader version 1_4, texture registers (t#) contain read-only texture coordinate data. This means that the texture coordinate set and the texture stage number are independent from each other. The texture stage number (from which to sample a texture) is determined by the destination register number (r0 to r5). For the texld instruction, the texture coordinate set is determined by the source register (t0 to t5), so the texture coordinate set can be mapped to any texture stage. In addition, the source register (specifying texture coordinates) for texld can also be a temporary register (r#), in which case the contents of the temporary register are used as texture coordinates.

  • Color registers contain per-pixel color values. The values are obtained by per-pixel iteration of the diffuse and specular color values in the vertex data. For pixel shader version 1_4 shaders, color registers are available only during the second phase.

    If the shade mode is set to D3DSHADE_FLAT, the iteration of both vertex colors (diffuse and specular) is disabled. Regardless of the shade mode, fog will still be iterated by the pipeline if pixel fog is enabled. Keep in mind that fog is applied later in the pipeline than the pixelshader.

    It is common to load the v0 register with the vertex diffuse color data. It is also common to load the v1 register with the vertex specular color data.

    Input color data values are clamped (saturated) to the range 0 through 1 because this is the valid input range for color registers in the pixel shader.

    Pixel shaders have read only access to color registers. The contents of these registers are iterated values, but iteration may be performed at much lower precision than texture coordinates.

Read Port Limit

The read port limit specifies the number of different registers of each register type that can be used as a source register in a single instruction.

 |  | Versions |  |  |
Name | Type | 1_1 | 1_2 | 1_3 | 1_4
c# | Constant register | 2 | 2 | 2 | 2
r# | Temporary register | 2 | 2 | 2 | 3
t# | Texture register | 2 | 3 | 3 | 1
v# | Color register | 2 | 2 | 2 | 2 in phase 2

For example, the color registers for almost all versions have a read port limit of two. This means that a single instruction can use a maximum of two different color registers (v0 and v1 for instance) as source registers. This example shows two color registers being used in the same instruction:

mad r0, v1, c2, v0

Read-only, Read/Write

The register types are identified according to read-only (RO) capability or read/write (RW) capability in the following table. Read-only registers can be used only as source registers in an instruction; they can never be used as a destination register.

 |  | Versions |  |  |
Name | Type | 1_1 | 1_2 | 1_3 | 1_4
c# | Constant register | RO | RO | RO | RO
r# | Temporary register | RW | RW | RW | RW
t# | Texture register | RW | RW | RW | See following note
v# | Color register | RO | RO | RO | RO

Registers that are RW capable can be used to store intermediate results. This includes the temporary registers and texture registers for some of the shader versions.

Note

  • For pixel shader version 1_4, texture registers are RO for texture addressing instructions, and texture registers can be neither read from nor written to by arithmetic instructions. Also, because texture registers have become texture coordinate registers, having RO access is not a regression of previous functionality.

Range

The range is the maximum and minimum register data value. The ranges vary based on the type of register. The ranges for some of the registers can be queried from the device caps using IDirect3D9::GetDeviceCaps.

Name | Type | Range | Versions
c# | Constant register | -1 to +1 | All versions
r# | Temporary register | - PixelShader1xMaxValue to + PixelShader1xMaxValue | All versions
t# | Texture register | - MaxTextureRepeat to + MaxTextureRepeat | All versions
v# | Color register | 0 to 1 | All versions

Early pixel shader hardware represents data in registers using a fixed-point number. This limits precision to a maximum of approximately eight bits for the fractional part of a number. Keep this in mind when designing a shader.

For pixel shader version 1_1 to 1_3, MaxTextureRepeat must be a minimum of one. For 1_4, MaxTextureRepeat must be a minimum of eight.

See D3DCAPS9 for more information about PixelShader1xMaxValue.


ps_2_0 Registers

Pixel shaders depend on registers to get vertex data, to output pixel data, to hold temporary results during calculations, and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 2_x.

Input Register Types

Register | Name | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Color Register | 2 | R | 1 | Unlimited | 4 | N | Partial(0001). See note 4 | Y
r# | Temporary Register | See note 1 | R/W | 3 | Unlimited | 4 | N | None | N
c# | Constant Float Register | 32 | R | 1 | 2 | 4 | N | 0000 | N
i# | Constant Integer Register | 16 | See note 2 | 1 | 1 | 4 | N | 0000 | N
b# | Constant Boolean Register | 16 | See note 2 | 1 | 1 | 1 | N | FALSE | N
p0 | Predicate Register | 1 | See note 2 | 1 | 1 | 1 | N | None | Y
s# | Sampler | 16 | See note 3 | 1 | 1 | 4 | N | See note 5 | Y
t# | Texture Coordinate Register | 8 | R | 1 | 1 | 4 | N | None | Y

Notes:

  1. 12 min/32 max: The number of r# registers is determined by D3DPSHADERCAPS2_0.NumTemps (which ranges from 12 to 32).
  2. Only usable by a flow control instruction.
  3. Only usable by a texture sampling instruction.
  4. partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  5. Defaults for sampler lookups exist, but values depend on texture format.

The number of readports is the number of different registers (for each register type) that can be read in a single instruction.

Output Register Types

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oC# | Output Color Register | See Multiple-element Textures (Direct3D 9) | W | 4 | N | None | N
oDepth | Output Depth Register | 1 | W | 1 | N | None | N


ps_2_x Registers

Pixel shaders depend on registers to get vertex data, to output pixel data, to hold temporary results during calculations, and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 2_x.

Input Register Types

Register | Name | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Color Register | 2 | R | 1 | Unlimited | 4 | N | Partial(0001). See note 4 | Y
r# | Temporary Register | See note 1 | R/W | 3 | Unlimited | 4 | N | None | N
c# | Constant Float Register | 32 | R | 1 | 2 | 4 | N | 0000 | N
i# | Constant Integer Register | 16 | See note 2 | 1 | 1 | 4 | N | 0000 | N
b# | Constant Boolean Register | 16 | See note 2 | 1 | 1 | 1 | N | FALSE | N
p0 | Predicate Register | 1 | See note 2 | 1 | 1 | 1 | N | None | Y
s# | Sampler | 16 | See note 3 | 1 | 1 | 4 | N | See note 5 | Y
t# | Texture Coordinate Register | 8 | R | 1 | 1 | 4 | N | None | Y

Notes:

  1. 12 min/32 max: The number of r# registers is determined by D3DPSHADERCAPS2_0.NumTemps (which ranges from 12 to 32).
  2. Only usable by a flow control instruction.
  3. Only usable by a texture sampling instruction.
  4. partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  5. Defaults for sampler lookups exist, but values depend on texture format.

The number of readports is the number of different registers (for each register type) that can be read in a single instruction.

Output Register Types

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oC# | Output Color Register | See Multiple-element Textures (Direct3D 9) | W | 4 | N | None | N
oDepth | Output Depth Register | 1 | W | 1 | N | None | N


ps_3_0 Registers

Pixel shaders depend on registers to get vertex data, to output pixel data, to hold temporary results during calculations, and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 3_0.

New Registers

Input Register

The Input Registers (v#) are now fully floating point and the Texture Coordinate Registers (t#) have been consolidated into it. The dcl_usage - ps at the top of the shader is used to describe what is containted in a particular Input_Register. A semantic for the pixel types is introduced (analogous to the vertex side) for this model. No clamping is performed when the input registers are defined as colors (like texture coordinates). The evaluation of the registers defined as color differs from the texture coordinates when multisampling.

Face Register

The face register (vFace) is new for this model. This is a floating point scalar register that will eventually contain the primitive area. In ps_3_0, however, only the sign of this register is valid. Hence, if the value is less than zero (the sign bit is set negative) the primitive is the back face (the area is negative, counterclockwise). Therefore, in ps_3_0 it only makes sense to compare this register against 0 (> 0 or < 0). Inside the pixel shader, the application can make a decision as to which lighting technique to use. Two-sided lighting can be achieved this way. This register requires a declaration, so undeclared usage will be flagged as an error. For lines and point primitives, this register is undefined. The face register can only be used as condition with the following instructions: setp_comp - ps, if_comp - ps, or break_comp - ps.

Loop Counter Register

The Loop Counter Register (aL) is new for this model. It automatically gets incremented in each execution of the loop - ps/endloop - ps block. It can be used in the block for relative addressing if needed. It is invalid to use Loop Counter Register outside the loop.

Position Register

The Position Register (vPos) is new for this model. It contains the current pixels (x, y) in the corresponding channels. The (z, w) channels are undefined. This register requires a declaration, so undeclared usage will be flagged as an error. When declared, this register must have exactly one of the following masks: .x, .y, .xy.

Input Register Types

Register | Name | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Register | 10 | R | 1 | Unlimited | 4 | aL | None | Yes
r# | Temporary Register | 32 | R/W | 3 | Unlimited | 4 | No | None | No
c# | Constant Float Register | 224 | R | 1 | Unlimited | 4 | No | 0000 | No
i# | Constant Integer Register | 16 | R | 1 | 1 | 4 | No | 0000 | No
b# | Constant Boolean Register | 16 | R | 1 | 1 | 1 | No | FALSE | No
p0 | Predicate Register | 1 | R | 1 | 1 | 1 | No | None | No
s# | Sampler | 16 | R | 1 | 1 | 4 | No | See note 1 | Yes
vFace | Face_Register | 1 | R | 1 | Unlimited | 1 | No | None | Yes
vPos | Position_Register | 1 | R | 1 | Unlimited | 4 | No | None | Yes
aL | Loop_Counter_Register | 1 | R | 1 | Unlimited | 1 | n/a | None | No

Notes:

  1. Defaults for sampler lookups exist, but values depend on texture format.

The number of readports is the number of different registers (for each register type) that can be read in a single instruction.

Output Register Types

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oC# | Output Color Register | See Multiple-element Textures (Direct3D 9) | W | 4 | No | None | No
oDepth | Output Depth Register | 1 | W | 1 | No | None | No


Input Color Register

Pixel shader input register containing vertex color.

Syntax

dcl v#.writeMask

where:

  • dcl - ps is a register declaration instruction.
  • v is an input register and # is the register number. The number of registers allowed is determined by the shader version.
  • writeMask determines which components (up to four) are written. Valid components are: (x,y,z,w) or (r,g,b,a).

Remarks

Color registers are read-only registers. Each register contains four-component RGBA values iterated from input vertices. They have lower precision than most registers, guaranteed to have 8 bits of unsigned data in the range (0, +1). You cannot use more than one in a single instruction.

See Also

ps_1_1__ps_1_2__ps_1_3__ps_1_4 Registers, ps_2_0 Registers, ps_2_x Registers, ps_3_0 Registers


Constant Boolean Register

This register is a collection of bits used in static flow control instructions (for example, if bool - ps - else - ps - endif - ps). There are 16 of them, therefore, a shader can have 16 independent branch conditions. They can be set using defi - ps or IDirect3DDevice9::SetPixelShaderConstantI.

The behavior of shader constants has changed between Direct3D 8 and Direct3D 9.

  • For Direct3D 9, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the APIs SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For Direct3D 8, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.
Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Constant Boolean Register |  |  |  |  |  |  | x | x | x


Constant Float Register

Pixel shader input register for a 4D floating-point constant.

They can be set using def - ps or IDirect3DDevice9::SetPixelShaderConstantF.

The behavior of shader constants has changed between Direct3D 8 and Direct3D 9.

  • For Direct3D 9, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the APIs SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For Direct3D 8, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.

Examples

Here is an example declaring two floating-point constants within a shader.

def c40, 0.0f,0.0f,0.0f,0.0f;

These constants are loaded every time IDirect3DDevice9::SetPixelShader is called.

If you are setting constant values with the API, there is no shader declaration required.


Constant Integer Register

Constant integer registers are used only by loop - ps and rep - ps.

They can be set using def - ps or IDirect3DDevice9::SetPixelShaderConstantI.

When used as an argument to the loop - ps instruction:

  • .x is the iteration count. (rep - ps uses only this component).
  • .y is the initial value for the loop counter.
  • .z is the increment step for the loop counter.
Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Constant Integer Register |  |  |  |  |  |  | x | x | x

The behavior of shader constants has changed between Direct3D 8 and Direct3D 9.

  • For Direct3D 9, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the APIs SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For Direct3D 8, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.


Loop Counter Register

The only register in this bank is the current loop counter (aL) register. It automatically gets incremented in each execution of the loop - ps/endloop - ps block. So it can be used in the block for relative addressing if needed and is invalid to use it outside the loop.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Loop Counter Register |  |  |  |  |  |  |  | x | x


Predicate Register

This pixel shader output register contains a per-channel boolean value.

Remarks

A predicate register is supported by the following versions:

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
predicate register |  |  |  |  |  |  | x | x | x

Here are the register properties.

Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
Predicate(p) | 1 | R/W | 1 | 1 | 4 | N/A | None | N

The predicate register can be modified with setp_comp - ps. There are no default values for this register; an application needs to set the register before it is used.


Sampler

A sampler is a input pseudo-register for a pixel shader, which is used to identify the sampling stage. There are 16 pixel shader sampling stage registers: s0 to s15. Therefore, up to 16 texture surfaces can be read in a single shader pass. The instructions that use a sampler register are texld and texldp.

Remarks

Sampler must be declared before use with the dcl_samplerType - ps instruction.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Sampler |  |  |  |  | x | x | x | x | x

Samplers are pseudo registers because you cannot directly read or write to them.

A sampling unit corresponds to the texture sampling stage, encapsulating the sampling-specific state provided by IDirect3DDevice9::SetSamplerState. Each sampler uniquely identifies a single texture surface, which is set to the corresponding sampler using the IDirect3DDevice9::SetTexture. However, the same texture surface can be set at multiple samplers.

At draw time, a texture cannot be simultaneously set as a render target and a texture at a stage.

A sampler might appear as the only argument in the texture load instruction: texldl - ps.

In ps_3_0, if a sampler is used, it needs to be declared at the beginning of the shader program using the dcl_samplerType - ps instruction.

Sampling a texture with a higher dimension than is present in the texture coordinates is illegal. Sampling a texture with a lower dimension than is present in the texture coordinates will ignore the extra texture coordinates.


Temporary Register

Pixel shader input temporary registers are used to hold intermediate results.

Remarks

Syntax

no declaration is required

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Temporary Register |  |  |  |  | x | x | x | x | x
  • There are 12 pixel-shader temporary registers: r0 to r11.
  • These registers are used for storing intermediate results during computations.
  • If a temporary register uses components that are not defined in previous code, shader validation will fail.
  • These are at least floating-point precision.
  • A maximum of three can be used in a single instruction.


Texture Coordinate Register

Pixel shader input register containing texture coordinates.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Texture Coordinate Register |  |  |  |  | x | x | x | x | x

A texture coordinate register contains texture coordinate data. Before a texture coordinate register is used, it must be declared by a pixel shader declaration. For details about how to declare a texture register, see dcl - ps.

In addition, here are some other properties of texture coordinate registers.

  • There are eight pixel-shader texture coordinate registers, t0 to t7.
  • These are read-only registers.
  • They contain four-component RGBA values iterated from input vertices.
  • They contain high precision, high dynamic range data values interpolated from the vertex data. Values are generated with perspective-correct interpolation. Data is floating-point precision, and is signed.
  • There is a maximum of one in a single instruction.
  • Multiple reads of a texture coordinate register within a shader must use identical Destination Register Write Mask.
  • The optional partial precision modifier [_pp] applies to dependent reads. This is because partial precision affects arithmetic operations involving the texture coordinate register. It will not affect the precision of texture address instructions because it does not affect the texture coordinate iterators.


Output Color Register

The pixel shader color output registers (oC#) are write-only registers that output results to multiple render targets.

Syntax

oC#

Where:

Name | Description
oC0 | render target #0
oC1 | render target #1
oC2 | render target #2
oC3 | render target #3

Remarks

  • If oCn is written but there is no corresponding render target, then this write to oCn is ignored.
  • The render states D3DRS_COLORWRITEENABLE, D3DRS_COLORWRITEENABLE1, D3DRS_COLORWRITEENABLE2 and D3DRS_COLORWRITEENABLE3 determine which components of oCn ultimately get written to the render target (after blend, if applicable). If the shader writes some but not all of the components defined by the D3DRS_COLORWRITEENABLE* render states for a given oCn register, then the unwritten channels produce undefined values in the corresponding render target. If none of the components of an oCn are written, the corresponding render target must not be updated at all (as stated above), so the D3DRS_COLORWRITEENABLE* render states do not apply.

Shader Model 2 Restrictions

  • oCn can only be written with the mov - ps instruction.
  • oC0 must be always written in the shader.
  • No source swizzle (except .xyzw = default swizzle) or source modifier is allowed when writing to any oCn.
  • No destination write mask (except .xyzw = default mask) or instruction modifier is allowed when writing to any oCn.
  • If oCn is written, then oC0 - oCn-1 must also be written. For example, to write to oC2, you must also write to oC0 and oC1.
  • At most one write to any oC# per shader is allowed.
  • For ps_2_x and ps_3_0, you cannot write to oC# and oD# registers within dynamic flow control or predication (writes to oC# inside static flow control is fine).

Shader Model 3 Restrictions

  • For ps_3_0, output registers oC# and oD# can be written any number of times. The output of the pixel shader comes from the contents of the output registers at the end of shader execution. If a write to an output register does not happen, perhaps due to flow control or if the shader just did not write it, the corresponding rendertarget is also not updated. If a subset of the channels in an output register are written, then undefined values will be written to the remaining channels.
  • For ps_3_0, the oC# registers can be written with any writemasks.
  • For ps_2_x and ps_3_0, you cannot write to oC# and oD# registers within dynamic flow control or predication (writes to oC# inside static flow control is fine).
  • You may not perform any gradient calculations (or operations that implicitly invoke gradient calculations such as texld - ps_2_0 and up, texldb - ps, texldp - ps) inside of flow control statements whose branching conditions vary on a per-primitive basis (ie: dynamic flow control instructions). Instruction predication is not considered dynamic flow control.

See Also

Multiple Render Targets (Direct3D 9)


Output Depth Register

The pixel shader output depth register (oDepth) is a write-only scalar register with the range [0..1] that returns a new depth value for a depth test against the depth-stencil buffer.

Syntax

oDepth

Where:

Name | Description
oDepth | New depth value for a depth test against the depth-stencil buffer

Remarks

It is important to be aware that writing to oDepth causes the loss of any hardware-specific depth buffer optimization algorithms (i.e. hierarchical Z) which accelerate depth test performance.

Replicate source swizzle (.x | .y | .z | .w) is required when writing to oDepth. Explicit write masks are not allowed.

Writing to the oDepth register replaces the interpolated depth value (and ignores any depth bias/slopescale renderstates). If no depth buffer has been created or attached to the device, then write to oDepth is ignored.

If you are multisampling and write to oDepth, since the pixel shader only runs once per pixel, your depth value is replicated for all covered sub-sample locations. The depth test still happens per-sample, but you don't have a per-sample depth value going into the comparison from the pixel shader like you would have if you didn't write oDepth.

If an application has a w-buffer set as its depth buffer, then it needs to take that into account while writing to oDepth. It potentially needs to send w-range information to the pixel shader and compute the w-range to scale the w-values written out to oDepth.

ps_2_0 and ps_2_x Restrictions
  • oDepth can only be written with the mov - ps instruction and can only be done once.
  • No source modifier is allowed when writing to oDepth.
  • No instruction modifier is allowed when writing to oDepth.
  • No writing to oDepth from within a flow control construct, or when using predication.
ps_3_0 Restrictions
  • For ps_3_0, output registers oC# and oD# can be written any number of times. The output of the pixel shader comes from the contents of the output registers at the end of shader execution. If a write to an output register does not happen, perhaps due to flow control or if the shader just did not write it, the corresponding render target is also not updated. If a subset of the channels in an output register are written, then undefined values will be written to the remaining channels.
  • You can write to oDepth within flow control or predication as long as all possible paths eventually write into the register.
  • You may not perform any gradient calculations (or operations that implicitly invoke gradient calculations such as texld - ps_2_0 and up, texldb - ps, texldp - ps) inside of flow control statements whose branching conditions vary on a per-primitive basis (ie: dynamic flow control instructions). Instruction predication is not considered dynamic flow control.


Software Shaders

Software shaders are implemented to allow development of shaders without underlying hardware support. They support the full feature set. Because they are implemented in software, they will not produce the best performance.

Version | Feature Set | Requirements
vs_2_sw | All the features of vs_2_x | Only supported by software vertex processing and a reference device.
vs_3_sw | All the features of vs_3_0 | Only supported by software vertex processing and a reference device.
ps_2_sw | All the features of ps_2_x | Only supported by a reference device.
ps_3_sw | All the features of ps_3_0 | Only supported by a reference device.

Some validations are relaxed for software shaders. This is useful for debugging and prototyping purposes. The following validations are relaxed: (all other validations remain the same)

Validation type | Relaxation
Instruction Counts: | This is relaxed for vs_2_sw, vs_3_sw and ps_2_sw, ps_3_sw. Unlimited instructions are allowed.
Float Constant Counts: | This is relaxed for vs_2_sw, vs_3_sw and ps_2_sw, ps_3_sw. Up to 8192 constants are allowed.
Integer Constant Counts: | This is relaxed for vs_2_sw, vs_3_sw and ps_2_sw, ps_3_sw. Up to 2048 constants are allowed.
Boolean Constant Counts: | This is relaxed for vs_2_sw, vs_3_sw and ps_2_sw, ps_3_sw. Up to 2048 constants are allowed.
Dependent-read depth: | This is relaxed for ps_2_sw. Like in vs_3_0 and ps_3_0, unlimited dependent reads are allowed.
Number of flow control instructions and labels: | This is relaxed for vs_2_sw. Unlimited flow control instructions and upto 2048 labels are allowed.
Loop count/start/step: | These are relaxed for vs_2_sw, vs_3_sw, ps_2_sw and ps_3_sw. Iteration start and interation step size for rep and loop instructions are 32-bit signed intergers. Interation count can be up to MAX_INT/64.
Read-port limits: | vs_2_sw, vs_3_sw, ps_2_sw and ps_3_sw have no read-port limit.
Number of interpolators: | There are 16 Registers - vs_3_0 (o#) in vs_3_sw and 10 ps_3_0 Registers (v#) for ps_3_sw.


X File Reference

This section contains reference information for the API elements used to work with DirectX .x files. These topics are new with the DirectX SDK Update (Summer 2004).

  • D3DX X File Interfaces
  • D3DX X File Functions
  • D3DX X File Structures
  • D3DX X File Constants

Templates are described in Templates.

Interfaces and functions in the Dxfile.h header are available to support legacy applications. See X File Reference (Legacy).


D3DX X File Interfaces

This section contains reference information for the COM interfaces used to read to and write from .x files.

  • ID3DXFile
  • ID3DXFileData
  • ID3DXFileEnumObject
  • ID3DXFileSaveData
  • ID3DXFileSaveObject

The following tables illustrate the relationship between the .x file interfaces.

Interface | Derives from | Derives from
 | IDirectXFile | IUnknown
IDirectXFileBinary | IDirectXFileObject | IUnknown
IDirectXFileData | IDirectXFileObject | IUnknown
IDirectXFileReference | IDirectXFileObject | IUnknown
 | IDirectXFileSaveObject | IUnknown


ID3DXFile

Applications use the methods of the ID3DXFile interface to create instances of the ID3DXFileEnumObject and ID3DXFileSaveObject interfaces, and to register templates.

ID3DXFile Members

Method | Description
ID3DXFile::CreateEnumObject | Creates an enumerator object that will read a .x file.
ID3DXFile::CreateSaveObject | Creates a save object that will be used to save data to a .x file.
ID3DXFile::RegisterEnumTemplates | Registers custom templates, given an ID3DXFileEnumObject enumeration object.
ID3DXFile::RegisterTemplates | Registers custom templates.

Remarks

An ID3DXFile object also contains a local template store. This local storage may be added to only with the ID3DXFile::RegisterEnumTemplates and ID3DXFile::RegisterTemplates methods.

ID3DXFileEnumObject and ID3DXFileSaveObject objects created with ID3DXFile::CreateEnumObject and ID3DXFile::CreateSaveObject also utilize the template store of the parent ID3DXFile object.

The ID3DXFile interface is obtained by calling the D3DXFileCreate function.

The globally unique identifier (GUID) for the ID3DXFile interface is IID_ID3DXFile.

The LPD3DXFILE type is defined as a pointer to the ID3DXFile interface.

typedef interface ID3DXFile *LPD3DXFILE;

Requirements

Header: Declared in D3DX9Xof.h.

Library: Use D3dx9.lib.


ID3DXFile::CreateEnumObject

Creates an enumerator object that will read a .x file.

HRESULT CreateEnumObject(
  LPCVOID pvSource,
  D3DXF_FILELOADOPTIONS loadflags,
  ID3DXFileEnumObject ** ppEnumObj
);

Parameters

pvSource
[out] The data source. Either:
  • A file name
  • A D3DXF_FILELOADMEMORY structure
  • A D3DXF_FILELOADRESOURCE structure
Depending on the value of loadflags.
loadflags
[in] Value that specifies the source of the data. This value can be one of the D3DXF_FILELOADOPTIONS flags.
ppEnumObj
[out] Address of a pointer to an ID3DXFileEnumObject interface, representing the created enumerator object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DXFERR_BADVALUE, D3DXFERR_PARSEERROR.

Remarks

After using this method, use one of the ID3DXFileEnumObject methods to retrieve a data object.

Requirements

Header: Declared in D3DX9Xof.h.

See Also

ID3DXFileEnumObject


ID3DXFile::CreateSaveObject

Creates a save object that will be used to save data to a .x file.

HRESULT CreateSaveObject(
  LPCVOID pData,
  D3DXF_FILESAVEOPTIONS flags,
  D3DXF_FILEFORMAT dwFileFormat,
  ID3DXFileSaveObject ** ppSaveObj
);

Parameters

pData
[in] Pointer to the name of the file to use for saving data.
flags
[in] Value that specifies the name of the file to which data is to be saved. This value can be one of the File Save Options flags.
dwFileFormat
[in] Indicates the format to use when saving the .x file. This value can be one of the File Formats flags. For more information, see Remarks.
ppSaveObj
[out] Address of a pointer to an ID3DXFileSaveObject interface, representing the created save object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DXFERR_BADVALUE, D3DXFERR_PARSEERROR.

Remarks

After using this method, use methods of the ID3DXFileSaveObject interface to create data objects and to save templates or data.

For the saved file format dwFileFormat, one of the binary, legacy binary, or text flags in File Formats must be specified. The file can be compressed by using the optional D3DXF_FILEFORMAT_COMPRESSED flag.

The file format values can be combined in a logical OR to create compressed text or compressed binary files. If you indicate that the file format should be text and compressed, the file will be written out first as text and then compressed. However, compressed text files are not as efficient as binary text files; in most cases, therefore, you will want to indicate binary and compressed.

Requirements

Header: Declared in D3DX9Xof.h.

See Also

ID3DXFileSaveObject


ID3DXFile::RegisterEnumTemplates

Registers custom templates, given an ID3DXFileEnumObject enumeration object.

HRESULT RegisterEnumTemplates(
  ID3DXFileEnumObject * pEnum
);

Parameters

pEnum
[in] Pointer to an ID3DXFileEnumObject enumeration object that contains templates.

Return Values

If the method succeeds, the return value is S_OK .

If the method fails, the following value will be returned:

D3DXFERR_BADVALUE.

Remarks

When this method is called, it copies templates stored with the ID3DXFileEnumObject, representing the file, to the local template store of the ID3DXFile object.

If an ID3DXFileEnumObject pointer is not available, call the ID3DXFile::RegisterTemplates method instead.

Requirements

Header: Declared in D3DX9Xof.h.

See Also

ID3DXFile::RegisterTemplates


ID3DXFile::RegisterTemplates

Registers custom templates.

HRESULT RegisterTemplates(
  LPCVOID pvData,
  SIZE_T cbSize
);

Parameters

pvData
[in] Pointer to a buffer consisting of a .x file in text or binary format that contains templates.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DXFERR_BADVALUE, D3DXFERR_PARSEERROR.

Remarks

The following code fragment provides an example call to RegisterTemplates And example contents for the buffer to which pvData points.

#define XSKINEXP_TEMPLATES \
    "xof 0303txt 0032\
    template XSkinMeshHeader \
    { \
        <3CF169CE-FF7C-44ab-93C0-F78F62D172E2> \
        WORD nMaxSkinWeightsPerVertex; \
        WORD nMaxSkinWeightsPerFace; \
        WORD nBones; \
    } \
    template VertexDuplicationIndices \
    { \
        <B8D65549-D7C9-4995-89CF-53A9A8B031E3> \
        DWORD nIndices; \
        DWORD nOriginalVertices; \
        array DWORD indices[nIndices]; \
    } \
    template SkinWeights \
    { \
        <6F0D123B-BAD2-4167-A0D0-80224F25FABB> \
        STRING transformNodeName;\
        DWORD nWeights; \
        array DWORD vertexIndices[nWeights]; \
        array float weights[nWeights]; \
        Matrix4x4 matrixOffset; \
    }"
.
.
.

LPD3DXFILE pD3DXFile = NULL;

if ( FAILED
        (hr = pD3DXFile->RegisterTemplates(
            (LPVOID)XSKINEXP_TEMPLATES,
            sizeof( XSKINEXP_TEMPLATES ) - 1 ) ) )
goto End;

All templates must specify a name and a UUID.

This method calls the ID3DXFile::RegisterEnumTemplates method, obtaining an ID3DXFileEnumObject interface pointer by calling ID3DXFile::CreateEnumObject with pvData as the first parameter.

Requirements

Header: Declared in D3DX9Xof.h.

See Also

ID3DXFile::RegisterEnumTemplates


ID3DXFileData

Applications use the methods of the ID3DXFileData interface to build or to access the immediate hierarchy of the data object. Template restrictions determine the hierarchy.

ID3DXFileData Members

Method | Description
ID3DXFileData::GetChild | Retrieves a child object in this file data object.
ID3DXFileData::GetChildren | Retrieves the number of children in this file data object.
ID3DXFileData::GetEnum | Retrieves the enumeration object in this file data object.
ID3DXFileData::GetId | Retrieves the GUID of this file data object.
ID3DXFileData::GetName | Retrieves the name of this file data object.
ID3DXFileData::GetType | Retrieves the template ID in this file data object.
ID3DXFileData::IsReference | Indicates whether this file data object is a reference object that points to another child data object.
ID3DXFileData::Lock | Accesses the .x file data.
ID3DXFileData::Unlock | Ends the lifespan of the ID3DXFileData::Lock pointer.

Remarks

Data types allowed by the template are called optional members. The optional members are not required, but an object might miss important information without them. These optional members are saved as children of the data object. A child can be another data object or a reference to an earlier data object.

The GUID for the ID3DXFileData interface is IID_ID3DXFileData.

The LPD3DXFILEDATA type is defined as a pointer to this interface.

typedef interface ID3DXFileData *LPD3DXFILEDATA;

Requirements

Header: Declared in D3DX9Xof.h.

Library: Use D3dx9.lib.


ID3DXFileData::GetChild

Retrieves a child object in this file data object.

HRESULT GetChild(
  SIZE_T uiChild,
  ID3DXFileData ** ppChild
);

Parameters

uiChild
[in] ID of the child object to retrieve.
ppChild
[in] Address of a pointer to receive the child object's interface pointer.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following values: D3DXFERR_BADVALUE, D3DXFERR_NOMOREOBJECTS.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileData::GetChildren

Retrieves the number of children in this file data object.

HRESULT GetChildren(
  SIZE_T * puiChildren
);

Parameters

puiChildren
[in] Address of a pointer to receive the number of children in this file data object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileData::GetEnum

Retrieves the enumeration object in this file data object.

HRESULT GetEnum(
  ID3DXFileEnumObject ** ppObj
);

Parameters

ppObj
[in] Address of a pointer to receive the enumeration object in this file data object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileData::GetId

Retrieves the GUID of this file data object.

HRESULT GetId(
  LPGUID pId
);

Parameters

pId
[out] Pointer to a GUID to receive the ID of this file data object. If the file data object has no ID, the returned parameter value will be GUID_NULL.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileData::GetName

Retrieves the name of this file data object.

HRESULT GetName(
  LPSTR szName,
  SIZE_T * puiSize
);

Parameters

szName
[in] Address of a pointer to receive the name of this file data object. If this parameter is NULL, then puiSize will return the size of the string. If szName points to valid memory, the name of this file data object will be copied into szName up to the number of characters given by puiSize.
puiSize
[in, out] Pointer to the size of the string that represents the name of this file data object. This parameter can be NULL if szName provides a reference to the name. This parameter will return the size of the string if szName is NULL.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Remarks

For this method to succeed, either szName or puiSize must be non-NULL.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileData::GetType

Retrieves the template ID in this file data object.

HRESULT GetType(
  CONST GUID * pType
);

Parameters

pType
[in] Pointer to the GUID representing the template in this file data object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileData::IsReference

Indicates whether this file data object is a reference object that points to another child data object.

BOOL IsReference();

Parameters

None.

Return Values

Returns TRUE if the file data object is a reference object; returns FALSE otherwise.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileData::Lock

Accesses the .x file data.

HRESULT Lock(
  SIZE_T * pSize,
  CONST VOID ** ppData
);

Parameters

pSize
[in] Pointer to the size of the .x file data.
ppData
[in] Address of a pointer to receive the ID3DXFileData file data object's interface pointer. See Remarks.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Remarks

The ppData pointer is only valid during a ID3DXFileData::Lock ... ID3DXFileData::Unlock sequence. You can make multiple lock calls. However, you must ensure that the number of lock calls matches the number of unlock calls.

Because file data is not guaranteed to be aligned properly with byte boundaries, you should access ppData with UNALIGNED pointers.

Returned parameter values are not guaranteed to be valid due to possible file corruption; therefore, your code should verify the returned parameter values.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileData::Unlock

Ends the lifespan of the ppData pointer returned by ID3DXFileData::Lock.

BOOL Unlock();

Parameters

None.

Return Values

The return value is S_OK.

Remarks

You must ensure that the number of ID3DXFileData::Lock calls matches the number of ID3DXFileData::Unlock calls. After calling Unlock, the ppData pointer returned by ID3DXFileData::Lock should no longer be used.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileEnumObject

Applications use the methods of the ID3DXFileEnumObject interface to cycle through the child file data objects in the file and to retrieve a child object by its globally unique identifier (GUID) or by its name.

ID3DXFileEnumObject Members

Method | Description
ID3DXFileEnumObject::GetChild | Retrieves a child object in this file data object.
ID3DXFileEnumObject::GetChildren | Retrieves the number of child objects in this file data object.
ID3DXFileEnumObject::GetDataObjectById | Retrieves the data object that has the specified GUID.
ID3DXFileEnumObject::GetDataObjectByName | Retrieves the data object that has the specified name.
ID3DXFileEnumObject::GetFile | Retrieves the ID3DXFile object.

Remarks

The GUID for the ID3DXFileEnumObject interface is IID_ID3DXFileEnumObject.

The LPD3DXFILEENUMOBJECT type is defined as a pointer to this interface.

typedef interface ID3DXFileEnumObject *LPD3DXFILEENUMOBJECT;

Requirements

Header: Declared in D3DX9Xof.h.

Library: Use D3dx9.lib.


ID3DXFileEnumObject::GetChild

Retrieves a child object in this file data object.

HRESULT GetChild(
  SIZE_T id,
  ID3DXFileData ** ppObj
);

Parameters

id
[in] ID of the child object to retrieve.
ppObj
[out] Address of a pointer to receive the child object's interface pointer.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DXFERR_BADVALUE, D3DXFERR_NOMOREOBJECTS.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileEnumObject::GetChildren

Retrieves the number of child objects in this file data object.

HRESULT GetChildren(
  SIZE_T * puiChildren
);

Parameters

puiChildren
[in] Address of a pointer to receive the number of child objects in this file data object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileEnumObject::GetDataObjectById

Retrieves the data object that has the specified GUID.

HRESULT GetDataObjectById(
  REFGUID rguid,
  LPD3DXFILEDATA * ppDataObj
);

Parameters

rguid
[in] Reference to the requested GUID.
ppDataObj
[out] Address of a pointer to an ID3DXFileData interface, representing the returned file data object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following:DXFILEERR_BADVALUE, DXFILEERR_NOTFOUND.

Remarks

Obtain the GUID rguid of the current file data object with the ID3DXFileData::GetId method.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileEnumObject::GetDataObjectByName

Retrieves the data object that has the specified name.

HRESULT GetDataObjectByName(
  LPCSTR szName,
  ID3DXFileData ** ppObj
);

Parameters

szName
[in] Pointer to the requested name.
ppObj
[out] Address of a pointer to an ID3DXFileData interface, representing the returned file data object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following:DXFILEERR_BADVALUE, DXFILEERR_NOTFOUND.

Remarks

Obtain the name szName of the current file data object with the ID3DXFileData::GetName method.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileEnumObject::GetFile

Retrieves the ID3DXFile object.

HRESULT GetFile(
  ID3DXFile ** ppFile
);

Parameters

ppFile
[out] Address of a pointer to an ID3DXFile interface, representing the returned object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileSaveData

Applications use the methods of the ID3DXFileSaveData interface to add data objects as children of a .x file data node.

ID3DXFileSaveData Members

Method | Description
ID3DXFileSaveData::AddDataObject | Adds a data object as a child of the ID3DXFileSaveData file data node.
ID3DXFileSaveData::AddDataReference | Adds a data reference as a child of this ID3DXFileSaveData file data node. The data reference points to a file data object.
ID3DXFileSaveData::GetId | Retrieves the GUID of this ID3DXFileSaveData file data node.
ID3DXFileSaveData::GetName | Retrieves the name of this ID3DXFileSaveData file data node.
ID3DXFileSaveData::GetSave | Retrieves a pointer to this ID3DXFileSaveObject file data node.
ID3DXFileSaveData::GetType | Retrieves the template ID of this file data node.

Remarks

The GUID for the ID3DXFileSaveObject interface is IID_ID3DXFileSaveObject.

The LPD3DXFileSaveData type is defined as a pointer to this interface.

typedef interface ID3DXFileSaveData *LPD3DXFILESAVEDATA;

Requirements

Header: Declared in D3DX9Xof.h.

Library: Use D3dx9.lib.


ID3DXFileSaveData::AddDataObject

Adds a data object as a child of the ID3DXFileSaveData file data node.

HRESULT AddDataObject(
  REFGUID rguidTemplate,
  LPCSTR szName,
  CONST GUID * pId,
  SIZE_T cbSize,
  LPCVOID pvData,
  ID3DXFileSaveData ** ppObj
);

Parameters

rguidTemplate
[in] GUID representing the data object's template.
szName
[in] Pointer to the name of the data object to add. Specify NULL if the object does not have a name.
pId
[in] Pointer to a GUID representing the data object. The data object must have been registered with ID3DXFile::RegisterTemplates or ID3DXFile::RegisterEnumTemplates. Specify NULL if the object does not have a GUID.
cbSize
[in] Size of the data object, in bytes.
pvData
[in] Pointer to a buffer containing all required data in the data object.
ppObj
[in, retval] Address of a pointer to an ID3DXFileSaveData interface, representing the file data node to which the data object will be added.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DXFERR_BADOBJECT, D3DXFERR_BADVALUE, E_OUTOFMEMORY.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileSaveData::AddDataReference

Adds a data reference as a child of this ID3DXFileSaveData file data node. The data reference points to a file data object.

HRESULT AddDataReference(
  LPCSTR szName,
  CONST GUID * pId
);

Parameters

szName
[in] Pointer to the name of the data object to add by reference. Specify NULL if the data object does not have a name.
pId
[in] Pointer to a GUID representing the data object to add by reference. If NULL, a reference will be added that points to the data object with the name given by szName.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DXFERR_BADOBJECT, D3DXFERR_BADVALUE, E_OUTOFMEMORY.

Remarks

The file data object being referenced must have either a name or a GUID. The file data object must also derive from a different parent ID3DXFileSaveData object.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileSaveData::GetId

Retrieves the GUID of this ID3DXFileSaveData file data node.

HRESULT GetId(
  LPGUID pId
);

Parameters

pId
[out] Pointer to a GUID to receive the ID of this file data node. If the object has no ID, the returned parameter value will be GUID_NULL.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileSaveData::GetName

Retrieves the name of this ID3DXFileSaveData file data node.

HRESULT GetName(
  LPSTR szName,
  SIZE_T * puiSize
);

Parameters

szName
[in] Address of a pointer to receive the name of this file data node. If this parameter is NULL, then puiSize will return the size of the string. If szName points to valid memory, the name of this file data node will be copied into szName up to the number of characters given by puiSize .
puiSize
[in, out] Pointer to the size of the string that represents the name of this file data node. This parameter can be NULL if szName provides a reference to the name. This parameter will return the size of the string if szName is NULL.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Remarks

For this method to succeed, either szName or puiSize must be non-NULL.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileSaveData::GetSave

Retrieves a pointer to this ID3DXFileSaveObject file data node.

HRESULT GetSave(
  ID3DXFileSaveObject ** ppObj
);

Parameters

ppObj
[out] Address of a pointer to an ID3DXFileSaveObject interface representing this file data node.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the following value will be returned: D3DXFERR_BADVALUE.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileSaveData::GetType

Retrieves the template ID of this file data node.

HRESULT GetType(
  GUID * type
);

Parameters

type
[in] Pointer to the GUID representing the template in this file data node.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DXFERR_BADOBJECT, D3DXFERR_BADVALUE.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileSaveObject

Applications use the methods of the ID3DXFileSaveObject interface to write a .x file to disk, and to add and save data objects and templates.

ID3DXFileSaveObject Members

Method | Description
ID3DXFileSaveObject::AddDataObject | Adds a data object as a child of the ID3DXFileSaveData object.
ID3DXFileSaveObject::GetFile | Gets the ID3DXFile interface of the object that created this ID3DXFileSaveObject object.
ID3DXFileSaveObject::Save | Saves a data object and its children to a .x file on disk.

Remarks

Templates are not required in every file. For example, you could put all templates into a single .x file rather than duplicating them in every .x file.

The ID3DXFileSaveObject interface is obtained by calling the ID3DXFile::CreateSaveObject method.

The globally unique identifier (GUID) for the ID3DXFileSaveObject interface is IID_ID3DXFileSaveObject.

The LPD3DXFILESAVEOBJECT type is defined as a pointer to this interface.

typedef interface ID3DXFileSaveObject *LPD3DXFILESAVEOBJECT;

Requirements

Header: Declared in D3DX9Xof.h.

Library: Use D3dx9.lib.


ID3DXFileSaveObject::AddDataObject

Adds a data object as a child of the ID3DXFileSaveData object.

HRESULT AddDataObject(
  REFGUID rguidTemplate,
  LPCSTR szName,
  CONST GUID * pId,
  SIZE_T cbSize,
  LPCVOID pvData,
  ID3DXFileSaveData ** ppObj
);

Parameters

rguidTemplate
[in] GUID representing the data object's template.
szName
[in] Pointer to the name of the data object. Specify NULL if the object does not have a name.
pId
[in] Pointer to a GUID representing the data object. Specify NULL if the object does not have a GUID.
cbSize
[in] Size of the data object, in bytes.
pvData
[in] Pointer to a buffer containing all required data in the data object.
ppObj
[in, retval] Address of a pointer to an ID3DXFileSaveData interface, representing the file data node to which the data object will be added.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DXFERR_BADOBJECT, DXFILEERR_BADVALUE, E_OUTOFMEMORY.

Remarks

If a data reference object will reference the data object, either the szName or pId parameter must be non-NULL.

Save the created data to disk by using the ID3DXFileSaveObject::Save method.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileSaveObject::GetFile

Gets the ID3DXFile interface of the object that created this ID3DXFileSaveObject object.

HRESULT GetFile(
  ID3DXFile ppFile
);

Parameters

ppFile
[in] Address of a pointer to an ID3DXFile object.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be one of the following: D3DXFERR_BADVALUE, E_NOINTERFACE, E_POINTER.

Requirements

Header: Declared in D3DX9Xof.h.


ID3DXFileSaveObject::Save

Saves a data object and its children to a .x file on disk.

HRESULT Save();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK. If the method fails, the return value can be the following: D3DXFERR_BADOBJECT.

Remarks

After this method succeeds, ID3DXFileSaveObject::AddDataObject, ID3DXFileSaveData::AddDataObject and ID3DXFileSaveData::AddDataReference can no longer be called until a new ID3DXFile object is created.

Requirements

Header: Declared in D3DX9Xof.h.


D3DX X File Functions

This section contains reference information for a function that you can use to work with .x files.

  • D3DXFileCreate


D3DXFileCreate

Creates an instance of an ID3DXFile object.

STDAPI D3DXFileCreate(
  ID3DXFile ** lplpDirectXFile
);

Parameters

lplpDirectXFile
Address of a pointer to an ID3DXFile interface, representing the created .x file object.

Return Values

If the function succeeds, the return value is S_OK. If the function fails, the return value can be one of the following: E_POINTER, E_OUTOFMEMORY.

Remarks

After using this function, use ID3DXFile::RegisterTemplates or ID3DXFile::RegisterEnumTemplates to register templates, ID3DXFile::CreateEnumObject to create an enumerator object, or ID3DXFile::CreateSaveObject to create a save object.

Requirements

Header: Declared in D3DX9Xof.h.

See Also

ID3DXFile::CreateEnumObject, ID3DXFile::CreateSaveObject, ID3DXFile::RegisterEnumTemplates, ID3DXFile::RegisterTemplates


D3DX X File Structures

This section contains information about the structures used with .x files.

  • D3DXF_FILELOADMEMORY
  • D3DXF_FILELOADRESOURCE
  • XFILECOMPRESSEDANIMATIONSET


D3DXF_FILELOADMEMORY

Identifies memory data.

typedef struct D3DXF_FILELOADMEMORY {
    LPCVOID lpMemory;
    SIZE_T dSize;
} D3DXF_FILELOADMEMORY, *LPD3DXF_FILELOADMEMORY;

Members

lpMemory
Pointer to a block of memory to be loaded.
dSize
Size of the block of memory to be loaded, in bytes.

Remarks

This structure identifies data to be loaded from memory when an application uses the ID3DXFile::CreateEnumObject method and specifies the D3DXF_FILELOAD_FROMMEMORY flag.


D3DXF_FILELOADRESOURCE

Identifies resource data.

typedef struct D3DXF_FILELOADRESOURCE {
    HMODULE hModule;
    LPCSTR lpName;
    LPCSTR lpType;
} D3DXF_FILELOADRESOURCE, *LPD3DXF_FILELOADRESOURCE;

Members

hModule
Handle of the module containing the resource to be loaded. If this member is NULL, the resource must be attached to the executable file that will use it.
lpName
Pointer to a string specifying the name of the resource to be loaded. For example, if the resource is a mesh, this member should specify the name of the mesh file.
lpType
Pointer to a string specifying the user-defined type identifying the resource.

Remarks

This structure identifies a resource to be loaded when an application uses the ID3DXFile::CreateEnumObject method and specifies the D3DXF_FILELOAD_FROMRESOURCE flag.


XFILECOMPRESSEDANIMATIONSET

Identifies compressed key frame animation data.

typedef struct XFILECOMPRESSEDANIMATIONSET {
    DWORD CompressedBlockSize;
    FLOAT TicksPerSec;
    DWORD PlaybackType;
    DWORD BufferLength;
} XFILECOMPRESSEDANIMATIONSET, *LPXFILECOMPRESSEDANIMATIONSET;

Members

CompressedBlockSize
Total size, in bytes, of the compressed data in the compressed key frame animation data buffer.
TicksPerSec
Number of animation key frame ticks that occur per second.
PlaybackType
Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.
BufferLength
Minimum buffer size, in bytes, required to hold compressed key frame animation data. Value is equal to ( ( CompressedBlockSize + 3 ) / 4 ).

See Also

ID3DXCompressedAnimationSet


D3DX X File Constants

This section contains information about the constants used with .x files.

  • D3DXF
  • D3DXFERR Return Values


D3DXF

X file format, load, and save options.

File Formats

The following table specifies the type of file data:

#defines for File Format | Value | Description
D3DXF_FILEFORMAT_BINARY | 0 | Legacy-format binary file. See X File Reference (Legacy).
D3DXF_FILEFORMAT_TEXT | 1 | Text file.
D3DXF_FILEFORMAT_COMPRESSED | 2 | Compressed file. With this flag, you must also specify the binary format or the text format.

File Load Options

The following table specifies file load options with .x files:

#define | Value | Description
D3DXF_FILELOAD_FromFile | 0 | Load data from a file.
D3DXF_FILELOAD_FROMWFILE | 1 | Load data from a file.
D3DXF_FILELOAD_FROMRESOURCE | 2 | Load data from a resource.
D3DXF_FILELOAD_FROMMEMORY | 3 | Load data from memory.

File Save Options

The following table specifies file save and load options with .x files:

#define | Value | Description
D3DXF_FILESAVE_TOFILE | 0 | Save to a file.
D3DXF_FILESAVE_TOWFILE | 1 | Save to a wide-character file.

Constant Information

Header | d3dx9xof.h
Minimum operating system | Windows 98

See Also

D3DXSaveMeshToX


D3DXFERR Return Values

The methods used to work with DirectX .x files can return the following values in addition to the standard COM return values.

typedef enum D3DXFERR_Return_Values
{
    D3DXFERR_BADARRAYSIZE,
    D3DXFERR_BADCACHEFILE,
    D3DXFERR_BADDataReference,
    D3DXFERR_BADFILE,
    D3DXFERR_BADFILEFLOATSIZE,
    D3DXFERR_BADFILETYPE,
    D3DXFERR_BADFILEVERSION,
    D3DXFERR_BADOBJECT,
    D3DXFERR_BADRESOURCE,
    D3DXFERR_BADTYPE,
    D3DXFERR_BADVALUE,
    D3DXFERR_FILENOTFOUND,
    D3DXFERR_NOMOREDATA,
    D3DXFERR_NOMOREOBJECTS,
    D3DXFERR_NOTDONEYET,
    D3DXFERR_NOTFOUND,
    D3DXFERR_PARSEERROR,
    D3DXFERR_RESOURCENOTFOUND,
} D3DXFERR Return Values, *LPD3DXFERR Return Values;

Constants

D3DXFERR_BADARRAYSIZE
An array exceeds the allowable size.
D3DXFERR_BADCACHEFILE
A cache file could not be read.
D3DXFERR_BADDataReference
Template member data could not be retrieved.
D3DXFERR_BADFILE
A file read or write operation failed.
D3DXFERR_BADFILEFLOATSIZE
File is not the expected size.
D3DXFERR_BADFILETYPE
File has an invalid format.
D3DXFERR_BADFILEVERSION
File has an invalid format version.
D3DXFERR_BADOBJECT
Data could not be read from or written to an object.
D3DXFERR_BADRESOURCE
An operation on a resource failed.
D3DXFERR_BADTYPE
File did not match known template types.
D3DXFERR_BADVALUE
A variable is outside its expected range; typically returned when an object pointer is invalid.
D3DXFERR_FILENOTFOUND
A valid handle could not be found for the specified file.
D3DXFERR_NOMOREDATA
Pointer offset extended beyond the end of the buffer.
D3DXFERR_NOMOREOBJECTS
No more child objects are available.
D3DXFERR_NOTDONEYET
Data type did not match allowed types.
D3DXFERR_NOTFOUND
Object could not be found from the specified parameters.
D3DXFERR_PARSEERROR
Data stream could not be parsed.
D3DXFERR_RESOURCENOTFOUND
A valid handle could not be found for the specified resource.

Remarks

The .x file error facility code _FACD3DXF is used to generate error codes. For example:

#define _FACD3DXF           0x876
#define D3DXFERR_BADOBJECT  MAKE_HRESULT( 1, _FACD3DXF, 900 )


X File Reference (Legacy)

This section contains reference information for the API elements for working with DirectX .x files to support legacy applications.

  • X File Interfaces
  • X File Functions
  • X File Structures
  • DXFILE Constants
  • Return Values


X File Interfaces

This section contains reference information for the COM interfaces used to read to and write from DirectX .x files. Deprecated.

  • IDirectXFile
  • IDirectXFileBinary
  • IDirectXFileData
  • IDirectXFileDataReference
  • IDirectXFileEnumObject
  • IDirectXFileObject
  • IDirectXFileSaveObject

The following tables illustrate the relationship between the .x file interfaces.

Interface | Derives from | Derives from
 | IDirectXFile | IUnknown
IDirectXFileBinary | IDirectXFileObject | IUnknown
IDirectXFileData | IDirectXFileObject | IUnknown
IDirectXFileReference | IDirectXFileObject | IUnknown
 | IDirectXFileSaveObject | IUnknown


IDirectXFile

Applications use the methods of the IDirectXFile interface to create instances of the IDirectXFileEnumObject and IDirectXFileSaveObject interfaces, and to register templates. Deprecated.

IDirectXFile Members

Method | Description
IDirectXFile::CreateEnumObject | Creates an enumerator object. Deprecated.
IDirectXFile::CreateSaveObject | Creates a save object. Deprecated.
IDirectXFile::RegisterTemplates | Registers custom templates. Deprecated.

Remarks

The globally unique identifier (GUID) for the IDirectXFile interface is IID_IDirectXFile.

The IDirectXFile interface is obtained by calling the DirectXFileCreate function.

The LPDIRECTXFILE type is defined as a pointer to this interface.

typedef interface IDirectXFile *LPDIRECTXFILE;

Requirements

Header: Declared in DXFile.h.

Library: Use D3dxof.lib.


IDirectXFile::CreateEnumObject

Creates an enumerator object. Deprecated.

HRESULT CreateEnumObject(
  LPVOID pvSource,
  DXFILELOADOPTIONS dwLoadOptions,
  LPDIRECTXFILEENUMOBJECT * ppEnumObj
);

Parameters

pvSource
[in] Pointer to data whose contents depend on the value of dwLoadOptions
dwLoadOptions
[in] Value that specifies the source of the data. This value can be one of the DXFILELOAD_xxx flags in DXFILE Constants.
ppEnumObj
[out, retval] Address of a pointer to an IDirectXFileEnumObject interface, representing the created enumerator object.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following: DXFILEERR_BADALLOC, DXFILEERR_BADFILEFLOATSIZE, DXFILEERR_BADFILETYPE, DXFILEERR_BADFILEVERSION, DXFILEERR_BADRESOURCE, DXFILEERR_BADVALUE, DXFILEERR_FILENOTFOUND, DXFILEERR_RESOURCENOTFOUND, DXFILEERR_URLNOTFOUND.

Remarks

After using this method, use one of the IDirectXFileEnumObject methods to retrieve a data object.

Requirements

Header: Declared in DXFile.h.


IDirectXFile::CreateSaveObject

Creates a save object. Deprecated.

HRESULT CreateSaveObject(
  LPCSTR szFileName,
  DXFILEFORMAT dwFileFormat,
  LPDIRECTXFILESAVEOBJECT* ppSaveObj
);

Parameters

szFileName
[in] Pointer to the name of the file to use for saving data.
dwFileFormat
[in] Indicates the format to use when saving the DirectX file. This value can be one of the DXFILEFORMAT_xxx flags in DXFILE Constants. For more information, see Remarks.
ppSaveObj
[out, retval] Address of a pointer to an IDirectXFileSaveObject interface, representing the created save object.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following: DXFILEERR_BADALLOC, DXFILEERR_BADFILE, DXFILEERR_BADVALUE.

Remarks

After using this method, use methods of the IDirectXFileSaveObject interface to create data objects and to save templates or data.

The default value for the file format is DXFILEFORMAT_BINARY. The file format values can be combined in a logical OR to create compressed text or compressed binary files. If a file is specified as both binary (0) and text (1), it will be saved as a text file because the value will be indistinguishable from the text file format value (0 + 1 = 1). If you indicate that the file format should be text and compressed, the file will first be written out as text and then compressed. However, compressed text files are not as efficient as binary text files, so in most cases you will want to indicate binary and compressed. Setting a file to be compressed without specifying a format will result in a binary, compressed file.

Requirements

Header: Declared in DXFile.h.

See Also

IDirectXFileSaveObject


IDirectXFile::RegisterTemplates

Registers custom templates. Deprecated.

HRESULT RegisterTemplates(
  LPVOID pvData,
  DWORD cbSize
);

Parameters

pvData
[in] Pointer to a buffer consisting of a DirectX file in text or binary format that contains templates.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values: DXFILEERR_BADFILEFLOATSIZE, DXFILEERR_BADFILETYPE, DXFILEERR_BADFILEVERSION, DXFILEERR_BADVALUE, DXFILEERR_PARSEERROR.

Remarks

The following code fragment provides an example call to RegisterTemplates And example contents for the buffer to which pvData points.

    TIDirectXFile * pDXFile;
    char *szTemplates = "xof 0303txt 0032\
        template SimpleData { \
            <2b934580-9e9a-11cf-ab39-0020af71e433> \
            DWORD item1;DWORD item2;DWORD item3;} \
        template ArrayData { \
            <2b934581-9e9a-11cf-ab39-0020af71e433> \
            DWORD cItems; array DWORD aItem[2][cItems]; [...] } \
        template RestrictedData { \
            <2b934582-9e9a-11cf-ab39-0020af71e433> \
            DWORD item; [SimpleData]}";
    hr = pDXFile->RegisterTemplates(szTemplates, strlen(szTemplates));

All templates must specify a name and a Universally Unique Identifier (UUID).

Requirements

Header: Declared in DXFile.h.


IDirectXFileBinary

Applications use the methods of the IDirectXFileBinary interface to read and retrieve information about binary data. Deprecated.

IDirectXFileObject
IDirectXFileBinary
IDirectXFileData
IDirectXFileDataReference

IDirectXFileBinary Members

Method | Description
IDirectXFileBinary::GetMimeType | Retrieves the Multipurpose Internet Mail Extensions (MIME) type for the binary data. Deprecated.
IDirectXFileBinary::GetSize | Retrieves the size of the binary data. Deprecated.
IDirectXFileBinary::Read | Reads the binary data. Deprecated.

Remarks

The GUID for the IDirectXFileBinary interface is IID_IDirectXFileBinary.

The LPDIRECTXFileBinary type is defined as a pointer to this interface.

typedef interface IDirectXFileBinary *LPDIRECTXFILEBINARY;

Requirements

Header: Declared in DXFile.h.

Library: Use D3dxof.lib.


IDirectXFileBinary::GetMimeType

Retrieves the Multipurpose Internet Mail Extensions (MIME) type for the binary data. Deprecated.

HRESULT GetMimeType(
  LPCSTR * pszMimeType
);

Parameters

pszMimeType
[out] Address of a pointer to receive the MIME type string.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be DXFILEERR_BADVALUE.

Remarks

When there is no MIME type specified in a DirectX file for a binary object, the function will set pszMimeType to NULL.

Requirements

Header: Declared in DXFile.h.


IDirectXFileBinary::GetSize

Retrieves the size of the binary data. Deprecated.

HRESULT GetSize(
  DWORD * pcbSize
);

Parameters

pcbSize
[out] Pointer to the returned size of the binary data, in bytes.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be DXFILEERR_BADVALUE.

Requirements

Header: Declared in DXFile.h.


IDirectXFileBinary::Read

Reads the binary data. Deprecated.

HRESULT Read(
  LPVOID pvData,
  DWORD cbSize,
  LPDWORD pcbRead
);

Parameters

pvData
[out] Pointer to the buffer that receives the data that has been read.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.
pcbRead
[out] Pointer to the number of bytes actually read.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values: DXFILEERR_BADVALUE, DXFILEERR_NOMOREDATA.

Requirements

Header: Declared in DXFile.h.


IDirectXFileData

Applications use the methods of the IDirectXFileData interface to build or to access the immediate hierarchy of the data object. Template restrictions determine the hierarchy. Data types allowed by the template are called optional members. The optional members are not required, but an object might miss important information without them. These optional members are saved as children of the data object. The children can be another data object, a reference to an earlier data object, or a binary object. Deprecated.

IDirectXFileObject
IDirectXFileBinary
IDirectXFileData
IDirectXFileDataReference

IDirectXFileData Members

Method | Description
IDirectXFileData::AddBinaryObject | Creates a binary object and adds it as a child object. Deprecated.
IDirectXFileData::AddDataObject | Adds a data object as a child object. Deprecated.
IDirectXFileData::AddDataReference | Creates and adds a data reference object as a child object. Deprecated.
IDirectXFileData::GetData | Retrieves the data for one of the object's members or the data for all members. Deprecated.
IDirectXFileData::GetNextObject | Retrieves the next child data object, data reference object, or binary object in the DirectX file. Deprecated.
IDirectXFileData::GetType | Retrieves the GUID of the object's template. Deprecated.

Remarks

The GUID for the IDirectXFileData interface is IID_IDirectXFileData.

The LPDIRECTXFILEDATA type is defined as a pointer to this interface.

typedef interface IDirectXFileData *LPDIRECTXFILEDATA;

Requirements

Header: Declared in DXFile.h.

Library: Use D3dxof.lib.


IDirectXFileData::AddBinaryObject

Creates a binary object and adds it as a child object. Deprecated.

HRESULT AddBinaryObject(
  LPCSTR szName,
  CONST GUID * pguid,
  LPCSTR szMimeType,
  LPVOID pvData,
  DWORD cbSize
);

Parameters

szName
[in] Pointer to the name of the object. Specify NULL if the object does not need a name.
pguid
[in] Pointer to the GUID representing the object. Specify NULL if the object does not need a GUID.
szMimeType
[in] Pointer to the object's MIME type.
pvData
[in] Pointer to the object's data.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC DXFILEERR_BADVALUE

Requirements

Header: Declared in DXFile.h.

See Also

IDirectXFileBinary::GetMimeType


IDirectXFileData::AddDataObject

Adds a data object as a child object. Deprecated.

HRESULT AddDataObject(
  LPDIRECTXFILEDATA pDataObj
);

Parameters

pDataObj
[in] Pointer to an IDirectXFileData interface, representing the file data object to add as a child object.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC DXFILEERR_BADVALUE

Remarks

Use the IDirectXFileSaveObject::CreateDataObject method to create the IDirectXFileData object before calling this method.

Requirements

Header: Declared in DXFile.h.

See Also

IDirectXFileSaveObject::CreateDataObject


IDirectXFileData::AddDataReference

Creates and adds a data reference object as a child object. Deprecated.

HRESULT AddDataReference(
  LPCSTR szRef,
  CONST GUID * pguidRef
);

Parameters

szRef
[in] Pointer to the name of the referenced data object. This parameter can be NULL if pguidRef provides a reference to the GUID.
pguidRef
[in] Pointer to the GUID representing the data. This parameter can be NULL if szRef provides a reference to the name.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC DXFILEERR_BADVALUE

Remarks

For this method to succeed, either the szRef or pguidRef parameter must be non-NULL.

Requirements

Header: Declared in DXFile.h.


IDirectXFileData::GetData

Retrieves the data for one of the object's members or the data for all members. Deprecated.

HRESULT GetData(
  LPCSTR szMember,
  DWORD * pcbSize,
  void ** ppvData
);

Parameters

szMember
[in] Pointer to the name of the member for which to retrieve data. Specify NULL to retrieve all required members' data.
pcbSize
[out] Pointer to receive the ppvData buffer size, in bytes.
ppvData
[out] Address of a pointer to the buffer to receive the data associated with szMember. If szMember is NULL, ppvData is set to point to a buffer containing all required members' data in a contiguous block of memory.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values: DXFILEERR_BADARRAYSIZE, DXFILEERR_BADDataReference, DXFILEERR_BADVALUE.

Remarks

This method retrieves the data for required members of a data object but no data for optional (child) members. Use IDirectXFileData::GetNextObject to retrieve child objects.

Requirements

Header: Declared in DXFile.h.

See Also

IDirectXFileData::GetNextObject


IDirectXFileData::GetNextObject

Retrieves the next child data object, data reference object, or binary object in the DirectX file. Deprecated.

HRESULT GetNextObject(
  LPDIRECTXFILEOBJECT * ppChildObj
);

Parameters

ppChildObj
[out, retval] Address of a pointer to an IDirectXFileObject interface, representing the returned child object's file object interface.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values: DXFILEERR_BADVALUE, DXFILEERR_NOMOREOBJECTS.

Remarks

To determine the type of object retrieved, use QueryInterface to query the retrieved object for support of IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary interfaces. The interface supported indicates the type of object (data, data reference, or binary).

Requirements

Header: Declared in DXFile.h.

See Also

IDirectXFileBinary, IDirectXFileData, IDirectXFileDataReference


IDirectXFileData::GetType

Retrieves the GUID of the object's template. Deprecated.

HRESULT GetType(
  CONST GUID ** ppguid
);

Parameters

ppguid
[out, retval] Address of a pointer to receive the GUID of the object's template.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be DXFILEERR_BADVALUE.

Requirements

Header: Declared in DXFile.h.


IDirectXFileDataReference

Applications use the methods of the IDirectXFileDataReference interface to support data reference objects. A data reference object refers to a data object that is defined earlier in the file. This enables you to use the same object multiple times without repeating it in the file. Deprecated.

IDirectXFileObject
IDirectXFileBinary
IDirectXFileData
IDirectXFileDataReference

IDirectXFileDataReference Members

Method | Description
IDirectXFileDataReference::Resolve | Resolves data references. Deprecated.

Remarks

After you have determined that an object is a data reference object, use the IDirectXFileDataReference::Resolve method to retrieve the referenced object defined earlier in the file. For information about how to identify a data reference object, see the IDirectXFileData interface.

The GUID for the IDirectXFileDataReference interface is IID_IDirectXFileDataReference.

The LPDIRECTXFILEDataReference type is defined as a pointer to this interface.

typedef interface IDirectXFileDataReference *LPDIRECTXFILEDATAREFERENCE;

Requirements

Header: Declared in DXFile.h.

Library: Use D3dxof.lib.


IDirectXFileDataReference::Resolve

Resolves data references. Deprecated.

HRESULT Resolve(
  LPDIRECTXFILEDATA * ppDataObj
);

Parameters

ppDataObj
[out, retval] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values: DXFILEERR_BADVALUE, DXFILEERR_NOTFOUND.

Requirements

Header: Declared in DXFile.h.


IDirectXFileEnumObject

Applications use the methods of the IDirectXFileEnumObject interface to cycle through the data objects in the file and to retrieve a data object by its globally unique identifier (GUID) or by its name. Deprecated.

IDirectXFileEnumObject Members

Method | Description
IDirectXFileEnumObject::GetDataObjectById | Retrieves the data object that has the specified GUID. Deprecated.
IDirectXFileEnumObject::GetDataObjectByName | Retrieves the data object that has the specified name. Deprecated.
IDirectXFileEnumObject::GetNextDataObject | Retrieves the next top-level object in the DirectX file. Deprecated.

Remarks

The GUID for the IDirectXFileEnumObject interface is IID_IDirectXFileEnumObject.

The LPDIRECTXFILEENUMOBJECT type is defined as a pointer to this interface.

typedef interface IDirectXFileEnumObject *LPDIRECTXFILEENUMOBJECT;

Requirements

Header: Declared in DXFile.h.

Library: Use D3dxof.lib.


IDirectXFileEnumObject::GetDataObjectById

Retrieves the data object that has the specified GUID. Deprecated.

HRESULT GetDataObjectById(
  REFGUID rguid,
  LPDIRECTXFILEDATA * ppDataObj
);

Parameters

rguid
[in] Reference to the requested GUID.
ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values: DXFILEERR_BADVALUE, DXFILEERR_NOTFOUND.

Requirements

Header: Declared in DXFile.h.


IDirectXFileEnumObject::GetDataObjectByName

Retrieves the data object that has the specified name. Deprecated.

HRESULT GetDataObjectByName(
  LPCSTR szName,
  LPDIRECTXFILEDATA * ppDataObj
);

Parameters

szName
[in] Pointer to the requested name.
ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values: DXFILEERR_BADVALUE, DXFILEERR_NOTFOUND.

Requirements

Header: Declared in DXFile.h.


IDirectXFileEnumObject::GetNextDataObject

Retrieves the next top-level object in the DirectX file. Deprecated.

HRESULT GetNextDataObject(
  LPDIRECTXFILEDATA * ppDataObj
);

Parameters

ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values: DXFILEERR_BADVALUE, DXFILEERR_NOMOREOBJECTS

Remarks

Top-level objects are always data objects. Data reference objects and binary objects can only be children of data objects.

Requirements

Header: Declared in DXFile.h.


IDirectXFileObject

Applications use the methods of the IDirectXFileObject interface to retrieve information about Microsoft DirectX file objects. Deprecated.

IDirectXFileObject
IDirectXFileBinary
IDirectXFileData
IDirectXFileDataReference

IDirectXFileObject Members

Method | Description
IDirectXFileObject::GetId | Retrieves a pointer to the GUID that identifies a DirectX file object. Deprecated.
IDirectXFileObject::GetName | Retrieves a pointer to a DirectX file object's name. Deprecated.

Remarks

The GUID for the IDirectXFileObject interface is IID_IDirectXFileObject.

The LPDIRECTXFILEOBJECT type is defined as a pointer to this interface.

typedef interface IDirectXFileObject *LPDIRECTXFILEOBJECT;

Requirements

Header: Declared in DXFile.h.

Library: Use D3dxof.lib.


IDirectXFileObject::GetId

Retrieves a pointer to the GUID that identifies a DirectX file object. Deprecated.

HRESULT GetId(
  LPGUID pGuid
);

Parameters

pGuid
[out, retval] Pointer to a GUID to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be DXFILEERR_BADVALUE.

Requirements

Header: Declared in DXFile.h.


IDirectXFileObject::GetName

Retrieves a pointer to a DirectX file object's name. Deprecated.

HRESULT GetName(
  LPSTR pstrNameBuf,
  LPDWORD pdwBufLen
);

Parameters

pstrNameBuf
[out] Pointer to the buffer in which the DirectX file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
[in, out] Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. The pdwBufLen parameter value will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC DXFILEERR_BADVALUE

Requirements

Header: Declared in DXFile.h.


IDirectXFileSaveObject

Applications use the methods of the IDirectXFileSaveObject interface to create data objects and to save templates and data objects. Note that templates are not required in every file. For example, you could put all templates into a single Microsoft DirectX file rather than duplicating them in every DirectX file. Deprecated.

IDirectXFileSaveObject Members

Method | Description
IDirectXFileSaveObject::CreateDataObject | Creates a data object. Deprecated.
IDirectXFileSaveObject::SaveData | Saves a data object and its children to a DirectX file. Deprecated.
IDirectXFileSaveObject::SaveTemplates | Saves templates to a DirectX file. Deprecated.

Remarks

The globally unique identifier (GUID) for the IDirectXFileSaveObject interface is IID_IDirectXFileSaveObject.

The IDirectXFileSaveObject interface is obtained by calling the IDirectXFile::CreateSaveObject method.

The LPDIRECTXFILESAVEOBJECT type is defined as a pointer to this interface.

typedef interface IDirectXFileSaveObject *LPDIRECTXFILESAVEOBJECT;

Requirements

Header: Declared in DXFile.h.

Library: Use D3dxof.lib.


IDirectXFileSaveObject::CreateDataObject

Creates a data object. Deprecated.

HRESULT CreateDataObject(
  REFGUID rguidTemplate,
  LPCSTR szName,
  CONST GUID * pguid,
  DWORD cbSize,
  LPVOID pvData,
  LPDIRECTXFILEDATA * ppDataObj
);

Parameters

rguidTemplate
[in] GUID representing the data object's template.
szName
[in] Pointer to the name of the data object. Specify NULL if the object does not have a name.
pguid
[in] Pointer to a GUID representing the data object. Specify NULL if the object does not have a GUID.
cbSize
[in] Size of the data object, in bytes.
pvData
[in] Pointer to a buffer containing all required member's data.
ppDataObj
[out, retval] Address of a pointer to an IDirectXFileData interface, representing the created file data object.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC DXFILEERR_BADVALUE

Remarks

If a data reference object will reference the data object, either the szName or pguid parameter must be non-NULL.

Save any templates by using the IDirectXFileSaveObject::SaveTemplates method before saving the data created by this method. Save the created data by using the IDirectXFileSaveObject::SaveData method.

If you need to save optional data, use the IDirectXFileData::AddDataObject method after using this method and before using IDirectXFileSaveObject::SaveData. If the object has child objects, add them before calling IDirectXFileSaveObject::SaveData.

Requirements

Header: Declared in DXFile.h.

See Also

IDirectXFileData::AddDataObject, IDirectXFileSaveObject::SaveData, IDirectXFileSaveObject::SaveTemplates


IDirectXFileSaveObject::SaveData

Saves a data object and its children to a DirectX file. Deprecated.

HRESULT SaveData(
  LPDIRECTXFILEDATA pDataObj
);

Parameters

pDataObj
[in] Pointer to an IDirectXFileData interface, representing the file data object to save.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be one of the following values: DXFILEERR_BADARRAYSIZE, DXFILEERR_BADVALUE.

Requirements

Header: Declared in DXFile.h.


IDirectXFileSaveObject::SaveTemplates

Saves templates to a DirectX file. Deprecated.

HRESULT SaveTemplates(
  DWORD cTemplates,
  CONST GUID ** ppguidTemplates
);

Parameters

cTemplates
[in] Total number of templates to save.
ppguidTemplates
[in] Address of a pointer to an array of the GUIDs for all templates to save.

Return Values

If the method succeeds, the return value is DXFILE_OK. If the method fails, the return value can be DXFILEERR_BADVALUE.

Remarks

The following code fragment provides an example call to IDirectXFileSaveObject::SaveTemplates and example contents for the array to which ppguidTemplates points.

IDirectXFileSaveObject * pDXFileSaveObject;

const GUID *aIds[] = {
    &DXFILEOBJ_SimpleData,
    &DXFILEOBJ_ArrayData,
    &DXFILEOBJ_RestrictedData};

hr = pDXFileSaveObject->SaveTemplates(3, aIds);

After using this method to save the templates, use the IDirectXFileSaveObject::CreateDataObject method to create a data object.

Requirements

Header: Declared in DXFile.h.

See Also

IDirectXFileSaveObject::CreateDataObject


X File Functions

This section contains reference information for the functions that you need to implement when you work with DirectX files. Deprecated.

The following function is implemented:

DirectXFileCreate


DirectXFileCreate

Creates an instance of a DirectXFile object. Deprecated.

STDAPI DirectXFileCreate(
  LPDIRECTXFILE * lplpDirectXFile
);

Parameters

lplpDirectXFile
Address of a pointer to an IDirectXFile interface, representing the created DirectXFile object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: DXFILEERR_BADALLOC, DXFILEERR_BADVALUE.

Remarks

After using this function, use IDirectXFile::RegisterTemplates to register templates, IDirectXFile::CreateEnumObject to create an enumerator object, or IDirectXFile::CreateSaveObject to create a save object.

Requirements

Header: Declared in DXFile.h.

See Also

IDirectXFile::CreateEnumObject, IDirectXFile::CreateSaveObject, IDirectXFile::RegisterTemplates


X File Structures

This section contains information about the structures used with DirectX files. Deprecated.

DXFILELOADMEMORY

DXFILELOADRESOURCE


DXFILELOADMEMORY

Identifies memory data. Deprecated.

typedef struct DXFILELOADMEMORY {
    LPVOID lpMemory;
    DWORD dSize;
} DXFILELOADMEMORY, *LPDXFILELOADMEMORY;

Members

lpMemory
Pointer to a block of memory to be loaded.
dSize
Size of the block of memory to be loaded, in bytes.

Remarks

This structure identifies a resource to be loaded when an application uses the IDirectXFile::CreateEnumObject method and specifies DXFILELOAD_FROMMEMORY.

See Also

IDirectXFile::CreateEnumObject, DXFILE Constants


DXFILELOADRESOURCE

Identifies resource data. Deprecated.

typedef struct DXFILELOADRESOURCE {
    HMODULE hModule;
    LPCTSTR lpName;
    LPCTSTR lpType;
} DXFILELOADRESOURCE, *LPDXFILELOADRESOURCE;

Members

hModule
Handle of the module containing the resource to be loaded. If this member is NULL, the resource must be attached to the executable file that will use it.
lpName
Pointer to a string specifying the name of the resource to be loaded. For example, if the resource is a mesh, this member should specify the name of the mesh file.
lpType
Pointer to a string specifying the user-defined type identifying the resource.

Remarks

This structure identifies a resource to be loaded when an application uses the IDirectXFile::CreateEnumObject method and specifies DXFILELOAD_FROMRESOURCE.

See Also

IDirectXFile::CreateEnumObject, DXFILE Constants


DXFILE Constants

The following flags are used to specify which channels in a texture to operate on. Deprecated.

DXFILEFORMAT

#define | Value | Description
DXFILEFORMAT_BINARY | 0 | Binary file.
DXFILEFORMAT_TEXT | 1 | Text file.
DXFILEFORMAT_COMPRESSED | 2 | Compressed file.

These #defines are declared in Dxfile.h.

DXFILELOADOPTIONS

#define | Value | Description
DXFILELOAD_FROMFILE | 0x00L | Load a file from a file.
DXFILELOAD_FROMRESOURCE | 0x01L | Load a file from a resource.
DXFILELOAD_FROMMEMORY | 0x02L | Load a file from memory.
DXFILELOAD_FROMSTREAM | 0x04L | Load a file from a stream.
DXFILELOAD_FROMURL | 0x08L | Load a file from a URL.

These #defines are declared in Dxfile.h.


Return Values

The methods used to work with DirectX .x files can return the following values in addition to the standard COM return values. Deprecated.

typedef enum Return_Values
{
    DXFILE_OK,
    DXFILEERR_BADALLOC,
    DXFILEERR_BADARRAYSIZE,
    DXFILEERR_BADCACHEFILE,
    DXFILEERR_BADDataReference,
    DXFILEERR_BADFILE,
    DXFILEERR_BADFILECOMPRESSIONTYPE,
    DXFILEERR_BADFILEFLOATSIZE,
    DXFILEERR_BADFILETYPE,
    DXFILEERR_BADFILEVERSION,
    DXFILEERR_BADINTRINSICS,
    DXFILEERR_BADOBJECT,
    DXFILEERR_BADRESOURCE,
    DXFILEERR_BADSTREAMHANDLE,
    DXFILEERR_BADTYPE,
    DXFILEERR_BADVALUE,
    DXFILEERR_FILENOTFOUND,
    DXFILEERR_INTERNALERROR,
    DXFILEERR_NOINTERNET,
    DXFILEERR_NOMOREDATA,
    DXFILEERR_NOMOREOBJECTS,
    DXFILEERR_NOMORESTREAMHANDLES,
    DXFILEERR_NOTDONEYET,
    DXFILEERR_NOTFOUND,
    DXFILEERR_PARSEERROR,
    DXFILEERR_RESOURCENOTFOUND,
    DXFILEERR_NOTEMPLATE,
    DXFILEERR_URLNOTFOUND,
} Return Values, *LPReturn Values;

Constants

DXFILE_OK
Command completed successfully.
DXFILEERR_BADALLOC
Memory allocation failed.
DXFILEERR_BADARRAYSIZE
Array size is invalid.
DXFILEERR_BADCACHEFILE
The cache file containing the .x file date is invalid. A cache file contains data retrieved from the network, cached on the hard disk, and retrieved in subsequent requests.
DXFILEERR_BADDataReference
Data reference is invalid.
DXFILEERR_BADFILE
File is invalid.
DXFILEERR_BADFILECOMPRESSIONTYPE
File compression type is invalid.
DXFILEERR_BADFILEFLOATSIZE
Floating-point size is invalid.
DXFILEERR_BADFILETYPE
File is not a DirectX .x file.
DXFILEERR_BADFILEVERSION
File version is not valid.
DXFILEERR_BADINTRINSICS
Intrinsics are invalid.
DXFILEERR_BADOBJECT
Object is invalid.
DXFILEERR_BADRESOURCE
Resource is invalid.
DXFILEERR_BADSTREAMHANDLE
Stream handle is invalid.
DXFILEERR_BADTYPE
Object type is invalid.
DXFILEERR_BADVALUE
Parameter is invalid.
DXFILEERR_FILENOTFOUND
File could not be found.
DXFILEERR_INTERNALERROR
Internal error occurred.
DXFILEERR_NOINTERNET
Internet connection not found.
DXFILEERR_NOMOREDATA
No further data is available.
DXFILEERR_NOMOREOBJECTS
All objects have been enumerated.
DXFILEERR_NOMORESTREAMHANDLES
No stream handles are available.
DXFILEERR_NOTDONEYET
Operation has not completed.
DXFILEERR_NOTFOUND
Object could not be found.
DXFILEERR_PARSEERROR
File could not be parsed.
DXFILEERR_RESOURCENOTFOUND
Resource could not be found.
DXFILEERR_NOTEMPLATE
No template available.
DXFILEERR_URLNOTFOUND
URL could not be found.


X File Format Reference

This section contains reference information for the DirectX (.x) file format.

  • Binary Encoding
  • Text Encoding
  • Templates

See Also

X File Reference


Binary Encoding

This section details the binary version of the DirectX (.x) file format as introduced with the release of DirectX 3.0.

The binary format is a tokenized representation of the text format. Tokens can be stand-alone or accompanied by primitive data records. Stand-alone tokens give grammatical structure, and record-bearing tokens supply the necessary data.

Note that all data is stored in little-endian format. A valid binary data stream consists of a header followed by templates and/or data objects.

This section discusses the following components of the binary file format and provides an example template and binary data object.

  • Header
  • Tokens
  • Token Records
  • Templates
  • Data
  • Examples


Header

The following definitions should be used when directly reading and writing the binary header.

Note Compressed data streams are not currently supported and are therefore not detailed here.

#define XOFFILE_FORMAT_MAGIC \
  ((long)'x' + ((long)'o' << 8) + ((long)'f' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_VERSION \
  ((long)'0' + ((long)'3' << 8) + ((long)'0' << 16) + ((long)'2' << 24))

#define XOFFILE_FORMAT_BINARY \
  ((long)'b' + ((long)'i' << 8) + ((long)'n' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_TEXT   \
  ((long)'t' + ((long)'x' << 8) + ((long)'t' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_COMPRESSED \
  ((long)'c' + ((long)'m' << 8) + ((long)'p' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_FLOAT_BITS_32 \
  ((long)'0' + ((long)'0' << 8) + ((long)'3' << 16) + ((long)'2' << 24))

#define XOFFILE_FORMAT_FLOAT_BITS_64 \
  ((long)'0' + ((long)'0' << 8) + ((long)'6' << 16) + ((long)'4' << 24))


Tokens

Tokens are written as little-endian WORDs. The following list of token values is divided into record-bearing and stand-alone tokens.

The record-bearing tokens are defined as follows.

#define TOKEN_NAME         1
#define TOKEN_STRING       2
#define TOKEN_INTEGER      3
#define TOKEN_GUID         5
#define TOKEN_INTEGER_LIST 6
#define TOKEN_FLOAT_LIST   7

The stand-alone tokens are defined as follows.

#define TOKEN_OBRACE      10
#define TOKEN_CBRACE      11
#define TOKEN_OPAREN      12
#define TOKEN_CPAREN      13
#define TOKEN_OBRACKET    14
#define TOKEN_CBRACKET    15
#define TOKEN_OANGLE      16
#define TOKEN_CANGLE      17
#define TOKEN_DOT         18
#define TOKEN_COMMA       19
#define TOKEN_SEMICOLON   20
#define TOKEN_TEMPLATE    31
#define TOKEN_WORD        40
#define TOKEN_DWORD       41
#define TOKEN_FLOAT       42
#define TOKEN_DOUBLE      43
#define TOKEN_CHAR        44
#define TOKEN_UCHAR       45
#define TOKEN_SWORD       46
#define TOKEN_SDWORD      47
#define TOKEN_VOID        48
#define TOKEN_LPSTR       49
#define TOKEN_UNICODE     50
#define TOKEN_CSTRING     51
#define TOKEN_ARRAY       52


Token Records

This section describes the format of the records for each of the record-bearing tokens. Information is divided into the following sections.

  • TOKEN_NAME
  • TOKEN_STRING
  • TOKEN_INTEGER
  • TOKEN_GUID
  • TOKEN_INTEGER_LIST
  • TOKEN_FLOAT_LIST

TOKEN_NAME

A variable-length record. The token is followed by a count value that specifies the number of bytes that follow in the name field. An ASCII name of length count completes the record.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | token_name
count | DWORD | 4 | Length of name field, in bytes
name | BYTE array | count | ASCII name

TOKEN_STRING

A variable-length record. The token is followed by a count value that specifies the number of bytes that follow in the string field. An ASCII string of length count continues the record, which is completed by a terminating token. The choice of terminator is determined by syntax issues discussed elsewhere.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | token_string
count | DWORD | 4 | Length of string field in bytes
strinG | BYTE array | count | ASCII string
terminator | DWORD | 4 | tOKEN_SEMICOLON or TOKEN_COMMA

TOKEN_INTEGER

A fixed length record. The token is followed by the integer value required.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | tOKEN_INTEGER
valuE | DWORD | 4 | Single integer

TOKEN_GUID

A fixed-length record. The token is followed by the four data fields as defined by the OSF DCE standard.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | tOKEN_GUID
Data1 | DWORD | 4 | UUID data field 1
Data2 | WORD | 2 | UUID data field 2
Data3 | WORD | 2 | UUID data field 3
Data4 | BYTE array | 8 | UUID data field 4

TOKEN_INTEGER_LIST

A variable-length record. The token is followed by a count value that specifies the number of integers that follow in the list field. For efficiency, consecutive integer lists should be compounded into a single list.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | tOKEN_INTEGER_LISt
count | DWORD | 4 | Number of integers in list field
list | DWORD | 4 x count | Integer list

TOKEN_FLOAT_LIST

A variable-length record. The token is followed by a count value that specifies the number of floats or doubles that follow in the list field. The size of the floating point value (float or double) is determined by the value of float sizespecified in the file header. For efficiency, consecutive TOKEN_FLOAT_LISTs should be compounded into a single list.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | tOKEN_FLOAT_LISt
count | DWORD | 4 | Number of floats or doubles in list field
list | float/double array | 4 or 8 x count | Float or double list


Templates

A template has the following syntax definition.

template              : TOKEN_TEMPLATE name TOKEN_OBRACE
                            class_id
                            template_parts
                            TOKEN_CBRACE

template_parts        : template_members_part TOKEN_OBRACKET
                        template_option_info
                        TOKEN_CBRACKET
                      | template_members_list

template_members_part : /* Empty */
                      | template_members_list

template_option_info  : ellipsis
                      | template_option_list

template_members_list :    template_members
                      | template_members_list template_members

template_members      : primitive
                      | array
                      | template_reference

primitive             : primitive_type optional_name TOKEN_SEMICOLON

array                 : TOKEN_ARRAY array_data_type name dimension_list
                        TOKEN_SEMICOLON

template_reference    : name optional_name YT_SEMICOLON

primitive_type        : TOKEN_WORD
                      | TOKEN_DWORD
                      | TOKEN_FLOAT
                      | TOKEN_DOUBLE
                      | TOKEN_CHAR
                      | TOKEN_UCHAR
                      | TOKEN_SWORD
                      | TOKEN_SDWORD
                      | TOKEN_LPSTR
                      | TOKEN_UNICODE
                      | TOKEN_CSTRING

array_data_type       : primitive_type
                      | name

dimension_list        : dimension
                      | dimension_list dimension

dimension             : TOKEN_OBRACKET dimension_size TOKEN_CBRACKET

dimension_size        : TOKEN_INTEGER
                      | name

template_option_list  : template_option_part
                      | template_option_list template_option_part

template_option_part  : name optional_class_id

name                  : TOKEN_NAME

optional_name         : /* Empty */
                      | name

class_id              : TOKEN_GUID

optional_class_id     : /* Empty */
                      | class_id

ellipsis              : TOKEN_DOT TOKEN_DOT TOKEN_DOT


Data

A data object has the following syntax definition.

object                : identifier optional_name TOKEN_OBRACE
                            optional_class_id
                            data_parts_list
                            TOKEN_CBRACE

data_parts_list       : data_part
                      | data_parts_list data_part

data_part             : data_reference
                      | object
                      | number_list
                      | float_list
                      | string_list

number_list           : TOKEN_INTEGER_LIST

float_list            : TOKEN_FLOAT_LIST

string_list           : string_list_1 list_separator

string_list_1         : string
                      | string_list_1 list_separator string

list_separator        : comma
                      | semicolon

string                : token_string

identifier            : name
                      | primitive_type

data_reference        : TOKEN_OBRACE name optional_class_id TOKEN_CBRACE

Note that in number_list and float_list data in binary files, TOKEN_COMMA and TOKEN_SEMICOLON are not used. The comma and semicolon are used in string_list data. Also note that you can only use data_reference for optional data members.


Examples

Two example binary template definitions and an example of a binary data object follow.

Note Data is stored in little-endian format, which is not shown in these examples.

The closed template RGB is identified by the UUID {55b6d780-37ec-11d0-ab39-0020af71e433} and has three members - r, g, and b - each of type float.

TOKEN_TEMPLATE, TOKEN_NAME, 3, 'R', 'G', 'B', TOKEN_OBRACE,
TOKEN_GUID, 55b6d780, 37ec, 11d0, ab, 39, 00, 20, af, 71, e4, 33,
TOKEN_FLOAT, TOKEN_NAME, 1, 'r', TOKEN_SEMICOLON,
TOKEN_FLOAT, TOKEN_NAME, 1, 'g', TOKEN_SEMICOLON,
TOKEN_FLOAT, TOKEN_NAME, 1, 'b', TOKEN_SEMICOLON,
TOKEN_CBRACE

The closed template Matrix4x4 is identified by the UUID {55b6d781-37ec-11d0-ab39-0020af71e433} and has one member - a two-dimensional array named matrix - of type float.

TOKEN_TEMPLATE, TOKEN_NAME, 9, 'M', 'a', 't', 'r', 'i', 'x', '4', 'x', '4', TOKEN_OBRACE,
TOKEN_GUID, 55b6d781, 37ec, 11d0, ab, 39, 00, 20, af, 71, e4, 33,
TOKEN_ARRAY, TOKEN_FLOAT, TOKEN_NAME, 6, 'm', 'a', 't', 'r', 'i', 'x',
TOKEN_OBRACKET, TOKEN_INTEGER, 4, TOKEN_CBRACKET,
TOKEN_OBRACKET, TOKEN_INTEGER, 4, TOKEN_CBRACKET,
TOKEN_CBRACE

The binary data object that follows shows an instance of the RGB template defined earlier. The example object is named blue, and its three members - r, g, and b - have the values 0.0, 0.0, and 1.0, respectively.

TOKEN_NAME, 3, 'R', 'G', 'B', TOKEN_NAME, 4, 'b', 'l', 'u', 'e', TOKEN_OBRACE,
TOKEN_FLOAT_LIST, 3, 0.0, 0.0, 1.0, TOKEN_CBRACE


Text Encoding

The DirectX .x file format is not specific to any application. It uses templates that don't depend on how the file is used. This allows the .x file format to be used by any client application.

This following sections deal with the content and syntax of the file format, which uses the .x extension in the DirectX SDK.

  • Data
  • Reserved Words, Header, and Comments
  • Templates
  • Use of Commas and Semicolons


Data

Data objects contain the actual data or a reference to that data. Each data object has a corresponding template that specifies the data type. The following sections discuss the form and parts of data objects.

Form, Identifier, and Name

Data objects have the following form.

<Identifier> [name] { [<UUID>]
    <member 1>;
...
    <member n>;
}

The identifier is compulsory and must match a previously defined data type or primitive. However, the name is optional.

Data Members

Data members can be one of the following: data object, data reference, integer list, float list, or string list.

A data object is a nested data object. This enables the hierarchical nature of the file format to be expressed. The types of nested data objects allowed in the hierarchy may be restricted.

A data reference is a reference to a previously encountered data object as shown in the following example.

{
  name |
  UUID |
  name UUID
}

An integer list is a semicolon-separated list of integers, as shown in the following example.

1; 2; 3;

A float list is a semicolon-separated list of floats, as shown in the following example.

1.0; 2.0; 3.0;

A string list is a semicolon-separated list of strings, as shown in the following example.

"Moose"; "Goats"; "Sheep";


Reserved Words, Header, and Comments

The table below shows which words are reserved and must not be used.

ARRAY | DWORD | UCHAR
BINARY | FLOAT | ULONGLONG
BINARY_RESOURCE | SDWORD | UNICODE
CHAR | STRING | WORD
CSTRING | SWORD |
DOUBLE | TEMPLATE |

The variable-length header is compulsory and must be at the beginning of the data stream. The header contains the following data.

Type | Required | Size (in bytes) | Value | Description
Magic Number | x | 4 | xof |
Version Number | x | 2 | 03 | Major version 3
 |  | 03 | Minor version 3
Format Type | x | 4 | txt | Text File
 |  | bin | Binary file
 |  | tzip | MSZip compressed text file
 |  | bzip | MSZip compressed binary file
Float Size | x | 0064 | 64-bit floats
x | "0032" | 32-bit floats

The values in the table are delimited by quotes to call attention to the number of characters in each value. Those with 4 bytes contain four characters, those with 2 bytes contain two characters.

Comments are applicable only in text files. Comments can occur anywhere in the data stream. A comment begins with either C++ style double-slashes (//), or a pound sign (#). The comment runs to the next new line. The following example shows valid comments.

#  This is a comment.
// This is another comment.


Templates

Templates define how the data stream is interpreted - the data is modulated by the template definition. This section discusses the following aspects of a template and provides an example template.

There is one special template - the header template. It is recommended that each application define a header template and use it to define application-specific information, such as version information. If present, this header is read by the .x file format API. If a flags member is available, it is used to determine how the following data is interpreted. The flags member, if defined, should be a DWORD. One bit is currently defined - bit 0. If this bit is clear, the following data in the file is binary. If set, the following data is text. You can use multiple header data objects to switch between binary and text within the file.

Template Form, Name, and UUID

A template has the following form.

template <template-name> {
<UUID>
    <member 1>;
...
    <member n>;
[restrictions]
}

The template name is an alphanumeric name that can include the underscore character (_). It must not begin with a digit. The UUID is a universally unique identifier formatted to the Open Software Foundation's Distributed Computing Environment standard and enclosed by angle brackets (< >). For example: <3D82AB43-62DA-11cf-AB39-0020AF71E433>.

Template Members

Template members consist of a named data type followed by an optional name or an array of a named data type. Valid primitive data types are defined in the following table.

Type | Size
WORD | 16 bits
DWORD | 32 bits
FLOAT | IEEE float
DOUBLE | 64 bits
CHAR | 8 bits
UCHAR | 8 bits
BYTE | 8 bits
STRING | NULL terminated string
CSTRING | Formatted C string (not supported)
UNICODE | Unicode string (not supported)

Additional data types defined by templates encountered earlier in the data stream can also be referenced within a template definition. No forward references are allowed.

Any valid data type can be expressed as an array in the template definition. The basic syntax is shown in the following example.

array <data-type> <name>[<dimension-size>];

<dimension-size> can either be an integer or a named reference to another template member whose value is then substituted. Arrays can be n-dimensional, where n is determined by the number of paired square brackets trailing the statement, as in the following example.

array DWORD FixedHerd[24];
array DWORD Herd[nCows];
array FLOAT Matrix4x4[4][4];

Template Restrictions

Templates can be open, closed, or restricted. These restrictions determine which data types can appear in the immediate hierarchy of a data object defined by the template. An open template has no restrictions, a closed template rejects all data types, and a restricted template allows a named list of data types.

The syntax for indicating an open template is three periods enclosed by square brackets.

[ ... ]

A comma-separated list of named data types followed optionally by their UUIDs enclosed by square brackets indicates a restricted template.

[ { data-type [ UUID ] , } ... ]

The absence of either of the above indicates a closed template.

Template Example

The following shows an example template.

template Mesh {
<3D82AB44-62DA-11cf-AB39-0020AF71E433>
DWORD nVertices;
array Vector vertices[nVertices];
DWORD nFaces;
array MeshFace faces[nFaces];
 [ ... ]                // An open template
}
template Vector {
<3D82AB5E-62DA-11cf-AB39-0020AF71E433>
FLOAT x;
FLOAT y;
FLOAT z;
}                        // A closed template
template FileSystem {
<UUID>
STRING name;
[ Directory <UUID>, File <UUID> ]    // A restricted template
}


Use of Commas and Semicolons

Using commas and semicolons can be the most complex syntax issue in the file format, and this usage is very strict. Commas are used to separate array members; semicolons terminate each data item.

For example, if a template is defined in the following manner:

template mytemp {
DWORD myvar;
}

Then an instance of this template looks like the following:

mytemp dataTemp {
1;
}

If a template containing another template is defined in the following manner;

template mytemp {
DWORD myvar;
DWORD myvar2;
}
template container {
FLOAT aFloat;
mytemp aTemp;
}

Then an instance of this template looks like the following:

container dataContainer {
1.1;
2;
3;;
}

Note that the second line that represents the mytemp inside container has two semicolons at the end of the line. The first semicolon indicates the end of the data item, aTemp (inside container), and the second semicolon indicates the end of the container.

If an array is defined in the following manner:

Template mytemp {

array DWORD myvar[3];

}

Then an instance of this looks like the following:

mytemp aTemp {
1, 2, 3;
}

In the array example, there is no need for the data items to be separated by semicolons because they are delineated by commas. The semicolon at the end marks the end of the array.

Consider a template that contains an array of data items defined by a template.

template mytemp {
DWORD myvar;
DWORD myvar2;
}
template container {
DWORD count;
array mytemp tempArray[count];
}

An instance of this would look like the following example.

container aContainer {
3;
1;2;,3;4;,5;6;;
}


Templates

This section lists the .x file templates. Template format is discussed in Templates.

  • Animation
  • AnimationKey
  • AnimationOptions
  • AnimationSet
  • AnimTicksPerSecond
  • Boolean
  • Boolean2d
  • ColorRGB
  • ColorRGBA
  • CompressedAnimationSet
  • Coords2d
  • DeclData
  • EffectDWord
  • EffectFloats
  • EffectInstance
  • EffectParamDWord
  • EffectParamFloats
  • EffectParamString
  • EffectString
  • FaceAdjacency
  • FloatKeys
  • Frame
  • FrameTransformMatrix
  • FVFData
  • Guid
  • IndexedColor
  • Material
  • MaterialWrap
  • Matrix4x4
  • Mesh
  • MeshFace
  • MeshFaceWraps
  • MeshMaterialList
  • MeshNormals
  • MeshTextureCoords
  • MeshVertexColors
  • Patch
  • PatchMesh
  • PatchMesh9
  • PMAttributeRange
  • PMInfo
  • PMVSplitRecord
  • SkinWeights
  • TextureFilename
  • TimedFloatKeys
  • Vector
  • VertexDuplicationIndices
  • VertexElement
  • XSkinMeshHeader


Animation

Contains animations referencing a previous frame. It should contain one reference to a frame and at least one set of AnimationKey templates. It also can contain an AnimationOptions data object.

template Animation
{
    < 3D82AB4F-62DA-11cf-AB39-0020AF71E433 >
    [...]
}

Where:

  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.


AnimationKey

Defines a set of animation keys. A matrix key is useful for sets of animation data that need to be represented as transformation matrices.

template AnimationKey
{
    < 10DD46A8-775B-11CF-8F52-0040333594A3 >
    DWORD keyType;
    DWORD nKeys;
    array TimedFloatKeys keys[nKeys];
}

Where:

  • keyType - Specifies whether the keys are rotation, scale, position, or matrix keys (using the integers 0, 1, 2, or 3, respectively).
  • nKeys - Number of keys.
  • keys - An array of keys. See TimedFloatKeys.


AnimationOptions

Enables you to set animation options.

template AnimationOptions
{
    < E2BF56C0-840F-11cf-8F52-0040333594A3 >
    DWORD openclosed;
    DWORD positionquality;
}

Where:

  • openclosed - Use 0 for a closed animation, or 1 for an open animation. By default, an animation is closed.
  • positionquality - Set the position quality for any position keys specified. Use 0 for spline positions or 1 for linear positions.


AnimationSet

Contains one or more Animation objects. Each animation within an animation set has the same time at any given point. Increasing the animation set's time increases the time for all the animations it contains.

template AnimationSet
{
    < 3D82AB50-62DA-11cf-AB39-0020AF71E433 >
    [ Animation < 3D82AB4F-62DA-11cf-AB39-0020AF71E433 > ]
}

Where:

  • [ Animation < 3D82AB4F-62DA-11cf-AB39-0020AF71E433 > ] - Optional animation template.


AnimTicksPerSecond

Describes an animation scale factor.

template AnimTicksPerSecond
{
    < 9E415A43-7BA6-4a73-8743-B73D47E88476 >
    DWORD AnimTicksPerSecond;
}

Where:

  • AnimTicksPerSecond - A scale factor to convert animation time stamps to global time. Its value divides the animation time by either 30, 60, 24 or 25.


Boolean

Defines a simple Boolean type.

template Boolean
{
    < 537da6a0-ca37-11d0-941c-0080c80cfa7b >
    DWORD truefalse;
}

Where:

  • truefalse - True for a Boolean, false otherwise.


Boolean2d

Defines a set of two Boolean values used in the MeshFaceWraps template to define the texture topology of an individual face.

template Boolean2d
{
    < 4885AE63-78E8-11cf-8F52-0040333594A3 >
    Boolean u;
    Boolean v;
}

Where:

  • u - Boolean value. See Boolean.
  • v - Boolean value. See Boolean.


ColorRGB

Defines the basic RGB color object.

template ColorRGB
{
    < D3E16E81-7835-11cf-8F52-0040333594A3 >
    float red;
    float green;
    float blue;
}


ColorRGBA

Defines a color object with an alpha component. This is used for the face color in the material template definition.

template ColorRGBA
{
    < 35FF44E0-6C7C-11cf-8F52-0040333594A3 >
    float red;
    float green;
    float blue;
    float alpha;
}


CompressedAnimationSet

Contains animation set data.

template CompressedAnimationSet
{
    <7F9B00B3-F125-4890-876E-1C42BF697C4D>
    DWORD CompressedBlockSize;
    FLOAT TicksPerSec;
    DWORD PlaybackType;
    DWORD BufferLength;
    array DWORD CompressedData[BufferLength];
}

Where:

  • CompressedBlockSize - Total size, in bytes, of the compressed data in the compressed key frame animation data buffer.
  • TicksPerSec - Number of animation key frame ticks that occur per second.
  • PlaybackType - Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.
  • BufferLength - Minimum buffer size, in bytes, required to hold compressed key frame animation data. Value is equal to ( ( CompressedBlockSize + 3 ) / 4 ).
  • CompressedData[BufferLength] - An array of compressed data values.

See Also

XFILECOMPRESSEDANIMATIONSET


Coords2d

Defines a two dimensional vector used to define a mesh's (u, v) texture coordinates.

template Coords2d
{
    < F6F23F44-7686-11cf-8F52-0040333594A3 >
    float u;
    float v;
}
  • u - u coordinate value.
  • v - v coordinate value.


DeclData

Describes a vertex declaration.

template DeclData
{
    < BF22E553-292C-4781-9FEA-62BD554BDD93 >
    DWORD nElements;
    array VertexElement Elements[nElements];
    DWORD nDWords;
    array DWORD data[nDWords];
}

Where:

  • nElements - Number of vertex declaration elements.
  • Elements[nElements] - Array of vertex declaration elements.
  • nDWords - Number of DWORDS.
  • data[nDWords] - Array of DWORDS that contain the data in each vertex element.


EffectDWord

Defines a legacy effect DWORD. This template has been replaced by the EffectParamDWord template.

template EffectDWord
{
    < 622C0ED0-956E-4da9-908A-2AF94F3CE716 >
    DWORD Value;
}


EffectFloats

Defines a legacy effect FLOAT. This template has been replaced by the EffectParamFloats template.

template EffectFloats
{
    < F1CFE2B3-0DE3-4e28-AFA1-155A750A282D >
    DWORD nFloats;
    array float Floats[nFloats];
}

Where:

  • nFloats - Number of floats.
  • Floats[nFloats] - Array of float values.


EffectInstance

Defines an effect instance.

template EffectInstance
{
    < E331F7E4-0559-4cc2-8E99-1CEC1657928F >
    STRING EffectFilename;
    [ ... ]
}

Where:

  • EffectFilename - Effect filename.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.


EffectParamDWord

Defines an effect DWORD. This template replaced the EffectDWord template.

template EffectParamDWord
{
    < E13963BC-AE51-4c5d-B00F-CFA3A9D97CE5 >
    STRING ParamName;
    DWORD Value;
}

Where:

  • ParamName - Parameter name.
  • Value - Parameter value.


EffectParamFloats

Defines effect floating-point numbers. This template replaces the EffectFloats template.

template EffectParamFloats
{
    < 3014B9A0-62F5-478c-9B86-E4AC9F4E418B >
    STRING ParamName;
    DWORD nFloats;
    array float Floats[nFloats];
}

Where:

  • ParamName - Name of the array of floats.
  • nFloats - Number of floating-point values in the array.
  • Floats[nFloats] - Array of floating-point values.


EffectParamString

Assigns a value to a parameter in an effect file.

template EffectParamString
{
    < 1DBC4C88-94C1-46ee-9076-2C28818C9481 >
    STRING ParamName;
    STRING Value;
}
  • ParamName - Parameter name in the effects file.
  • Value - Value assigned to the parameter.

This template replaces the former EffectString template.


EffectString

Legacy template used to assign a value in an effect file. This template has been replaced by the EffectParamString template.

template EffectString
{
    < D55B097E-BDB6-4c52-B03D-6051C89D0E42 >
    STRING Value;
}


FaceAdjacency

This template is instantiated on a per-mesh basis, holding information about which vertices in the mesh are duplicates of each other. Duplicates result when a vertex sits on a smoothing group or material boundary. The purpose of this template is to allow the loader to determine which vertices exhibiting different peripheral parameters are actually the same vertexes in the model. Certain applications (mesh simplification, for example) can make use of this information.

template FaceAdjacency
{
    < A64C844A-E282-4756-8B80-250CDE04398C >
    DWORD nIndices;
    array DWORD indices[nIndices];
}

Where:

  • nIndices - Number of indices in the mesh.
  • indices[nIndices] - Array of indices.


FloatKeys

Defines an array of floating-point numbers (floats) and the number of floats in that array. This is used for defining sets of animation keys.

template FloatKeys
{
    < 10DD46A9-775B-11cf-8F52-0040333594A3 >
    DWORD nValues;
    array float values[nValues];
}
  • nValues - Number of floats.
  • values[nValues] - Array of float values.


Frame

Defines a coordinate frame, or "frame of reference." The Frame template is open and can contain any object. The D3DX mesh-loading functions recognize Mesh, FrameTransformMatrix, and Frame template instances as child objects when loading a Frame instance.

template Frame
{
    < 3D82AB46-62DA-11CF-AB39-0020AF71E433 >
    [...]
}

The frame template recognizes child Frame and Mesh nodes inside a frame and can recognize user-defined templates through a callback function.


FrameTransformMatrix

Defines a local transform for a frame (and all its child objects).

template FrameTransformMatrix
{
    < F6F23F41-7686-11cf-8F52-0040333594A3 >
    Matrix4x4 frameMatrix;
}

Where:

  • frameMatrix - A Matrix4x4 template. See Matrix4x4.


FVFData

Specifies the mesh data minus the position data.

template FVFData
{
    < B6E70A0E-8EF9-4e83-94AD-ECC8B0C04897 >
    DWORD dwFVF;
    DWORD nDWords;
    array DWORD data[nDWords];
}

Where:

  • dwFVF - A FVF code.
  • nDWords - Binary data. The number of DWORDS.
  • data[nDWords] - Array of DWORDS that contain the data in each vertex element.


Guid

Defines a GUID that can be used in other templates.

template Guid
{
    < a42790e0-7810-11cf-8f52-0040333594a3 >
    DWORD data1;
    WORD data2;
    WORD data3;
    array UCHAR data4[8];
}

Where the parameters together form the binary storage format for a GUID:

  • data1 - 32-bit unsigned integer data value
  • data2 - 16-bit unsigned integer data value
  • data3 - 16-bit unsigned integer data value
  • data4 - An array of unsigned characters


IndexedColor

Consists of an index parameter and an RGBA color and is used for defining mesh vertex colors. The index defines the vertex to which the color is applied.

template IndexedColor
{
    < 1630B820-7842-11cf-8F52-0040333594A3 >
    DWORD index;
    ColorRGBA indexColor;
}

Where:

  • index - A DWORD. See the description above.
  • indexColor - A ColorRGBA template. See ColorRGBA.


Material

Defines a basic material color that can be applied to either a complete mesh or a mesh's individual faces. The power is the specular exponent of the material.

Note The ambient color requires an alpha component.

TextureFilename is an optional data object. If this object is not present, the face is untextured.

template Material
{
    < 3D82AB4D-62DA-11CF-AB39-0020AF71E433 >
    ColorRGBA faceColor;
    FLOAT power;
    ColorRGB specularColor;
    ColorRGB emissiveColor;
    [...]
}

Where:

  • faceColor - Face color. A ColorRGBA template. See ColorRGBA.
  • power - Material specular color exponent.
  • specularColor - Material specular color. A ColorRGB template. See ColorRGB.
  • emissiveColor - Material emissive color. A ColorRGB template. See ColorRGB.


MaterialWrap

Defines a set of two Boolean values used in the MeshFaceWraps template to define the texture topology of an individual face. Use instead of Boolean2d when the texture coordinates (u, v) span the range of 0 to 2 instead of 0 to 1.

template MaterialWrap
{
    < 4885ae60-78e8-11cf-8f52-0040333594a3 >
    Boolean u;
    Boolean v;
}

Where:

  • u - Boolean value. See Boolean.
  • v - Boolean value. See Boolean.

Note The MeshFaceWraps template is no longer used.


Matrix4x4

Defines a 4 x 4 matrix. This is used as a frame transformation matrix.

template Matrix4x4
{
    < F6F23F45-7686-11cf-8F52-0040333594A3 >
    array float matrix[16];
}

Where:

  • array float matrix[16] - Array of 16 floats.


Mesh

Defines a simple mesh. The first array is a list of vertices, and the second array defines the faces of the mesh by indexing into the vertex array.

template Mesh
{
    <3D82AB44-62DA-11CF-AB39-0020AF71E433>
    DWORD nVertices;
    array Vector vertices[nVertices];
    DWORD nFaces;
    array MeshFace faces[nFaces];
    [...]
}

Where:

  • nVertices - Number of vertices.
  • array Vector vertices[nVertices] - Array of vertices, each of type Vector. See Vector.
  • nFaces - Number of faces.
  • array MeshFace faces[nFaces] - Array of faces, each of type MeshFace. See MeshFace.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible. Material and TextureFilename templates are typically used.


MeshFace

Used by the Mesh template to define a mesh's faces. Each element of the nFaceVertexIndices array references a mesh vertex used to build the face.

template MeshFace
{
    < 3D82AB5F-62DA-11cf-AB39-0020AF71E433 >
    DWORD nFaceVertexIndices;
    array DWORD faceVertexIndices[nFaceVertexIndices];
}

Where:

  • nFaceVertexIndices - Number of indices.
  • array DWORD faceVertexIndices[nFaceVertexIndices] - Array of indices.


MeshFaceWraps

Used to define the texture topology of each face in a wrap. The value of the nFaceWrapValues member should be equal to the number of faces in a mesh.

template MeshFaceWraps
{
    < ED1EC5C0-C0A8-11D0-941C-0080C80CFA7B >
    DWORD nFaceWrapValues;
    array Boolean2d faceWrapValues[nFaceWrapValues];
}

This template is no longer used.


MeshMaterialList

Used in a mesh object to specify which material applies to which faces. The nMaterials member specifies how many materials are present, and materials specify which material to apply.

template MeshMaterialList
{
    < F6F23F42-7686-11CF-8F52-0040333594A3 >
    DWORD nMaterials;
    DWORD nFaceIndexes;
    array DWORD faceIndexes[nFaceIndexes];
    [Material <3D82AB4D-62DA-11CF-AB39-0020AF71E433>]
}

Where:

  • nMaterials - A DWORD. The number of materials.
  • nFaceIndexes - A DWORD. The number of indices.
  • faceIndexes[nFaceIndexes] - An arrray of DWORDs containing the face indices.


MeshNormals

Defines normals for a mesh. The first array of vectors is the normal vectors themselves, and the second array is an array of indexes specifying which normals should be applied to a given face. The value of the nFaceNormals member should be equal to the number of faces in a mesh.

template MeshNormals
{
    < F6F23F43-7686-11cf-8F52-0040333594A3 >
    DWORD nNormals;
    array Vector normals[nNormals];
    DWORD nFaceNormals;
    array MeshFace faceNormals[nFaceNormals];
}

Where:

  • nNormals - Number of normals.
  • array Vector normals[nNormals] - Array of normals. See Vector.
  • nFaceNormals - Number of face normals.
  • array MeshFace faceNormals[nFaceNormals] - Array of mesh face normals. See MeshFace.


MeshTextureCoords

Defines a mesh's texture coordinates.

template MeshTextureCoords
{
    < F6F23F40-7686-11cf-8F52-0040333594A3 >
    DWORD nTextureCoords;
    array Coords2d textureCoords[nTextureCoords] ;
}

Where:

  • nTextureCoords - Number of texture coordinates.
  • array Coords2d textureCoords[nTextureCoords] - Array of 2D texture coordinates. See Coords2d.


MeshVertexColors

Specifies vertex colors for a mesh, instead of applying a material per face or per mesh.

template MeshVertexColors
{
    <1630B821-7842-11cf-8F52-0040333594A3>
    DWORD nVertexColors;
    array IndexColor vertexColors[nVertexColors];
}

Where:

  • nVertexColors - Number of colors. This matches the number of vertices in the mesh.
  • array IndexColor vertexColors[nVertexColors] - Array of indexed colors. See IndexedColor.


Patch

Defines a Bézier control patch. The array defines the control points for the patch.

template Patch
{
    < A3EB5D44-FC22-429D-9AFB-3221CB9719A6 >
    DWORD nControlIndices;
    array DWORD controlIndices[nControlIndices];
}

Where:

  • nControlIndices - Number of control point indices.
  • array DWORD controlIndices[nControlIndices] - Array of control point indices.

The type of patch is defined by the number of control points, as shown in the following table.

Number of control points | Type
10 | Cubic Bézier triangular patch
15 | Quartic Bézier triangular patch
16 | Cubic Bézier quad rectangle patch

The order of the control points are given in a spiral pattern, as shown in the following diagrams for triangular and rectangular patches.

Triangular patches used the following pattern.

Rectangular patches use the following pattern.


PatchMesh

Defines a mesh defined by Bézier patches. The first array is a list of vertices, and the second array defines the patches for the mesh by indexing into the vertex array.

template PatchMesh
{
    < D02C95CC-EDBA-4305-9B5D-1820D7704BBF >
    DWORD nVertices;
    array Vector vertices[nVertices];
    DWORD nPatches;
    array Patch patches[nPatches];
    [ ... ]
}

Where:

  • nVertices - Number of vertices.
  • vertices[nVertices] - Array of vertices. See Vector.
  • nPatches - Number of patches.
  • patches[nPatches] - Array of patches. See Patch.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.

The patches use the vertices in the array of vertices as the control points for each patch. This is a legacy template. The latest patch mesh template is PatchMesh9.


PatchMesh9

Defines a mesh defined by Bézier patches. The first array is a list of vertices, and the second array defines the patches for the mesh by indexing into the vertex array.

template PatchMesh9
{
    < B9EC94E1-B9A6-4251-BA18-94893F02C0EA >
    DWORD Type;
    DWORD Degree;
    DWORD Basis;
    DWORD nVertices;
    array Vector vertices[nVertices];
    DWORD nPatches;
    array Patch patches[nPatches];
    [ ... ]
}

Where:

  • Type - Patch mesh type: rectangle, triangle, or N-patch.
  • Degree - Degree of the variables in the curve equation.
  • Basis - Basis type of a high-order patch surface.
  • nVertices - Number of vertices.
  • vertices[nVertices] - Array of vertices. See Vector.
  • nPatches - Number of patches.
  • patches[nPatches] - Array of patches. See Patch.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.

The patches use the vertices in the array of vertices as the control points for each patch.


PMAttributeRange

Not supported. Used internally by DirectX to represent and save a progressive mesh. This template should be used only with D3DX functions to read and write .x files.

template PMAttributeRange
{
    < 917E0427-C61E-4a14-9C64-AFE65F9E9844 >
    DWORD iFaceOffset;
    DWORD nFacesMin;
    DWORD nFacesMax;
    DWORD iVertexOffset;
    DWORD nVerticesMin;
    DWORD nVerticesMax;
}


PMInfo

Not supported. Used internally by DirectX.

template PMInfo
{
    < B6C3E656-EC8B-4b92-9B62-681659522947 >
    DWORD nAttributes;
    array PMAttributeRange attributeRanges[nAttributes];
    DWORD nMaxValence;
    DWORD nMinLogicalVertices;
    DWORD nMaxLogicalVertices;
    DWORD nVSplits;
    array PMVSplitRecord splitRecords[nVSplits];
    DWORD nAttributeMispredicts;
    array DWORD attributeMispredicts[nAttributeMispredicts];
}


PMVSplitRecord

Not supported. Used internally by DirectX.

template PMVSplitRecord
{
    < 574CCC14-F0B3-4333-822D-93E8A8A08E4C >
    DWORD iFaceCLW;
    DWORD iVlrOffset;
    DWORD iCode;
}


SkinWeights

This template is instantiated on a per-mesh basis. Within a mesh, a sequence of n instances of this template will appear, where n is the number of bones (X file frames) that influence the vertices in the mesh. Each instance of the template basically defines the influence of a particular bone on the mesh. There is a list of vertex indices, and a corresponding list of weights.

template SkinWeights
{
    < 6F0D123B-BAD2-4167-A0D0-80224F25FABB >
    STRING transformNodeName;
    DWORD nWeights;
    array DWORD vertexIndices[nWeights];
    array float weights[nWeights];
    Matrix4x4 matrixOffset;
}

Where:

  • The name of the bone whose influence is being defined is transformNodeName, and nWeights is the number of vertices affected by this bone.
  • The vertices influenced by this bone are contained in vertexIndices, and the weights for each of the vertices influenced by this bone are contained in weights.
  • The matrix matrixOffset transforms the mesh vertices to the space of the bone. When concatenated to the bone's transform, this provides the world space coordinates of the mesh as affected by the bone. See Matrix4x4.


TextureFilename

Enables you to specify the file name of a texture to apply to a mesh or a face. This template should appear within a material object.

template TextureFilename
{
    < A42790E1-7810-11cf-8F52-0040333594A3 >
    string filename;
}


TimedFloatKeys

Defines a set of floats and a positive time used in animations.

template TimedFloatKeys
{
    < F406B180-7B3B-11cf-8F52-0040333594A3 >
    DWORD time;
    FloatKeys tfkeys;
}

Where:

  • tfkeys - See FloatKeys.


Vector

Defines a vector.

template Vector
{
    < 3D82AB5E-62DA-11cf-AB39-0020AF71E433 >
    float x;
    float y;
    float z;
}


VertexDuplicationIndices

This template is instantiated on a per-mesh basis, holding information about which vertices in the mesh are duplicates of each other. Duplicates result when a vertex sits on a smoothing group or material boundary. The purpose of this template is to allow the loader to determine which vertices exhibiting different peripheral parameters are actually the same vertexes in the model. Certain applications (mesh simplification, for example) can make use of this information.

template VertexDuplicationIndices
{
    < B8D65549-D7C9-4995-89CF-53A9A8B031E3 >
    DWORD nIndices;
    DWORD nOriginalVertices;
    array DWORD indices[nIndices];
}

Where:

  • nIndices - Number of vertex indices. This is the number of vertices in the mesh.
  • nOriginalVertices - Number of vertices in the mesh before any duplication occurs.
  • The value indices[n] holds the vertex index that vertex[n] in the vertex array for the mesh would have had if no duplication had occurred. Indices in this array that are the same, therefore, indicate duplicate vertices.


VertexElement

Describes an individual vertex element in a vertex declaration.

template VertexElement
{
    < F752461C-1E23-48f6-B9F8-8350850F336F >
    DWORD Type;
    DWORD Method;
    DWORD Usage;
    DWORD UsageIndex;
}

Where:

  • Type - Vertex data type. See D3DDECLTYPE.
  • Method - Tessellator processing method. See D3DDECLMETHOD.
  • Usage - Intended use of the vertex data. See D3DDECLUSAGE.
  • UsageIndex - Modifies the usage data. See D3DDECLUSAGE.

See Also

D3DVERTEXELEMENT9


XSkinMeshHeader

This template is instantiated on a per-mesh basis only in meshes that contain exported skinning information. The purpose of this template is to provide information about the nature of the skinning information that was exported.

template XSkinMeshHeader
{
    < 3CF169CE-FF7C-44ab-93C0-F78F62D172E2 >
    WORD nMaxSkinWeightsPerVertex;
    WORD nMaxSkinWeightsPerFace;
    WORD nBones;
}

Where:

  • nMaxSkinWeightsPerVertex - Maximum number of transforms that affect a vertex in the mesh.
  • nMaxSkinWeightsPerFace - Maximum number of unique transforms that affect the three vertices of any face.
  • nBones - Number of bones that affect vertices in this mesh.


DDS File Reference

The DirectDraw Surface (.dds) file format is used to store textures and cubic environment maps, both with and without mipmap levels. This format can store uncompressed and compressed pixel formats, and is the preferred file format for storing DXTn compressed data. This file format is supported by the DirectX Texture tool (DirectX Texture Editor (Dxtex.exe)), as well as some non-Microsoft tools, and by the D3DX library.

This format was introduced with DirectX 7. In DirectX 8, support for volume textures was added.

File Layout

The basic structure of a .dds file is a header, and one or more surfaces written to a binary file. The header consists of a FOURCC and a DDSURFACEDESC2 structure. This header contains all the information needed to determine the contents of the entire file. The image below shows the layout of a .dds file.

DDS file format layout

Surface Format Header

The DDSURFACEDESC2 structure describes the file contents using the standard flags and values defined in the DirectDraw documentation, but files should use a restricted set of values to ensure full compatibility. A robust reader should verify key values and a robust writer should ensure all required flags are set for the different fields and options to ensure easy loading by the application or other tool. Also, a robust reader should not use a field unless the corresponding flag is set, and a robust writer should set all undefined fields to 0.

The table below shows the members of the DDSURFACEDESC2 structure.

Member | Description
DWORD dwSize | Size of structure. This member must be set to 124.
DWORD dwFlags | Flags to indicate valid fields. Always include DDSD_CAPS, DDSD_PIXELFORMAT, DDSD_WIDTH, DDSD_HEIGHT.
DWORD dwHeight | Height of the main image in pixels
DWORD dwWidth | Width of the main image in pixels
DWORD dwPitchOrLinearSize | For uncompressed formats, this is the number of bytes per scan line (DWORD> aligned) for the main image. dwFlags should include DDSD_PITCH in this case. For compressed formats, this is the total number of bytes for the main image. dwFlags should be include DDSD_LINEARSIZE in this case.
DWORD dwDepth | For volume textures, this is the depth of the volume. dwFlags should include DDSD_DEPTH in this case.
DWORD dwMipMapCount | For items with mipmap levels, this is the total number of levels in the mipmap chain of the main image. dwFlags should include DDSD_MIPMAPCOUNT in this case.
DWORD dwReserved1[11] | Unused
DDPIXELFORMAT ddpfPixelFormat | 32-byte value that specifies the pixel format structure.
DDCAPS2 ddsCaps | 16-byte value that specifies the capabilities structure.
DWORD dwReserved2 | Unused

Note that the field names used in this description do not correspond exactly with the DDSURFACEDESC2 fields due to the restrictions placed on the .dds file format, but a standard DDSURFACEDESC2 structure can and should be used. Use the magic DDS value and the header dwSize value to validate the file.

The pixel format of the image is given in the ddpfPixelFormat field of the header, and can describe all the formats supported by Direct3D. DDS files are usually restricted to either RGB or FOURCC formats, and the use of other formats is not generally supported. Restrict usage to RGB formats A8R8G8B8, A1R5G5B5, A4R4G4B4, R8G8B8, R5G6B5; and FOURCC formats DXT1, DXT2, DXT3, DXT4, and DXT5 to ensure the best support. A well-written reader should handle more formats, if possible.

The following table shows the layout of the DDPIXELFORMAT structure.

Member | Description
DWORD dwSize | Size of structure. This member must be set to 32.
DWORD dwFlags | Flags to indicate valid fields. Uncompressed formats will usually use DDPF_RGB to indicate an RGB format, while compressed formats will use DDPF_FOURCC with a four-character code.
DWORD dwFourCC | This is the four-character code for compressed formats. dwFlags should include DDPF_FOURCC in this case. For DXTn compression, this is set to "DXT1", "DXT2", "DXT3", "DXT4", or "DXT5".
DWORD dwRGBBitCount | For RGB formats, this is the total number of bits in the format. dwFlags should include DDPF_RGB in this case. This value is usually 16, 24, or 32. For A8R8G8B8, this value would be 32.
DWORD dwRBitMask, DWORD dwGBitMask, DWORD dwBBitMask | For RGB formats, these three fields contain the masks for the red, green, and blue channels. For A8R8G8B8, these values would be 0x00ff0000, 0x0000ff00, and 0x000000ff respectively.
DWORD dwRGBAlphaBitMask | For RGB formats, this contains the mask for the alpha channel, if any. dwFlags should include DDPF_ALPHAPIXELS in this case. For A8R8G8B8, this value would be 0xff000000.

The final details of the format are inferred from the capabilities bits set in the ddsCaps field of the header. The layout of the ddsCaps structure is shown in the table below.

Member | Description
DWORD dwCaps1 | DDS files should always include DDSCAPS_TEXTURE. If the file contains mipmaps, DDSCAPS_MIPMAP should be set. For any .dds file with more than one main surface, such as a mipmaps, cubic environment map, or volume texture, DDSCAPS_COMPLEX should also be set.
DWORD dwCaps2 | For cubic environment maps, DDSCAPS2_CUBEMAP should be included as well as one or more faces of the map (DDSCAPS2_CUBEMAP_POSITIVEX, DDSCAPS2_CUBEMAP_NEGATIVEX, DDSCAPS2_CUBEMAP_POSITIVEY, DDSCAPS2_CUBEMAP_NEGATIVEY, DDSCAPS2_CUBEMAP_POSITIVEZ, DDSCAPS2_CUBEMAP_NEGATIVEZ). For volume textures, DDSCAPS2_VOLUME should be included.
DWORD Reserved[2] | Unused

Note that as of DirectX 8, cubic environment maps are always written with all faces defined.

  • DDS File Layout for Textures
  • DDS File Layout for Cubic Environment Maps
  • DDS File Layout for Volume Textures
  • DDS Bit Flag Values


DDS File Layout for Textures

For simple uncompressed textures, a .dds file should contain DDSD_PITCH and a DDPF_RGB pixel format surface. The pitch value should be DWORD-aligned. In this case, the main image should be (dwPitchOrLinearSize-by-dwHeight) bytes total.

If the file also contains mipmaps, the DDSD_MIPMAPCOUNT, DDSCAPS_MIPMAP, and DDSCAPS_COMPLEX flags should be set, and the dwMipMapCount field should contain the total number of levels defined in the file (for a 256-by-256 image, this field would be 9). The pitch for each mipmap-level image is computed from dwWidth and the pixel format, which is then DWORD-aligned.

A 256-by-256 main image with a pixel format of R8G8B8 (three bytes per pixel) and all mipmap levels would contain the following layers:

Texture Size/Type | # Bytes
"DDS", 256x256, pitch=768, R8G8B8, 24 bits, mipmapcount = 9, (TEXTURE, PITCH, COMPLEX, MIPMAP, RGB) | 128
256-by-256 main image | 196608
128-by-128 mipmap image | 49152
64-by-64 mipmap image | 12288
32-by-32 mipmap image | 3072
16-by-16 mipmap image | 768
8-by-8 mipmap image | 192
4-by-4 mipmap image | 48
2-by-2 mipmap image | 12
1-by-1 mipmap image | 3

For simple compressed textures, the file should contain DDSD_LINEARSIZE and a DDPF_FOURCC pixel format surface. In this case, the image should be dwPitchOrLinearSize bytes total. If the file contains mipmaps, the DDSD_MIPMAPCOUNT, DDSCAPS_COMPLEX, DDSCAPS_MIPMAP, and dwMipMapCount fields should be set.

For DXTn compressed formats, the size of each mipmap level image is one-fourth the size of the previous, with a minimum of 8 (DXT1) or 16 (DXT2-5) bytes (this is true only for square textures). For example, a 256-by-256 main image, with a pixel format of DXT1 and all mipmap levels, would contain the following:

Texture Size/Type | # Bytes
DDS, 256x256, linearsize = 32768, 128 bytes DXT1, mipmapcount = 9, (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, FOURCC) | 128
256-by-256 main image | 32768
128-by-128 mipmap image | 8192
64-by-64 mipmap image | 2048
32-by-32 mipmap image | 512
16-by-16 mipmap image | 128
8-by-8 mipmap image | 32
4-by-4 mipmap image | 8
2-by-2 mipmap image | 8
1-by-1 mipmap image | 8

If mipmaps are generated, all levels down to 1-by-1 are usually written. Some tools may not support partial mipmap chains.

When computing DXTn compressed sizes for non-square textures, the following formula should be used at each mipmap level:

max(1, width ÷ 4) x max(1, height ÷ 4) x 8(DXT1) or 16(DXT2-5)

A 256-by-64 main image, with a pixel format of DXT1 and all mipmap levels, would contain the following:

Texture Size/Type | # Bytes
"DDS ", 256x64, linearsize = 8192, DXT1, mipmapcount = 9, (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, FOURCC) | 128 bytes
256-by-64 main image | 8192
128-by-32 mipmap image | 2048
64-by-16 mipmap image | 512
32-by-8 mipmap image | 128
16-by-4 mipmap image | 32
8-by-2 mipmap image | 16
4-by-1 mipmap image | 8
2-by-1 mipmap image | 8
1-by-1 mipmap image | 8


DDS File Layout for Cubic Environment Maps

For cubic environment maps, one or more faces of a cube are written to the file, using either uncompressed or compressed formats, and all faces must be the same size. Each face can have mipmaps defined, although all faces must have the same number of mipmap levels. If a file contains a cube map, DDSCAPS_COMPLEX, DDSCAPS2_CUBEMAP, and one or more of DSCAPS2_CUBEMAP_POSITIVEX/Y/Z and/or DDSCAPS2_CUBEMAP_NEGATIVEX/Y/Z should be set. The faces are written in the order: positive x, negative x, positive y, negative y, positive z, negative z, with any missing faces omitted. Each face is written with its main image, followed by any mipmap levels.

For example, a 256-by-256 cube map with positive x, negative y, and positive z faces, a pixel format of DXT1, and all mipmap levels would contain the following:

Texture Size/Type | # Bytes
"DDS ", 256x256, linearsize = 32768, DXT1, 128, (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, CUBEMAP, POSITIVEX, NEGATIVEY, POSITIVEZ, FOURCC) |
256-by-256 positive x main image | 32768
128-by-128 positive x mipmap image | 8192
64-by-64 positive x mipmap image | 2048
32-by-32 positive x mipmap image | 512
16-by-16 positive x mipmap image | 128
8-by-8 positive x mipmap image | 32
4-by-4 positive x mipmap image | 8
2-by-2 positive x mipmap image | 8
1-by-1 positive x mipmap image | 8
256-by-256 negative y main image | 32768
128-by-128 negative y mipmap image | 8192
64-by-64 negative y mipmap image | 2048
32-by-32 negative y mipmap image | 512
16-by-16 negative y mipmap image | 128
8-by-8 negative y mipmap image | 32
4-by-4 negative y mipmap image | 8
2-by-2 negative y mipmap image | 8
1-by-1 negative y mipmap image | 8
256-by-256 positive z main image | 32768
128-by-128 positive z mipmap image | 8192
64-by-64 positive z mipmap image | 2048
32-by-32 positive z mipmap image | 512
16-by-16 positive z mipmap image | 128
8-by-8 positive z mipmap image | 32
4-by-4 positive z mipmap image | 8
2-by-2 positive z mipmap image | 8
1-by-1 positive z mipmap image | 8

Note As of DirectX 8, cube maps are always written with all faces defined.


DDS File Layout for Volume Textures

A volume texture is an extension of the standard texture for Direct3D 9, and can be defined with or without mipmaps. If a file contains a volume texture, DDSCAPS_COMPLEX, DDSCAPS2_VOLUME, DDSD_DEPTH, and dwDepth should be set. For volumes without mipmaps, each depth slice is written to the file in order. If mipmaps are included, all depth slices for a given mipmap level are written together, with each level containing half as many slices as the previous level with a minimum of 1. Volume textures do not support DXTn compression as of Direct3D 9.

For example, a 64-by-64-by-4 volume map, a pixel format of R8G8B8 (3 bytes per pixel), and all mipmap levels would contain the following:

Texture Size/Type | # Bytes
"DDS ", 64x64x4, pitch=768, pixel format=R8G8B8, bitcount=24, mipmapcount=7, (DEPTH, TEXTURE, PITCH, COMPLEX, MIPMAP, VOLUME, RGB) | 128 bytes
64-by-64 slice 1 of 4 main image. | 12288 bytes
64-by-64 slice 2 of 4 main image. | 12288 bytes
64-by-64 slice 3 of 4 main image. | 12288 bytes
64-by-64 slice 4 of 4 main image. | 12288 bytes
32-by-32 slice 1 of 2 mipmap image. | 3072 bytes
32-by-32 slice 2 of 2 mipmap image. | 3072 bytes
16-by-16 slice 1 of 1 mipmap image. | 768 bytes
8-by-8 slice 1 of 1 mipmap image. | 192 bytes
4-by-4 slice 1 of 1 mipmap image. | 48 bytes
2-by-2 slice 1 of 1 mipmap image. | 12 bytes
1-by-1 slice 1 of 1 mipmap image. | 3 bytes

Note that the smallest mipmap level is only 3 bytes because the bitcount is 24 and there is no added compression at this level.


DDS Bit Flag Values

A number of fields make use of the standard DirectDraw bit flags. Those that are used for DirectDraw surface (DDS) files are included here for reference.

The dwFlags member of the original DDSURFACEDESC2 structure can be set to one or more of the following values:

Flag | Value
DDSD_CAPS | 0x00000001
DDSD_HEIGHT | 0x00000002
DDSD_WIDTH | 0x00000004
DDSD_PITCH | 0x00000008
DDSD_PIXELFORMAT | 0x00001000
DDSD_MIPMAPCOUNT | 0x00020000
DDSD_LINEARSIZE | 0x00080000
DDSD_DEPTH | 0x00800000

The ddpfPixelFormat member of the DDSURFACEDESC2 structure can be set to one or more of the following values:

Flag | Value
DDPF_ALPHAPIXELS | 0x00000001
DDPF_FOURCC | 0x00000004
DDPF_RGB | 0x00000040

The dwCaps1 member of the DDSCAPS2 structure can be set to one or more of the following values:

Flag | Value
DDSCAPS_COMPLEX | 0x00000008
DDSCAPS_TEXTURE | 0x00001000
DDSCAPS_MIPMAP | 0x00400000

The dwCaps2 member of the DDSCAPS2 structure can be set to one or more of the following values:

Flag | Value
DDSCAPS2_CUBEMAP | 0x00000200
DDSCAPS2_CUBEMAP_POSITIVEX | 0x00000400
DDSCAPS2_CUBEMAP_NEGATIVEX | 0x00000800
DDSCAPS2_CUBEMAP_POSITIVEY | 0x00001000
DDSCAPS2_CUBEMAP_NEGATIVEY | 0x00002000
DDSCAPS2_CUBEMAP_POSITIVEZ | 0x00004000
DDSCAPS2_CUBEMAP_NEGATIVEZ | 0x00008000
DDSCAPS2_VOLUME | 0x00200000


DirectX 9 for Windows Vista

Welcome to DirectX graphics for Windows Vista. DirectX provides a base level of support for hardware acceleration of graphics rendering, blending and compositing for applications and the Windows Vista desktop architecture. This documentation specifically refers to the Windows Vista extensions for DirectX graphics. To develop the power of DirectX for Windows Vista, you must install the Windows Vista SDK as well as the DirectX SDK.

  • Feature Summary
  • Beta 2 Features in DirectX for Windows Vista
  • Beta 1 Features in DirectX for Windows Vista
  • Direct3D 9Ex Reference
  • Direct3D 9 Video Reference


Feature Summary

This documentation specifically refers to the Windows Vista extensions for DirectX graphics. To develop the power of DirectX for Windows Vista, you must install the Windows Vista SDK as well as the DirectX SDK. Applications using DirectX for Windows Vista must be using hardware that implements the Windows Vista WDDM (Windows Device Driver Model). Currently this includes the Nvidia NV3x and ATI R300/400 class of hardware. Drivers that do not implement the WDDM, will not be able to instantiate Windows Vista DirectX graphics interfaces.

Discover the new DirectX graphics features in Windows Vista in one of these sections:

  • Device Behavior Changes
  • Disabling Multithreaded Software Vertex Processing
  • One Bit Surfaces
  • Reading Depth/Stencil Buffers
  • Sharing Resources
  • sRGB Conversion Before Blending
  • StretchRect Improvements
  • Texture Creation in System Memory

Device Behavior Changes

Devices are now only lost under two circumstances; when the hardware is reset because it is hanging, and when the device driver is stopped. When hardware hangs, the device can be reset by calling IDirect3DDevice9Ex::ResetEx. If hardware hangs, texture memory is lost.

After a driver is stopped, the IDirect9Ex object must be recreated to resume rendering.

When the presentation area is obscured by another window in windowed mode, or when a fullscreen application is minimized, IDirect3DDevice9Ex::PresentEx will return S_D3DPRESENTATIONOCCLUDED. Full screen applications can resume rendering when they receive a WM_ACTIVATEAPP callback message.

In previous versions of DirectX, when an application experienced a mode change, the only way to recover was to reset the device and re-create all video memory resources and swap chains. Now with DirectX for Windows Vista, calling Reset after a mode change does not cause texture memory surfaces, textures and state information to be lost and these resources do not need to be recreated.

Disabling Multithreaded Software Vertex Processing

A new caps bit (D3DCREATE_DISABLE_PSGP_THREADING) has been added that will disable multithreading for software vertex processing (swvp). Use this macro:

#define D3DCREATE_DISABLE_PSGP_THREADING

to generate a behavior flag for IDirect3D9::Createdevice.

One Bit Surfaces

There is a new one bit surface format type which can be especially useful for processing text glyphs. The new format is called D3DFMT_A1. A one-bit surface is designed to be either used as a per-pixel texture, or the render target output generated by ComposeRects or ColorFill. There are no separate caps for the surface width and height; an implementation must support a single size surface that is 2K texels x 8K texels.

A one-bit surface has one bit per texel; therefore, a one would mean that all components (r,g,b,a) of a pixel are 1, and zero would mean that all components are equal to 0. You may use one-bit surfaces with the following APIs: ColorFill, UpdateSurface and UpdateTexture.

When a one-bit surface is read, the runtime can perform either point sample or convolution filtering. The convolution filter is adjustable (see IDirect3DDevice9Ex::SetConvolutionMonoKernel).

There are some restrictions for one-bit surfaces:

  • Mip-mapping is not supported
  • sRGB data can not be read or written to a one-bit surface.
  • A one-bit surface cannot be used as a vertex texture or for multisampling.

Reading Depth/Stencil Buffers

Use IDirect3DDevice9::UpdateSurface to read or write depth/stencil data from surfaces obtained from IDirect3DDevice9::CreateDepthStencilSurface or IDirect3DDevice9::GetDepthStencilSurface.

First, create a lockable, depth only or stencil only surface using IDirect3DDevice9::CreateOffscreenPlainSurface. Use one of the following formats:

  • D3DFMT_D16_LOCKABLE
  • D3DFMT_D32F_LOCKABLE
  • D3DFMT_D32_LOCKABLE
  • D3DFMT_S8_LOCKABLE

Second, transfer data between the depth/stencil buffer and the newly-created lockable depth or stencil surface. The transfer is performed using IDirect3DDevice9::UpdateSurface.

UpdateSurface will fail when both surfaces are a LOCKABLE format or both are non-lockable.

Transferring non-existent data will result in an error (for example, transferring from a non-lockable depth-only surface to a D3DFMT_S8_LOCKABLE surface).

The rest of the restrictions for IDirect3DDevice9::UpdateSurface still apply.

Sharing Resources

Direct3D resources can now be shared between devices or processes. This applies to any Direct3D resource including textures, vertex buffers, index buffers, or surfaces (such as render targets, depth stencil buffers or off-screen plain surfaces). To be shared, you need to designate a resource for sharing at the time of creation, and locate the resource in the default pool (D3DPOOL_DEFAULT). Once a resource is created for sharing, it can be shared across devices within a process, or shared across processes.

To enable shared resources, the resource creation APIs have an additional handle parameter. This is a HANDLE that points to the shared resource. In previous revisions of DirectX, this argument has been part of the API signature, but has been unused and must be set to NULL. Starting with Windows Vista, use pSharedHandle in the following ways:

  • Set the pointer (pSharedHandle) to NULL to not share a resource. This is just like the behavior of DirectX prior to Windows Vista.
  • To create a shared resource, call any resource creation API (see below) with an uninitialized handle (the pointer itself is not NULL (pSharedHandle != NULL), but the pointer points to a NULL value (*pSharedHandle == NULL)). The API will generate a shared resource and return a valid handle.
  • To access a shared resource, simply use the shared resource handle.

Resource creation APIs include - CreateTexture, CreateVolumeTexture, CreateCubeTexture, CreateRenderTarget, CreateVertexBuffer, CreateIndexBuffer, CreateDepthStencilSurface, and CreateOffscreenPlainSurface.

There are some restrictions for using shared resources. These include:

  • Lockable resources (textures with D3DUSAGE_DYNAMIC, vertex buffers and index buffers, for instance) can experience poor performance when shared. Lockable rendertargets will fail to be shared on some hardware.
  • References to a cross-process shared resource must have the same dimensions as the original resource. When passing a handle across process, include the dimension information so that the reference can be created identically.
  • Shared cross-process surfaces provide no synchronization mechanism. Read/write changes to a shared surface may not reflect a referencing process's view of the surface when expected. To provide synchronization, use event queries or lock the texture.
  • Only the process that initially creates a shared resource can lock it (any process that opens a reference to that shared resource cannot lock it).
  • If a shared resource is locked, there is no validation for other processes to know if the resource is available.

sRGB Conversion Before Blending

You can now check to see if the device can convert pipeline data to sRGB before frame-buffer blending. This implies that the device converts the render-target values from sRGB. To see if conversion is supported by the hardware, check for this cap:

D3DPMISCCAPS_POSTBLENDSRGBCONVERT

This cap identifies hardware that supports conversion to sRGB before blending. This capability is important for the high quality rendering from fp16 frame buffers in the desktop window manager (DWM).

StretchRect Improvements

In previous versions of DirectX, StretchRect has many restrictions to accommodate different drivers (see IDirect3DDevice9::StretchRect). Windows Vista is built on the Windows Device Driver Model (WDDM). This new driver model is much more robust, and allows drivers to handle special cases in the hardware.

In general, the only remaining restriction is that the render target must have been created with render-target usage (D3DUSAGE_RENDERTARGET). This restriction is lifted if you are doing a simple copy (where the source and dest are the same format, same size and there are no sub-rectangles).

Texture Creation in System Memory

Applications that need more flexibility over the use, allocation and deletion of the system memory can now create textures from a system memory pointer. For example, an application could create a Direct3D texture from a GDI system-memory bitmap pointer.

You need to do two things to create such a texture:

  • Allocate enough system memory to hold the texture surface. The minimum number of bytes is width x height x bytes per pixel.
  • Pass the handle to the system memory pointer (you will need to cast it correctly) to IDirect3DDevice9::CreateTexture.

Here is the function prototype for IDirect3DDevice9::CreateTexture:

STDMETHOD(CreateTexture)(THIS_ UINT Width, UINT Height, UINT Levels,
    DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9** ppTexture,
    HANDLE* pSharedHandle)

A system-memory texture has the following restrictions:

  • The texture pitch must equal texture width times the number of bytes per pixel.
  • When using compressed formats (DXT formats), the application is responsible for allocating the correct size.
  • Only textures with a single mipmap level are supported.
  • The value passed to CreateTexture for the Pool argument must be D3DPOOL_SYSTEMMEM.
  • This API wraps the supplied memory in a texture. Do not deallocate this memory until you are done with it.


Beta 2 Features in DirectX for Windows Vista

The following features have changed in this update of DirectX for Windows Vista:

  • Device State
  • Detecting Missing Frames

Device State

This update improves the way that the DirectX device changes states. Fewer situations now cause a lost device, and mode changes no longer require an application to recreate swap chains and other resources. See Lost Device Behavior Changes, IDirect3DDevice9Ex::CheckDeviceState. Changes have also been made to the return values of the IDirect3DDevice9Ex::PresentEx and IDirect3DDevice9Ex::ResetEx methods to accommodate this change.

Detecting Missing Frames

An application that does not call Present once for every monitor refresh can cause noticeably jerky animations. This can be caused when an application tries to do too much rendering work for a single frame. In this update, two methods were added to IDirect3DSwapChain9Ex to help applications determine when glitches are happening. See D3DPRESENTSTATS (DirectX 9Ex only), IDirect3DSwapChain9Ex::GetPresentStatistics and IDirect3DSwapChain9Ex::GetLastPresentCount for more details.

See Also

Feature Summary


Beta 1 Features in DirectX for Windows Vista

The following features have changed in the previous DirectX for Windows Vista update:

  • Disabling Multithreaded Software Vertex Processing
  • One Bit Surfaces
  • Reading Depth/Stencil Buffers
  • Sharing Resources
  • sRGB Conversion Before Blending
  • StretchRect Improvements
  • Texture Creation in System Memory

Disabling Multithreaded Software Vertex Processing

DirectX for Windows Vista provides a way to disable multithreading for software vertex processing (swvp). See Disabling Multithreaded Software Vertex Processing.

One Bit Surfaces

A new surface format called D3DFMT_A1 is provided. This format is useful for processing text glyphs. See One Bit Surfaces.

Reading Depth/Stencil Buffers

IDirect3DDevice9::UpdateSurface now allows applications to read or write depth/stencil data from surfaces obtained from IDirect3DDevice9::CreateDepthStencilSurface or IDirect3DDevice9::GetDepthStencilSurface. See One Bit Surfaces.

Sharing Resources

DirectX for Windows Vista now allows resources to be shared between devices or processes. See Sharing Resources, IDirect3DDevice9Ex::CheckResourceResidency.

sRGB Conversion Before Blending

There is a new device capability that you can use to detect if the hardware supports converting pipeline data to sRGB before frame-buffer blending. See sRGB Conversion Before Blending.

StretchRect Improvements

DirectX for Windows Vista relaxes many of the restrictions to the StretchRect method. See StretchRect Improvements, IDirect3DDevice9Ex::ComposeRect.

Texture Creation in System Memory

With this release, applications have more flexability over allocation and deletion of the system memory because they can create textures from a system memory pointers. See Textures.


Direct3D 9Ex Reference

This page has been deprecated. See Direct3D Reference.


Direct3D 9Ex Interfaces

This page has been deprecated. See D3D Interfaces.


Direct3D 9Ex Functions

This page has been deprecated. See D3D Functions.


Direct3D 9Ex Structures

This page has been deprecated. See D3D Structures.


Direct3D 9Ex Enumerations

This page has been deprecated. See D3D Enumerations.


Direct3D 9Ex Constants

This page has been deprecated. See D3D Constants.


Direct3D 9 Video Reference

This section contains the reference pages for the Direct3D 9 Video Reference API.

  • IDirect3DDXVADevice9 Interface
  • IDirect3DVideoDevice9 Interface
  • DXVA Structures

See Also

Direct3D 9 Video Reference

© 2007 Microsoft Corporation. All rights reserved.


Direct3DDXVA Interfaces

This section contains the reference pages for the Direct3D 9 Video API.

  • IDirect3DDXVADevice9 Interface
  • IDirect3DVideoDevice9 Interface

See Also

Direct3D 9 Video Reference


IDirect3DDXVADevice9 Interface

IDirect3DDXVADevice9 Members

Method | Description
IDirect3DDXVADevice9::BeginFrame | Begins frame processing.
IDirect3DDXVADevice9::EndFrame | Ends frame processing and passes miscellaneous data to the device.
IDirect3DDXVADevice9::Execute | Sends an instruction to the device to perform the operation specified by the FunctionNum parameter.
IDirect3DDXVADevice9::QueryStatus | Queries the processing status of a data buffer.


IDirect3DDXVADevice9::BeginFrame

Begins frame processing.

HRESULT BeginFrame(
  IDirect3DSurface9* pDstSurface,
  DWORD SizeInputData,
  VOID* pInputData,
  DWORD pSizeOutputData,
  VOID* pOutputData
);

Parameters

pDstSurface
[in] Pointer to surface where the decoded frame will be written.
SizeInputData
[in] DWORD indicating the size of any additional input data required by the BeginFrame method.
pInputData
[in] Pointer to the additional input data required by the BeginFrame method.
pSizeOutputData
[out] Pointer to a DWORD indicating the size of the output data returned from the BeginFrame method.
pOutputData
[out] Pointer to the output data returned by the BeginFrame method.

Return Values

Requirements

Header: Declared in Dxva.h.

See Also

IDirect3DDXVADevice9 Interface


IDirect3DDXVADevice9::EndFrame

Ends frame processing and passes miscellaneous data to the device.

HRESULT EndFrame(
  DWORD SizeMiscData,
  VOID* pMiscData
);

Parameters

SizeMiscData
[in] Size of the data pointed to by the pMiscData parameter.
pMiscData
[out] Pointer to miscellaneous data that is sent to the device.

Return Values

Requirements

Header: Declared in Dxva.h.

See Also

IDirect3DDXVADevice9 Interface


IDirect3DDXVADevice9::Execute

Send an instruction to the device to perform the operation specified by the FunctionNum parameter.

HRESULT Execute(
  DWORD  FunctionNum,
  VOID* pInputData,
  DWORD  InputSize,
  VOID* pOuputData,
  DWORD OutputSize,
  DWORD NumBuffers,
  DXVABufferInfo* pBufferInfo
);

Parameters

FunctionNum
[in] The operation to be performed.
pInputData
[in] Pointer to private input data passed to the driver.
InputSize
[in] Length of private input data.
pOuputData
[in] Pointer to private output data passed to the driver.
OutputSize
[in] Length of private data buffer.
NumBuffers
[in] Number of DXVABufferInfo structures passed.
pBufferInfo
[in] Pointer to an array of DXVABufferInfo structures.

Return Values

Requirements

Header: Declared in Dxva.h.

See Also

IDirect3DDXVADevice9 Interface


IDirect3DDXVADevice9::QueryStatus

Queries the processing status of a data buffer.

HRESULT QueryStatus(
  IDirect3DSurface9* pSurface,
  DWORD Flags
);

Parameters

pSurface
[in] Surface to query status on.
Flags
[in] Flag indicating the type of query to perform. If zero, this method tests whether the surface is safe to use for updates. If AMVA_QUERYRENDERSTATUSF_READ, this method tests whether the surface is safe to use for reading.

Return Values

Requirements

Header: Declared in Dxva.h.

See Also

IDirect3DDXVADevice9 Interface


IDirect3DVideoDevice9 Interface

IDirect3DVideoDevice9 Members

Method | Description
IDirect3DVideoDevice9::CreateDXVADevice | Creates the specified device.
IDirect3DVideoDevice9::CreateSurface | Create a surface that is DXVA compatible.
IDirect3DVideoDevice9::GetDXVACompressedBufferInfo | Returns compressed buffer information.
IDirect3DVideoDevice9::GetDXVAGuids | Returns an array of device GUIDs.
IDirect3DVideoDevice9::GetDXVAInternalInfo | Returns internal information about a device.
IDirect3DVideoDevice9::GetUncompressedDXVAFormats | Returns information about the uncompressed format supported by the specified device GUID.


IDirect3DVideoDevice9::CreateDXVADevice

Creates the specified device.

HRESULT CreateDXVADevice(
  GUID* pGuid,
  DXVAUncompDataInfo* pUncompData,
  LPVOID pData,
  DWORD DataSize,
  IDirect3DDXVADevice9** ppDXVADevice
);

Parameters

pGuid
[in] Pointer to a GUID that identifies the device we want to create.
pUncompData
[in] Pointer to an DXVAUncompDataInfo struture.
pData
[in] Pointer to private data that should be passed to the created device.
DataSize
[in] Size of the private data.
ppDXVADevice
[out] Pointer to the new device. See IDirect3DDXVADevice9 Interface.

Return Values

Requirements

Header: Declared in Dxva.h.

See Also

IDirect3DVideoDevice9 Interface


IDirect3DVideoDevice9::CreateSurface

Create a surface that is DXVA compatible.

HRESULT CreateSurface(
  UINT Width,
  UINT Height,
  UINT BackBuffers,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Usage,
  IDirect3DSurface9** ppSurface,
  HANDLE* pHandle
);

Parameters

Width
[in] Surface width in pixels.
Height
[in] Surface height in pixels.
BackBuffers
[in] Number of back buffers.
Format
[in] Surface format.
Pool
[in] Pool to allocate surface in.
Usage
[in] Surface usage.
ppSurface
[out] Pointer to surface interface.
pHandle
[in] Reserved, must be NULL.

Return Values

Requirements

Header: Declared in Dxva.h.

See Also

IDirect3DVideoDevice9 Interface


IDirect3DVideoDevice9::GetDXVACompressedBufferInfo

Returns compressed buffer information.

HRESULT GetDXVACompressedBufferInfo(
  GUID* pGuid,
  DXVAUncompDataInfo* pUncompData,
  DWORD* pNumBuffers,
  DXVACompBufferInfo* pBufferInfo
);

Parameters

pGuid
[in] Pointer to guid to get info upon.
pUncompData
[out] Pointer to a DXVAUncompDataInfo structure.
pNumBuffers
[out] Pointer to a DWORD that describes the number of buffers to allocate.
pBufferInfo
[out] Pointer to a DXVACompBufferInfo structure.

Return Values

Requirements

Header: Declared in Dxva.h.

See Also

IDirect3DVideoDevice9 Interface


IDirect3DVideoDevice9::GetDXVAGuids

Returns and array of device GUIDs.

HRESULT GetDXVAGuids(
  DWORD* pNumGuids,
  GUID* pGuids
);

Parameters

pNumGuids
[in, out] Pointer to a DWORD - on input this value specifies the size of the pGuids array, on output this value specifies the number of GUIDs written to the array.
pGuids
[in, out] Pointer to an array of GUIDs or NULL if the caller wants to determine how many GUIDs will be returned.

Return Values

Requirements

Header: Declared in Dxva.h.

See Also

IDirect3DVideoDevice9 Interface


IDirect3DVideoDevice9::GetDXVAInternalInfo

Returns internal information about a device.

HRESULT GetDXVAInternalInfo(
  GUID* pGuid,
  DXVAUncompDataInfo* pUncompData,
  DWORD* pMemoryUsed
);

Parameters

pGuid
[in] Pointer to a GUID that we want info upon.
pUncompData
[out] Pointer to a DXVAUncompDataInfo structure.
pMemoryUsed
[out] Pointer to a DWORD.

Return Values

Requirements

Header: Declared in Dxva.h.

See Also

IDirect3DVideoDevice9 Interface


IDirect3DVideoDevice9::GetUncompressedDXVAFormats

Returns information about the uncompressed format supported by the specified device GUID.

HRESULT GetUncompressedDXVAFormats(
  GUID* pGuid,
  DWORD* pNumFormats,
  D3DFORMAT* pFormats
);

Parameters

pGuid
[in] Pointer to a GUID that we want uncompressed format info for.
pNumFormats
[out] Pointer to a DWORD that on input describes the size of the format array and on output returns the number of formats written to the array.
pFormats
[in, out] Pointer to a D3DFORMAT array.

Return Values

Requirements

Header: Declared in Dxva.h.

See Also

IDirect3DVideoDevice9 Interface


DXVA Structures

This section contains the reference pages for the Direct3D 9 Video API.

  • DXVABufferInfo
  • DXVACompBufferInfo
  • DXVAUncompDataInfo

See Also

Direct3D 9 Video Reference


DXVABufferInfo

typedef struct DXVABufferInfo {
    VOID* pCompSurface;
    DWORD DataOffset;
    DWORD DataSize;
} DXVABufferInfo, *LPDXVABufferInfo;

Members

pCompSurface
Pointer to a buffer containing compressed data.
DataOffset
Offset of relevant data from the beginning of buffer.
DataSize
Size of relevant data.

Requirements

Header: Declared in Dxva.h.


DXVACompBufferInfo

typedef struct DXVACompBufferInfo {
    DWORD NumCompBuffers;
    DWORD WidthToCreate;
    DWORD HeightToCreate;
    DWORD BytesToAllocate;
    DWORD Usage;
    D3DPOOL Pool;
    D3DFORMAT Format;
} DXVACompBufferInfo, *LPDXVACompBufferInfo;

Members

NumCompBuffers
Number of buffers required for compressed data.
WidthToCreate
Width of surface to create.
HeightToCreate
Height of surface to create.
BytesToAllocate
Total number of bytes used by each surface.
Usage
Usage used to create the compressed buffer.
Pool
Pool where the compressed buffer belongs.
Format
Format used to create the compressed buffer.

Requirements

Header: Declared in Dxva.h.


DXVAUncompDataInfo

typedef struct DXVAUncompDataInfo {
    DWORD UncompWidth;
    DWORD UncompHeight;
    D3DFORMAT UncompFormat;
} DXVAUncompDataInfo, *LPDXVAUncompDataInfo;

Members

UncompWidth
Width of uncompressed data.
UncompHeight
Height of uncompressed data.
UncompFormat
Format of uncompressed data.

Requirements

Header: Declared in Dxva.h.


HLSL

HLSL is the High Level Shading Language for DirectX. Using HLSL, you can create C like programmable shaders for the Direct3D pipeline.

HLSL was created starting with DirectX 8 to set up the programmable 3D pipeline. In DirectX 8, the pipeline was programmed with a combination of assembly instructions, HLSL instructions and fixed-function statements. With the introduction of the Direct3D 10 API, the pipeline is now virtually 100% programmable using only HLSL; in fact, assembly is no longer used to generate shader code with Direct3D 10.

  • Reference (DirectX HLSL) - The reference section has a complete listing of the language syntax, as well as intrinsic functions that are built into the langauge to simplify your coding requirements.


Programming Guide

This programming guide will help you understand how to create shaders written in the High Level Shading Language. This programming language is used to create vertex, geometry, and pixel shaders for the Direct3D 10 pipeline, as well as the vertex and pixel shaders used by the Direct3D 9 pipeline.

  • Shaders

Basic topics will help you understand how to write basic vertex and pixel shader code, compile the shader code, and initialize pipeline stages by binding the shaders to the pipeline.

Intermediate topics show you how to use functionality that is either brand new to Direct3D 10, or has been enhanced by Direct3D 10 . This includes the geometry shader stage (which is new to Direct3D 10), adding user metadata to shader variables with semantics and annotations, using the effect framework to manage state changes efficiently, and introducing the texture sampling objects in Direct3D 10.

Advanced topics are more focused on preformance and efficiency topics. These include using system-value parameters in Direct3D 10 to make shader stages operate on per primitive data, explaining shader signatures and how they help link shader inputs and outputs, and demonstrating other efficienct topics like packing shader constants, working with resource arrays, and using multiple render targets in single pass rendering.

See Also

HLSL


Shaders

At a very high level, data enters the graphics pipeline as a stream of primitives and is processed by up to as many as three shader stages:

  • A vertex shader performs per-vertex processing such as transformations, skinning, vertex displacement, and calculating per-vertex material attributes. Tessellation of higher-order primitives should be done before the vertex shader executes. As a minimum, a vertex shader must output vertex position in homogeneous clip space. Optionally, the vertex shader can output texture coordinates, vertex color, vertex lighting, fog factors, and so on.
  • A geometry shader performs per-primitive processing such as material selection and silhouette-edge detection, and can generate new primitives for point sprite expansion, fin generation, shadow volume extrusion, and single pass rendering to multiple faces of a cube texture.
  • A pixel shader performs per-pixel processing such as texture blending, lighting model computation, and per-pixel normal and/or environmental mapping. Pixel shaders work in concert with vertex shaders; the output of a vertex shader provides the inputs for a pixel shader. In Direct3D 9 some pixel operations (such as fog blending, stencil operations, and render-target blending) occur after the pixel shader is finished.

These stages are completely programmable using the High Level Shading Language (see HLSL). Authored HLSL shaders can be compiled at author-time or at runtime, and set at runtime into the appropriate pipeline stage.

All Direct3D 10 shaders are compiled with the shader model 4 target. Functions like D3D10CompileShader and D3D10CompileEffectFromMemory require a shader profile to tell the compiler which shader model to compile for.

Compiling Shaders

There are two ways to compile shaders and effects with the HLSL compiler.

  • Runtime compilation using API functions such as D3DX10CompileFromFile for Direct3D 10 shaders or API functions like D3DXCompileShader, and D3DXAssembleShader for Direct3D 9 shaders.
  • Offline compilation using the shader-compiler tool.

Internally, the HLSL compiler implements two version of the compiler. The new version that was first introduced in Direct3D 10 (with the DirectX December 2006 SDK) and the legacy compiler that was introduced in Direct3D 9. It is not recommended that you use the legacy compiler to compile shaders; it is much more complex due to hardware restrictions in early pixel shaders. However, it is possible to use either the default compiler or the legacy compiler when compiling your shaders or effects.

The default compiler no longer directly supports shader model 1 (specifically ps_1_x shader targets) which simplifies the code that was very hardware dependent. To avoid the need to modify shader targets to shader model 2 or higher in existing code, use the /Gec switch which tells the compiler to promote all ps_1_x targets to ps_2_0 targets.

If you need to compile shaders with the legacy compiler, you may do so by supplying the appropriate flags to the API or command-line switches to the shader-compiler tool.

Effects that specify ps_1_x targets will instead compile to ps_2_0 targets because this is the minimum shader version supported by the DirectX 10 HLSL compiler. This switch has no effect when used with higher level compile targets.

To compile a shader with the DirectX 9 HLSL compiler using an API call, use the D3DXSHADER_USE_LEGACY_D3DX9_31_DLL flag. Applications must make sure to include the OCT2006_d3dx9_31_x86.cab or OCT2006_d3dx9_31_x64.cab in their redistributable packages if they are planning on using this flag. See Installing DirectX with DirectSetup for more details.

See Also

HLSL


Using Shaders in Direct3D 9

  • Compiling a Shader for Specific Hardware
  • Initializing Shader Constants
  • Binding a Shader Parameter to a Particular Register
  • Rendering a Programmable Shader
  • Debugging Shaders
  • Building and Rendering Fragments

Compiling a Shader for Specific Hardware

Beginning with the December 2006 SDK, the DirectX 10 HLSL compiler is now the default compiler in both DirectX 9 and DirectX 10. See DirectX 10 HLSL Compiler (Direct3D 10) for details.

Shaders were first added to Microsoft DirectX in DirectX 8.0. At that time, several virtual shader machines were defined, each roughly corresponding to a particular graphics processor produced by the top 3D graphics vendors. For each of these virtual shader machines, an assembly language was designed. Programs written to the shader models (names vs_1_1 and ps_1_1 - ps_1_4) were relatively short and were generally written by developers directly in the appropriate assembly language. The application would pass this human-readable assembly language code to the D3DX library using D3DXAssembleShader and get back a binary representation of the shader which would in turn get passed using IDirect3DDevice9::CreateVertexShader or IDirect3DDevice9::CreatePixelShader. For more detail, see the software development kit (SDK).

The situation in Direct3D 9 is similar. An application passes an HLSL shader to D3DX using D3DXCompileShader and gets back a binary representation of the compiled shader which in turn is passed to Microsoft Direct3D using IDirect3DDevice9::CreatePixelShader or IDirect3DDevice9::CreateVertexShader. The runtime does not know anything about HLSL, only the binary assembly shader models. This is nice because it means that the HLSL compiler can be updated independent of the Direct3D runtime. You can also compile shaders offline using fxc.

In addition to the development of the HLSL compiler, Direct3D 9 also introduced the assembly-level shader models to expose the functionality of the latest generation of graphics hardware. Application developers can work in assembly for these new models (vs_2_0, vs_3_0, ps_2_0, ps_3_0) but we expect most developers to move to HLSL for shader development.

Of course, the ability to write an HLSL program to express a particular shading algorithm does not automatically enable it to run on any given hardware. An application calls D3DX to compile a shader into binary assembly code with D3DXCompileShader. One of the limitations with this entry point is a parameter that defines which of the assembly-level models (or compilation targets) the HLSL compiler should use to express the final shader code. If an application is doing HLSL shader compilation at run time (as opposed to compile time or offline), the application could examine the capabilities of the Direct3D device and select the compilation target to match. If the algorithm expressed in the HLSL shader is too complex to execute on the selected compilation target, compilation will fail. This means that while HLSL is a huge benefit to shader development, it does not free developers from the realities of shipping games to a target audience with graphics devices of varying capabilities. As a game developer, you still have to manage a tiered approach to your visuals; this means writing better shaders for more capable graphics cards and writing more basic versions for older cards. With well written HLSL, however, this burden can be eased significantly.

Rather than compile HLSL shaders using D3DX on the customer's machine at application load time or on first use, many developers choose to compile their shader from HLSL to binary assembly code before they even ship. This keeps their HLSL source code away from prying eyes and also ensures that all the shaders their application will ever run have gone through their internal quality assurance process. A convenient utility for compiling shaders offline is fxc. This tool has a number of options that you can use to compile code for the specified compile target. Studying the disassembled output can be very educational during development if you want to optimize your shaders or just generally get to know the virtual shader machine's capabilities at a more detailed level. These options are summarized below:

Initializing Shader Constants

Shader constants are contained in the constant table. This can be accessed with the ID3DXConstantTable interface. Global shader variables can be initialized in shader code. These are initialized at run time by calling ID3DXConstantTable::SetDefaults.

Binding a Shader Parameter to a Particular Register

The compiler will automatically assign registers to global variables. The compiler would assign Environment to sampler register s0, SparkleNoise to sampler register s1, and k_s to constant register c0 (assuming no other sampler or constant registers were already assigned) for the following three global variables:

sampler Environment;
sampler SparkleNoise;
float4 k_s;

It is also possible to bind variables to a specific register. To force the compiler to assign to a particular register, use the following syntax:

register(RegisterName)

where RegisterName is the name of the specific register. The following examples demonstrate the specific register assignment syntax, where the sampler Environment will be bound to sampler register s1, SparkleNoise will be bound to sampler register s0, and k_s will be bound to constant register c12:

sampler Environment : register(s1);
sampler SparkleNoise : register(s0);
float4 k_s : register(c12);

Rendering a Programmable Shader

A shader is rendered by setting the current shader in the device, initializing the shader constants, telling the device where the varying input data is coming from, and finally rendering the primitives. Each of these can be accomplished by calling the following methods respectively:

  • IDirect3DDevice9::SetVertexShader
  • IDirect3DDevice9::SetVertexShaderConstantF
  • IDirect3DDevice9::SetStreamSource
  • IDirect3DDevice9::DrawPrimitive

Debugging Shaders

The DirectX extension for Microsoft Visual Studio .NET is provides a fully integrated HLSL debugger within the Visual Studio .NET Integrated Development Environment (IDE). In order to prepare for shader debugging, you must install the right tools on your machine (see Getting Started Debugging Shaders (Direct3D 9)). If you already have the right tools installed, you can also try the Goal 5 - Shader Debugging Tutorial.

Building and Rendering Fragments

Fragments can be compiled, linked, and rendered with or without effects. Since it is easier to take advantage of an effect, this case will be shown first.

Building and Rendering Fragments from an Effect

Given an effect that contains an HLSL or an assembly fragment, (see Writing Shader Fragments), compile the fragment by calling D3DXGatherFragmentsFromFile as shown here:

DWORD         g_dwShaderFlags; // Shader compilate and link flags
LPD3DXBUFFER  g_pCompiledFragments = NULL;

    D3DXGatherFragmentsFromFile( L"FragmentLinker.fx", NULL,
                NULL, g_dwShaderFlags, &g_pCompiledFragments, NULL );

D3DXGatherFragmentsFromFile requires the .fx file, pointers to the #define and #include handlers (both set to NULL in this example), and the shader compile flags. The method returns a buffer which contains the compiled shader fragment. The method can return a second buffer with compile errors, which is set to NULL in this example because it is not used. D3DXGatherFragments is overloaded to handle loading fragments from a string, a file, or a resource.

Set your debugger to break on this method to look for compile errors in the debugger. The compiler can catch errors in syntax, but it cannot check for registers that are shared incorrecly due to the fact that it has no way to predict which parameters a user may want to share between fragments.

You need a fragment linker to manage the compiled fragments. Create the fragment linker by calling D3DXCreateFragmentLinker:

ID3DXFragmentLinker* g_pFragmentLinker = NULL;     // Fragment linker interface
IDirect3DDevice9*    pd3dDevice        = NULL;

    // Initialize the device before using it
    ...

    // Create the fragment linker interface
    D3DXCreateFragmentLinker( pd3dDevice, 0, &g_pFragmentLinker );

Then simply add the compiled fragments to the fragment linker using ID3DXFragmentLinker::AddFragments.

    // Add the compiled fragments to a list
    g_pFragmentLinker->AddFragments(
              (DWORD*)g_pCompiledFragments->GetBufferPointer() );

ID3DXFragmentLinker::AddFragments requires a pointer to the DWORD stream that contains the compiled shader.

After compiling fragments and creating a fragment linker, there are several ways to link fragments. One way to link a vertex shader fragment is to call ID3DXFragmentLinker::LinkVertexShader. Here is an example that links two vertex shader fragments:

    // Get a handle to each fragment
    D3DXHANDLE fragmentHandle[2];
    fragmentHandle[0] =
        (D3DXHANDLE)g_pFragmentLinker->GetFragmentHandleByName("Ambient");
    fragmentHandle[1] =
        (D3DXHANDLE)g_pFragmentLinker->GetFragmentHandleByName("AmbientDiffuseFragment");

    // Link the fragments together to form a vertex shader
    IDirect3DVertexShader9* pVertexShader = NULL;
    g_pFragmentLinker->LinkVertexShader( "vs_1_1", g_dwShaderFlags,
              fragmentHandle, 2, &pVertexShader, NULL );

This requires a shader compile target, the shader compile and link flags, and a handle to each of the fragments to link. If the fragments are successfully linked, ID3DXFragmentLinker::LinkVertexShader returns a vertex shader (IDirect3DVertexShader9). The vertex shader needs to be set in the effect before rendering. But before this, here's how the shader is declared in the effect:

VertexShader MyVertexShader; // Vertex shader set by the application

The effect technique contains all the state set for a pass. This pass specifies the vertex shader like this:

technique RenderScene
{
    pass P0
    {
        VertexShader = <MyVertexShader>;
        PixelShader = compile ps_1_1 ModulateTexture();
    }
}

With the effect's vertex shader created and initialized, the render code also sets the uniform constants and calls the render loop. Set the uniform constants similar to this:

    // Update the uniform shader constants.
    g_pEffect->SetMatrix( "g_mWorldViewProjection", &mWorldViewProjection );
    g_pEffect->SetMatrix( "g_mWorld", &mWorld );
    g_pEffect->SetFloat( "g_fTime", (float)fTime );

Then render the effect by setting the current technique and pass:

    // Render the scene
    if( SUCCEEDED( pd3dDevice->BeginScene() ) )
    {
        // Apply the technique contained in the effect
        UINT cPasses, iPass;
        g_pEffect->Begin(&cPasses, 0);

        for (iPass = 0; iPass < cPasses; iPass++)
        {
            g_pEffect->BeginPass(iPass);

            // Render the mesh with the applied technique
            g_pMesh->DrawSubset(0);

            g_pEffect->EndPass();
        }
        g_pEffect->End();

        pd3dDevice->EndScene();
    }

When setting uniform shader constants, it is more efficient to cache a handle to the parameter by calling ID3DXBaseEffect::GetParameterByName. This avoids the string lookup that is necessary when calling effect methods like ID3DXBaseEffect::SetMatrix.

  // Instead of setting a uniform constant like this in the render loop
  g_pEffect->SetMatrix( "g_mWorldViewProjection", &mWorldViewProjection );

  // Get a handle to a uniform constant outside of the render loop
  D3DXHANDLE hParameter;
  GetParameterByName( hParameter,"g_mWorldViewProjection");

  ...

  // Use the handle to set the uniform constant in the render loop
  g_pEffect->SetMatrix(hParameter);

Building and Rendering Fragments Without an Effect

Building a fragment that does not live in an effect is very similar to building a fragment that is in an effect. You still use D3DXGatherFragments to compile one or more fragments. If the fragments are HLSL, they will be compiled. If the fragments are assembly fragments, they will be assembled. You still create a fragment linker(created by D3DXCreateFragmentLinker), add all the fragments to the linker (with ID3DXFragmentLinker::AddFragments), and link the fragments together to create a vertex shader with ID3DXFragmentLinker::LinkVertexShader.

Rendering a fragment without an effect is slightly different, because you cannot use the effect to set the uniform shader constants. Because every vertex or pixel shader contains a constant table (ID3DXConstantTable), you will need to get the constant table and use it to initialize the uniform shader constants.

    LPD3DXCONSTANTTABLE pConstantTable;
    LPD3DXBUFFER pShaderBuf;
    IDirect3DVertexShader9* pVertexShader = NULL;

    // Compile the fragments to a buffer.
    D3DXGatherFragmentsFromFile( L"FragmentLinker.fx", NULL, NULL,
            g_dwShaderFlags, &g_pCompiledFragments, NULL );

    g_pFragmentLinker->AddFragments((DWORD*)g_pCompiledFragments->GetBufferPointer());
    g_pFragmentLinker->LinkShader(
        "vs_1_1",
        g_dwShaderFlags,
        aHandles,
        NUM_FRAGMENTS,
        &pShaderBuf,
        NULL);
    D3DXGetShaderConstantTable(
        (DWORD*)pShaderBuf->GetBufferPointer(),
        &pConstantTable );

    pDevice->CreateVertexShader(
        (DWORD*)pShaderBuf->GetBufferPointer(),
        &pVertexShader);
    RELEASE(pShaderBuf);

The fragment linking operation efficiently links together HLSL fragments and assembly fragments, and generates a shader object from one or more fragments. The constant table generated from a fragment is identical to the constant table generated from a shader. This is because each binary shader contains the constant table and the shader input declarations.

See Also

Shaders


Using Shaders in Direct3D 10

The pipeline has three shader stages and each one gets is programmed from a shader written in HLSL. All Direct3D 10 shaders are written in HLSL, targeting shader model 4.

Differences between Direct3D 9 and Direct3D 10:

Unlike in earlier Direct3D 9 Shader Models, where shaders could be authored in an intermediate assembly language, Shader Model 4.0 shaders are only authored in HLSL. Offline compilation of shaders into device-consumable bytecode is still supported, and recommended for most scenarios.

This example uses only a vertex shader. Because all shaders are built from the common shader core, learning how to use a vertex shader is very similar to using a geometry or pixel shader.

Once you have authored an HLSL shader (this example uses the vertex shader HLSLWithoutFX.vsh), you will need to prepare it for the particular pipeline stage that will use it. To do this you need to:

  • Compile a Shader
  • Create a Shader Object
  • Set the Shader Object
  • Repeat for all 3 Shader Stages

These steps need to be repeated for each shader in the pipeline.

Compile a Shader

The first step is to compile the shader, to check to see that you have coded the HLSL statements correctly. This is done by calling D3D10CompileShader and supplying it with several parameters as shown here:

    IPD3D10Blob * pBlob;

    // Compile the vertex shader from the file
    D3D10CompileShader( strPath, strlen( strPath ), "HLSLWithoutFX.vsh",
        NULL, NULL, "Ripple", "vs_4_0", dwShaderFlags, &pBlob, NULL );

This function takes the following parameters:

  • The name of the file ( and length of the name string in bytes ) that contains the shader. This example uses a vertex shader only (in the file HLSLWithoutFX.vsh file where the file extension .vsh is an abbreviation for vertex shader).
  • The shader function name. This example compiles a vertex shader from the Ripple function which takes a single input and returns an output struct (the function is from the HLSLWithoutFX sample):
    VS_OUTPUT Ripple( in float2 vPosition : POSITION )
  • A pointer to all macros used by the shader. Use D3D10_SHADER_MACRO to help define your macros; simply create a name string that contains all the macro names (with each name separated by a space) and a definition string (with each macro body separated by a space). Both strings need to be NULL terminated.
  • A pointer to any other files that you need included to get your shaders to compile. This uses the ID3D10Include interface which has two user-implemented methods: Open and Close. To make this work, you will need to implement the body of the Open and Close methods; in the Open method add the code you would use to open whatever include files you want, in the Close function add the code to close the files when you are done with them.
  • The name of the shader function to compile. This shader compiles the Ripple function.
  • The shader profile to target when compiling. Since you can compile a function into a vertex, geometry, or pixel shader, the profile tells the compiler which type of shader and which shader model to compare the code against.
  • Shader compiler flags. These flags tell the compiler what information to put into the compiled output and how you want the output code optimized: for speed, for debug, etc. See Effect Constants (Direct3D 10) for a listing of the available flags. The sample contains some code you can use to set the compiler flag values for your project - this is mainly a question of whether or not you want to generate debug information.
  • A pointer to the buffer that contains the compiled shader code. The buffer also contains any embedded debug and symbol table information requested by the compiler flags.
  • A pointer to a buffer that contains a listing of errors and warnings that were encountered during the compile, which are the same messages you would see in the debug output if you were running the debugger while compiling the shader. NULL is an acceptable value when you don't want the errors returned to a buffer.

If the shader compiles successfully, a pointer to the shader code is returned as a ID3D10Blob interface. It is called the Blob interface because the pointer is to a location in memory that is made up of an array of DWORD's. The interface is provided so that you can get a pointer to the compiled shader which you will need in the next step.

Beginning with the December 2006 SDK, the DirectX 10 HLSL compiler is now the default compiler in both DirectX 9 and DirectX 10. See DirectX 10 HLSL Compiler (Direct3D 10) for details.

Get a Pointer to a Compiled Shader

Several API methods require a pointer to a compiled shader. This argument is usually called pShaderBytecode because it points to a compiled shader represented as a sequence of byte codes. To get a pointer to a compiled shader, first compile the shader by calling D3D10CompileShader or a similar function. If compilation is successful, the compiled shader is returned in an ID3D10Blob interface. Finally, use the ID3D10Blob::GetBufferPointer method to return the pointer.

Create a Shader Object

Once the shader is compiled, call CreateVertexShader to create the shader object:

    ID3D10VertexShader ** ppVertexShader
    ID3D10Blob pBlob;

    // Create the vertex shader
    hr = pd3dDevice->CreateVertexShader( (DWORD*)pBlob->GetBufferPointer(),
        pBlob->GetBufferSize(), &ppVertexShader );

    // Release the pointer to the compiled shader once you are done with it
    pBlob->Release();

To create the shader object, pass the pointer to the compiled shader into CreateVertexShader. Since you had to successfully compile the shader first, this call will almost certainly pass, unless you have a memory problem on your machine.

You can create as many shader objects as you like and simply keep pointers to them. This same mechanism works for geometry and pixel shaders assuming you match the shader profiles (when you call the compile method) to the interface names (when you call the create method).

Set the Shader Object

The last step is set the shader to the pipeline stage. Since there are three shader stages in the pipeline, you will need to make three API calls, one for each stage.

    // Set a vertex shader
    pd3dDevice->VSSetShader( g_pVS10 );

The call to VSSetShader takes the pointer to the vertex shader created in step 1. This sets the shader in the device. The vertex shader stage is now initialized with its vertex shader code, all that remains is initializing any shader variables.

Repeat for all 3 Shader Stages

Repeat these same set of steps to build any vertex or pixel shader or even a geometry shader that outputs to the pixel shader.

See Also

Shaders


Reference (DirectX HLSL)

The HLSL reference documentation specifies the language characteristics. It is broken into several sections.

  • Language Syntax (DirectX HLSL) - Programming shaders in HLSL requires that you understand the language syntax, that is, how you write HLSL code. This includes code to declare and initialize variables, write user-defined shader functions, and add flow control statements to make your functions more powerful.
  • Shader Models (DirectX HLSL) - The HLSL compiler implements rules and restrictions based on shader models. The code in each vertex shader, geometry shader (if you are using Direct3D 10) and pixel shader are validated against a shader model, which you supply at compile time.
  • Intrinsic Functions (DirectX HLSL) - HLSL has many intrinsic functions. These are implemented and tested so that you can use them knowing that they are already debugged and they perform well. If you choose to write your own functions, see the language syntax section for writing user-defined functions.
  • Appendix (DirectX HLSL) - The appendix is included for completeness. It includes a listing of the keywords and reserved words; these words cannot be used as identifiers in your programs. It also includes a listing of the language grammar for reference.

See Also

HLSL


Language Syntax (DirectX HLSL)

HLSL shaders are made up of variables, and functions, which in turn are made up of statements. The language syntax documents how to define and declare variables, add flow control so that shaders can made runtime decisions based on variables, and write custom functions.

  • Variables
  • Flow Control
  • Functions
  • Statements

See Also

HLSL


Variables (DirectX HLSL)

HLSL variables are similar to variables defined in the C programming language. Similar to C, variables have some naming restrictions, have scoping properties that depend on where they are declared, and can have user metadata attached to them. Like C, there are several standard data types. Unlike C, there are also additional data types defined by HLSL to help maximize the performance of 4-component vectors that use matrix math to operate on 3D graphics data.

  • Variable Syntax
  • Data Types
  • Semantics

See Also

Language Syntax (DirectX HLSL)


Variable Syntax (DirectX HLSL)

Use the following syntax rules to declare HLSL variables.

[Storage_Class] [Type_Modifier]

Type Name[Index] [: Semantic] [= Initializers] [Annotations] [: Register];

Parameters

Storage_Class
Optional storage-class modifiers that give the compiler hints about variable scope and lifetime.

Global variable declarations prefixed with the uniform keyword are uniform inputs to the shader. All non-static global variables are uniform by default.

Global variable declarations can be prefixed with the shared keyword. This is a hint to the effect framework that the value of this parameter is intended to be shared between effect objects.

Value | Description
extern | A global variable marked extern is an external input to the shader. A global variable that is not declared to be either static or extern is assumed to be extern. You cannot declare a global variable with both extern and static.
nointerpolation | Do not interpolate the outputs of a vertex shader before passing them to a pixel shader.
shared | Mark a variable for sharing between effects.
static | Mark a local variable so that it persists between function calls. Marking a global variable as static makes it no longer visible to an application.
uniform | Mark a variable whose data is constant throughout the execution of a shader (such as a material color in a vertex shader). All global variable are considered uniform by default. Variables whose data changes through the course of shader execution (like position data in a vertex shader) should not be marked uniform.
volatile | This is a hint to the effect system that this parameter changes frequently. This modifier only applies to a global parameter.

Storage class modifiers are optional and may be specified in any order, as long as they occur before the variable type.

Type_Modifier
Optional type-modifier.
Value | Description
const | A variable whose value cannot be changed by a shader; therefore it must be initialized in the variable declaration.
row_major | Organizing four components in a single row so they can be stored in a single constant register.
column_major | Organizing 4 components in a single column to facilitate matrix math.
Type
Any HLSL type listed in Data Types (DirectX HLSL).
Name[Index]
ASCII string that uniquely identifies the name of a variable within a shader. A variable can be defined as a single variable or optionally as an array of variables; index is the optional array size, it is a positive integer greater than or equal to 1.
Semantic
Optional parameter-usage information, used by the compiler to link shader inputs and outputs. There are several predefined semantics for vertex and pixel shaders. Only top-level parameter semantics are meaningful to the compiler.
Initializers
Optional initializer(s). The number of initializers should match the number of components in Type. Global variables marked extern must contain a literal value; variables marked static must be initialized with a constant.
Annotations
Optional metadata attached to global variables. An annotation is a string designed to allow additional metadata to be attached to a variable. Annotations are used by the effect framework and ignored by HLSL. Annotations cannot be referenced by a shader.
Register
Optional register assignment; use this to assign a variable to a particular constant register. If the variable type will not fit into a single register, consecutive registers are used. May include an optional shader profile.
Packoffset
Optional packing assignment; use this to assign an element to a particular register subcomponent. May include an optional shader profile.

Examples

Here are several examples of shader-variable declarations.

float fVar;

float4 color;
float fVar = 3.1f;

int iVar[3];

int iVar[3] = {1,2,3};

uniform float4 position : SV_POSITION;
const float4 lightDirection = {0,0,1};

See Also

Variables (DirectX HLSL)


Data Types (DirectX HLSL)

HLSL supports many different intrinsic data types. This table shows which types to use to define shader variables.

Use This Intrinsic Type | To Define This Shader Variable
Scalar | One-component scalar
Vector, Matrix | Multiple-component vector or matrix
Sampler, Shader, Texture | Sampler, shader, or texture object
Struct, User Defined | Custom structure or typedef

To help you better understand how to use vectors and matrices in HLSL, you may want to read this background information on how HLSL uses per-component math.

See Also

Variables (DirectX HLSL)


Scalar Types (DirectX HLSL)

HLSL supports several scalar data types.

  • bool - true or false.
  • int - 32-bit signed integer.
  • uint - 32-bit unsigned integer.
  • half - 16-bit floating point value. Note that this data type is only provided for language compatibility. Direct3D 10 shader targets map all half data types to float data types.
  • float - 32-bit floating point value.
  • double - 64-bit floating point value.

Differences between Direct3D 9 and Direct3D 10:

In Direct3D 10, the following types are modifiers to the float type.

  • snorm float - IEEE 32-bit signed-normalized float in range -1 to 1 inclusive.
  • unorm float - IEEE 32-bit unsigned-normalized float in range 0 to 1 inclusive.

For example, here is a 4-component signed-normalized float-variable declaration.

snorm float4 fourComponentIEEEFloat;

HLSL also supports the ASCII string type. There are no operations or states that accept strings. String parameters and annotations can, however, be queried by effects.

See Also

Data Types (DirectX HLSL)


Vector Type (DirectX HLSL)

A vector contains between one and four scalar components; every component of a vector must be of the same type.

TypeNumber Name
TypeComponents Name

Components

TypeComponents
A single name that contains two parts. The first part is one of the scalar types. The second part is the number of components, which must be between 1 and 4 inclusive..
Name
An ASCII string that uniquely identifies the variable name.

Examples

Here are some examples:

bool    bVector;   // scalar containing 1 Boolean
int1    iVector = 1;
float3  fVector = { 0.2f, 0.3f, 0.4f };

A vector can be declared using this syntax also:

vector <Type, Number> VariableName

Here are some examples:

vector <int,    1> iVector = 1;
vector <double, 4> dVector = { 0.2, 0.3, 0.4, 0.5 };

See Also

Data Types (DirectX HLSL)


Matrix Type (DirectX HLSL)

A matrix is a special data type that contains between one and sixteen components. Every component of a matrix must be of the same type.

TypeComponents Name

Components

TypeComponents
A single name that contains three parts. The first part is one of the scalar types. The second part is the number of rows. The third part is the number of columns. The number of rows and columns is a positive integer between 1 and 4 inclusive.
Name
An ASCII string that uniquely identifies the variable name.

Examples

Here are some examples:

int1x1    iMatrix;   // integer matrix with 1 row,  1 column
int4x1    iMatrix;   // integer matrix with 4 rows, 1 column
int1x4    iMatrix;   // integer matrix with 1 row, 4 columns
double3x3 dMatrix;   // double matrix with 3 rows, 3 columns

float2x2 fMatrix = { 0.0f, 0.1, // row 1
                     2.1f, 2.2f // row 2
                   };

A matrix can be declared using this syntax also:

matrix <Type, Number> VariableName

The matrix type uses the angle brackets to specify the type, the number of rows, and the number of columns. This example creates a floating-point matrix, with two rows and two columns. Any of the scalar data types can be used.

Here is an example:

matrix <float, 2, 2> fMatrix = { 0.0f, 0.1, // row 1
                                 2.1f, 2.2f // row 2
                               };

See Also

Data Types (DirectX HLSL)


Per-Component Math Operations (DirectX HLSL)

With HLSL, you can program shaders at an algorithm level. To understand the language, you will need to know how to declare variables and functions, use intrinsic functions, define custom data types and use semantics to connect shader arguments to other shaders and to the pipeline.

Once you learn how to author shaders in HLSL, you will need to learn about API calls so that you can: compile a shader for particular hardware, initialize shader constants, and initialize other pipeline state if necessary.

  • The Vector Type
  • The Matrix Type
  • Examples

The Vector Type

A vector is a data structure that contains between one and four components.

bool    bVector;   // scalar containing 1 Boolean
bool1   bVector;   // vector containing 1 Boolean
int1    iVector;   // vector containing 1 int
float3  fVector;   // vector containing 3 floats
double4 dVector;   // vector containing 4 doubles

The integer immediately following the data type is the number of components on the vector.

Initializers can also be included in the declarations.

bool    bVector = false;
int1    iVector = 1;
float3  fVector = { 0.2f, 0.3f, 0.4f };
double4 dVector = { 0.2, 0.3, 0.4, 0.5 };

Alternatively, the vector type can be used to make the same declarations:

vector <bool,   1> bVector = false;
vector <int,    1> iVector = 1;
vector <float,  3> fVector = { 0.2f, 0.3f, 0.4f };
vector <double, 4> dVector = { 0.2, 0.3, 0.4, 0.5 };

The vector type uses angle brackets to specify the type and number of components.

Vectors contain up to four components, each of which can be accessed using one of two naming sets:

  • The position set: x,y,z,w
  • The color set: r,g,b,a

These statements both return the value in the third component.

// Given
float4 pos = float4(0,0,2,1);

pos.z    // value is 2
pos.b    // value is 2

Naming sets can use one or more components, but they cannot be mixed.

// Given
float4 pos = float4(0,0,2,1);
float2 temp;

temp = pos.xy  // valid
temp = pos.rg  // valid

temp = pos.xg  // NOT VALID because the position and color sets were used.

Specifying one or more vector components when reading components is called swizzling. For example:

float4 pos = float4(0,0,2,1);
float2 f_2D;
f_2D = pos.xy;   // read two components
f_2D = pos.xz;   // read components in any order
f_2D = pos.zx;

f_2D = pos.xx;   // components can be read more than once
f_2D = pos.yy;

Masking controls how many components are written.

float4 pos = float4(0,0,2,1);
float4 f_4D;
f_4D    = pos;     // write four components

f_4D.xz = pos.xz;  // write two components
f_4D.zx = pos.xz;  // change the write order

f_4D.xzyw = pos.w; // write one component to more than one component
f_4D.wzyx = pos;

Assignments cannot be written to the same component more than once. So the left side of this statement is invalid:

f_4D.xx = pos.xy;   // cannot write to the same destination components

Also, the component name spaces cannot be mixed. This is an invalid component write:

f_4D.xg = pos.rgrg;    // invalid write: cannot mix component name spaces

Accessing a vector as a scalar will access the first component of the vector. The following two statements are equivalent.

f_4D.a = pos * 5.0f;
f_4D.a = pos.r * 5.0f;

The Matrix Type

A matrix is a data structure that contains rows and columns of data. The data can be any of the scalar data types, however, every element of a matrix is the same data type. The number of rows and columns is specified with the row-by-column string that is appended to the data type.

int1x1    iMatrix;   // integer matrix with 1 row,  1 column
int2x1    iMatrix;   // integer matrix with 2 rows, 1 column
...
int4x1    iMatrix;   // integer matrix with 4 rows, 1 column
...
int1x4    iMatrix;   // integer matrix with 1 row, 4 columns
double1x1 dMatrix;   // double matrix with 1 row,  1 column
double2x2 dMatrix;   // double matrix with 2 rows, 2 columns
double3x3 dMatrix;   // double matrix with 3 rows, 3 columns
double4x4 dMatrix;   // double matrix with 4 rows, 4 columns

The maximum number of rows or columns is 4; the minimum number is 1.

A matrix can be initialized when it is declared:

float2x2 fMatrix = { 0.0f, 0.1, // row 1
                     2.1f, 2.2f // row 2
                   };

Or, the matrix type can be used to make the same declarations:

matrix <float, 2, 2> fMatrix = { 0.0f, 0.1, // row 1
                                 2.1f, 2.2f // row 2
                               };

The matrix type uses the angle brackets to specify the type, the number of rows, and the number of columns. This example creates a floating-point matrix, with two rows and two columns. Any of the scalar data types can be used.

This declaration defines a matrix of float values (32-bit floating-point numbers) with two rows and three columns:

matrix <float, 2, 3> fFloatMatrix;

A matrix contains values organized in rows and columns, which can be accessed using the structure operator "." followed by one of two naming sets:

  • The zero-based row-column position:
    • _m00, _m01, _m02, _m03
    • _m10, _m11, _m12, _m13
    • _m20, _m21, _m22, _m23
    • _m30, _m31, _m32, _m33
  • The one-based row-column position:
    • _11, _12, _13, _14
    • _21, _22, _23, _24
    • _31, _32, _33, _34
    • _41, _42, _43, _44

Each naming set starts with an underscore followed by the row number and the column number. The zero-based convention also includes the letter "m" before the row and column number. Here's an example that uses the two naming sets to access a matrix:

// given
float2x2 fMatrix = { 1.0f, 1.1f, // row 1
                     2.0f, 2.1f  // row 2
                   };

float f_1D;
f_1D = matrix._m00; // read the value in row 1, column 1: 1.0
f_1D = matrix._m11; // read the value in row 2, column 2: 2.1

f_1D = matrix._11;  // read the value in row 1, column 1: 1.0
f_1D = matrix._22;  // read the value in row 2, column 2: 2.1

Just like vectors, naming sets can use one or more components from either naming set.

// Given
float2x2 fMatrix = { 1.0f, 1.1f, // row 1
                     2.0f, 2.1f  // row 2
                   };
float2 temp;

temp = fMatrix._m00_m11 // valid
temp = fMatrix._m11_m00 // valid
temp = fMatrix._11_22   // valid
temp = fMatrix._22_11   // valid

A matrix can also be accessed using array access notation, which is a zero-based set of indices. Each index is inside of square brackets. A 4x4 matrix is accessed with the following indices:

  • [0][0], [0][1], [0][2], [0][3]
  • [1][0], [1][1], [1][2], [1][3]
  • [2][0], [2][1], [2][2], [2][3]
  • [3][0], [3][1], [3][2], [3][3]

Here is an example of accessing a matrix:

float2x2 fMatrix = { 1.0f, 1.1f, // row 1
                     2.0f, 2.1f  // row 2
                   };
float temp;

temp = fMatrix[0][0] // single component read
temp = fMatrix[0][1] // single component read

Notice that the structure operator "." is not used to access an array. Array access notation cannot use swizzling to read more than one component.

float2 temp;
temp = fMatrix[0][0]_[0][1] // invalid, cannot read two components

However, array accessing can read a multi-component vector.

float2 temp;
float2x2 fMatrix;
temp = fMatrix[0] // read the first row

As with vectors, reading more than one matrix component is called swizzling. More than one component can be assigned, assuming only one name space is used. These are all valid assignments:

// Given these variables
float4x4 worldMatrix = float4( {0,0,0,0}, {1,1,1,1}, {2,2,2,2}, {3,3,3,3} );
float4x4 tempMatrix;

tempMatrix._m00_m11 = worldMatrix._m00_m11; // multiple components
tempMatrix._m00_m11 = worldMatrix.m13_m23;

tempMatrix._11_22_33 = worldMatrix._11_22_33; // any order on swizzles
tempMatrix._11_22_33 = worldMatrix._24_23_22;

Masking controls how many components are written.

// Given
float4x4 worldMatrix = float4( {0,0,0,0}, {1,1,1,1}, {2,2,2,2}, {3,3,3,3} );
float4x4 tempMatrix;

tempMatrix._m00_m11 = worldMatrix._m00_m11; // write two components
tempMatrix._m23_m00 = worldMatrix.m00_m11;

Assignments cannot be written to the same component more than once. So the left side of this statement is invalid:

// cannot write to the same component more than once
tempMatrix._m00_m00 = worldMatrix.m00_m11;

Also, the component name spaces cannot be mixed. This is an invalid component write:

// Invalid use of same component on left side
tempMatrix._11_m23 = worldMatrix._11_22;

Matrix Ordering

Matrix packing order for uniform parameters is set to column-major by default. This means each column of the matrix is stored in a single constant register. On the other hand, a row-major matrix packs each row of the matrix in a single constant register. Matrix packing can be changed with the #pragmapack_matrix directive, or with the row_major or the col_major keyword.

The data in a matrix is loaded into shader constant registers before a shader runs. There are two choices for how the matrix data is read: in row-major order or in column-major order. Column-major order means that each matrix column will be stored in a single constant register, and row-major order means that each row of the matrix will be stored in a single constant register. This is an important consideration for how many constant registers are used for a matrix.

A row-major matrix is laid out like the following:

11 | 12 | 13 | 14
21 | 22 | 23 | 24
31 | 32 | 33 | 34
41 | 42 | 43 | 44

A column-major matrix is laid out like the following:

11 | 21 | 31 | 41
12 | 22 | 32 | 42
13 | 23 | 33 | 43
14 | 24 | 34 | 44

Row-major and column-major matrix ordering determine the order the matrix components are read from shader inputs. Once the data is written into constant registers, matrix order has no effect on how the data is used or accessed from within shader code. Also, matrices declared in a shader body do not get packed into constant registers. Row-major and column-major packing order has no influence on the packing order of constructors (which always follows row-major ordering).

The order of the data in a matrix can be declared at compile time or the compiler will order the data at runtime for the most efficient use.

Examples

HLSL uses two special types, a vector type and a matrix type to make programming 2D and 3D graphics easier. Each of these types contain more than one component; a vector contains up to four components, and a matrix contains up to 16 components. When vectors and matrices are used in standard HLSL equations, the math performed is designed to work per-component. For instance, HLSL implements this multiply:

float4 v = a*b;

as a four-component multiply. The result is four scalars:

float4 v = a*b;

v.x = a.x*b.x;
v.y = a.y*b.y;
v.z = a.z*b.z;
v.w = a.w*a.w;

This is four multiplications where each result is stored in a separate component of v. This is called a four-component multiply. HLSL uses component math which makes writing shaders very efficient.

This is very different from a multiply which is typically implemented as a dot product which generates a single scalar:

v = a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w;

A matrix also uses per-component operations in HLSL:

float3x3 mat1,mat2;
...
float3x3 mat3 = mat1*mat2;

The result is a per-component multiply of the two matrices (as opposed to a standard 3x3 matrix multiply). A per component matrix multiply yields this first term:

mat3.m00 = mat1.m00 * mat2._m00;

This is different from a 3x3 matrix multiply which would yield this first term:

// First component of a four-component matrix multiply
mat.m00 = mat1._m00 * mat2._m00 +
          mat1._m01 * mat2._m10 +
          mat1._m02 * mat2._m20 +
          mat1._m03 * mat2._m30;

Overloaded versions of the multiply intrinsic function handle cases where one operand is a vector and the other operand is a matrix. Such as: vector * vector, vector * matrix, matrix * vector, and matrix * matrix. For instance:

float4x3 World;

float4 main(float4 pos : SV_POSITION) : SV_POSITION
{
    float4 val;
    val.xyz = mul(pos,World);
    val.w = 0;

    return val;
}

produces the same result as:

float4x3 World;

float4 main(float4 pos : SV_POSITION) : SV_POSITION
{
    float4 val;
    val.xyz = (float3) mul((float1x4)pos,World);
    val.w = 0;

    return val;
}

This example casts the pos vector to a column vector using the (float1x4) cast. Changing a vector by casting, or swapping the order of the arguments supplied to multiply is equivalent to transposing the matrix.

Automatic cast conversion causes the multiply and dot intrinsic functions to return the same results as used here:

{
  float4 val;
  return mul(val,val);
}

This result of the multiply is a 1x4 * 4x1 = 1x1 vector. This is equivalent to a dot product:

{
  float4 val;
  return dot(val,val);
}

which returns a single scalar value.

See Also

Data Types (DirectX HLSL)


Sampler Type (DirectX HLSL)

Use the following syntax to declare a sampler variable.

Differences between Direct3D 9 and Direct3D 10:

Here is the syntax for a sampler in Direct3D 9.

sampler Name =

sampler_state

{

[= Initializers];

};

Here is the syntax for a sampler in Direct3D 10.

SamplerState Name[Index]

{

[= Initializers];

};

Parameters

Name
ASCII string that uniquely identifies the sampler variable.
[Index]
Optional array size; a positive integer greater than or equal to 1. Used in a Direct3D 10 declaration.
Initializers

Differences between Direct3D 9 and Direct3D 10:

Initializers are statements that assign sampler state. Initializers must appear within a statement block.

In Direct3D 9, you must include at least one initializer which is a pointer to the texture that uses this sampler. Here is an example.

Texture = <g_MeshTexture>;

All other initializer(s) in Direct3D9 and all initializer(s) in Direct3D 10 are optional.

Example

Differences between Direct3D 9 and Direct3D 10:

Here is an example of a Direct3D 9 sampler from BasicHLSL Sample.

sampler MeshTextureSampler =
sampler_state
{
    Texture = <g_MeshTexture>;
    MipFilter = LINEAR;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
};

Here is an example of a Direct3D 10 sampler from BasicHLSL10 Sample.

SamplerState MeshTextureSampler
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

See Also

Data Types (DirectX HLSL)


Shader Type (DirectX HLSL)

Declare a shader variable within an effect pass using the following syntax.

SetShaderAPI Compile( ShaderTarget, ShaderFunction );

Parameters

SetShaderAPI
The Direct3D API call that creates the shader object.

Differences between Direct3D 9 and Direct3D 10:

The calling API's for Direct3D 10 are ID3D10Device::VSSetShader, ID3D10Device::GSSetShader, or ID3D10Device::PSSetShader.

The calling API's for Direct3D 9 are IDirect3DDevice9::SetVertexShader or IDirect3DDevice9::SetPixelShader.
ShaderTarget
The shader model to compile against. This is valid for any target including .

Differences between Direct3D 9 and Direct3D 10:

Shader targets for Direct3D 9 include all the targets implemented in shader model 1, shader model 2, and shader model 3.

Shader targets for Direct3D 10 include the Direct3D 9 targets plus the shader model 4 targets: vs_4_0, gs_4_0, and ps_4_0.
ShaderFunction
An ASCII string that contains the name of the shader entrypoint function; this is the function that begins execution when the shader is invoked.

Example

Differences between Direct3D 9 and Direct3D 10:

Here are two examples, one in Direct3D 9 and the other in Direct3D 10. Both examples create a vertex shader and pixel shader object, compiled for a particular shader model. In the Direct3D 10 example, there is no geometry shader, so the pointer is set to NULL.

// Direct3D 9
technique RenderSceneWithTexture1Light
{
    pass P0
    {
        VertexShader = compile vs_2_0 RenderSceneVS( 1, true, true );
        PixelShader  = compile ps_2_0 RenderScenePS( true );
    }
}

// Direct3D 10
technique10 Render
{
    pass P0
    {
        SetVertexShader( CompileShader( vs_4_0, VS() ) );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_4_0, PS() ) );
    }
}

See Also

Data Types (DirectX HLSL)


Texture Type (DirectX HLSL)

Use the following syntax to declare a texture variable.

Type Name;

Parameters

Type
One of the following types: texture (untyped, for backwards compatibility), Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D, TextureCube.
Name
An ASCII string that uniquely identifies the variable name.

Remarks

There are three parts to using a texture.

  1. Declaring a texture variable. This is done with the syntax shown above. For example, these are valid declarations.
    2. texture g_MeshTexture;
 or
Texture2D g_MeshTexture;
  2. Declaring and initializing a sampler object. This is done with slightly different syntax in Direct3D 9 and Direct3D 10. For details on sampler object syntax, see Sampler Type (DirectX HLSL).
  3. Invoking a texture function in a shader.

Differences between Direct3D 9 and Direct3D 10:

Direct3D 9 uses intrinsic texture functions to perform texture operations. This example is from the BasicHLSL Sample and uses tex2D (Direct3D 9 HLSL) to perform texture sampling.

Output.RGBColor = tex2D(MeshTextureSampler, In.TextureUV) * In.Diffuse;

Direct3D 10 uses templated texture objects instead. Here is an example of the equivalent texture operation. This example is from the BasicHLSL10 Sample and uses the sample texture-object function.

Output.RGBColor = g_MeshTexture.Sample(MeshTextureSampler, In.TextureUV) * In.Diffuse;

See Also

Data Types (DirectX HLSL)


Struct Type (DirectX HLSL)

Use the following syntax to declare a structure.

struct Name

{

Type[RxC] MemberName;

...

}

Parameters

Name
An ASCII string that uniquely identifies the structure name.
Type[RxC]
The member type with an optional row x column array size specifier. A structure contains at least one element and every element in a structure is the same type. R is the number of rows, c is the number of columns. Both numbers are unsigned integers between 1 and 4 inclusive.
MemberName
An ASCII string that uniquely identifies the member name.

Examples

Here are some examples of structure declarations.

struct struct1
{
  int    a;   // single integer
}

struct struct2
{
  int    a;         // single integer
  float  b;         // single float
  int4x1 iMatrix;   // integer matrix with 4 rows, 1 column
}

When compiled into shader code structure member are packed in line with HLSL packing rules.

See Also

Data Types (DirectX HLSL)


User-Defined Type (DirectX HLSL)

Use the following syntax to declare a user-defined type.

typedef [const] Type Name[Index];

Parameters

[const]
Optional. This keyword explicitly marks the type as a constant.
Type
Identifies the data type; must be one of the HLSL intrinsic data types.
Name
An ASCII string that uniquely identifies the variable name.
Index
Optional array size. Must be an unsigned integer between 1 and 4 inclusive.

In addition to the built-in intrinsic data types, HLSL supports user-defined or custom types which follow this syntax:

Remarks

User-defined types are not case-insensitive. For convenience, the following types are automatically defined at super-global scope.

typedef vector <bool, #> bool#;
typedef vector <int, #> int#;
typedef vector <uint, #> uint#;
typedef vector <half, #> half#;
typedef vector <float, #> float#;
typedef vector <double, #> double#;

typedef matrix <bool, #, #> bool#x#;
typedef matrix <int, #, #> int#x#;
typedef matrix <uint, #, #> uint#x#;
typedef matrix <half, #, #> half#x#;
typedef matrix <float, #, #> float#x#;
typedef matrix <double, #, #> double#x#;

The pound sign (#) represents an integer digit between 1 and 4.

For compatibility with DirectX 8 effects, the following types are automatically defined at super-global scope:

typedef int DWORD;
typedef float FLOAT;
typedef vector <float, 4> VECTOR;
typedef matrix <float, 4, 4> MATRIX;
typedef string STRING;
typedef texture TEXTURE;
typedef pixelshader PIXELSHADER;
typedef vertexshader VERTEXSHADER;

See Also

Data Types (DirectX HLSL)


Flow Control (DirectX HLSL)

Most current graphic's hardware is designed to run a shader line by line, executing each HLSL statement once. A flow-control statement determines at runtime which statement block to execute next. Using a flow-control statement, a shader can repeat loop through a set of statements, or jump (branch) to an instruction other than the one on the next line. Some flow-control statements support static control that is specified at compile time; others offer predicated control which is a per-component decision made at runtime, and still others support dynamic control which is a decision made at runtime based on the contents of a variable.

HLSL supports the following flow-control statements.

  • break
  • continue
  • do
  • for
  • if
  • stop
  • switch
  • while

See Also

Language Syntax (DirectX HLSL)


break Statement (DirectX HLSL)

Exit the surrounding loop (do, for, while).

break;

Parameters

None

See Also

Flow Control


continue Statement (DirectX HLSL)

Stop executing the current loop (do, for, while), update the loop conditions, and begin executing from the top of the loop.

continue;

Parameters

None

See Also

Flow Control


do Statement (DirectX HLSL)

Iteratively execute a series of statements, based on the evaluation of the conditional.

do

{

Statement Block;

} while( Conditional )

Parameters

Statement Block
One or more statements.
Conditional
A conditional expression. The statement block is executed before the expression is evaluated. The loop is exited when the expression evaluates to false.

See Also

Flow Control


for Statement (DirectX HLSL)

Iteratively execute a series of statements, based on the evaluation of the conditional expression.

[Attribute] for ( Initializer; Conditional; Iterator )

{

Statement Block;

}

Parameters

Attribute
An optional parameter that controls how the statement is compiled. When no attribute is specified the compiler will first attempt to emit a rolled version of the loop, and if that fails, or if some operations would be easier if the loop was unrolled, will fall back to an unrolled version of the loop.
Attribute | Description
unroll(x) | Unroll the loop until it stops executing. Can optionally specify the maximum number of times the loop is to execute.
loop | Generate code that uses flow control to execute each iteration of the loop.
Initializer
The initial value of the loop counter.
Conditional
A conditional expression. If the conditional expression evaluates to true, the statement block is executed. The loop ends when the expression evaluates to false.
Iterator
Update the value of the loop counter.
Statement Block
One or more HLSL statements.

See Also

Flow Control


if Statement (DirectX HLSL)

Conditionally execute a series of statements, based on the evaluation of the conditional expression.

[Attribute] if ( Conditional )

{

Statement Block;

}

Parameters

Attribute
An optional parameter that controls how the statement is compiled.
Attribute | Description
branch | Evaluate only one side of the if statement depending on the given condition.
flatten | Evaluate both sides of the if statement and choose between the two resulting values.
Conditional
A conditional expression. The expression is evaluated, and if true, the statement block is executed.
Statement Block
One or more HLSL statements.

Remarks

When the compiler uses the branch method for compiling an if statement it will generate code that will evaluate only one side of the if statement depending on the given condition. For example, in the if statement:

[branch] if(x)
{
    x = sqrt(x);
}

The if statement has an implicit else block, which is equivalent to x = x. Because we have told the compiler to use the branch method with the preceding branch attribute, the compiled code will evaluate x and execute only the side that should be executed; If x is zero, then it will execute the else side, and if it is non-zero it will execute the then side.

Conversely, if the flatten attribute is used, then the compiled code will evaluate both sides of the if statement and choose between the two resulting values using the original value of x. Here is an example of a usage of the flatten attribute:

[flatten] if(x)
{
    x = sqrt(x);
}

There are certain cases where using the branch or flatten attributes may generate a compile error. The branch attribute may fail if either side of the if statement contains a gradient function, such as tex2D. The flatten attribute may fail if either side of the if statement contains a stream append statement or any other statement that has side-effects.

An if statement can also use an optional else block. If the if expression is true, the code in the statement block associated with the if statement is processed. Otherwise, the statement block associated with the optional else block is processed.

See Also

Flow Control


stop Statement (DirectX HLSL)

Stop execution at the current statement and return the output.

stop;

Parameters

None

Remarks

This statement is available when a function is inlined.

At global scope, stop is functionally identical to return; within a function, stop stops the shader rather than stopping the function.

See Also

Flow Control


switch Statement (DirectX HLSL)

Transfer control to a different statement block within the switch body depending on the value of a selector.

[Attribute] switch( Selector ) {

case 0 :

{ StatementBlock; }

break;

case 1 :

{ StatementBlock; }

break;

case n :

{ StatementBlock; }

break;

default :

{ StatementBlock; }

break;

Parameters

Attribute
An optional parameter that controls how the statement is compiled. When no attribute is specified, the compiler may use a hardware switch or emit a series of if statements.
Attribute | Description
flatten | Compile the statement as a series of if statements, each with the flatten attribute.
branch | Compile the statement as a series of if statements each with the branch attribute.
forcecase | Force a switch statement in the hardware.
call | The bodies of the individual cases in the switch will be moved into hardware subroutines and the switch will be a series of subroutine calls.
Selector
A variable. The case statements inside the curly brackets will each check this variable to see if the SwitchValue matches their particular CaseValue.
StatementBlock
One or more statements.

Remarks

[branch] switch(a)
{
    case 0:
        return 0;
    case 1:
        return 1;
    case 2:
        return 3;
    default:
        return 6;
}

Is equivalent to:

[branch] if( a == 2 )
    return 3;
else if( a == 1 )
    return 1;
else if( a == 0 )
    return 0;
else
    return 6;

Here are example usages of forcecase and call flow control attributes:

[forcecase] switch(a)
{
    case 0:
        return 0;
    case 1:
        return 1;
    case 2:
        return 3;
    default:
        return 6;
}

[call] switch(a)
{
    case 0:
        return 0;
    case 1:
        return 1;
    case 2:
        return 3;
    default:
        return 6;
}

See Also

Flow Control


while Statement (DirectX HLSL)

Execute a statement block until the conditional expression fails.

[Attribute] while ( Conditional )

{

Statement Block;

}

Parameters

Attribute

An optional parameter that controls how the statement is compiled.

Attribute | Description
unroll(x) | Unroll the loop until it stops executing. Optionally, you can specify the maximum number of times the loop can execute.
loop | Use flow-control statements in the compiled shader; do not unroll the loop.

Conditional

A conditional expression. If the expression evaluates to true, the statement block is executed. The loop ends when the expression evaluates to false.

Statement Block

One or more statements.

See Also

Flow Control


Functions (DirectX HLSL)

Functions encapsulate HLSL statements. This enables you to debug a set of functions and then reuse the across shaders or effects. You may want to create a function that encapsulates the functionality of a vertex shader, pixel shader or texture shader. Other times, you may want to write a helper function that performs some commonly used task, and then call that helper function from your shader function. The rules for writing shader functions for HLSL are very similar to writing C functions.

  • Syntax
  • Paremeters
  • Return Statement
  • Signatures

HLSL also has a number of built-in Intrinsic Functions (DirectX HLSL). Because all intrinsic functions are tested and performance optimized, it is good practice to use an intrinsic function where possible instead of creating your own function.

See Also

HLSL


Function Declaration Syntax (DirectX HLSL)

HLSL functions are declared with the following syntax.

[StorageClass] Return_Value Name ( [argument list] )

{

[StatementBlock]

};

Parameters

StorageClass
Further define a function with storage duration, linkage, and scope.
Value | Description
inline | Each copy of the function has its own body; this decreases the overhead of calling the function. By default, all functions are inlined. Inlined functions do not support recursion.
target | The platform for which the function has been authored.
Name
An ASCII string that uniquely identifies the name of the shader function.
[argument list]
Optional argument list, which is a comma-separated list of parameter declarations.
[StatementBlock]
Optional statement(s) that make up the body of the function. See Statement Blocks (DirectX HLSL). A function defined without a body is called a function prototype; the function body must be defined elsewhere.

Return Value

The return type of the function. May be any one of these types.

Remarks

User defined functions can be overloaded. Each function must have a unique combination of its name, return value, parameter types, parameter order, or target platform. For a list of the intrinsic functions, see Intrinsic Functions (DirectX HLSL).

See Also

Functions (DirectX HLSL)


Function Arguments (DirectX HLSL)

Function arguments are inputs and outputs from a function. They are listed in an comma-separated argument list, in a function declaration. Similar to C functions, each argument must have a parameter name and type declared. An HLSL argument may also have a semantic to define how the data in the argument will be used.

Each argument is declared with the following syntax.

[Modifier] Type Name [: Semantic] [= Initializer(s)]

Parameters

Modifier
Optional term that identifies an argument as an input, an output, or both.
Value | Description
in | Input only
inout | Input and an output
out | Output only
uniform | Input only constant data

Parameters are always passed by value. in indicates that the value of the parameter should be copied in from the calling application before the function begins. out indicates that the last value of the parameter should be copied out, and returned to the calling application when the function returns. inout is a shorthand for specifying both.

A uniform value comes from a constant register; each vertex shader or pixel shader invocation see the same initial value for a uniform variable. Global variables are treated as if they are declared uniform. For non-top-level functions, uniform is synonymous with in. If no parameter usage is specified, the parameter usage is assumed to be in.

Type
The argument type; can be any valid HLSL type.
Name
An ASCII string that uniquely identifies the name of the shader function. The name can also have an interpolation modifier appended. See Interpolation Modifier
Semantic
Optional string that identifes the intended usage of the data. See Shader Semantics (DirectX HLSL).
Initializer(s)
Optional value(s) to initialize the argument. Multiple values are required to initialize multi-component data types.

Interpolation Modifier

These interpolation modifiers can be appended to any shader input or output argument. They only have meaning for pixel shader arguments.

Modifier | Description
_linear | Use linear interpolation. This is the default value.
_centroid | Use centroid interpolation (useful for improving anti-aliasing)
_nointerpolation | Do not interpolate. This modifier can only be used on uints and ints.
_noperspective | Use interpolation without perspective-correction.

See Also

Functions (DirectX HLSL)


return Statement (DirectX HLSL)

A return statement signals the end of a function.

return;

The simplest return statement returns control from the function to the calling program; it returns no value.

void main()
{
    return ;
}

However, a return statement can return one or more values. This example returns a literal value:

float main( float input : COLOR0) : COLOR0
{
    return 0;
}

This example returns the scalar result of an expression.

return  light.enabled = true ;

This example returns a four-component vector that is constructed from a local variable and a literal.

return  float4(color.rgb, 1) ;

This example returns a four-component vector that is constructed from the result that is returned from an intrinsic function, together with literal values.

float4 func(float2 a: POSITION): COLOR
{
    return float4(sin(length(a) * 100.0) * 0.5 + 0.5, sin(a.y * 50.0), 0, 1);
}

This example returns a structure that contains one or more members.

float4x4 WorldViewProj;

struct VS_OUTPUT
{
    float4 Pos  : POSITION;
};

VS_OUTPUT VertexShader_Tutorial_1(float4 inPos : POSITION )
{
    VS_OUTPUT out;
    out.Pos = mul(inPos, WorldViewProj );
    return out;
};

See Also

Functions (DirectX HLSL)


Signatures (DirectX HLSL)

A shader signature is a list of the parameters that are either input to or output from a shader function. In Direct3D 10, adjacent stages effectively share a register array, where the output shader (or pipeline stage) writes data to specific locations in the register array and the input shader must read from the same locations. The API uses shader signatures to bind shader outputs with inputs without the overhead of semantic resolution.

In Direct3D 10, input signatures are generated from a shader-input declaration and the output signature is generated from a shader-output declaration. An input signature is said to be compatible with an output signature when the output signature is a strict subset (argument type and order match) of the input signature. The most straightforward way to achieve this is to link corresponding shader inputs and outputs by the same structure type.

Here is an example of compatible signatures.

// Vertex Shader Output Signature
Struct VSOut
{
  float4 Pos: SV_Position;
  float3 MyNormal: Normal;
  float2 MyTex : Texcoord0;
}

// Pixel Shader Input Signature
Struct PSInWorks
{
  float4 Pos: SV_Position;
  float3 MyNormal: Normal;
}

Here is an example of incompatible signatures; the order of parameters in the input signature does not match the order in the output signature.

// Vertex Shader Output Signature
Struct VSOut
{
  float4 Pos: SV_Position;
  float3 MyNormal: Normal;
  float2 MyTex : Texcoord0;
}

// Pixel Shader Input Signature
Struct PSInFails
{
  float3 MyNormal: Normal;
  float4 Pos: SV_Position;
}

PSInWorks is a compatible subset of VSOut (the first two entries match both type and order with the first two entries in VSOut). However, PSInFails is incompatible because the ordering does not match with VSOut.


Statements (DirectX HLSL)

HLSL statements are combinations of variables and functions that make up expressions; like a sentence, an HLSL statement requires operators that determine how an expression will be evaluated. You may create inidividual statements in a shader, or create several statements in a group called a statement block. In order to create HLSL statements, you will need to know the syntax for writing expressions, and the operators that you will use to combine expressions.

  • Expressions
  • Operators
  • Statement Blocks

See Also

Language Syntax (DirectX HLSL)


Expressions (DirectX HLSL)

Expressions are sequences of variables And literals, punctuated by operators. A literal is an explicit data value, such as 1 for an integer or 2.1 for a floating-point number. Literals are often used to assign a value to a variable.

An expression followed by a semicolon (;) is called a statement. Statements range in complexity from simple expressions to blocks of statements that accomplish a sequence of actions. Flow-control statements determine the order statements are executed.

A statement block also indicates subscope. Variables declared within a statement block are only recognized within the block. HLSL statements determine the order in which expressions are evaluated. Each expression can be one of the following.

  • An expression
  • A statement block
  • A return statement
  • A flow-control statement

See Also

Statements (DirectX HLSL)


Operators (DirectX HLSL)

Expressions are sequences of variables and literals punctuated by operators. Operators determine how the variables and literals are combined, compared, selected, and so on. The operators include:

Operator Name | Operators
Additive and Multiplicative Operators | +, -, *, /, %
Array Operator | [i]
Assignment Operators | =, +=, -=, *=, /=, %=
Binary Casts | C rules for float and int, C rules or HLSL intrinsics for bool
Bitwise Operators | ~, <<, >>, &, |, ^, <<=, >>=, &=, |=, ^=
Boolean Math Operators | &&, ||, ?:
Cast Operator | (type)
Comma Operator | ,
Comparison Operators | <, >, ==, !=, <=, >=
Prefix or Postfix Operators | ++, --
Structure Operator | .
Unary Operators | !, -, +

Many of the operators are per-component, which means that the operation is performed independently for each component of each variable. For example, a single component variable has one operation performed. On the other hand, a four-component variable has four operations performed, one for each component.

Additive and Multiplicative Operators

The additive and multiplicative operators are: +, -, *, /, %

int i1 = 1;
int i2 = 2;
int i3 = i1 + i2;  // i3 = 3
i3 = i1 * i2;        // i3 = 1 * 2 = 2

i3 = i1/i2;       // i3 = 1/3 = 0.333. Truncated to 0 because i3 is an integer.
i3 = i2/i1;       // i3 = 2/1 = 2

float f1 = 1.0;
float f2 = 2.0f;
float f3 = f1 - f2; // f3 = 1.0 - 2.0 = -1.0
f3 = f1 * f2;         // f3 = 1.0 * 2.0 = 2.0

f3 = f1/f2;        // f3 = 1.0/2.0 = 0.5
f3 = f2/f1;        // f3 = 2.0/1.0 = 2.0

The modulus operator returns the remainder of a division. This produces different results when using integers and floating-point numbers. Integer remainders that are fractional will be truncated.

int i1 = 1;
int i2 = 2;
i3 = i1 % i2;      // i3 = remainder of 1/2, which is 1
i3 = i2 % i1;      // i3 = remainder of 2/1, which is 0
i3 = 5 % 2;        // i3 = remainder of 5/2, which is 1
i3 = 9 % 2;        // i3 = remainder of 9/2, which is 1

The modulus operator truncates a fractional remainder when using integers.

f3 = f1 % f2;      // f3 = remainder or 1.0/2.0, which is 0.5
f3 = f2 % f1;      // f3 = remainder of 2.0/1.0, which is 0.0

The % operator is defined only in cases where either both sides are positive or both sides are negative. Unlike C, it also operates on floating-point data types, as well as integers.

Array Operator

The array member selection operator "[i]" selects one or more components in an array. It is a set of square brackets that contain a zero-based index.

int arrayOfInts[4] = { 0,1,2,3 };
arrayOfInts[0] = 2;
arrayOfInts[1] = arrayOfInts[0];

The array operator can also be used to access a vector.

float4 4D_Vector = { 0.0f, 1.0f, 2.0f, 3.0f  };
float 1DFloat = 4D_Vector[1];          // 1.0f

By adding an additional index, the array operator can also access a matrix.

float4x4 mat4x4 = {{0,0,0,0}, {1,1,1,1}, {2,2,2,2}, {3,3,3,3} };
mat4x4[0][1] = 1.1f;
float 1DFloat = mat4x4[0][1];      // 0.0f

The first index is the zero-based row index. The second index is the zero-based column index.

Assignment Operators

The assignment operators are: =, +=, -=, *=, /=

Variables can be assigned literal values:

int i = 1;
float f2 = 3.1f;
bool b = false;
string str = "string";

Variables can also be assigned the result of a mathematical operation:

int i1 = 1;
i1 += 2;           // i1 = 1 + 2 = 3

A variable can be used on either side of the equals sign:

float f3 = 0.5f;
f3 *= f3;          // f3 = 0.5 * 0.5 = 0.25

Division for floating-point variables is as expected because decimal remainders are not a problem.

float f1 = 1.0;
f1 /= 3.0f;        // f1 = 1.0/3.0 = 0.333

Be careful if you are using integers that may get divided, especially when truncation affects the result. This example is identical to the previous example, except for the data type. The truncation causes a very different result.

int i1 = 1;
i1 /= 3;           // i1 = 1/3 = 0.333, which gets truncated to 0

Binary Casts

Casting operation between int and float will convert the numeric value into the appropriate representations following C rules for truncating an int type. Casting a value from a float to an int and back to a float will result in a lossy conversion based on the precision of the target.

Binary casts may also be performed using Intrinsic Functions (DirectX HLSL), which reinterpret the bit representation of a number into the target data type.

asfloat() // Cast to float
asint()   // Cast to int
asuint()  // Cast to uint

Bitwise Operators

HLSL supports the following bitwise operators, which follow the same precedence as C with regard to other operators. The following table describes the new operators.

Operator | Function
~ | Logical Not
<< | Left Shift
>> | Right Shift
& | Logical And
| | Logical Or
^ | Logical Xor
<<= | Left Shift Equal
>>= | Right Shift Equal
&= | And Equal
|= | Or Equal
^= | Xor Equal

Bitwise operators are defined to operate only on int and uint data types. Attempting to use bitwise operators on float, or struct data types will result in an error.

Boolean Math Operators

The Boolean math operators are: &&, ||, ?:

bool b1 = true;
bool b2 = false;
bool b3 = b1 && b2 // b3 = true AND false = false
b3 = b1 || b2                // b3 = true OR false = true

Unlike short-circuit evaluation of &&, ||, and ?: in C, HLSL expressions never short-circuit an evaluation because they are vector operations. All sides of the expression are always evaluated.

Boolean operators function on a per-component basis. This means that if you compare two vectors, the result is a vector containing the Boolean result of the comparison for each component.

For expressions that use Boolean operators, the size and component type of each variable are promoted to be the same before the operation occurs. The promoted type determines the resolution at which the operation takes place, as well as the result type of the expression. For example an int3 + float expression would be promoted to float3 + float3 for evaluation, and its result would be of type float3.

Cast Operator

An expression preceded by a type name in parenthesis is an explicit type cast. A type cast converts the original expression to the data type of the cast. In general, the simple data types can be cast to the more complex data types (with a promotion cast), but only some complex data types can be cast into simple data types (with a demotion cast).

Comma Operator

The comma operator (,) separates one or more expressions that are to be evaluated in order. The value of the last expression in the sequence is used as the value of the sequence.

Here is one case worth calling attention to. If the constructor type is accidentally left off the right side of the equals sign, the right side now contains four expressions, separated by three commas.

// Instead of using a constructor
float4 x = float4(0,0,0,1);

// The type on the right side is accidentally left off
float4 x = (0,0,0,1);

The comma operator evaluates an expression from left to right. This reduces the right hand side to:

float4 x = 1;

HLSL uses scalar promotion in this case, so the result is as if this were written as follows:

float4 x = float4(1,1,1,1);

In this instance, leaving off the float4 type from the right side is probably a mistake that the compiler is unable to detect because this is a valid statement.

Comparison Operators

The comparison operators are: <, >, ==, !=, <=, >=.

Compare values that are greater than (or less than) any scalar value:

if( dot(lightDirection, normalVector)  >  0 )
   // Do something; the face is lit

if( dot(lightDirection, normalVector) &< 0 )
   // Do nothing; the face is backwards

Or, compare values equal to (or not equal to) any scalar value:

if(color.a  == 0)
   // Skip processing because the face is invisible

if(color.a  != 0)
   // Blend two colors together using the alpha value

Or combine both and compare values that are greater than or equal to (or less than or equal to) any scalar value:

if( position.z >= oldPosition.z )
   // Skip the new face because it is behind the existing face

if( currentValue &<= someInitialCondition )
   // Reset the current value to its initial condition

Each of these comparisons can be done with any scalar data type. Comparison operators do not support the complex data types such as vector, matrix, or the object types.

Prefix or Postfix Operators

The prefix and postfix operators are: ++, --. Prefix operators change the contents of the variable before the expression is evaluated. Postfix operators change the contents of the variable after the expression is evaluated.

In this case, a loop uses the contents of i to keep track of the loop count.

float4 arrayOfFloats[4] = { 1.0f, 2.0f, 3.0f, 4.4f };

for (int i = 0; i<4; )
{
    arrayOfFloats[i++] *= 2;
}

Because the postfix increment operator (++) is used, arrayOfFloats[i] is multiplied by 2 before i is incremented. This could be slightly rearranged to use the prefix increment operator. This one is harder to read, although both examples are equivalent.

float4 arrayOfFloats[4] = { 1.0f, 2.0f, 3.0f, 4.4f };

for (int i = 0; i<4; )
{
    arrayOfFloats[++i - 1] *= 2;
}

Because the prefix operator (++) is used, arrayOfFloats[i+1 - 1] is multiplied by 2 after i is incremented.

The prefix decrement and postfix decrement operator (--) are applied in the same sequence as the increment operator. The difference is that decrement subtracts 1 instead of adding 1.

Structure Operator

The structure member selection operator (.) is a period. Given this structure:

struct position
{
float4 x;
float4 y;
float4 z;
};

It can be read like this:

struct position pos = { 1,2,3 };

float 1D_Float = pos.x
1D_Float = pos.y

Each member can be read or written with the structure operator:

struct position pos = { 1,2,3 };
pos.x = 2.0f;
pos.z = 1.0f;       // z = 1.0f
pos.z = pos.x      // z = 2.0f

Unary Operators

The unary operators are: !, -, +

Unary operators operate on a single operand.

bool b = false;
bool b2 = !b;      // b2 = true
int i = 2;
int i2 = -i;       // i2 = -2
int j = +i2;       // j = +2

Operator Precedence

When an expression contains more than one operator, operator precedence determines the order of evaluation.

Remarks

Curly braces ({,}) start and end a statement block. When a statement block uses a single statement, the curly braces are optional.

See Also

Statements (DirectX HLSL)


Statement Blocks (DirectX HLSL)

A statement block contains one or more statements; each statement is made up of expressions and operators.

{
   statement 1;
   statement 2;
   ...
   statement n;
}

A statement block also indicates subscope. Variables declared within a statement block are only recognized within the block.

See Also

Statements (DirectX HLSL)


Shader Semantics (DirectX HLSL)

A semantic is a string attached to a shader input or output that conveys information about the intended use of a parameter. Semantics are required on all variables passed between shader stages. The syntax for adding a semantic to a shader variable is shown here (Variable Syntax (DirectX HLSL)).

In general, data passed between pipeline stages is completely generic and is not uniquely interpreted by the system; arbitrary semantics are allowed which have no special meaning. In certain cases however, the hardware will perform a fixed-function operation based on the semantic. Parameters (in Direct3D 10) which contain these special semantics are referred to as system-value semantics.

  • Vertex Shader Semantics
  • Pixel Shader Semantics
  • System-Value Semantics
  • Double Binding Semantics

Vertex Shader Semantics

These semantics have meaning when attached to a vertex-shader parameters. These semantics are supported in both Direct3D 9 and Direct3D 10.

Input | Description | Type
BINORMAL[n] | Binormal | float4
BLENDINDICES[n] | Blend indices | uint
BLENDWEIGHT[n] | Blend weights | float
COLOR[n] | Diffuse and specular color | float4
NORMAL[n] | Normal vector | float4
POSITION[n] | Vertex position in object space. | float4
POSITIONT | Transformed vertex position. | float4
PSIZE[n] | Point size | float
TANGENT[n] | Tangent | float4
TEXCOORD[n] | Texture coordinates | float4
Output | Description | Type
COLOR[n] | Diffuse or specular color | float4
FOG | Vertex fog | float
POSITION[n] | Position of a vertex in homogenous space. Compute position in screen-space by dividing (x,y,z) by w. Every vertex shader must write out a parameter with this semantic. | float4
PSIZE | Point size | float
TESSFACTOR[n] | Tessellation factor | float
TEXCOORD[n] | Texture coordinates | float4

n is an optional integer between 0 and the number of resources supported. For example, POSITION0, TEXCOOR1, etc.

Pixel Shader Semantics

These semantics have meaning when attached to a pixel-shader input parameter. These semantics are supported in both Direct3D 9 and Direct3D 10.

Input | Description | Type
COLOR[n] | Diffuse or specular color. | float4
TEXCOORD[n] | Texture coordinates | float4
VFACE | Floating-point scalar that indicates a back-facing primitive. A negative value faces backwards, while a positive value faces the camera. | float
VPOS | Contains the current pixel (x,y) location. | float2
Output | Description | Type
COLOR[n] | Output color | float4
DEPTH[n] | Output depth | float

n is an optional integer between 0 and the number of resources supported. For example, PSIZE0, COLOR1, etc.

The COLOR semantic is only valid in shader compatibility mode (that is, when the shader is created using D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY).

System-Value Semantics

System-value semantics are new to Direct3D 10. All system-values begin with an SV_ prefix, a common example is SV_POSITION, which is interpreted by the rasterizer stage. The system-values are valid at other parts of the pipeline. For instance, SV_Position can be specified as an input to a vertex shader as well as an output. Pixel shaders can only write to parameters with the SV_Depth and SV_Target system-value semantics.

Other system values (SV_VertexID, SV_PrimitiveID, SV_InstanceID, SV_IsFrontFace) can only be input into the first active shader in the pipeline that can interpret the particular value; after that it is the responsibility of the shader function to pass the values to subsequent stages. For example, SV_PrimitiveID cannot be interpreted by the vertex-shader stage since a vertex can be a member of multiple primitives. As a result, SV_PrimitiveID is only available to the geometry-shader stage, or the pixel-shader stage if the geometry-shader stage is inactive.

These semantics have been added to Direct3D 10; they are not available in Direct3D 9.

System-Value Semantics | Description | Type
SV_ClipDistance[n] | Clip distance data | float
SV_CullDistance[n] | Cull distance data | float
SV_Depth | Depth buffer data | float
SV_InstanceID | Per-instance identifier | uint
SV_IsFrontFace | A visible primitive | bool
SV_Position | Vertex position in homogenous space | float4
SV_PrimitiveID | Per-primitive identifier | uint
SV_RenderTargetArrayIndex | Render-target array index. | uint
SV_Target[n], where 0 <= n <= 7 | A render-target array | float
SV_VertexID | Per-vertex identifier | uint
SV_ViewportArrayIndex | Viewport array index | uint

A few of the Direct3D 10 semantics map directly to Direct3D 9 semantics.

Direct3D 10 Semantic | Direct3D 9 Equivalent Semantic
SV_Depth | DEPTH
SV_Position | POSITION
SV_Target | COLOR

Limitations when writing SV_Depth.

  • When multisampling (MultisampleEnable is TRUE in D3D10_RASTERIZER_DESC) and writing a depth value (using a pixel shader), the single value written out is also used in the depth test; so the ability to render primitive edges at higher resolution is lost when multisampling.
  • When using dynamic-flow control, it is impossible to determine at compile time whether a shader that writes SV_Depth in some paths will be guaranteed to write SV_Depth in every execution. Failure to write SV_Depth when declared results in undefined behavior (which may or may not include discard of the pixel).
  • Any float32 value including +/-INF and NaN can be written to SV_Depth.
  • Writing SV_Depth is still valid when performing Dual Source Color Blending.
Note to Direct3D 9 developers:

For Direct3D 9 targets, shader semantics must map to valid Direct3D 9 semantics. For backwards compatibility POSITION0 (and its variant names) is treated as SV_Position, COLOR is treated as SV_TARGET.

Double Binding Semantics

You can apply the same semantic to more than one parameter. For instance:

float4x4 WorldView[60] : WORLDVIEW : register(c16);

float4 main( float3 Pos : SV_POSITION, int4 IPos : SV_POSITION ) : SV_POSITION
{
    float3 P = mul(float4(Pos, 1), (float4x3)WorldView[IPos.w]);
    return float4(P,1);
}

This function takes two arguments: a three-component, floating-point position and a four-component, integer position. The integer position is used as an index into the array of world-view matrices.

See Also

Variables (DirectX HLSL)


Shader Models (DirectX HLSL)

The the High Level Shading Language for DirectX implements a series of shader models. Using HLSL, you can create C-like programmable shaders for the Direct3D pipeline. Each shader model builds on the capabilites of the model before it, implementing more functionality with fewer restrictions.

Shader model 1 started with DirectX 8 and included assembly level and C-like instructions. This model has many limitations caused by early programmable shader hardware. Shader model 2 and 3 greatly expanded on the number of instructions, and constants shaders could use. They are much more powerful than shader model 1, but still carry some of the existing limitations of the first shader model.

Starting with Windows Vista, shader model 4 is a complete redesign. It allows unlimited instructions and constants (within hardware constraints of your machine), has templated objects to make texture sampling clearner and more efficient, and has the fewest restrictions of any shader model. It does however require the Windows Driver Model which is only available on the Windows Vista (or later) operating system.

Shader Profiles

Each shader model supports certain shader profiles; each profile is a shader or effect compile target.

Shader Model | Shader Profiles
Shader Model 1 (DirectX HLSL) | vs_1_1
Shader Model 2 (DirectX HLSL) | ps_2_0, ps_2_x, vs_2_0, vs_2_x
Shader Model 3 (DirectX HLSL) | ps_3_0, vs_3_0
Shader Model 4 (DirectX HLSL) | gs_4_0, ps_4_0, vs_4_0

Differences between Direct3D 9 and Direct3D 10:

Direct3D 9 support shader models 1, 2, and 3. See Effect Profiles.

Direct3D 10 support shader models 2 and higher. See Effect Profiles.

Effect Profiles

Differences between Direct3D 9 and Direct3D 10:

Direct3D 9 support effect-framework profiles fx_1_0 and fx_2_0.

Direct3D 10 supports effect-framework profiles fx_2_0 and fx_4_0.

See Also

Reference (DirectX HLSL)


Shader Model 1 (DirectX HLSL)

Shader Model 1 was the first shader model created in DirectX. It introduced vertex and pixel shaders to the first implementation of the programmable pipeline.

Feature | Capability
Instruction Set
  • HLSL functions
  • Vertex shader assembly instructions (see Instructions - vs_1_1). Support for pixel shader instructions (ps_1_x) has been deprecated. To compile ps_1_x shaders as ps_2_0 shaders see Compiling Shader Model 1.
Register Set
  • Vertex shader registers
Vertex Shader Max | 128 instructions
Shader Profiles | vs_1_1

For more details on shader model 1, see:

  • Vertex Shader

See Also

Shader Models (DirectX HLSL)


Shader Model 2 (DirectX HLSL)

Shader Model 2 added additional capabilities to shader model 1.

Feature | Capability
Instruction Set
  • HLSL functions
  • Assembly instructions (see Instructions - vs_2_0, Instructions - vs_2_x, ps_2_0 Instructions, ps_2_x Instructions)
Register Set
  • Pixel shader registers (see ps_2_0 Registers, ps_2_x Registers)
  • Vertex shader registers (see Registers - vs_2_0, Registers - vs_2_x)
Pixel Shader Max
  • ps_2_0 - 32 texture + 64 arithmetic
  • ps_2_x - 96 minimum, and up to the number of slots in D3DCAPS9.D3DPSHADERCAPS2_0.NumInstructionSlots. See D3DPSHADERCAPS2_0
Vertex Shader Max | 256 instructions
Shader Profiles | ps_2_0, ps_2_x, vs_2_0, vs_2_x

For more details on shader model 2, see:

  • Pixel Shader 2.0, Pixel Shader 2.x
  • Vertex Shader 2.0, Vertex Shader 2.x

See Also

Shader Models (DirectX HLSL)


Shader Model 3 (DirectX HLSL)

Shader Model 3 added additional capabilities to shader model 2.

Feature | Capability
Instruction Set
  • HLSL functions
  • Assembly instructions (see ps_3_0 Instructions, Instructions - vs_3_0)
Register Set
  • Pixel shader registers (see ps_3_0 Registers)
  • Vertex shader registers (see Registers - vs_3_0)
Pixel Shader Max | 512 minimum, and up to the number of slots in D3DCAPS9.MaxPixelShader30InstructionSlots (see D3DPSHADERCAPS2_0).
Vertex Shader Max | 512 minimum, and up to the number of slots in D3DCAPS9.MaxVertexShader30InstructionSlots (see D3DCAPS9).
Shader Profiles | ps_3_0, vs_3_0

For more details on model 3 shaders, see:

  • Pixel Shader 3.0
  • Vertex Shader 3.0

See Also

Shader Models (DirectX HLSL)


Shader Model 4 (DirectX HLSL)

Shader Model 4 is a superset of the capabilites in shader model 3 with the exception that shader model 4 does not support the features in shader model 1. It has been designed using a common-shader core which provides a common set of features to all programmable shaders, which are only programmable using HLSL.

Feature | Capability
Instruction Set | HLSL functions
Register Set | The register set has been replaced by constant and texture buffers.
Vertex Shader Max | No restriction
Pixel Shader Max | No restriction
Shader Profiles | gs_4_0, ps_4_0, vs_4_0*

* - Direct3D 10 also supports the following effect-framework profiles: fx_2_0 and fx_4_0.

Shader model 4 also supports a new pipeline stage, the geometry shader stage, and two new object types. A stream-output object designed for streaming data out of the geometry stage and templated texture objects that replace HLSL texture sampling functions.

  • Common-Shader Core
  • Constants
  • Geometry-Shader Object
  • Stream-Output Object
  • Texture Object

Packing Rules for Constant Variables (DirectX HLSL)

See Also

Shader Models (DirectX HLSL)


Common-Shader Core (DirectX HLSL)

In shader model 4 all shader stages implement the same base functionality using a common-shader core. In addition, each of the three shader stages (vertex, geometry, and pixel) offer functionality unique to each stage, such as the ability to generate new primitives from the geometry shader stage or to discard a specific pixel in the pixel shader stage. Here is a conceptual diagram of how data flows through a shader stage, and the relationship of the common-shader core with shader memory resources:

Figure 1. Common-Shader Core

  • Input Data: A vertex shader receives its inputs from the input assembler stage; geometry and pixel shaders receive their inputs from the previous shader stage. Additional inputs include system-generated values, which are consumable by the first unit in the pipeline to which they are applicable.
  • Output Data: Shaders generate output results to be passed onto the subsequent stage in the pipeline. For a geometry shader, the amount of data output from a single invocation can vary. Some outputs are interpreted by the common-shader core (such as vertex position and render-target-array index), others are designed to be interpreted by an application.
  • Shader Code: Shaders can read from memory, perform vector floating point and integer arithmetic operations, or flow control operations. There is no limit to the number of statements that can be implemented in a shader.
  • Samplers: Samplers define how to sample and filter textures. As many as 16 samplers can be bound to a shader simultaneously.
  • Textures: Textures can be filtered using samplers or read on a per-texel basis directly with the load intrinsic function.
  • Buffers: Buffers are never filtered, but can be read from memory on a per-element basis directly with the load intrinsic function. As many as 128 texture and buffer resources (combined) can be bound to a shader simultaneously.
  • Constant Buffers: Constant buffers are optimized for shader constant-variables. As many as 16 constant buffers can be bound to a shader stage simultaneously. They are designed for more frequent update from the CPU; therefore, they have additional size, layout, and access restrictions.

Differences between Direct3D 9 and Direct3D 10:

In Direct3D 9, each shader unit had a single, small constant register file to store all constant shader variables. Accommodating all shaders with this limited constant space required frequent recycling of constants by the CPU.

In Direct3D 10, constants are stored in immutable buffers in memory and are managed like any other resource. There is no limit to the number of constant buffers an application can create. By organizing constants into buffers by frequency of update and usage, the amount of bandwidth required to update constants to accommodate all shaders can be significantly reduced.

Integer and Bitwise Support

The common shader core provides a full set of IEEE-compliant 32-bit integer and bitwise operations. These operations enable a new class of algorithms in graphics hardware - examples include compression and packing techniques, FFT's, and bitfield program-flow control.

The int and uint data types in Direct3D 10 HLSL map to 32 bit integers in hardware.

Differences between Direct3D 9 and Direct3D 10:

In Direct3D 9 stream inputs marked as integer in HLSL were interpreted as floating-point. In Direct3D 10, stream inputs marked as integer are interpreted as a 32 bit integer.

In addition, boolean values are now all bits set or all bits unset. Data converted to bool will be interpreted as TRUE if the value is not equal to 0.0f (both positive and negative zero are allowed to be FALSE) and FALSE otherwise.

Bitwise operators

The common shader core supports the following bitwise operators:

Operator | Function
~ | Logical Not
<< | Left Shift
>> | Right Shift
& | Logical And
| | Logical Or
^ | Logical Xor
<<= | Left shift Equal
>>= | Right Shift Equal
&= | And Equal
|= | Or Equal
^= | Xor Equal

Bitwise operators are defined to operate only on Int and UInt data types. Attempting to use bitwise operators on float, or struct data types will result in an error. Bitwise operators follow the same precedence as C with regard to other operators.

Binary Casts

Casting between an integer and a floating-point type will convert the numeric value following C truncation rules. Casting a value from a float, to an int, back to a float is a lossy conversion dependent on the precision of the target data type. Here are some of the conversion functions: asfloat (DirectX HLSL), asint (DirectX HLSL), asuint (DirectX HLSL).

Binary casts can also be performed using HLSL intrinsic functions. These cause the compiler to reinterpret the bit representation of a number into the target data type.


Shader Constants (DirectX HLSL)

In shader model 4, shader constants are stored in one or more buffer resources in memory. They can be organized into two types of buffers: constant buffers (cbuffers) and texture buffers (tbuffers). Constant buffers are optimized for constant-variable usage, which is characterized by lower-latency access and more frequent update from the CPU. For this reason, additional size, layout, and access restrictions apply to these resources. Texture buffers are accessed like textures and perform better for arbitrarily indexed data. Regardless of which type of resource you use, there is no limit to the number of constant buffers or texture buffers an application can create.

Declaring a constant buffer or a texture buffer looks very much like a structure declaration in C.

BufferType Name

{

VariableDeclaration;

...

};

Parameters

BufferType
[in] The buffer type.
BufferType | Description
cbuffer | constant buffer
tbuffer | texture buffer
Name
[in] ASCII string containing a unique buffer name.
VariableDeclaration
[in] Variable declaration, similar to a structure member declaration. This can be any HLSL type or effect object (except a texture or a sampler object).

Remarks

A constant buffer is a specialized buffer resource that is accessed like a buffer. Each constant buffer can hold up to 4096 vectors; each vector contains up to four 32-bit values. As many as 16 constant buffers can be bound to a shader stage simultaneously.

A texture buffer is a specialized buffer resource that is accessed like a texture. Texture access (as compared with buffer access) can have better performance for arbitrarily indexed data.

A buffer resource is designed to minimize the overhead of setting shader constants. The effect framework will manage updating constant and texture buffers, or you can use the Direct3D API to update buffers (see Copying and Accessing Resource Data (Direct3D 10) for information). An application can also copy data from another buffer (such as a render target or a stream-output target) into a constant buffer.

Unlike other Direct3D 10 buffer and texture resources which must be bound to the pipeline using a view, a shader-resource buffer (a constant or texture buffer) is bound directly without the need of a view.

Differences between Direct3D 9 and Direct3D 10:

Unlike the auto-allocation of constants in Direct3D 9 which did not perform packing and instead assigned each variable to a set of float4 registers, HLSL constant variables follow packing rules in Direct3D 10.

Examples

To make efficient use of bandwidth and maximize performance, the application can organize its constant variables into buffers by frequency of update and usage. For instance, data that needs to be updated per object, should be grouped into a different buffer than data used by all objects and materials in the scene.

cbuffer myObject
{
  float4x4 matWorld;
  float3   vObjectPosition;
  int      arrayIndex;
}

cbuffer myScene
{
  float3   vSunPosition;
  float4x4 matView;
}

This example declares two constant buffers and organizes the data in each based on their frequency of update: data that needs to be updated on a per-object basis (like a world matrix) is grouped into myObject which could be updated for each object. This is separate from data that characterizes a scene and is therefore likely to be updated much less often (when the scene changes).

Here is an example from Skinning10 Sample that is a texture buffer made up of an array of matrices.

tbuffer tbAnimMatrices
{
    matrix g_mTexBoneWorld[MAX_BONE_MATRICES];
};

See Also

Shader Model 4 (DirectX HLSL)


Geometry-Shader Object (DirectX HLSL)

[maxvertexcount(NumVerts)]

void ShaderName (

PrimitiveType DataType Name [ NumElements ],

inout StreamOutputObject

);

Parameters

NumVerts
[in] The maximum number of vertices that the shader can create; must be an integer.
ShaderName
[in] ASCII string that contains a unique name for the geometry-shader function.
PrimitiveType DataType Name [ NumElements ]

PrimitiveType - Primitive type; which detemines the order of the primitive data.

Primitive Type | Description
point | Point list
line | Line list or line strip
triangle | Triangle list or triangle strip
lineadj | Line list with adjacency or line strip with adjacency
triangleadj | Triangle list with adjacency or triangle strip with adjacency

DataType - [in] Input data type; can be any HLSL data type.

Name - Argument name; this is an ASCII string. NumElements is an optional array size if the argument is an array.

StreamOutputObject
The declaration of the stream-output object.

Return Value

None

Examples

This example is from exercise 1 from the Direct3D 10 Shader Model 4.0 Workshop.

[maxvertexcount(3)]
void GSScene( triangleadj GSSceneIn input[6], inout TriangleStream<PSSceneIn> OutputStream )
{
    PSSceneIn output = (PSSceneIn)0;

    for( uint i=0; i<6; i+=2 )
    {
        output.Pos = input[i].Pos;
        output.Norm = input[i].Norm;
        output.Tex = input[i].Tex;

        OutputStream.Append( output );
    }

    OutputStream.RestartStrip();
}


Stream-Output Object (DirectX HLSL)

A stream-output object is a templated object that streams data out of the geometry-shader stage. Use the following syntax to declare a stream-output object.

inout StreamOutputObject<DataType> Name;

Parameters

StreamOutputObject<DataType> Name

The stream-output object (SO) declaration.

Stream-Output Object Types | Description
PointStream | A sequence of point primitives
LineStream | A sequence of line primitives
TriangleStream | A sequence of triangle primitives

DataType - Output data type; can be any HLSL data type. Must be surrounded by the angle brackets.

Name - Variable name; an ASCII string that uniquely identifies the object.

Example

This is an example of a stream-output object declaration that streams out triangle primitives whose data is defined by the PS_CUBEMAP_IN structure. The geometry-shader is limited to generating 18 vertices.

struct PS_CUBEMAP_IN
{
    float4 Pos : SV_POSITION;     // Projection coord
    float2 Tex : TEXCOORD0;       // Texture coord
    uint RTIndex : SV_RenderTargetArrayIndex;
};

[maxvertexcount(18)]
inout TriangleStream<PS_CUBEMAP_IN> CubeMapStream;

This is a code snippet from the CubeMapGS Sample.

Stream-Output Object Methods

Use the following syntax to call stream-output-object methods.

Object.Method

The following methods are implemented.

Methods | Description
Append | Append output data to an existing stream.
RestartStrip | End the current primitive strip and start a new primitive strip.

See Also

Shader Model 4 (DirectX HLSL)


Append (DirectX HLSL Stream-Output Object)

Append geometry-shader-output data to an existing stream.

Append(

StreamDataType

);

Parameters

StreamDataType
Data input description. This description must match the stream-object template parameter called DataType

Return Value

None

Example

This code snippet (from the CubeMapGS Sample) shows a partial example of appending triangle strip primitives to a stream-output object.

[maxvertexcount(18)]
void GS_CubeMap( triangle GS_CUBEMAP_IN input[3],
                 inout TriangleStream<PS_CUBEMAP_IN> CubeMapStream )
{
    for( int f = 0; f < 6; ++f )
    {
        // Compute screen coordinates
        PS_CUBEMAP_IN output;
        output.RTIndex = f;
        for( int v = 0; v < 3; v++ )
        {
            output.Pos = mul( input[v].Pos, g_mViewCM[f] );
            output.Pos = mul( output.Pos, mProj );
            output.Tex = input[v].Tex;
            CubeMapStream.Append( output );
        }
        CubeMapStream.RestartStrip();
    }
}

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Stream-Output Object


RestartStrip (DirectX HLSL Stream-Output Object)

End the current-primitive strip and start a new strip. If the current strip does not have enough vertices emitted to fill the primitive topology, the incomplete primitive at the end will be discarded.

RestartStrip();

Parameters

None

Return Value

None

Remarks

The output is always assumed to be a triangle strip. To output a triangle list, you must call RestartStrip() between each triangle. Triangle fans are unsupported.

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Stream-Output Object


Texture Object (DirectX HLSL)

In Direct3D 10, the samplers and textures are specified independently; texture sampling is implemented with a templated-texture object. This templated object has a specific format, returns a specific type, and implements several methods. Here is the syntax for accessing a templated-texture object.

Object.Method;

Parameters

Object
A texture object. Must be one of the following types.
Type | Description
Buffer | Buffer
Texture1D | One dimension texture
Texture1DArray | Array of one-dimension textures
Texture2D | Two-dimension texture
Texture2DArray | Array of two-dimensional textures
Texture2DMS | Two-dimension multi-sampled texture
Texture2DArray | Array of two-dimension multi-sampled textures
Texture3D | Three dimension texture
TextureCUBE | Cube texture
Method
One of the following methods.
Methods | Description
GetDimensions | Get the texture dimension for a specified mipmap level.
Load | Load data without any filtering or sampling.
Sample | Sample a texture.
SampleCmp | Sample a texture, using a comparison value to reject samples.
SampleCmpLevelZero | Sample a texture (mipmap level 0 only), using a comparison value to reject samples.
SampleGrad | Sample a texture using a gradient to influence the way the sample location is calculated.
SampleLevel | Sample a texture on the specified mipmap level.

Return Type

The return type is implied to be float4 unless specified otherwise, with the exception of the MSAA texture objects that always need the type and sample count specified. The return type is the same as the texture resource type (DXGI_FORMAT). In other words, it can be any of the following types.

Type | Description
float | IEEE 32-bit float
int | 32-bit signed integer
unsigned int | 32-bit unsigned integer
snorm | IEEE 32-bit float in range -1 to 1 inclusive
unorm | IEEE 32-bit float in range 0 to 1 inclusive
any texture type or struct | The number of components returned must be between 1 and 3 inclusive.

In addition, the return type can be any texture type including a structure. However, it must be less then 4 components such as a float1 type which returns one component.

Example

sampler MySamp;
Texture2D <float4> MyTex;

float4 main( float2 TexCoords[2] : TEXCOORD ) : SV_Target
{
    return MyTex.Sample( MySamp, TexCoords[0] ));
}
Differences between Direct3D9 and Direct3D10:

In Direct3D 9, samplers are bound to specific textures; in Direct3D 10, textures and samplers are independent objects. Each templated-texture object implements texture sampling methods that take both the texture and the sampler as input parameters.

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Shader Model 4


GetDimension (DirectX HLSL Texture Object)

Get texture-size information.

void Object.GetDimension(

UINT Level,

UINT Width,

UINT Levels

);

Parameters

Object
A texture-object type.
Level
[in] The mipmap level to access.
Width
[out] The texture width, in texels.
Levels
[out] The number of mipmap levels.

Return Value

None

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Texture-Object


Load (DirectX HLSL Texture Object)

Read texel data without any filtering or sampling.

void Object.Load(

int Location,

int Offset

);

Parameters

Object
A texture-object type.
Location
[in] Texture coordinates; the last component specifies the mipmap level. Since some texture types require a different number of texture coordinates, the type of this parameter is dependent on the texture type.
Texture Type | Parameter Type
Buffer | int
Texture1D | int2
Texture1DArray, Texture 2D | int3
Texture2DArray, Texture3D | int4

    For example, to access a 2D texture, supply UV coordinates for the first two components and a mipmal level for the third component.

    Offset
    [in] Optional offset applied to the texture coordinates before sampling. The offset type is dependent on the texture-object type.
    Texture Type | Offset Type
    Texture1D | int1
    Texture2D | int2

    Return Value

    None

    Minimum Shader Model

    This function is supported in the following shader models.

    Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

    See Also

    Texture-Object


Sample (DirectX HLSL Texture Object)

Sample a texture.

DXGI_FORMAT Object.Sample(

sampler S,

float Location

[, int Offset]

);

Parameters

Object
A texture-object type.
S
[in] Sampler object. The argument type is dependent on the texture-object type.
Texture-Object Type | Sampler Type
Texture1D, Texture1DArray | Sampler1D
Texture2D, Texture2DArray | Sampler2D
Texture3D | Sampler3D
TextureCUBE | SamplerCUBE
Location
[in] Texture coordinates. The argument type is dependent on the texture-object type.
Texture-Object Type | Parameter Type
Texture1D | float
Texture1DArray | float2
Texture2D, Texture2DArray | float3
Texture3D, TextureCUBE | float4
offset
[in] Optional texture coordinate offset. An offset (if specified) is applied to the location before sampling. The argument type is dependent on the texture-object type.
Texture-Object Type | Parameter Type
Texture1D, Texture1DArray | int
Texture2D, Texture2DArray | int2
Texture3D, TextureCUBE | int3

See applying integer offsets.

Return Value

The texture format which is one of the typed values listed in DXGI_FORMAT.

Remarks

Texture sampling uses the texel position to look up a texel value. An offset can be applied to the position before look up. The sampler state contains the sampling and filtering options. This method can be invoked within a pixel shader; but is not supported in a vertex shader or a geometry shader.

Calculating Texel Positions

Texture coordinates are floating-point values that reference texture data, which is also known as normalized texture space. Address wrapping modes are applied in this order (texture coordinates + offsets + wrap mode) to modify texture coordinates outside the [0...1] range.

For texture arrays, there is an additional value in the location parameter to specify an index into a texture array. This index is treated as a scaled float value (as opposed to the normalized space for standard texture coordinates). The conversion to an integer index is done in the following order (float + round-to-nearest-even integer + clamp to the array range).

Applying Texture Coordinate Offsets

The offset parameter modifies the texture coordinates, in texel space. Even though texture coordinates are normalized floating-point numbers, the offset applies an integer offset.

The data format returned is determined by the texture format. For example, if the texture resource was defined with the DXGI_FORMAT_A8B8G8R8_UNORM_SRGB format, then the sampling operation will convert sampled texels from gamma 2.0 to 1.0, filter, and output the result as a floating-point value in the range [0..1].

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Texture-Object


SampleCmp (DirectX HLSL Texture Object)

Sample a texture and compare the result to a comparison value.

uint Object.SampleCmp(

SamplerComparisonState S,

float Location,

float Comparison

[, int Offset]

);

The comparison is a single component comparison between the first component stored in the texture, and the comparison value passed into the method. This method can be invoked within a pixel shader, but is not supported in a vertex or geometry shader.

Parameters

Object
Any non-array texture-object type.
S
[in] Sampler comparison state.
Location
[in] Texture coordinates. The argument type is dependent on the texture-object type.
Texture-Object Type | Parameter Type
Texture1D | float
Texture2D | float2
Texture3D, TextureCUBE | float3
Comparison
Floating-point value to use as a comparison value.
Offset
[in] Optional texture coordinate offset. An offset (if specified) is applied to the location before sampling. The argument type is dependent on the texture-object type.
Texture-Object Type | Parameter Type
Texture1D | int
Texture2D | int2
Texture3D, TextureCUBE | int3

See applying integer offsets.

Return Value

Returns 1 if the comparison passes; otherwise 0.

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Texture-Object


SampleCmpLevelZero (DirectX HLSL Texture Object)

Sample a texture and compare the result to a comparison value. This function is similar to calling SampleCmp on mipmap level 0 only.

uint Object.SampleCmpLevelZero(

SamplerComparisonState s,

float Location,

float Comparison

[, int Offset]

);

The comparison is a single component comparison between the first component stored in the texture, and the comparison value passed into the method.

Parameters

Object
Any non-array texture-object type.
s
[in] Sampler comparison state.
Location
[in] Texture coordinates. The argument type is dependent on the texture-object type.
Texture-Object Type | Parameter Type
Texture1D | float
Texture2D | float2
Texture3D, TextureCUBE | float3
Comparison
Floating-point value to use as a comparison value.
Offset
[in] Optional texture coordinate offset. An offset (if specified) is applied to the location before sampling. The argument type is dependent on the texture-object type.
Texture-Object Type | Parameter Type
Texture1D | int
Texture2D | int2
Texture3D, TextureCUBE | int3

See applying integer offsets.

Return Value

Returns 1 if the comparison passes; otherwise 0.

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Texture-Object


SampleGrad (DirectX HLSL Texture Object)

Sample a texture using a gradient to influence the way the sample location is calculated.

uint Object.SampleGrad(

sampler S,

float DDX,

float DDY

[, int Offset]

);

The comparison is a single component comparison between the first component stored in the texture, and the comparison value passed into the method.

Parameters

Object
Any non-array texture-object type.
S
[in] Sampler comparison state.
DDX
[in] The rate of change of the surface geometry in the x direction.
DDY
[in] The rate of change of the surface geometry in the y direction.

Return Value

Returns 1 if the comparison passes; otherwise 0.

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Texture-Object


SampleLevel (DirectX HLSL Texture Object)

Sample a texture using a mipmap-level offset.

uint Object.SampleCmpLevelZero(

sampler S,

float Location,

float Comparison

[, int Offset]

);

This function is similar to sample except that it uses the LOD level (in the last component of the location parameter) to choose the mipmap level. For example, a 2D texture uses the first two components for uv coordinates and the third component for the mipmap level.

Parameters

Object
Any non-array texture-object type.
S
[in] Sampler. The argument type is dependent on the texture-object type.
Texture-Object Type | Parameter Type
Texture1D | Sampler1D
Texture2D | Sampler2D
Texture3D | Sampler3D
TextureCUBE | SamplerCUBE
Location
[in] Texture coordinates. The argument type is dependent on the texture-object type.
Texture-Object Type | Parameter Type
Texture1D | float
Texture2D | float2
Texture3D, TextureCUBE | float3
Offset
[in] Optional texture coordinate offset. An offset (if specified) is applied to the location before sampling. The argument type is dependent on the texture-object type.
Texture-Object Type | Parameter Type
Texture1D | int
Texture2D | int2
Texture3D, TextureCUBE | int3

See applying integer offsets.

Return Value

Returns 1 if the comparison passes; otherwise 0.

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Texture-Object


Packing Rules for Constant Variables (DirectX HLSL)

Packing rules dictate how tightly data can be arranged when it is stored. HLSL implements packing rules for VS output data, GS input and output data, and PS input and output data (data is not packed for VS inputs because the IA stage cannot unpack data).

HLSL packing rules are similar to performing a #pragma pack 4 with Visual Studio, which packs data into 4 byte boundaries. Additionally, HLSL packs data so that it does not cross a 16-byte boundary. Variables are packed into a given four-component vector until the variable will straddle a 4-vector boundary; the next variables will get bounced to the next four-component vector.

Each structure forces the next variable to start on the next four-component vector. This sometimes generates padding for arrays of structures. The resulting size of any structure will always be evenly divisible by sizeof( 4-component vector ).

Here are some examples of structures and their corresponding packed sizes (given: a float1 occupies 4 bytes):

//  2 x 16byte elements
cbuffer IE
{
    float4 Val1;
    float2 Val2;  // starts a new vector
    float2 Val3;
};

//  3 x 16byte elements
cbuffer IE
{
    float2 Val1;
    float4 Val2;  // starts a new vector
    float2 Val3;  // starts a new vector
};

//  1 x 16byte elements
cbuffer IE
{
    float1 Val1;
    float1 Val2;
    float2 Val3;
};

//  1 x 16byte elements
cbuffer IE
{
    float1 Val1;
    float2 Val2;
    float1 Val3;
};

//  2 x 16byte elements
cbuffer IE
{
    float1 Val1;
    float1 Val1;
    float1 Val1;
    float2 Val2;    // starts a new vector
};

//  1 x 16byte elements
cbuffer IE
{
    float3 Val1;
    float1 Val2;
};

//  1 x 16byte elements
cbuffer IE
{
    float1 Val1;
    float3 Val2;
};

//  2 x 16byte elements
cbuffer IE
{
    float1 Val1;
    float1 Val1;
    float3 Val2;        // starts a new vector
};

// 3 x 16byte elements
cbuffer IE
{
    float1 Val1;

    struct     {
        float4 SVal1;    // starts a new vector
        float1 SVal2;    // starts a new vector
    } Val2;
};

// 3 x 16byte elements
cbuffer IE
{
    float1 Val1;
    struct     {
        float1 SVal1;     // starts a new vector
        float4 SVal2;     // starts a new vector
    } Val2;
};

// 3 x 16byte elements
cbuffer IE
{
    struct     {
        float4 SVal1;
        float1 SVal2;    // starts a new vector
    } Val1;

    float1 Val2;   // starts a new vector
};


Intrinsic Functions (DirectX HLSL)

    The following table lists the intrinsic functions available in HLSL. Each function has a brief description, and a link to a reference page that has more detail about the input argument and return type.

    Name | Syntax | Description
abs | abs(x) | Absolute value (per component).
acos | acos(x) | Returns the arccosine of each component of x. Each component should be in the range [-1, 1].
all | all(x) | Test if all components of x are nonzero.
any | any(x) | Test if any component of x is nonzero.
asfloat | asfloat(x) | Convert the input type to a float.
asin | asin(x) | Returns the arcsine of each component of x. Each component should be in the range [-pi/2, pi/2].
asint | asint(x) | Convert the input type to an integer.
asuint | asuint(x) | Convert the input type to an unsigned integer.
atan | atan(x) | Returns the arctangent of x. The return values are in the range [-pi/2, pi/2].
atan2 | atan2(y, x) | Returns the arctangent of y/x. The signs of y and x are used to determine the quadrant of the return values in the range [-pi, pi]. atan2 is well-defined for every point other than the origin, even if x equals 0 and y does not equal 0.
ceil | ceil(x) | Returns the smallest integer which is greater than or equal to x.
clamp | clamp(x, min, max) | Clamps x to the range [min, max].
clip | clip(x) | Discards the current pixel, if any component of x is less than zero. This can be used to simulate clip planes, if each component of x represents the distance from a plane.
cos | cos(x) | Returns the cosine of x.
cosh | cosh(x) | Returns the hyperbolic cosine of x.
cross | cross(a, b) | Returns the cross product of two 3D vectors a and b.
D3DCOLORtoUBYTE4 | D3DCOLORtoUBYTE4(x) | Swizzles and scales components of the 4D vector x to compensate for the lack of UBYTE4 support in some hardware.
ddx | ddx(x) | Returns the partial derivative of x with respect to the screen-space x-coordinate.
ddy | ddy(x) | Returns the partial derivative of x with respect to the screen-space y-coordinate.
degrees | degrees(x) | Converts x from radians to degrees.
determinant | determinant(m) | Returns the determinant of the square matrix m.
distance | distance(a, b) | Returns the distance between two points, a and b.
dot | dot(a, b) | Returns the dot product of two vectors, a and b.
exp | exp(x) | Returns the base-e exponent.
exp2 | exp2(x) | Base 2 exponent (per component).
faceforward | faceforward(n, i, ng) | Returns -n * sign(•(i, ng)).
floor | floor(x) | Returns the greatest integer which is less than or equal to x.
fmod | fmod(a, b) | Returns the floating point remainder f of a / b such that a = i * b + f, where i is an integer, f has the same sign as x, and the absolute value of f is less than the absolute value of b.
frac | frac(x) | Returns the fractional part f of x, such that f is a value greater than or equal to 0, and less than 1.
frexp | frexp(x, exp) | Returns the mantissa and exponent of x. frexp returns the mantissa, and the exponent is stored in the output parameter exp. If x is 0, the function returns 0 for both the mantissa and the exponent.
fwidth | fwidth(x) | Returns abs(ddx(x)) + abs(ddy(x))
isfinite | isfinite(x) | Returns true if x is finite, false otherwise.
isinf | isinf(x) | Returns true if x is +INF or -INF, false otherwise.
isnan | isnan(x) | Returns true if x is NAN or QNAN, false otherwise.
ldexp | ldexp(x, exp) | Returns x * 2exp
length | length(v) | Returns the length of the vector v.
lerp | lerp(a, b, s) | Returns a + s(b - a). This linearly interpolates between a and b, such that the return value is a when s is 0, and b when s is 1.
lit | lit(n • l, n • h, m) | Returns a lighting vector (ambient, diffuse, specular, 1):ambient = 1;diffuse = (n • l < 0) ? 0 : n • l; specular = (n • l < 0) || (n • h < 0) ? 0 : (n • h * m);
log | log(x) | Returns the base-e logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.
log10 | log10(x) | Returns the base-10 logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.
log2 | log2(x) | Returns the base-2 logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.
max | max(a, b) | Selects the greater of a and b.
min | min(a, b) | Selects the lesser of a and b.
modf | modf(x, out ip) | Splits the value x into fractional and integer parts, each of which has the same sign as x. The signed fractional portion of x is returned; the integer portion is stored in the output parameter ip.
mul | mul(a, b) | Performs matrix multiplication between a and b. If a is a vector, it is treated as a row vector. If b is a vector, it is treated as a column vector. The inner dimension acolumns and brows must be equal. The result has the dimension arows x bcolumns.
noise | noise(x) | Not yet implemented.
normalize | normalize(v) | Returns the normalized vector v / length(v). If the length of v is 0, the result is indefinite.
pow | pow(x, y) | Returns xy.
radians | radians(x) | Converts x from degrees to radians.
reflect | reflect(i, n) | Returns the reflection vector v, given the entering ray direction i, and the surface normal n, such that v = i - 2n * (i•n).
refract | refract(i, n, R) | Returns the refraction vector v, given the entering ray direction i, the surface normal n, and the relative index of refraction R. If the angle between i and n is too great for a given R, refract returns (0,0,0).
round | round(x) | Rounds x to the nearest integer
rsqrt | rsqrt(x) | Returns 1 / sqrt(x)
saturate | saturate(x) | Clamps x to the range [0, 1]
sign | sign(x) | Computes the sign of x. Returns -1 if x is less than 0, 0 if x equals 0, and 1 if x is greater than zero.
sin | sin(x) | Returns the sine of x
sincos | sincos(x, out s, out c) | Returns the sine and cosine of x. sin(x) is stored in the output parameter s. cos(x) is stored in the output parameter c.
sinh | sinh(x) | Returns the hyperbolic sine of x
smoothstep | smoothstep(min, max, x) | Returns 0 if x < min. Returns 1 if x > max. Returns a smooth Hermite interpolation between 0 and 1, if x is in the range [min, max].
sqrt | sqrt(x) | Square root (per component)
step | step(a, x) | Returns (x >= a) ? 1 : 0
tan | tan(x) | Returns the tangent of x
tanh | tanh(x) | Returns the hyperbolic tangent of x
tex1D | tex1D(s, t) | 1D texture lookup. s is a sampler or a sampler1D object. t is a scalar.
tex1Dbias | tex1Dbias(s, t) | 1D texture lookup with bias. s is a sampler or sampler1D object. t is a 4D vector. The mip level is biased by t.w before the lookup takes place.
tex1Dgrad | tex1Dgrad(s, t, ddx, ddy) | 1D texture lookup with a gradient. s is a sampler or sampler1D object. t is a 4D vector. The gradient values (ddx, ddy) select the appropriate mipmap level of the texture for sampling.
tex1Dlod | tex1Dlod(s, t) | 1D texture lookup with LOD. s is a sampler or sampler1D object. t is a 4D vector. The mipmap LOD is specified in t.
tex1Dproj | tex1Dproj(s, t) | 1D texture lookup with projective divide. s is a sampler or sampler1D object. t is a 4D vector. t is divided by its last component before the lookup takes place.
tex2D | tex2D(s, t) | 2D texture lookup. s is a sampler or a sampler2D object. t is a 2D texture coordinate.
tex2Dbias | tex2Dbias(s, t) | 2D texture lookup with bias. s is a sampler or sampler2D object. t is a 4D vector. The mip level is biased by t.w before the lookup takes place.
tex2Dgrad | tex2Dgrad(s, t, ddx, ddy) | 2D texture lookup with a gradient. s is a sampler or sampler2D object. t is a 4D vector. The gradient values (ddx, ddy) select the appropriate mipmap level of the texture for sampling.
tex2Dlod | tex2Dlod(s, t) | 2D texture lookup with LOD. s is a sampler or sampler2D object. t is a 4D vector. The mipmap LOD is specified in t.
tex2Dproj | tex2Dproj(s, t) | 2D texture lookup with projective divide. s is a sampler or sampler2D object. t is a 4D vector. t is divided by its last component before the lookup takes place.
tex3D | tex3D(s, t) | 3D texture lookup. s is a sampler or a sampler3D object. t is a 3D texture coordinate.
tex3Dbias | tex3Dbias(s, t) | 3D texture lookup with bias. s is a sampler or sampler3D object. t is a 4D vector. The mip level is biased by t.w before the lookup takes place.
tex3Dgrad | tex3Dgrad(s, t, ddx, ddy) | 3D texture lookup with a gradient. s is a sampler or sampler3D object. t is a 4D vector. The gradient values (ddx, ddy) select the appropriate mipmap level of the texture for sampling.
tex3Dlod | tex3Dlod(s, t) | 3D texture lookup with LOD. s is a sampler or sampler3D object. t is a 4D vector. The mipmap LOD is specified in t.
tex3Dproj | tex3Dproj(s, t) | 3D texture lookup with projective divide. s is a sampler or sampler3D object. t is a 4D vector. t is divided by its last component before the lookup takes place.
texCUBE | texCUBE(s, t) | cube texture lookup. s is a sampler or a samplerCUBE object. t is a 3D texture coordinate.
texCUBEbias | texCUBEbias(s, t) | cube texture lookup with bias. s is a sampler or sampler2D object. t is a 4D vector. The mip level is biased by t.w before the lookup takes place.
texCUBEgrad | texCUBEgrad(s, t, ddx, ddy) | cube texture lookup with a gradient. s is a sampler or samplerCUBE object. t is a 4D vector. The gradient values (ddx, ddy) select the appropriate mipmap level of the texture for sampling.
texCUBElod | tex3Dlod(s, t) | cube texture lookup with LOD. s is a sampler or samplerCUBE object. t is a 4D vector. The mipmap LOD is specified in t.
texCUBEproj | texCUBEproj(s, t) | cube texture lookup with projective divide. s is a sampler or samplerCUBE object. t is a 4D vector. t is divided by its last component before the lookup takes place.
transpose | transpose(m) | Returns the transpose of the matrix m. If the source is dimension mrows x mcolumns, the result is dimension mcolumns x mrows.

    See Also

    Reference (DirectX HLSL)


abs (DirectX HLSL)

Returns the absolute value of the specified value.

ret abs(x)

Parameters

x
[in] The specified value.

Return Value

The absolute value of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float, int | any
ret | same as input x | same as input x | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1 and ps_1_4

See Also

Intrinsic Functions (DirectX HLSL)


acos (DirectX HLSL)

Returns the arccosine of the specified value.

ret acos(x)

Parameters

x

[in] The specified value. Each component should be a floating-point value within the range of −1 to 1.

Return Value

The arccosine of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1 only

See Also

Intrinsic Functions (DirectX HLSL)


all (DirectX HLSL)

Determines if all components of the specified value are non-zero.

ret all(x)

Parameters

x

[in] The specified value.

Return Value

True if all components of the x parameter are non-zero; otherwise, false.

Remarks

This function is similar to the any HLSL intrinsic function. The any function determines if any components of the specified value are non-zero, while the all function determines if all components of the specified value are non-zero.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float, int, bool | any
ret | scalar | bool | 1

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1 and ps_1_4

See Also

Intrinsic Functions (DirectX HLSL)


any (DirectX HLSL)

Determines if any components of the specified value are non-zero.

ret any(x)

Parameters

x

[in] The specified value.

Return Value

True if any components of the x parameter are non-zero; otherwise, false.

Remarks

This function is similar to the all HLSL intrinsic function. The any function determines if any components of the specified value are non-zero, while the all function determines if all components of the specified value are non-zero.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float, int, bool | any
ret | scalar | bool | 1

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1 and ps_1_4

See Also

Intrinsic Functions (DirectX HLSL)


asfloat (DirectX HLSL)

Converts the input type to a floating-point number.

ret asfloat(x)

Parameters

x
[in] The type to convert.

Return Value

A converted floating-point number.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | int, UINT | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


asin (DirectX HLSL)

Returns the arcsine of the specified value.

ret asin(x)

Parameters

x

[in] The specified value.

Return Value

The arcsine of the x parameter.

Remarks

Each component of the x parameter should be within the range of −π/2 to π/2.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


asint (DirectX HLSL)

Converts the input type to a integer.

ret asint(x)

Parameters

x
[in] The type to convert.

Return Value

A converted integer.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float, UINT | any
ret | same as input x | int | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


asuint (DirectX HLSL)

Converts the input type to an unsigned integer.

ret asint(x)

Parameters

x
[in] The type to convert.

Return Value

A converted unsigned integer.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float, int | any
ret | same as input x | UINT | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | no
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


atan (DirectX HLSL)

Returns the arctangent of the specified value.

ret atan(x)

Parameters

x

[in] The specified value.

Return Value

The arctangent of the x parameter. This value is within the range of −π/2 to π/2.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


atan2 (DirectX HLSL)

Returns the arctangent of two values (x,y).

ret atan2(y, x)

Parameters

y

[in] The y value.

x

[in] The x value.

Return Value

The arctangent of (y,x).

Remarks

The signs of the x and y parameters are used to determine the quadrant of the return values within the range of −π to π. The atan2 HLSL intrinsic function is well-defined for every point other than the origin, even if y equals 0 and x does not equal 0.

Type Description

Name | Template Type | Component Type | Size
y | same as input x | float | same dimension(s) as input x
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


ceil (DirectX HLSL)

Returns the smallest integer value that is greater than or equal to the specified value.

ret ceil(x)

Parameters

x

[in] The specified value.

Return Value

The smallest integer value (returned as a floating-point type) that is greater than or equal to the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


clamp (DirectX HLSL)

Clamps the specified value to the specified minimum and maximum range.

ret clamp(x, min, max)

Parameters

x

[in] A value to clamp.

min

[in] The specified minimum range.

max

[in] The specified maximum range.

Return Value

The clamped value for the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float, int | any
min | same as input x | float, int | same dimension(s) as input x
max | same as input x | float, int | same dimension(s) as input x
ret | same as input x | float, int | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1 and ps_1_4

See Also

Intrinsic Functions (DirectX HLSL)


clip (DirectX HLSL)

Discards the current pixel if the specified value is less than zero.

clip(x)

Use this function to simulate clipping planes if each component of the x parameter represents the distance from a plane.

Parameters

x

[in] The specified value.

Return Value

None.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | yes (pixel shader only)

See Also

Intrinsic Functions (DirectX HLSL)


cos (DirectX HLSL)

Returns the cosine of the specified value.

ret cos(x)

Parameters

x

[in] The specified value.

Return Value

The cosine of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


cosh (DirectX HLSL)

Returns the hyperbolic cosine of the specified value.

ret cosh(x)

Parameters

x

[in] The specified value.

Return Value

The hyperbolic cosine of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


cross (DirectX HLSL)

Returns the cross product of two floating-point, 3D vectors.

ret cross(x, y)

Parameters

x

[in] The first floating-point, 3D vector.

y

[in] The second floating-point, 3D vector.

Return Value

The cross product of the x parameter and the y parameter.

Type Description

Name | Template Type | Component Type | Size
x | vector | float | 3
y | vector | float | 3
ret | vector | float | 3

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1 and ps_1_4

See Also

Intrinsic Functions (DirectX HLSL)


D3DCOLORtoUBYTE4 (DirectX HLSL)

Converts a floating-point, 4D vector set by a D3DCOLOR to a UBYTE4.

ret D3DCOLORtoUBYTE4(x)

This function swizzles and scales components of the x parameter. Use this function to compensate for the lack of UBYTE4 support in some hardware.

Parameters

x

[in] The floating-point vector4 to convert.

Return Value

The UBYTE4 representation of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | vector | float | 4
ret | vector | integer | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


ddx (DirectX HLSL)

Returns the partial derivative of the specified value with respect to the screen-space x-coordinate.

ret ddx(x)

This function computes the partial derivative with respect to the screen-space x-coordinate. To compute the partial derivative with respect to the screen-space y-coordinate, use the ddy function.

This function is only supported in pixel shaders.

Parameters

x

[in] The specified value.

Return Value

The partial derivative of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


ddy (DirectX HLSL)

Returns the partial derivative of the specified value with respect to the screen-space y-coordinate.

ret ddy(x)

This function computes the partial derivative with respect to the screen-space y-coordinate. To compute the partial derivative with respect to the screen-space x-coordinate, use the ddx function.

This function is only supported in pixel shaders.

Parameters

x

[in] The specified value.

Return Value

The partial derivative of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


degrees (DirectX HLSL)

Converts the specified value from radians to degrees.

ret degrees(x)

Parameters

x

[in] The specified value.

Return Value

The result of converting the x parameter from radians to degrees.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


determinant (DirectX HLSL)

Returns the determinant of the specified floating-point, square matrix.

ret determinant(m)

Parameters

m

[in] The specified value.

Return Value

The floating-point, scalar value that represents the determinant of the m parameter.

Type Description

Name | Template Type | Component Type | Size
m | matrix | float | any (number of rows = number of columns)
ret | scalar | float | 1

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1 and ps_1_4

See Also

Intrinsic Functions (DirectX HLSL)


distance (DirectX HLSL)

Returns a distance scalar between two vectors.

ret distance(x, y)

Parameters

x

[in] The first floating-point vector to compare.

y

[in] The second floating-point vector to compare.

Return Value

A floating-point, scalar value that represents the distance between the x parameter and the y parameter.

Type Description

Name | Template Type | Component Type | Size
x | vector | float | any
y | vector | float | same dimension(s) as input x
ret | scalar | float | 1

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


dot (DirectX HLSL)

Returns the dot product of two vectors.

ret dot(x, y)

Parameters

x

[in] The first vector.

y

[in] The second vector.

Return Value

The dot product of the x parameter and the y parameter.

Type Description

Name | Template Type | Component Type | Size
x | vector | float, int | any
y | vector | float, int | same dimensions(s) as input x
ret | scalar | float, int | 1

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes

See Also

Intrinsic Functions (DirectX HLSL)


exp (DirectX HLSL)

Returns the base-e exponential, or ex, of the specified value.

ret exp(x)

Parameters

x

[in] The specified value.

Return Value

The base-e exponential of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


exp2 (DirectX HLSL)

Returns the base 2 exponential, or 2x, of the specified value.

ret exp2(x)

Parameters

x

[in] The specified floating-point value.

Return Value

The base 2 exponential of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


faceforward (DirectX HLSL)

Flips the surface-normal (if needed) to face in a direction opposite to i; returns the result in n.

ret faceforward(n, i, ng)

This function uses the following formula: −n × sign(dot(i, ng)).

Parameters

n
[in] The resulting floating-point surface-normal vector.
i
[in] A floating-point, incident vector that points from the view position to the shading position.
ng
[in] A floating-point surface-normal vector.

Return Value

A floating-point, surface normal vector that is facing the view direction.

Type Description

Name | Template Type | Component Type | Size
n | vector | float | any
i | vector | float | same dimension(s) as input n
ng | vector | float | same dimensions as input n
ret | vector | float | same dimensions as input n

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1 and ps_1_4

See Also

Intrinsic Functions (DirectX HLSL)


floor (DirectX HLSL)

Returns the largest integer that is less than or equal to the specified value.

ret floor(x)

Parameters

x

[in] The specified value.

Return Value

The largest integer value (returned as a floating-point type) that is greater than or equal to the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


fmod (DirectX HLSL)

Returns the remainder of the division of two values.

ret fmod(x, y)

This function calculates the floating-point remainder f of x / y such that x = i × y + f, where i is an integer, f has the same sign as x, and the absolute value of f is less than the absolute value of y.

Parameters

x

[in] The floating-point dividend.

y

[in] The floating-point divisor.

Return Value

The floating-point remainder of the x parameter divided by the y parameter.

Remarks

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
y | same as input x | float | same dimension(s) as input x
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


frac (DirectX HLSL)

Returns the fractional (or decimal) part of the specified floating-point value.

ret frac(x)

This function returns the fractional part f of x, such that f is a value greater than or equal to 0, and less than 1.

Parameters

x

[in] The specified value.

Return Value

The fractional part of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | vs_1_1

See Also

Intrinsic Functions (DirectX HLSL)


frexp (DirectX HLSL)

Returns the mantissa and exponent of the specified floating-point value.

ret frexp(x, exp)

The return value is the mantissa, and the value returned by exp parameter is the exponent.

Parameters

x

[in] The specified floating-point value. If the x parameter is 0, this function returns 0 for both the mantissa and the exponent.

exp

[out] The returned exponent of the x parameter.

Return Value

The mantissa of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
exp | same as input x | float | same dimension(s) as input x
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes (ps_2_x only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


fwidth (DirectX HLSL)

Returns the absolute value of the partial derivatives of the specified value.

ret fwidth(x)

This function computes the following: abs(ddx(x)) + abs(ddy(x)).

This function is only supported in pixel shaders.

Parameters

x

[in] The specified value.

Return Value

The absolute value of the partial derivatives of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes (ps_2_x only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


isfinite (DirectX HLSL)

Determines if the specified floating-point value is finite.

ret isfinite(x)

Parameters

x

[in] The specified value.

Return Value

True if the x parameter is finite; otherwise false.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | scalar | bool | 1

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


isinf (DirectX HLSL)

Determines if the specified value is infinite.

ret isinf(x)

Parameters

x

[in] The specified value.

Return Value

True if the x parameter is +INF or −INF. Otherwise, false.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | scalar | bool | 1

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


isnan (DirectX HLSL)

Determines if the specified value is NAN or QNAN.

ret isnan(x)

Parameters

x

[in] The specified value.

Return Value

True if the x parameter is NAN or QNAN. Otherwise, false.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | scalar | bool | 1

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


ldexp (DirectX HLSL)

Returns the result of multiplying the specified value by two, raised to the power of the specified exponent.

ret ldexp(x, exp)

This function uses the following formula: x * 2exp

Parameters

x

[in] The specified value.

exp

[in] The specified exponent.

Return Value

The result of multiplying a the x parameter by two, raised to the power of the exp parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, matrix | float | any
exp | same as input x | float | same dimension(s) as input x
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


length (DirectX HLSL)

Returns the length of the specified floating-point vector.

ret length(x)

Parameters

x

The specified floating-point vector.

Return Value

A floating-point scalar that represents the length of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | vector | float | any
ret | scalar | float | 1

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


lerp (DirectX HLSL)

Performs a linear interpolation between two values.

ret lerp(x, y, s)

This function performs linear interpolation based on the following formula: x + s (y − x).

This function interpolates between the x parameter and the y parameter, such that the return value is x when the s parameter is 0, and y when s is 1.

Parameters

x

[in] The first-floating point value.

y

[in] The second-floating point value.

s

[in] A value that linearly interpolates between the the x parameter and the y parameter.

Return Value

The result of the linear interpolation.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
y | same as input x | float | same dimension(s) as input x
s | same as input x | float | same dimension(s) as input x
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 and ps_1_4)

See Also

Intrinsic Functions (DirectX HLSL)


lit (DirectX HLSL)

Returns a lighting coefficient vector from two dot products and an exponent.

ret lit(n_dot_l, n_dot_h, m)

This function returns a lighting coefficient vector (ambient, diffuse, specular, 1) where:

  • ambient = 1.
  • diffuse = ((n • l) < 0) ? 0 : n • l.
  • specular = ((n • l) < 0) || ((n • h) < 0) ? 0 : ((n • h) * m).

Where the vector n is the normal vector, l is the direction to light and h is the half vector.

Parameters

n_dot_l

[in] The dot product of the normalized surface normal and the light vector.

n_dot_h

[in] The dot product of the half-angle vector and the surface normal.

m

[in] A specular exponent.

Return Value

The lighting coefficient vector.

Type Description

Name | Template Type | Component Type | Size
n_dot_l | scalar | float | 1
n_dot_h | scalar | float | 1
m | scalar | float | 1
ret | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


log (DirectX HLSL)

Returns the base-e logarithm of the specified value.

ret log(x)

Parameters

x

[in] The specified value.

Return Value

The base-e logarithm of the x parameter. If the x parameter is negative, this function returns indefinite. If the x parameter is 0, this function returns -INF.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


log2 (DirectX HLSL)

Returns the base-2 logarithm of the specified value.

ret log2(x)

Parameters

x

[in] The specified value.

Return Value

The base-2 logarithm of the x parameter. If the x parameter is negative, this function returns indefinite. If the x parameter is 0, this function returns +INF.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


log10 (DirectX HLSL)

Returns the base-10 logarithm of the specified value.

ret log10(x)

Parameters

x

[in] The specified value.

Return Value

The base-10 logarithm of the x parameter. If the x parameter is negative, this function returns indefinite. If the x is 0, this function returns -INF.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


max (DirectX HLSL)

Selects the greater of x and y.

ret max(x, y)

Parameters

x

[in] The x input value.

y

[in] The y input value.

Return Value

The x or y parameter, whichever is the largest value.

Type Description

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int | any
y | in | same as input x | float, int | same dimension(s) as input x
ret | return type | same as input x | float, int | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 and ps_1_4)

See Also

Intrinsic Functions (DirectX HLSL)


min (DirectX HLSL)

Selects the lesser of x and y.

ret min(x, y)

Parameters

x

[in] The x input value.

y

[in] The y input value.

Return Value

The x or y parameter, whichever is the smallest value.

Type Description

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int | any
y | in | same as input x | float, int | same dimension(s) as input x
ret | return type | same as input x | float, int | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 and ps_1_4)

See Also

Intrinsic Functions (DirectX HLSL)


modf (DirectX HLSL)

Splits the value x into fractional and integer parts, each of which has the same sign as x.

ret modf(x, out ip)

Parameters

x

[in] The x input value.

ip

[out] The integer portion of x.

Return Value

The signed-fractional portion of x.

Type Description

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int | any
ip | out | same as input x | float, int | same dimension(s) as input x
ret | out | same as input x | float, int | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


mul (DirectX HLSL)

Multiplies x and y using matrix math. The inner dimension x-columns and y-rows must be equal.

ret mul(x, y)

Parameters

x

[in] The x input value. If x is a vector, it treated as a row vector.

y

[in] The y input value. If y is a vector, it treated as a column vector.

Return Value

The result of x x y. The result has the dimension x-rows x y-columns.

Type Description

There are 9 overloaded versions of this function; the overloaded versions handle the different cases for the types and sizes of the input arguments.

Version | Name | Purpose | Template Type | Component Type | Size
1 |  |  |  |  |
 | x | in | scalar | float, int | 1
 | y | in | scalar | same as input x | 1
 | ret | out | scalar | same as input x | 1
2 |  |  |  |  |
 | x | in | scalar | float, int | 1
 | y | in | vector | float, int | any
 | ret | out | vector | float, int | same dimension(s) as input y
3 |  |  |  |  |
 | x | in | scalar | float, int | 1
 | y | in | matrix | float, int | any
 | ret | out | matrix | same as input y | same dimension(s) as input y
4 |  |  |  |  |
 | x | in | vector | float, int | any
 | y | in | scalar | float, int | 1
 | ret | out | vector | float, int | same dimension(s) as input x
5 |  |  |  |  |
 | x | in | vector | float, int | any
 | y | in | vector | float, int | same dimension(s) as input x
 | ret | out | scalar | float, int | 1
6 |  |  |  |  |
 | x | in | vector | float, int | any
 | y | in | matrix | float, int | rows = same dimension(s) as input x, columns = any
 | ret | out | vector | float, int | same dimension(s) as input y columns
7 |  |  |  |  |
 | x | in | matrix | float, int | any
 | y | in | scalar | float, int | 1
 | ret | out | matrix | float, int | same dimension(s) as input x
8 |  |  |  |  |
 | x | in | matrix | float, int | any
 | y | in | vector | float, int | number of columns in input x
 | ret | out | vector | float, int | number of rows in input x
9 |  |  |  |  |
 | x | in | matrix | float, int | any
 | y | in | matrix | float, int | rows = number of columns in input x
 | ret | out | matrix | float, int | rows = number of rows in input x, columns = number of columns in input y

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes

See Also

Intrinsic Functions (DirectX HLSL)


noise (DirectX HLSL)

Generates a random value using the Perlin-noise algorithm.

ret noise(x)

Parameters

x

[in] A floating-point vector from which to generate Perlin noise.

Return Value

The Perlin noise value within a range between -1 and 1.

Remarks

Perlin noise values change smoothly from one point to another over a space, creating natural looking, randomly generated values. You can use Perlin noise to generate procedural textures for effects like smoke and fire.

Type Description

Name | Template Type | Component Type | Size
x | vector | float | any
ret | scalar | float | 1

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (tx_1_0 only)

See Also

Intrinsic Functions (DirectX HLSL)


normalize (DirectX HLSL)

Normalizes the specified floating-point vector.

ret normalize(x)

Parameters

x

[in] The specified floating-point vector.

Return Value

The normalized x parameter. If the length of the x parameter is 0, the result is indefinite.

Remarks

The normalize HLSL intrinsic function uses the following formula: x / length(x).

Type Description

Name | Template Type | Component Type | Size
x | vector | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


pow (DirectX HLSL)

Returns the specified value raised to the specified power.

ret pow(x, y)

Parameters

x

[in] The specified value.

y

[in] The specified power.

Return Value

The x parameter raised to the power of the y parameter.

Remarks

The pow HLSL intrinsic function calculates the following: xy.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
y | same as input x | float | same dimension(s) as input x
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


radians (DirectX HLSL)

Converts the specified value from degrees to radians.

ret radians(x)

Parameters

x

[in] The specified value.

Return Value

The x parameter converted from degrees to radians.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes

See Also

Intrinsic Functions (DirectX HLSL)


reflect (DirectX HLSL)

Returns a reflection vector using an entering ray direction and a surface normal.

ret reflect(i, n)

Parameters

i

[in] A floating-point, reflection vector.

n

[in] A floating-point, ray direction vector.

Return Value

A floating-point, reflection vector.

Remarks

This function calculates the reflection vector v using the following formula: v = i - 2 * dot(i, n) * n.

Type Description

Name | Template Type | Component Type | Size
i | vector | float | any
n | vector | float | same dimension(s) as input i
ret | vector | float | same dimension(s) as input i

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes

See Also

Intrinsic Functions (DirectX HLSL)


refract (DirectX HLSL)

Returns a refraction vector using an entering ray direction, a surface normal, and a refraction index.

ret refract(i, n, η)

Parameters

i

[in] A floating-point, ray direction vector.

n

[in] A floating-point, surface normal vector.

η

[in] A floating-point, refraction index scalar.

Return Value

A floating-point, refraction vector. If the angle between the i parameter and the n parameter is too great for a given η parameter, this function returns (0,0,0).

Type Description

Name | Template Type | Component Type | Size
i | vector | float | any
n | vector | float | same dimension(s) as input i
η | scalar | float | 1
refraction vector | vector | float | same dimension(s) as input i

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


round (DirectX HLSL)

Rounds the specified value to the nearest integer.

ret round(x)

Parameters

x

[in] The specified value.

Return Value

The x parameter, rounded to the nearest integer within a floating-point type.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


rsqrt (DirectX HLSL)

Returns the reciprocal of the square root of the specified value.

ret rsqrt(x)

Parameters

x

[in] The specified value.

Return Value

The reciprocal of the square root of the x parameter.

Remarks

This function uses the following formula: 1 / sqrt(x).

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


saturate (DirectX HLSL)

Clamps the specified value within the range of 0 to 1.

ret saturate(x)

Parameters

x

[in] The specified value.

Return Value

The x parameter, clamped within the range of 0 to 1.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes

See Also

Intrinsic Functions (DirectX HLSL)


sign (DirectX HLSL)

Returns the sign of the specified value.

ret sign(x)

Parameters

x

[in] The specified value.

Return Value

−1 if the x parameter is less than zero, 0 if the x parameter equals zero, and 1 if the x parameter is greater than zero.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float, int | any
ret | same as input x | int | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 and ps_1_4)

See Also

Intrinsic Functions (DirectX HLSL)


sin (DirectX HLSL)

Returns the sine of the specified value.

ret sin(x)

Parameters

x

[in] The specified value.

Return Value

The sine of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


sincos (DirectX HLSL)

Returns the sine and cosine of the specified value.

sincos(x, out s, out c)

Parameters

x

[in] The specified value.

s

[out] Returns the sine of the x parameter.

c

[out] Returns the cosine of the x parameter.

Return Value

None.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
s | same as input x | float | same dimension(s) as input x
c | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


sinh (DirectX HLSL)

Returns the hyperbolic sine of the specified value.

ret sinh(x)

Parameters

x

[in] The specified value.

Return Value

The hyperbolic sine of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


smoothstep (DirectX HLSL)

Returns a smooth Hermite interpolation of the specified value between the range of 0 and 1.

ret smoothstep(min, max, x)

Parameters

min

[in] The minimum range of the x parameter.

max

[in] The maximum range of the x parameter.

x

[in] The specified value to be interpolated.

Return Value

0 if the x parameter is less than the min parameter; 1 if the x parameter is greater than the min parameter; otherwise, a value between 0 and 1 if the x parameter is within the range of the min parameter and the max parameter.

Remarks

Use the smoothstep HLSL intrinsic function to create a smooth transition between two values. For example, you can use this function to blend two colors smoothly.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
min | same as input x | float | same dimension(s) as input x
max | same as input x | float | same dimension(s) as input x
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


sqrt (DirectX HLSL)

Returns the square root of the specified floating-point value, per component.

ret sqrt(x)

Parameters

x

[in] The specified floating-point value.

Return Value

The square root of the x parameter, per component.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


step (DirectX HLSL)

Compares two values, returning 0 or 1 based on which value is greater.

ret step(y, x)

Parameters

y

[in] The first floating-point value to compare.

x

[in] The second floating-point value to compare.

Return Value

1 if the x parameter is greater than or equal to the y parameter; otherwise, 0.

Remarks

This function uses the following formula: (x >= y) ? 1 : 0. The function returns either 0 or 1 depending on whether the x parameter is greater than the y parameter. To compute a smooth interpolation between 0 and 1, use the smoothstep HLSL intrinsic function.

Type Description

Name | Template Type | Component Type | Size
y | scalar, vector, or matrix | float | any
x | same as input y | float | same dimension(s) as input y
ret | same as input y | float | same dimension(s) as input y

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 and ps_1_4)

See Also

Intrinsic Functions (DirectX HLSL)


tan (DirectX HLSL)

Returns the tangent of the specified value.

ret tan(x)

Parameters

x

[in] The specified value.

Return Value

The tangent of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


tanh (DirectX HLSL)

Returns the hyperbolic tangent of the specified value.

ret tanh(x)

Parameters

x

[in] The specified value.

Return Value

The hyperbolic tangent of the x parameter.

Type Description

Name | Template Type | Component Type | Size
x | scalar, vector, or matrix | float | any
ret | same as input x | float | same dimension(s) as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes (vs_1_1 only)

See Also

Intrinsic Functions (DirectX HLSL)


tex1D (DirectX HLSL)

Samples a 1D texture.

ret tex1D(s, t)

Parameters

s

[in] The input sampler state.

t

[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | scalar | float | 1
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | yes (pixel shader only)

See Also

Intrinsic Functions (DirectX HLSL)


tex1Dbias (DirectX HLSL)

Samples a 1D texture after biasing the mip level by t.w.

ret tex1Dbias(s, t)

Parameters

s

[in] The input sampler state.

t

[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


tex1Dlod (DirectX HLSL)

Samples a 1D texture with mipmaps. The mipmap LOD is specified in t.w.

ret tex1Dlod(s, t)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


tex1Dgrad (DirectX HLSL)

Samples a 1D texture using a gradient to select the mip level.

ret tex1Dgrad(s, t, ddx, ddy)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.
ddx
[in] Rate of change of the surface geometry in the x direction.
ddx
[in] Rate of change of the surface geometry in the y direction.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 1
ddx | in | vector | float | 1
ddy | in | vector | float | 1
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes1 (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes2 (pixel shader only)
Shader Model 1 (DirectX HLSL) | no
  1. Significant code reordering is done to move gradient computations outside of flow control.
  2. If the D3DPSHADERCAPS2_0 cap is set with D3DD3DPSHADERCAPS2_0_GRADIENTINSTRUCTIONS, the compiler maps this function to texldd.

See Also

Intrinsic Functions (DirectX HLSL)


tex1Dproj (DirectX HLSL)

Samples a 1D texture using a projective divide; the texture coordinate is divided by t.w before the lookup takes place.

ret tex1Dproj(s, t)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


tex2D (DirectX HLSL)

Samples a 2D texture.

ret tex2D(s, t)

Parameters

s

[in] The input sampler state.

t

[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler2D | 1
t | in | scalar | float | 1
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | yes (pixel shader only)

See Also

Intrinsic Functions (DirectX HLSL)


tex2Dbias (DirectX HLSL)

Samples a 2D texture after biasing the mip level by t.w.

ret tex2Dbias(s, t)

Parameters

s

[in] The input sampler state.

t

[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler2D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


tex2Dlod (DirectX HLSL)

Samples a 2D texture with mipmaps. The mipmap LOD is specified in t.w.

ret tex2Dlod(s, t)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler2D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


tex2Dgrad (DirectX HLSL)

Samples a 2D texture using a gradient to select the mip level.

ret tex2Dgrad(s, t, ddx, ddy)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.
ddx
[in] Rate of change of the surface geometry in the x direction.
ddx
[in] Rate of change of the surface geometry in the y direction.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler2D | 1
t | in | vector | float | 1
ddx | in | vector | float | 1
ddy | in | vector | float | 1
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes1 (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes2 (pixel shader only)
Shader Model 1 (DirectX HLSL) | no
  1. Significant code reordering is done to move gradient computations outside of flow control.
  2. If the D3DPSHADERCAPS2_0 cap is set with D3DD3DPSHADERCAPS2_0_GRADIENTINSTRUCTIONS, the compiler maps this function to texldd.

See Also

Intrinsic Functions (DirectX HLSL)


tex2Dproj (DirectX HLSL)

Samples a 2D texture using a projective divide; the texture coordinate is divided by t.w before the lookup takes place.

ret tex2Dproj(s, t)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler2D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


tex3D (DirectX HLSL)

Samples a 3D texture.

ret tex3D(s, t)

Parameters

s

[in] The input sampler state.

t

[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler3D | 1
t | in | scalar | float | 1
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | yes (pixel shader only)

See Also

Intrinsic Functions (DirectX HLSL)


tex3Dbias (DirectX HLSL)

Samples a 3D texture after biasing the mip level by t.w.

ret tex3Dbias(s, t)

Parameters

s

[in] The input sampler state.

t

[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler3D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


tex3Dlod (DirectX HLSL)

Samples a 3D texture with mipmaps. The mipmap LOD is specified in t.w.

ret tex3Dlod(s, t)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler3D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


tex3Dgrad (DirectX HLSL)

Samples a 3D texture using a gradient to select the mip level.

ret tex3Dgrad(s, t, ddx, ddy)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.
ddx
[in] Rate of change of the surface geometry in the x direction.
ddx
[in] Rate of change of the surface geometry in the y direction.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler3D | 1
t | in | vector | float | 1
ddx | in | vector | float | 1
ddy | in | vector | float | 1
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes1 (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes2 (pixel shader only)
Shader Model 1 (DirectX HLSL) | no
  1. Significant code reordering is done to move gradient computations outside of flow control.
  2. If the D3DPSHADERCAPS2_0 cap is set with D3DD3DPSHADERCAPS2_0_GRADIENTINSTRUCTIONS, the compiler maps this function to texldd.

See Also

Intrinsic Functions (DirectX HLSL)


tex3Dproj (DirectX HLSL)

Samples a 3D texture using a projective divide; the texture coordinate is divided by t.w before the lookup takes place.

ret tex3Dproj(s, t)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler3D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


texCUBE (DirectX HLSL)

Samples a cube texture.

ret texCUBE(s, t)

Parameters

s

[in] The input sampler state.

t

[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | samplerCUBE | 1
t | in | scalar | float | 1
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | yes (pixel shader only)

See Also

Intrinsic Functions (DirectX HLSL)


texCUBEbias (DirectX HLSL)

Samples a cube texture after biasing the mip level by t.w.

ret texCUBEbias(s, t)

Parameters

s

[in] The input sampler state.

t

[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | samplerCUBE | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


texCUBElod (DirectX HLSL)

Samples a cube texture with mipmaps. The mipmap LOD is specified in t.w.

ret texCUBElod(s, t)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | samplerCUBE | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | no
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


texCUBEgrad (DirectX HLSL)

Samples a cube texture using a gradient to select the mip level.

ret texCUBEgrad(s, t, ddx, ddy)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.
ddx
[in] Rate of change of the surface geometry in the x direction.
ddx
[in] Rate of change of the surface geometry in the y direction.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | samplerCUBE | 1
t | in | vector | float | 1
ddx | in | vector | float | 1
ddy | in | vector | float | 1
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes1 (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes2 (pixel shader only)
Shader Model 1 (DirectX HLSL) | no
  1. Significant code reordering is done to move gradient computations outside of flow control.
  2. If the D3DPSHADERCAPS2_0 cap is set with D3DD3DPSHADERCAPS2_0_GRADIENTINSTRUCTIONS, the compiler maps this function to texldd.

See Also

Intrinsic Functions (DirectX HLSL)


texCUBEproj (DirectX HLSL)

Samples a cube texture using a projective divide; the texture coordinate is divided by t.w before the lookup takes place.

ret texCUBEproj(s, t)

Parameters

s
[in] The input sampler state.
t
[in] The input texture coordinate.

Return Value

The value of the texture data.

Type Description

Name | In/Out | Template Type | Component Type | Size
s | in | object | samplerCUBE | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes (pixel shader only)
Shader Model 3 (DirectX HLSL) | yes (pixel shader only)
Shader Model 2 (DirectX HLSL) | yes (pixel shader only)
Shader Model 1 (DirectX HLSL) | no

See Also

Intrinsic Functions (DirectX HLSL)


transpose (DirectX HLSL)

Transposes the specified input matrix.

ret transpose(x)

Parameters

x

[in] The specified matrix.

Return Value

The transposed value of the x parameter.

Remarks

If the dimensions of the source matrix are rows × columns, the resulting matrix is columns × rows.

Type Description

Name | Template Type | Component Type | Size
x | matrix | float, int, bool | any
ret | matrix | float, int, bool | rows = same number of columns as input x, columns = same number of rows as input x

Minimum Shader Model

This function is supported in the following shader models.

Shader Model | Supported
Shader Model 4 (DirectX HLSL) | yes
Shader Model 3 (DirectX HLSL) | yes
Shader Model 2 (DirectX HLSL) | yes
Shader Model 1 (DirectX HLSL) | yes

See Also

Intrinsic Functions (DirectX HLSL)


Appendix (DirectX HLSL)

The HLSL appendix lists additional information such as the words that are recognized as keywords by the language, and the grammar used for creating HLSL statements. It is published here for completeness.

  • Keywords (DirectX HLSL)
  • Reserved Words (DirectX HLSL)
  • Grammar (DirectX HLSL)

See Also

Reference (DirectX HLSL)


Keywords (DirectX HLSL)

The following words are recognized as keywords by the HLSL language. Keywords are predefined reserved identifiers that have special meanings. They cannot be used as identifiers in your program.

Keywords are not case sensitive. They are displayed here in camel casing for ease of readabilily.

BlendState, Bool, Break
CBuffer, Compile, Const, Continue
DepthStencilState, DepthStencilView, Discard, Do, Double
Else, Extern
False, Float, For
GeometryShader
Half
If, In, Inline
Inout, Int
Matrix
Namespace, Nointerpolation
Out
Pass, PixelShader
RasterizerState, RenderTargetView, Return, Register
Sampler
Sampler1D, Sampler2D, Sampler3D, SamplerCUBE, Sampler_state, Shared, Stateblock, Stateblock_state, Static, String, Struct, Switch
TBuffer, Technique, Technique10, texture1, Texture1D, Texture1D, Texture1DArray, texture2D, Texture2D, Texture2DArray, Texture2DMS, Texture2DMSArray, texture3D, Texture3D, textureCUBE, TextureCube, True, Typedef
Uniform
Vector, VertexShader, Void, Volatile, While
  1. The only exception for case sensitivity is the word texture, which is all lower case, and is used for backward compatibility with legacy shaders.

See Also

Appendix (DirectX HLSL)


Reserved Words (DirectX HLSL)

The following words are reserved for use by the HLSL language. Do not use them to name variables or functions in your HLSL code.

auto
case, catch
char, class, const_cast
default, delete, dynamic_cast
enum
explicit
friend
goto
long
mutable
new
operator
private, protected, public
reinterpret_cast
short, signed, sizeof, static_cast
template, this, throw
try, typename
union, unsigned
using
virtual

See Also

Appendix (DirectX HLSL)


Grammar (DirectX HLSL)

HLSL statements are constructed using the following rules for grammar.

  • Whitespace
  • Floating point numbers
  • Integer numbers
  • Characters
  • Strings
  • Identifiers
  • Operators

Whitespace

The following characters are recognized as white space.

SPACE
TAB
EOL
C style comments (/* */)
C++ style comments (//)
Assembly style comments in asm blocks (;)

Floating point numbers

Floating point numbers are represented in HLSL as follows:

  • fractional-constant exponent-part(opt) floating-suffix(opt)

    digit-sequence exponent-part floating-suffix(opt)

  • fractional-constant :

    digit-sequence(opt) . digit-sequence

    digit-sequence .

  • exponent-part :

    e sign(opt) digit-sequence

    E sign(opt) digit-sequence

  • sign : one of

    + -

  • digit-sequence :

    digit

    digit-sequence digit

  • floating-suffix : one of

    h H f F

Integer numbers

Integer numbers are represented in HLSL as follows:

  • integer-constant integer-suffix(opt)
  • integer-constant: one of

    # (decimal number)

    0# (octal number)

    0x# (hex number)

  • integer-suffix can be any one of these:

    u U l L

Characters

Characters are represented in HLSL as follows:

'c' | (character)
'\a' '\b' '\f' '\b' '\r' '\t' '\v' | (escapes)
'\###' | (octal escape, each # is an octal digit)
'\x#' | (hex escape, # is hex number, any number of digits)
'\c' | (c is other character, including backslash and quotation marks)

Escapes are not supported in preprocessor expressions.

Strings

Strings are represented in HLSL as follows:

"s" (s is any string with escapes).

Identifiers

Identifiers are represented in HLSL as follows:

    [A-Za-z_][A-Za-z0-9_]*

Operators

##, #@, ++, --, &, &, &, ||, ==, ::, <<, <<=, >>, >>=, ...,
<=, >=, !=, *=, /=, +=, -=, %=, &=, |=, ^=, ->

Also any other single character that did not match another rule.

See Also

Appendix (DirectX HLSL)


Graphics Tools

Use the following tool to compile shaders and effects for Direct3D 9 and Direct3D 10.

  • Effect-Compiler Tool

See Also

DirectX Graphics


Effect-Compiler Tool

FXC (fxc.exe) is an offline tool for compiling hlsl shaders and effects for all versions of Direct3D.

  • Syntax
  • Offline Compiling

See Also

Graphics Tools


Syntax

Here is the syntax for calling FXC.exe, the effect-compiler tool. For an example, see Offline Compiling.

fxc SwitchOptions Filename

Arguments

SwitchOptions
[in] Compile options. This is a list of 2 (required) or more (optional) options with a space between each.
Required SwitchOptions | Description
/E <name> | Shader entrypoint
/T <profile> | Shader model (see profiles)
Optional SwitchOptions | Description
/Cc | Output color-coded assembly
/D <id>=<text> | Define macro
/Fc <file> | Output assembly code listing file
/Fh <file> | Output header file containing object code
/Fo <file> | Output object file
/Fx <file> | Output assembly code and hex listing file
/P <file> | Preprocess to file (must be used alone)
/Gdp | Disable effect performance mode
/Gec | Enable backwards compatibility mode
/Ges | Enable strict mode
/Gfa | Avoid flow control constructs
/Gfp | Prefer flow control constructs
/Gis | Force IEEE strictness
/Gpp | Force partial precision
/I <include> | Additional include path
/LD | Compile using the DirectX 9 HLSL compiler. See the limitations in Compiling for Legacy Shader Models.
/nologo | Suppress copyright message
/Od | Disable optimizations
/Op | Disable preshaders
/O0 /O1, /02, /03 | Optimization level 0..3. 1 is default
/Vd | Disable validation
/Vi | Display details about the include process
/Vn <name> | Use name as variable name in header file
/Zi | Enable debugging information
/Zpc | Pack matrices in column-major order
/Zpr | Pack matrices in row-major order
Filename
[in] The file that contains the shader(s) and/or the effect(s).

Profiles

Each shader model is labeled with an HLSL profile. To compile a shader against a particular shader model, choose the appropriate shader profile from the following table.

Shader Type | Profiles
Vertex Shader | vs_1_1, vs_2_0, vs_2_a, vs_2_sw, vs_3_0, vs_3_sw, vs_4_0
Pixel Shader | ps_2_0, ps_2_a, ps_2_b, ps_2_sw, ps_3_0, ps_3_sw, ps_4_0
Texture Shader | tx_1_0
Effect (may contain any combination of vertex, pixel and geometry shaders) | fx_2_0, fx_4_0

Use the API to get the vertex, geometry, and pixel-shader profile best suited to a given device by calling these functions: D3D10GetVertexShaderProfile, D3D10GetPixelShaderProfile, and D3D10GetGeometryShaderProfile

For examples using the current compiler, see Current. To use the legacy compiler for older shader models, see Legacy.

See Also

Effect-Compiler Tool


Offline Compiling

The effect-compiler tool (fxc.exe) is designed for offline compilation of HLSL shaders and effects. The tool is located at:

(SDK root)\Utilities\Bin\x86\

  • Compiling with the Current Compiler
  • Compiling with the Legacy Compiler
  • Compiling Shader Model 1 with the Current Compiler

Differences between Direct3D 9 and Direct3D 10:

Beginning with the December 2006 SDK, the DirectX 10 HLSL compiler (Effect-Compiler Tool) (which includes many improvements in code generation) is the default compiler. For applications that want to continue to compile against the DirectX 9 compiler rules (fxc.exe), you may use fxc.exe with the /LD switch (this requires the D3DX9_31.DLL).

The DirectX 10 HLSL compiler does not have direct support for ps_1_x shaders. To use fxc on ps_1_x shaders requires the /Gec switch to enable backwards compatibility. Effects that specify ps_1_x targets will instead compile to ps_2_0 targets because this is the minimum shader version supported by the DirectX 10 HLSL compiler. This switch has no effect when used with higher level compile targets.

Compiling with the Current Compiler

The shader models supported by the current compiler are shown in Profiles. This example uses compiles an effect from the BasicHLSL10.fx file (see BasicHLSL10 Sample). for the shader model 4 target.

// For a release build
fxc /T fx_4_0 /Fo BasicHLSL10.fxo BasicHLSL10.fx

In this example:

  • fx_4_0 is the target profile.
  • BasicHLSL10.fxo is the output-object file containing the compiled effect.
  • BasicHLSL10.fx is the input effect file.
// For a debug build
fxc /Od /Zi /T fx_4_0 /Fo BasicHLSL10.fxo BasicHLSL10.fx

The debug options include additional options to disable compiler optimizations and enable debug information like line numbers and symbols. The binary representation of the shader is written to a file called BasicHLSL10.fxo, which is an arbitrary abbreviation for the fxc output file.

For a full listing of the command-line options, see the syntax page.

Effects can be compiled into object files using the fxc.exe tool with a target of fx_2_0 or fx_4_0. The object file can then be used to create an effect directly, using D3DXCreateEffect or D3DX10CreateEffectFromFile.

Compiling with the Legacy Compiler

Beginning with Direct3D 10, some shader models are no longer supported. These include pixel shader models: ps_1_1, ps_1_2, ps_1_3, and ps_1_4 which support very limited resources and are dependent on hardware. The compiler has been redesigned with shader model 2 (or greater) which allows for greater efficiencies with compilation. This of course will require that you are running on hardware that supports shader models 2 and greater.

If you still want to compile shaders using the legacy compiler, use the /LD switch. This supports shader models 1, 2 and 3 and does not contain the improvements and bug fixes found in the current compiler.

Compiling Shader Model 1 with the Current Compiler

The legacy compiler is not recommended for compiling new shader code due to the limitations caused by pixel shaders in shader model 1 (see Compiling with the Legacy Compiler). However, there are libraries of existing shaders that were created for ps_1_x.

To use the current compiler to build shader model 1 pixel shaders and effects, use the /Gec switch. This causes the effect-compiler tool to compile all ps_1_x targets to ps_2_0 targets. This can be done without changing any existing shader or effect code. This switch has no effect when used with higher level compile targets.

See Also

Effect-Compiler Tool


DirectX Input

  • XInput
  • DirectInput


XInput

This section provides information about the XInput API, which allows applications to interact with the Xbox 360 Controller when it is connected to a Windows PC.

  • Programming Guide
  • Samples
  • XInput Reference


Programming Guide

This guide contains information on how to use the XInput API to interact with the Xbox 360 Controller when it is connected to a Windows PC.

  • Getting Started - This section contains a description of XInput and describes how to get started using XInput in your application.
  • XInput and DirectInput - This section contains information on the differences between XInput and DirectInput, and how you can use both side by side.

For more information about specific API methods, see the Reference pages.


Getting Started With XInput

XInput is an API that allows applications to receive input from the Xbox 360 Controller for Windows. Controller rumble effects and voice input and output are supported.

This topic provides a brief overview of the capabilities of XInput and how to set it up in an application. It includes the following:

  • Introduction to XInput
  • Using XInput

Introduction to XInput

The Xbox 360 console uses a gaming controller that is compatible with Windows. Applications can use the XInput API to communicate with these controllers when they are plugged into a Windows PC (up to four unique controllers can be plugged in at a time).

Using this API, any connected Xbox 360 Controller can be queried for its state, and vibration effects can be set. Controllers that have the headset attached can also be queried for sound input and output devices that can be used with the headset for voice processing.

Operating System Requirements

XInput is supported on Windows XP (Service Pack 1) and above.

The Xbox 360 Controller

The Xbox 360 Controller has two analog directional sticks, each with a digital button, two analog triggers, a digital directional pad with four directions, and eight digital buttons. The states of each of these inputs are returned in the XINPUT_GAMEPAD structure when the XInputGetState function is called.

The controller also has two vibration motors to supply force feedback effects to the user. The speeds of these motors are specified in the XINPUT_VIBRATION structure that is passed to the XInputSetState function to set vibration effects.

Optionally, a headset can be connected to the controller. The headset has a microphone for voice input, and a headphone for sound output. Using the XInputGetDSoundAudioDeviceGuids function, you can retrieve the GUIDs that correspond to the DirectSound devices for the microphone and headphone, and receive voice input and send sound output using DirectSound APIs.

Note Drivers for the Xbox 360 Controller are not included in the SDK or the DirectX redistributable. The drivers are available via Windows Update, or at windowsgaming.com.

Using XInput

Using XInput is as simple as calling the XInput functions as required. Using the XInput functions, you can retrieve controller state, get headset DirectSound GUIDs, and set controller rumble effects.

Multiple Controllers

The XInput API supports up to four controllers connected at any time. The XInput functions all require a dwUserIndex parameter that is passed in to identify the controller being set or queried. This ID will be in the range of 0-3 and is set automatically by XInput. The number corresponds to the port that the controller is plugged into, and is not modifiable.

Each controller displays which ID it is using by lighting up a quadrant on the "ring of light" in the center of the controller. A dwUserIndex value of 0 corresponds to the top-left quadrant; the numbering proceeds around the ring in clockwise order.

Applications should support multiple controllers. For examples on how to support multiple controllers, see the Samples.

Getting Controller State

Throughout the duration of an application, getting state from a controller will probably be done most often. From frame to frame in a game application, state should be retrieved and game information updated to reflect the controller changes.

To retrieve state, use the XInputGetState function:

DWORD dwResult;
for (DWORD i=0; i< MAX_CONTROLLERS; i++ )
{
    XINPUT_STATE state;
    ZeroMemory( &state, sizeof(XINPUT_STATE) );

        // Simply get the state of the controller from XInput.
        dwResult = XInputGetState( i, &state );

        if( dwResult == ERROR_SUCCESS )
    {
        // Controller is connected
    }
        else
    {
            // Controller is not connected
    }
}

Note that the return value of XInputGetState can be used to determine if the controller is connected. Applications should define a structure to hold internal controller information; this information should be compared against the results of XInputGetState to determine what changes, such as button presses or analog controller deltas, were made that frame. In the above example, g_Controllers represents such a structure.

Once the state has been retrieved in a XINPUT_STATE structure, you can check it for changes and get specific information about controller state.

The dwPacketNumber member of the XINPUT_STATE structure can be used to check if the state of the controller has changed since the last call to XInputGetState. If dwPacketNumber does not change between two sequential calls to XInputGetState, then there has been no change in state. If it differs, then the application should check the Gamepad member of the XINPUT_STATE structure to get more detailed state information.

Dead Zone

In order for users to have a consistent gameplay experience, your game must implement dead zone correctly. The dead zone is "movement" values reported by the controller even when the analog thumbsticks are untouched and centered. There is also a dead zone for the 2 analog triggers.

Note Games that use XInput that do not filter dead zone at all will experience poor gameplay. Please note that some controllers are more sensitive than others, thus the dead zone may vary from unit to unit. It is recommended that you test your games with several Xbox 360 controllers on different systems.

Applications should use "dead zones" on analog inputs (triggers, sticks) to indicate when a movement has been made sufficiently on the stick or trigger to be considered valid.

Your application should check for dead zones and respond appopriately, as in this example:

// Zero value if thumbsticks are within the dead zone
if( (state.Gamepad.sThumbLX < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE &&
     state.Gamepad.sThumbLX > -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) &&
    (state.Gamepad.sThumbLY < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE &&
     state.Gamepad.sThumbLY > -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) )
{
   state.Gamepad.sThumbLX = 0;
   state.Gamepad.sThumbLY = 0;
}

if( (state.Gamepad.sThumbRX < XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE &&
     state.Gamepad.sThumbRX > -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE) &&
    (state.Gamepad.sThumbRY < XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE &&
state.Gamepad.sThumbRY > -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE) )
{
   state.Gamepad.sThumbRX = 0;
   state.Gamepad.sThumbRY = 0;
}

Note that you may define your own dead zones for the sticks and triggers (anywhere from 0-65534), or you may use the provided deadzones defined as XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE, and XINPUT_GAMEPAD_TRIGGER_THRESHOLD in XInput.h:

#define XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE  7849
#define XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE 8689
#define XINPUT_GAMEPAD_TRIGGER_THRESHOLD    30

Once the deadzone is enforced, you may find it useful to scale the resulting range [0.0..1.0] floating point, and optionally apply a non-linear transform.

For example, with driving games, it may be helpful to cube the result to provide a better feel to driving the cars using a gamepad, as cubing the result gives you more precision in the lower ranges, which is desirable, since gamers typically either apply soft force to get subtle movement or apply hard force all the way in one direction to get rapid response.

Setting Vibration Effects

In addition to getting the state of the controller, you may also send vibration data to the controller to alter the feedback provided to the user of the controller. The controller contains two rumble motors that can be independently controlled by passing values to the XInputSetState function.

The speed of each motor can be specified using a WORD value in the XINPUT_VIBRATION structure that is passed to the XInputSetState function as follows:

XINPUT_VIBRATION vibration;
ZeroMemory( &vibration, sizeof(XINPUT_VIBRATION) );
vibration.wLeftMotorSpeed = 32000; // use any value between 0-65535 here
vibration.wRightMotorSpeed = 16000; // use any value between 0-65535 here
XInputSetState( i, &vibration );

Note that the right motor is the high-frequency motor, the left motor is the low-frequency motor. They do not always need to be set to the same amount, as they provide different effects.

Getting DirectSound GUIDs

The headset that can be connected to an Xbox 360 Controller has two functions: it can record sound using a microphone, and it can play back sound using a headphone. In the XInput API, these functions are accomplished through DirectSound, using the IDirectSound8 and IDirectSoundCapture8 interfaces.

To associate the headset microphone and headphone with their appropriate DirectSound interfaces, you must get the DirectSound GUIDs for the capture and render devices by calling XInputGetDSoundAudioDeviceGuids.

XInputGetDSoundAudioDeviceGuids( i, &dsRenderGuid, &dsCaptureGuid );

Once you have retrieved the GUIDs you can create the appropriate interfaces by calling DirectSoundCreate8 and DirectSoundCaptureCreate8 like this:

// Create IDirectSound8 using the controller's render device
if( FAILED( hr = DirectSoundCreate8( &dsRenderGuid, &pDS, NULL ) ) )
   return hr;

// Set coop level to DSSCL_PRIORITY
if( FAILED( hr = pDS->SetCooperativeLevel( hWnd, DSSCL_NORMAL ) ) )
   return hr;

// Create IDirectSoundCapture using the controller's capture device
if( FAILED( hr = DirectSoundCaptureCreate8( &dsCaptureGuid, &pDSCapture, NULL ) ) )
   return hr;

See Also

XInput Reference | XInput Samples | DirectSound Reference

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


XInput and DirectInput

XInput is an API that allows applications to receive input from the Xbox 360 Controller for Windows. This document describes the differences between XInput and DirectInput implementations of the Xbox 360 Controller and how you can support XInput devices and legacy DirectInput devices at the same time.

The New Standard: XInput

XInput is now available for game development. This is the new input standard for both the Xbox 360 and Windows XP Service Pack 1 and above, and Windows Vista. The APIs are available through the DirectX SDK and the driver is available on Windows Update and Windowsgaming.com.

There are several advantages to using XInput over DirectInput:

  • XInput is easier to use and requires less setup than DirectInput
  • Both Xbox 360 and Windows programming will use the same sets of core APIs, allowing programming to translate cross-platform much easier
  • There will be a large installed base of Xbox 360 controllers
  • XInput devices (i.e. The Xbox 360 controllers) will have vibration functionality only when using XInput APIs
  • Future controllers released for the Xbox 360 console (i.e. steering wheels) will also work on Windows

Using the Xbox 360 Controller with DirectInput

The Xbox 360 Controller is properly enumerated on DirectInput, and can be used with the DirectInput APIs. However, some functionality provided by XInput will be missing from the DirectInput implementation:

  • The left and right trigger buttons will act as a single button, not independently
  • The vibration effects will not be available
  • Querying for headset devices will not be available

The combination of the left and right triggers in DirectInput is by design. Games have always assumed that DirectInput device axes are centered when there is no user interaction with the device. However, the Xbox 360 controller was designed to register minimum value, not center, when the triggers are not being held. Older games would therefore assume user interaction.

The solution was to combine the triggers, setting one trigger to a positive direction and the other to a negative direction, so no user interaction is indicative to DirectInput of the 'control' being at center.

In order to test the trigger values separately, you must use XInput.

XInput and DirectInput Side by Side

By supporting XInput only, your game will not work with legacy DirectInput devices. XInput will not recognize these devices.

If you want your game to support legacy DirectInput devices, you may use DirectInput and XInput side by side. When enumerating your DirectInput devices, all DirectInput devices will enumerate correctly. All XInput devices will show up as both XInput and DirectInput devices, but they should not be handled through DirectInput. You will need to determine which of your Dinput devices are legacy devices, and which are XInput devices, and remove them from the enumeration of DirectInput devices.

To do this, insert this code into your DirectInput enumeration callback:

#include <wbemidl.h>
#include <oleauto.h>
#include <wmsstd.h>

//-----------------------------------------------------------------------------
// Enum each PNP device using WMI and check each device ID to see if it contains
// "IG_" (ex. "VID_045E&PID_028E&IG_00").  If it does, then it's an XInput device
// Unfortunately this information can not be found by just using DirectInput
//-----------------------------------------------------------------------------
BOOL IsXInputDevice( const GUID* pGuidProductFromDirectInput )
{
    IWbemLocator*           pIWbemLocator  = NULL;
    IEnumWbemClassObject*   pEnumDevices   = NULL;
    IWbemClassObject*       pDevices[20]   = {0};
    IWbemServices*          pIWbemServices = NULL;
    BSTR                    bstrNamespace  = NULL;
    BSTR                    bstrDeviceID   = NULL;
    BSTR                    bstrClassName  = NULL;
    DWORD                   uReturned      = 0;
    bool                    bIsXinputDevice= false;
    UINT                    iDevice        = 0;
    VARIANT                 var;
    HRESULT                 hr;

    // CoInit if needed
    hr = CoInitialize(NULL);
    bool bCleanupCOM = SUCCEEDED(hr);

    // Create WMI
    hr = CoCreateInstance( __uuidof(WbemLocator),
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           __uuidof(IWbemLocator),
                           (LPVOID*) &pIWbemLocator);
    if( FAILED(hr) || pIWbemLocator == NULL )
        goto LCleanup;

    bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );if( bstrNamespace == NULL ) goto LCleanup;
    bstrClassName = SysAllocString( L"Win32_PNPEntity" );   if( bstrClassName == NULL ) goto LCleanup;
    bstrDeviceID  = SysAllocString( L"DeviceID" );          if( bstrDeviceID == NULL )  goto LCleanup;

    // Connect to WMI
    hr = pIWbemLocator->ConnectServer( bstrNamespace, NULL, NULL, 0L,
                                       0L, NULL, NULL, &pIWbemServices );
    if( FAILED(hr) || pIWbemServices == NULL )
        goto LCleanup;

    // Switch security level to IMPERSONATE.
    CoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL,
                       RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE );

    hr = pIWbemServices->CreateInstanceEnum( bstrClassName, 0, NULL, &pEnumDevices );
    if( FAILED(hr) || pEnumDevices == NULL )
        goto LCleanup;

    // Loop over all devices
    for( ;; )
    {
        // Get 20 at a time
        hr = pEnumDevices->Next( 10000, 20, pDevices, &uReturned );
        if( FAILED(hr) )
            goto LCleanup;
        if( uReturned == 0 )
            break;

        for( iDevice=0; iDevice<uReturned; iDevice++ )
        {
            // For each device, get its device ID
            hr = pDevices[iDevice]->Get( bstrDeviceID, 0L, &var, NULL, NULL );
            if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != NULL )
            {
                // Check if the device ID contains "IG_".  If it does, then it's an XInput device
                    // This information can not be found from DirectInput
                if( wcsstr( var.bstrVal, L"IG_" ) )
                {
                    // If it does, then get the VID/PID from var.bstrVal
                    DWORD dwPid = 0, dwVid = 0;
                    WCHAR* strVid = wcsstr( var.bstrVal, L"VID_" );
                    if( strVid && swscanf( strVid, L"VID_%4X", &dwVid ) != 1 )
                        dwVid = 0;
                    WCHAR* strPid = wcsstr( var.bstrVal, L"PID_" );
                    if( strPid && swscanf( strPid, L"PID_%4X", &dwPid ) != 1 )
                        dwPid = 0;

                    // Compare the VID/PID to the DInput device
                    DWORD dwVidPid = MAKELONG( dwVid, dwPid );
                    if( dwVidPid == pGuidProductFromDirectInput->Data1 )
                    {
                        bIsXinputDevice = true;
                        goto LCleanup;
                    }
                }
            }
            SAFE_RELEASE( pDevices[iDevice] );
        }
    }

LCleanup:
    if(bstrNamespace)
        SysFreeString(bstrNamespace);
    if(bstrDeviceID)
        SysFreeString(bstrDeviceID);
    if(bstrClassName)
        SysFreeString(bstrClassName);
    for( iDevice=0; iDevice<20; iDevice++ )
        SAFE_RELEASE( pDevices[iDevice] );
    SAFE_RELEASE( pEnumDevices );
    SAFE_RELEASE( pIWbemLocator );
    SAFE_RELEASE( pIWbemServices );

    if( bCleanupCOM )
        CoUninitialize();

    return bIsXinputDevice;
}

//-----------------------------------------------------------------------------
// Name: EnumJoysticksCallback()
// Desc: Called once for each enumerated joystick. If we find one, create a
//       device interface on it so we can play with it.
//-----------------------------------------------------------------------------
BOOL CALLBACK EnumJoysticksCallback( const DIDEVICEINSTANCE* pdidInstance,
                                     VOID* pContext )
{
    HRESULT hr;

    if( IsXInputDevice( &pdidInstance->guidProduct ) )
        return DIENUM_CONTINUE;

     // Device is verified not XInput, so add it to the list of DInput devices

     return DIENUM_CONTINUE;
}

See Also

Getting Started With XInput | XInput Reference | XInput Samples | DirectInput

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


Samples

Several XInput samples are provided in the SDK. These samples are accessible using the sample browser.

SimpleController

This sample uses XInput and visually displays the state of each of the 4 controllers. Uses XInputGetState.

RumbleController

This sample shows how to set the rumble amount on each of the 4 controllers. Uses XInputGetState and XInputSetState.

AudioController

This sample uses XInput and DirectSound to read the headset microphone and play it back on the headset for each of the controllers. Uses XInputGetDSoundAudioDeviceGuids.

XInputGame

This sample shows how to combine Direct3D and XInput as well as how to handle unplugged controllers. Uses XInputGetState and XInputSetState.

See Also

Getting Started With XInput | XInput Functions

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


XInput Reference

  • XInput Functions
  • XInput Structures


XInput Functions

Function | Description
XInputGetDSoundAudioDeviceGuids | Retrieves the sound rendering and sound capture device GUIDs that are associated with the headset connected to the specified controller.
XInputGetCapabilities | Retrieves the capabilities and features of a connected controller.
XInputGetKeystroke | Retrieves a gamepad input event.
XInputGetState | Retrieves the current state of the specified controller.
XInputSetState | Sends data to a connected controller.
XInputEnable | Sets the reporting state of XInput.


XInputGetCapabilities

Retrieves the capabilities and features of a connected controller.

DWORD XInputGetCapabilities(
  DWORD dwUserIndex,
  DWORD dwFlags,
  XINPUT_CAPABILITIES* pCapabilities
);

Parameters

dwUserIndex
[in] Index of the user's controller. Can be a value in the range 0–3. For information about how this value is determined and how the value maps to indicators on the controller, see Multiple Controllers.
dwFlags
[in] Input flags that identify the controller type. If this value is 0, then the capabilities of all controllers connected to the system are returned. Currently, only one value is supported:
Value | Description
XINPUT_FLAG_GAMEPAD | Limit query to devices of Xbox 360 Controller type.

Any value of dwflags other than the above or 0 is illegal and will result in an error break when debugging.

pCapabilities
[out] Pointer to an XINPUT_CAPABILITIES structure that receives the controller capabilities.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the controller is not connected, the return value is ERROR_DEVICE_NOT_CONNECTED.

If the function fails, the return value is an error code defined in Winerror.h. The function does not use SetLastError to set the calling thread's last-error code.

Requirements

Header: Declared in XInput.h.

Library: Use Xinput.lib.

See Also

XInput Functions | XInputGetState, XInputSetState


XInputGetKeystroke

Retrieves a gamepad input event.

DWORD XInputGetKeystroke(
  DWORD dwUserIndex,
  DWORD dwReserved,
  PXINPUT_KEYSTROKE pKeystroke
);

Parameters

dwUserIndex
[in] Index of the signed-in gamer associated with the device. Can be a value in the range 0–XUSER_MAX_COUNT − 1, or XUSER_INDEX_ANY to fetch the next available input event from any user.
dwReserved
[in] Input flags that identify the device type.
Value | Description
XINPUT_FLAG_GAMEPAD | Limit input event fetch to the gamepad.
pKeystroke
[out] Pointer to an XINPUT_KEYSTROKE structure that receives an input event.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If no new keys have been pressed, the return value is ERROR_EMPTY.

If the controller is not connected or the user has not activated it, the return value is ERROR_DEVICE_NOT_CONNECTED. (See Remarks.)

If the function fails, the return value is an error code defined in Winerror.h. The function does not use SetLastError to set the calling thread's last-error code.

Remarks

Wireless controllers are not considered active upon system startup, and calls to any of the XInput functions before a wireless controller is made active return ERROR_DEVICE_NOT_CONNECTED. Game titles must examine the return code and be prepared to handle this condition. Wired controllers are automatically activated when they are inserted. Wireless controllers are activated when the user presses the START or Xbox Guide button to power on the controller.

The functions XInputGetCapabilities, XInputGetState, and XInputGetKeystroke ignore the port number if XDEVICE_PORT_FLAG_KEYBOARD is specified. If this flag is specified, the same debug keyboard appears to be plugged into all four ports.

Requirements

Header: Declared in XInput.h.

Library: Use Xinput.lib.

See Also

XInput Functions | XINPUT_KEYSTROKE

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


XInputGetState

Retrieves the current state of the specified controller.

DWORD XInputGetState(
  DWORD dwUserIndex,
  XINPUT_STATE* pState
);

Parameters

dwUserIndex
[in] Index of the user's controller. Can be a value from 0 to 3. For information about how this value is determined and how the value maps to indicators on the controller, see Multiple Controllers.
pState
[out] Pointer to an XINPUT_STATE structure that receives the current state of the controller.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the controller is not connected, the return value is ERROR_DEVICE_NOT_CONNECTED.

If the function fails, the return value is an error code defined in Winerror.h. The function does not use SetLastError to set the calling thread's last-error code.

Remarks

When XInputGetState is used to retrieve controller data, the left and right triggers are each reported separately. For legacy reasons, when DirectInput® retrieves controller data, the two triggers share the same axis. The legacy behavior is noticeable in the current Game Device Control Panel, which uses DirectInput for controller state.

Requirements

Header: Declared in XInput.h.

Library: Use Xinput.lib.

See Also

XInput Functions | XInputSetState, XINPUT_STATE, XINPUT_GAMEPAD


XInputSetState

Sends data to a connected controller. This function is used to activate the vibration function of a controller.

DWORD XInputSetState(
  DWORD dwUserIndex,
  XINPUT_VIBRATION* pVibration
);

Parameters

dwUserIndex
[in] Index of the user's controller. Can be a value from 0 to 3. For information about how this value is determined and how the value maps to indicators on the controller, see Multiple Controllers.
pVibration
[in, out] Pointer to an XINPUT_VIBRATION structure containing the vibration information to send to the controller.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the controller is not connected, the return value is ERROR_DEVICE_NOT_CONNECTED.

If the function fails, the return value is an error code defined in Winerror.h. The function does not use SetLastError to set the calling thread's last-error code.

Requirements

Header: Declared in XInput.h.

Library: Use Xinput.lib.

See Also

XInput Functions | XInputGetState, XINPUT_VIBRATION


XInputGetDSoundAudioDeviceGuids

Retrieves the sound rendering and sound capture device GUIDs that are associated with the headset connected to the specified controller.

DWORD XInputGetDSoundAudioDeviceGuids(
  DWORD dwUserIndex,
  GUID* pDSoundRenderGuid,
  GUID* pDSoundCaptureGuid
);

Parameters

dwUserIndex
[in] Index of the user's controller. Can be a value in the range 0–3. For information about how this value is determined and how the value maps to indicators on the controller, see Multiple Controllers.
pDSoundRenderGuid
[out] Pointer that receives the GUID of the headset sound rendering device.
pDSoundCaptureGuid
[out] Pointer that receives the GUID of the headset sound capture device.

Return Values

If the function successfully retrieves the device IDs for render and capture, the return code is ERROR_SUCCESS.

If there is no headset connected to the controller, the function will also retrieve ERROR_SUCCESS with GUID_NULL as the values for pDSoundRenderGuid and pDSoundCaptureGuid.

If the controller port device is not physically connected, the function will return ERROR_DEVICE_NOT_CONNECTED.

If the function fails, it will return a valid Win32 error code.

Requirements

Header: Declared in XInput.h.

Library: Use Xinput.lib.

See Also

XInput Functions | XInputGetState

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


XInputEnable

Sets the reporting state of XInput.

void XInputEnable(
  BOOL enable
);

Parameters

enable
If enable is FALSE, XInput will only send neutral data in response to XInputGetState (all buttons up, axes centered, and triggers at 0). XInputSetState calls will be registered but not sent to the device. Sending any value other than FALSE will restore reading and writing functionality to normal.

Return Values

None.

Remarks

This function is meant to be called when an application gains or loses focus (such as via WM_ACTIVATEAPP). Using this function, you will not have to change the XInput query loop in your application as neutral data will always be reported if XInput is disabled.

In a controller that supports vibration effects:

  • Passing FALSE will stop any vibration effects currently playing. In this state, calls to XInputSetState will be registered, but not passed to the device.
  • Passing TRUE will pass the last vibration request (even if it is 0) sent to XInputSetState to the device.

Requirements

Header: Declared in XInput.h.

Library: Use Xinput.lib.

See Also

XInput Functions | XInputGetState, XInputSetState, XINPUT_STATE, XINPUT_GAMEPAD


XInput Structures

Structure | Description
XINPUT_CAPABILITIES | Describes the capabilities of a connected controller. XINPUT_CAPABILITIES is returned by the XInputGetCapabilities function.
XINPUT_GAMEPAD | Describes the current state of the Xbox 360 Controller.
XINPUT_VIBRATION | Specifies motor speed levels for the vibration function of a controller.
XINPUT_STATE | Represents the state of a controller.


XINPUT_CAPABILITIES

Describes the capabilities of a connected controller. XINPUT_CAPABILITIES is returned by the XInputGetCapabilities function.

typedef struct _XINPUT_CAPABILITIES {
    BYTE Type;
    BYTE SubType;
    WORD Flags;
    XINPUT_GAMEPAD Gamepad;
    XINPUT_VIBRATION Vibration;
} XINPUT_CAPABILITIES, *PXINPUT_CAPABILITIES;

Members

Type
Controller type. Must be one of the following values.
Value | Description
XINPUT_DEVTYPE_GAMEPAD | The device is a game controller.
SubType
Subtype of the game controller.
Subtype | Meaning
XINPUT_DEVSUBTYPE_ARCADE_STICK | Arcade style joystick
XINPUT_DEVSUBTYPE_GAMEPAD | Gamepad
XINPUT_DEVSUBTYPE_WHEEL | Wheel

Note For restrictions on the use of this subtype value, see the Remarks section below. Additional subtypes may be added in the future.

Flags
Features of the controller.
Value | Description
XINPUT_CAPS_VOICE_SUPPORTED | The device has an integrated voice device.
Gamepad
XINPUT_GAMEPAD structure that describes available controller features and control resolutions.
Vibration
XINPUT_VIBRATION structure that describes available vibration functionality and resolutions.

Remarks

XInputGetCapabilities returns XINPUT_CAPABILITIES to indicate the characteristics and available functionality of a specified controller.

XInputGetCapabilities sets the structure members to indicate which inputs the device supports. For binary state controls, such as digital buttons, the corresponding bit reflects whether or not the control is supported by the device. For proportional controls, such as thumbsticks, the value indicates the resolution for that control. Some number of the least significant bits may not be set, indicating that the control does not provide resolution to that level.

The SubType member indicates the specific subtype of controller present. Games may detect the controller subtype and tune their handling of controller input or output based on subtypes that are well suited to their game genre. For example, a car racing game might check for the presence of a wheel controller to provide finer control of the car being driven. However, titles must not disable or ignore a device based on its subtype – subtypes not recognized by the game or for which the game is not specifically tuned should be treated as a standard Xbox 360 Controller (XINPUT_DEVSUBTYPE_GAMEPAD).

Requirements

Header: Declared in XInput.h.

See Also

XInput Structures | XInputGetCapabilities, XINPUT_GAMEPAD, XINPUT_VIBRATION


XINPUT_GAMEPAD

Describes the current state of the Xbox 360 Controller.

typedef struct _XINPUT_GAMEPAD {
    WORD wButtons;
    BYTE bLeftTrigger;
    BYTE bRightTrigger;
    SHORT sThumbLX;
    SHORT sThumbLY;
    SHORT sThumbRX;
    SHORT sThumbRY;
} XINPUT_GAMEPAD, *PXINPUT_GAMEPAD;

Members

wButtons
Bitmask of the device digital buttons, as follows. A set bit indicates that the corresponding button is pressed.
#define XINPUT_GAMEPAD_DPAD_UP          0x00000001
#define XINPUT_GAMEPAD_DPAD_DOWN        0x00000002
#define XINPUT_GAMEPAD_DPAD_LEFT        0x00000004
#define XINPUT_GAMEPAD_DPAD_RIGHT       0x00000008
#define XINPUT_GAMEPAD_START            0x00000010
#define XINPUT_GAMEPAD_BACK             0x00000020
#define XINPUT_GAMEPAD_LEFT_THUMB       0x00000040
#define XINPUT_GAMEPAD_RIGHT_THUMB      0x00000080
#define XINPUT_GAMEPAD_LEFT_SHOULDER    0x0100
#define XINPUT_GAMEPAD_RIGHT_SHOULDER   0x0200
#define XINPUT_GAMEPAD_A                0x1000
#define XINPUT_GAMEPAD_B                0x2000
#define XINPUT_GAMEPAD_X                0x4000
#define XINPUT_GAMEPAD_Y                0x8000

Bits that are set but not defined above are reserved, and their state is undefined.

bLeftTrigger
The current value of the left trigger analog control. The value is between 0 and 255.
bRightTrigger
The current value of the right trigger analog control. The value is between 0 and 255.
sThumbLX
Left thumbstick x-axis value. Each of the thumbstick axis members is a signed value between -32768 and 32767 describing the position of the thumbstick. A value of 0 is centered. Negative values signify down or to the left. Positive values signify up or to the right. The constants XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE or XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE can be used as a positive and negative value to filter a thumbstick input.
sThumbLY
Left thumbstick y-axis value. The value is between -32768 and 32767.
sThumbRX
Right thumbstick x-axis value. The value is between -32768 and 32767.
sThumbRY
Right thumbstick y-axis value. The value is between -32768 and 32767.

Remarks

This structure is used by the XINPUT_STATE structure when polling for changes in the state of the controller.

The specific mapping of button to game function varies depending on the game type.

The constant XINPUT_GAMEPAD_TRIGGER_THRESHOLD may be used as the value which bLeftTrigger and bRightTrigger must be greater than to register as pressed. This is optional, but often desirable. Xbox 360 Controller buttons do not manifest crosstalk.

Requirements

Header: Declared in XInput.h.

See Also

XInput Structures | XInputGetState, XINPUT_STATE


XINPUT_KEYSTROKE

Specifies keystroke data returned by XInputGetKeystroke.

typedef struct _XINPUT_KEYSTROKE {
    WORD VirtualKey;
    WCHAR Unicode;
    WORD Flags;
    BYTE UserIndex;
    BYTE HidCode;
} XINPUT_KEYSTROKE, *PXINPUT_KEYSTROKE;

Members

VirtualKey
Virtual-key code of the key, button, or stick movement. See XInput.h for a list of valid virtual-key (VK_xxx) codes. Also, see Remarks below.
Unicode
This member is unused and the value is zero.
Flags
Flags that indicate the keyboard state at the time of the input event. This member can be any combination of the following flags:
Value | Description
XINPUT_KEYSTROKE_KEYDOWN | The key was pressed.
XINPUT_KEYSTROKE_KEYUP | The key was released.
XINPUT_KEYSTROKE_REPEAT | A repeat of a held key.
UserIndex
Index of the signed-in gamer associated with the device. Can be a value in the range 0–3.
HidCode
HID code corresponding to the input. If there is no corresponding HID code, this value is zero.

Remarks

A virtual-key code is a byte value that represents a particular physical key on the keyboard, not the character or characters (possibly none) that the key can be mapped to based on keyboard state. The keyboard state at the time a virtual key is pressed modifies the character reported. For example, VK_4 might represent a "4" or a "$", depending on the state of the SHIFT key.

A reported keyboard event includes the virtual key that caused the event, whether the key was pressed or released (or is repeating), and the state of the keyboard at the time of the event. The keyboard state includes information about whether any CTRL, ALT, or SHIFT keys are down.

If the keyboard event represents an Unicode character (for example, pressing the "A" key), the Unicode member will contain that character. Otherwise, Unicode will contain the value zero.

The valid virtual-key (VK_xxx) codes are defined in XInput.h. In addition to codes that indicate key presses, the following codes indicate controller input.

Value | Description
VK_PAD_A | A button
VK_PAD_B | B button
VK_PAD_X | X button
VK_PAD_Y | Y button
VK_PAD_RSHOULDER | Right shoulder button
VK_PAD_LSHOULDER | Left shoulder button
VK_PAD_LTRIGGER | Left trigger
VK_PAD_RTRIGGER | Right trigger
VK_PAD_DPAD_UP | Directional pad up
VK_PAD_DPAD_DOWN | Directional pad down
VK_PAD_DPAD_LEFT | Directional pad left
VK_PAD_DPAD_RIGHT | Directional pad right
VK_PAD_START | START button
VK_PAD_BACK | BACK button
VK_PAD_LTHUMB_PRESS | Left thumbstick click
VK_PAD_RTHUMB_PRESS | Right thumbstick click
VK_PAD_LTHUMB_UP | Left thumbstick up
VK_PAD_LTHUMB_DOWN | Left thumbstick down
VK_PAD_LTHUMB_RIGHT | Left thumbstick right
VK_PAD_LTHUMB_LEFT | Left thumbstick left
VK_PAD_LTHUMB_UPLEFT | Left thumbstick up and left
VK_PAD_LTHUMB_UPRIGHT | Left thumbstick up and right
VK_PAD_LTHUMB_DOWNRIGHT | Left thumbstick down and right
VK_PAD_LTHUMB_DOWNLEFT | Left thumbstick down and left
VK_PAD_RTHUMB_UP | Right thumbstick up
VK_PAD_RTHUMB_DOWN | Right thumbstick down
VK_PAD_RTHUMB_RIGHT | Right thumbstick right
VK_PAD_RTHUMB_LEFT | Right thumbstick left
VK_PAD_RTHUMB_UPLEFT | Right thumbstick up and left
VK_PAD_RTHUMB_UPRIGHT | Right thumbstick up and right
VK_PAD_RTHUMB_DOWNRIGHT | Right thumbstick down and right
VK_PAD_RTHUMB_DOWNLEFT | Right thumbstick down and left

Requirements

Header: Declared in XInput.h.

See Also

XInputGetKeystroke


XINPUT_STATE

Represents the state of a controller.

typedef struct _XINPUT_STATE {
    DWORD dwPacketNumber;
    XINPUT_GAMEPAD Gamepad;
} XINPUT_STATE, *PXINPUT_STATE;

Members

dwPacketNumber
State packet number. The packet number indicates whether there have been any changes in the state of the controller. If the dwPacketNumber member is the same in sequentially returned XINPUT_STATE structures, the controller state has not changed.
Gamepad
XINPUT_GAMEPAD structure containing the current state of an Xbox 360 Controller.

Remarks

The dwPacketNumber member is incremented only if the status of the controller has changed since the controller was last polled.

Requirements

Header: Declared in XInput.h.

See Also

XInput Structures | XInputGetState, XINPUT_GAMEPAD


XINPUT_VIBRATION

Specifies motor speed levels for the vibration function of a controller.

typedef struct _XINPUT_VIBRATION {
    WORD wLeftMotorSpeed;
    WORD wRightMotorSpeed;
} XINPUT_VIBRATION, *PXINPUT_VIBRATION;

Members

wLeftMotorSpeed
Speed of the left motor. Valid values are in the range 0 to 65,535. Zero signifies no motor use; 65,535 signifies 100 percent motor use.
wRightMotorSpeed
Speed of the right motor. Valid values are in the range 0 to 65,535. Zero signifies no motor use; 65,535 signifies 100 percent motor use.

Remarks

The left motor is the low-frequency rumble motor. The right motor is the high-frequency rumble motor. The two motors are not the same, and they create different vibration effects.

Requirements

Header: Declared in XInput.h.

See Also

XInput Structures | XInputSetState, XINPUT_GAMEPAD, XInputGetCapabilities


DirectInput

This section provides information about the Microsoft DirectInput component of the Microsoft DirectX application programming interface (API). The DirectInput API is used to process data from a keyboard, mouse, joystick, or other game controller.

Roadmap

Information on using DirectInput is presented in the following sections. Use this page to guide you through the documentation based on your level of experience as a DirectInput developer.

Introduction to DirectInput. High-level overview of the capabilities of DirectInput and the steps you'll take to implement it. Start with this section if you're new to DirectInput.

Understanding DirectInput. Introduction to the objects and interfaces of DirectInput and how they are related to the Microsoft Windows message system. Read this section if you're new to DirectInput.

Using DirectInput. Guide to the API. This section contains more detailed conceptual information than the previous two sections, as well as information about the API elements you'll use for setting up devices, retrieving data, and implementing force-feedback effects. If you're a novice, at least familiarize yourself with the contents of this section. Later, you can refer to topics as you need them. Use this section in conjunction with the DirectInput C/C++ Reference.

Programming Tips and Tools. Advanced programming topics and a guide to the DirectInput tools provided with the DirectX software development kit (SDK).

DirectInput Tutorials. Step-by-step tutorials, often based on samples in the SDK. If you learn best from sample code, this is a good place to start after reading Introduction to DirectInput and Understanding DirectInput.

DirectInput Samples. A guide to the DirectInput C/C++ samples included in the SDK, illustrating the use and capabilities of DirectInput.

DirectInput C/C++ Reference. Reference information for the API. Use this section when you need to know the details of an interface, method, structure, macro, or other element.


Introduction to DirectInput

DirectInput is an API for input devices including the mouse, keyboard, joystick, and other game controllers, as well as for force-feedback (input/output) devices.

This topic provides a brief overview of the capabilities of DirectInput and how to set it up in an application. For a more comprehensive view of how DirectInput works, see Understanding DirectInput. For a step-by-step guide to using the DirectInput API, see the following topics:

  • Using DirectInput
  • DirectInput Tutorials

The Power of DirectInput

DirectInput enables an application to retrieve data from input devices even when the application is in the background. It also provides full support for any type of input device, as well as for force feedback.

Through action mapping, applications can retrieve input data without needing to know what kind of device is being used to generate it.

The extended services and improved performance of DirectInput make it a valuable tool for games, simulations, and other real-time interactive applications running under Windows.

DirectInput does not provide any advantages for applications that use the keyboard for text entry or the mouse for navigation. For more information, see Interaction with Windows.

Getting Started with DirectInput

This topic is an overview of what is involved in setting up and using DirectInput in a simple application.

For details and examples of these steps, see Using DirectInput and DirectInput Tutorials.

Note To understand DirectInput, it is essential to understand the following terms:

DirectInput object
The root DirectInput interface.
Device
A keyboard, mouse, joystick, or other input device.
DirectInputDevice object
Code representing a keyboard, mouse, joystick, or other input device.
Device object
Code representing a key, button, trigger, and so on found on a DirectInput device object. Also called device object instance.

The following steps represent a simple implementation of DirectInput in which the application takes responsibility for ascertaining what device object (button, axis, and so on) generated each item of data.

  1. Create the DirectInput object.

    You use methods of this object to enumerate devices and create DirectInput device objects.

  2. Enumerate devices.

    This is not an essential step if you intend to use only the system mouse or keyboard. To ascertain what other input devices are available on the user's system, have DirectInput enumerate them. Each time DirectInput finds a device that matches the criteria you set, it gives you the opportunity to examine the device's capabilities. It also retrieves a unique identifier that you can use to create a DirectInput device object representing the device.

  3. Create a DirectInputDevice object for each device you want to use.

    To do this, you need the unique identifier retrieved during enumeration. For the system mouse or keyboard, you can use a standard globally unique identifier (GUID).

  4. Set up the device.

    For each device, first set the cooperative level, which determines the way the device is shared with other applications or the system. You must also set the data format used for identifying device objects, such as buttons and axes, within data packets. If you intend to retrieve buffered data-that is, events rather than states-you also need to set a buffer size. Optionally, at this stage you can retrieve information about the device and tailor the application's behavior accordingly. You can also set properties such as the range of values returned by joystick axes.

  5. Acquire the device.

    At this stage you tell DirectInput that you are ready to receive data from the device.

  6. Retrieve data.

    At regular intervals, typically on each pass through the message loop or rendering loop, get either the current state of each device or a record of events that have taken place since the last retrieval. If you prefer, you can have DirectInput notify you whenever an event occurs.

  7. Act on the data.

    The application can respond either to the state of buttons and axes or to events such as a key being pressed or released.

  8. Close DirectInput.

    Before exiting, your application should unacquire all devices and release them, then release the DirectInput object.

This is not the only approach to implementing DirectInput. To take advantage of the great variety of input devices available now and later, and to simplify configuration for the user, you can use action mapping.

By setting an action map for a device, you let DirectInput decide which device object to use for each application action. For example, instead of specifying that the throttle in your racing game must always be controlled by the y-axis, you can create an action called AXIS_THROTTLE and have DirectInput assign that action to the most appropriate axis available on the device. When you retrieve events, you identify them by their associated actions rather than by the device objects that generated them.


Understanding DirectInput

This topic covers the underlying structure of Microsoft DirectInput and its relationship to the Microsoft Windows message system.

For practical information about how to implement the elements of DirectInput introduced here, see Using DirectInput.

DirectInput Objects

An input-only DirectInput implementation consists of the DirectInput object, which supports IDirectInput8 Interface, a Component Object Model (COM) interface, and a DirectInputDevice object for each input device that provides data. Each DirectInputDevice object in turn has device objects, which are individual controls or switches, such as keys, buttons, or axes. Device objects are also called device object instances.

Each DirectInputDevice object represents one input device, such as a mouse, keyboard, or joystick. In the DirectInput API, the word joystick means any type of input device other than a mouse or keyboard. A piece of hardware that is really a combination of different types of input devices, such as a keyboard with a touchpad, can be represented by two or more DirectInputDevice objects. A force-feedback device is represented by a single joystick object that handles both input and output.

DirectInputDevice objects instantiate the IDirectInputDevice8 Interface. The application ascertains the number and type of device objects available by using the IDirectInputDevice8::EnumObjects method. Individual device objects are not encapsulated as code objects, but are described in DIDEVICEOBJECTINSTANCE structures.

All DirectInput interfaces are available in ANSI and Unicode versions. If "UNICODE" is defined during compilation, the Unicode versions are used.

Interaction with Windows

Because DirectInput works directly with the device drivers, it either suppresses or ignores Windows mouse and keyboard messages. It also ignores mouse and keyboard settings made by the user in Control Panel. It does, however, use the calibrations set for a joystick or other game controller.

DirectInput does not recognize keyboard character repeat settings. When using buffered data, DirectInput interprets each press and release as a single event with no repetition. When using immediate data, DirectInput is concerned only with the present physical state of the keys, not with keyboard events as interpreted by Windows.

DirectInput does not perform any character conversion or translation. For example, the SHIFT key is treated like any other key, not as a modifier of another keypress. Keys return the same identifiers regardless of the user's system language settings.

Under Windows 2000, acquiring the keyboard in exclusive mode prevents any applications that are subsequently launched from receiving keyboard data.

Because DirectInput works directly with the mouse driver, it bypasses the subsystem of Windows that interprets mouse data for windowed applications. Applications that rely on the Windows cursor for navigation should continue to use the standard Windows mouse messages and Microsoft Win32 functions.

When using the system mouse in exclusive mode, DirectInput suppresses mouse messages, and therefore Windows is unable to show the standard cursor.

DirectInput ignores Control Panel settings such as acceleration and swapped buttons. However, DirectInput recognizes settings in the driver itself. For example, if the user has a three-button mouse and uses the driver-utility software to make the middle button a double-click shortcut, DirectInput reports a click of the middle button as two clicks of the primary button.


Using DirectInput

This topic is a guide to implementing Microsoft DirectX. For a broader overview, see Understanding DirectInput.

This programming guide also provides the following subsections:

  • DirectInput Devices
  • DirectInput Device Data
  • Force Feedback

Creating DirectInput

The first step in any Microsoft DirectInput application is obtaining the IDirectInput8 Interface. You can do this most easily by calling the DirectInput8Create function.

You should create a single DirectInput object and not release it until the application terminates.

DirectInput Device Enumeration

DirectInput can query the system for all available input devices, determine whether they are connected, and return information about them. This process is called enumeration.

If your application is using only the standard keyboard or mouse, or both, you do not need to enumerate the available input devices. As explained under Creating a DirectInput Device, you can use predefined global variables when calling the IDirectInput8::CreateDevice method.

The following code example, where lpdi is a pointer to the IDirectInput8 Interface interface, creates a keyboard device:

LPDIRECTINPUTDEVICE8  lpdiKeyboard;

lpdi->CreateDevice(GUID_SysKeyboard, &lpdiKeyboard, NULL);

The first parameter in IDirectInput8::CreateDevice is an instance GUID that identifies the instance of the device for which the interface is to be created. Microsoft DirectInput has two predefined GUIDs, GUID_SysMouse and GUID_SysKeyboard, which represent the system mouse and keyboard. You can pass one of these identifiers into the IDirectInput8::CreateDevice method. The global variable GUID_Joystick should not be used as a parameter for IDirectInput8::CreateDevice because it is a product GUID, not an instance GUID.

Note If the computer has more than one mouse, input from all mice is combined to form the system device. The same is true for multiple keyboards.

DirectInput provides four other predefined GUIDs primarily for testing.

  • GUID_SysKeyboardEm
  • GUID_SysKeyboardEm2
  • GUID_SysMouseEm
  • GUID_SysMouseEm2

Passing one of these GUIDs to IDirectInput8::CreateDevice grants access to the system keyboard or mouse through an emulation layer, at either level 1 or level 2. These GUIDs always represent the system mouse or keyboard. They are aliases for GUID_SysKeyboard and GUID_SysMouse, so they are not enumerated by IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics unless the DIEDFL_INCLUDEALIASES flag is passed.

For devices other than the system mouse or keyboard, use the instance GUID for the device returned by IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics. The instance GUID for a device is always the same. You can allow the user to select a device from a list of those enumerated, then save the GUID to a configuration file and use it again in later sessions.


DirectInput Devices

This section contains information about the code objects that represent devices such as mice, keyboards, and joysticks. The following topics are covered:

  • Acquiring Devices
  • Cooperative Levels
  • Creating a DirectInput Device
  • Device Capabilities
  • Device Data Formats
  • Device Object Enumeration
  • Device Properties
  • Device Setup

For information about how to retrieve and interpret data from devices, see DirectInput Device Data.


Acquiring Devices

Acquiring a DirectInput device means giving your application access to it. As long as a device is acquired, DirectInput is making its data available to your application. If the device is not acquired, you can manipulate its characteristics but not obtain any data.

Acquisition is not permanent. Your application might acquire and release a device many times.

In certain cases, depending on the cooperative level, a device is released automatically whenever the application moves to the background. The mouse is automatically released when the user clicks a menu, because at this point, Windows assumes control of the device.

You must release a device before changing its properties. The only exception is that you can change the gain for a force-feedback device while it is in an acquired state.

The acquisition mechanism is needed for two reasons:

  1. DirectInput must be able to tell the application when the flow of data from the device has been interrupted by the system. For example, if the user has switched to another application with ALT+TAB and has used the input device in that application, your application needs to know that the input no longer belongs to it and that the state of the buffers might have changed.

    Consider an application with the DISCL_FOREGROUND cooperative level. The user holds down the SHIFT key and switches to another application. Then the user releases the key and switches back to the first application. As far as the first application is concerned, the SHIFT key is still down. The acquisition mechanism, by telling the application that input was lost, enables it to recover from these conditions.

  2. Your application can alter the properties of the device, and without safeguards, DirectInput would need to check the properties each time you wanted to retrieve data. This would be very inefficient and could allow for disaster; for example, a hardware interrupt accessing a data buffer just as you were changing the buffer size.

    Therefore, DirectInput requires that your application release the device before changing its properties. When you reacquire it, DirectInput checks the properties and decides on the optimal way of transferring data from the device to the application. This is done only once, so the data retrieval methods can be very fast.

Windows does not have access to the mouse when your application is using it in exclusive mode. If you want Windows to acquire the mouse, you must release it.


Cooperative Levels

The cooperative level of a device determines how the input is shared with other applications and with the Windows system. You set it by using the IDirectInputDevice8::SetCooperativeLevel method.

/* hwnd is the top-level window handle. */
lpdiDevice->SetCooperativeLevel(hwnd,
        DISCL_NONEXCLUSIVE | DISCL_FOREGROUND)

The parameters are the handle to the top-level window associated with the device (generally the application window) and one or more flags.

Flags | Notes
DISCL_NONEXCLUSIVE DISCL_BACKGROUND | The default setting
DISCL_NONEXCLUSIVE DISCL_FOREGROUND |
DISCL_EXCLUSIVE DISCL_FOREGROUND |
DISCL_EXCLUSIVE DISCL_BACKGROUND | Not valid for keyboard or mouse

For the keyboard, you can also include DISCL_NOWINKEY in combination with DISCL_NONEXCLUSIVE. This flag disables the Windows logo key so that users cannot inadvertently break out of the application. In exclusive mode, the Windows logo key is always disabled.

Note Even if the cooperative level for the application is disabling the Windows logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping UI is displayed.

The cooperative level has two main components: whether the device is being used in the foreground or the background, and whether it is being used exclusively or nonexclusively.

Foreground vs. Background

Exclusive vs. Nonexclusive

Consider the example of a music player that accepts input from a hand-held remote-control device, even when the application is running in the background. Now suppose you run a similar application that plays movies in response to signals from the same remote control. What happens when the user presses Play? Both programs start playing, which is probably not what the user wants. To prevent this from happening, each application should have the DISCL_EXCLUSIVE flag set so that only one of them can be running at a time.

To use force-feedback effects, an application must have exclusive access to the device.

Windows itself requires exclusive access to the system mouse. The reason is that system mouse events, such as a click on an inactive window, could force an application to unacquire the device, with potentially harmful results such as a loss of data from the input buffer. So when an application has exclusive access to the system mouse, created by passing GUID_SysMouse to IDirectInput8::CreateDevice, Windows is not allowed any access and no mouse messages are generated. A further side effect is that the cursor disappears.


Creating a DirectInput Device

To get input data from a device, you first have to create an object to represent that device.

The following code example, where lpdi is a pointer to the IDirectInput8 Interface interface, creates a keyboard device:

LPDIRECTINPUTDEVICE8  lpdiKeyboard;

lpdi->CreateDevice(GUID_SysKeyboard, &lpdiKeyboard, NULL);

The first parameter in IDirectInput8::CreateDevice is an instance globally unique identifier (GUID) that identifies the instance of the device for which the interface is to be created. DirectInput has two predefined GUIDs, GUID_SysMouse and GUID_SysKeyboard, which represent the system mouse and keyboard. You can pass one of these identifiers into the IDirectInput8::CreateDevice method. The global variable GUID_Joystick should not be used as a parameter for IDirectInput8::CreateDevice because it is a product GUID, not an instance GUID.

Note If the computer has more than one mouse, input from all of them is combined to form the system device. The same is true for multiple keyboards.

DirectInput provides four other predefined GUIDs primarily for testing.

  • GUID_SysKeyboardEm

  • GUID_SysKeyboardEm2

  • GUID_SysMouseEm

  • GUID_SysMouseEm2.

Passing one of these GUIDs to IDirectInput8::CreateDevice grants access to the system keyboard or mouse through an emulation layer, at either level 1 or level 2. These GUIDs always represent the system mouse or keyboard. They are aliases for GUID_SysKeyboard and GUID_SysMouse, so they are not enumerated by IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics unless the DIEDFL_INCLUDEALIASES flag is passed.

For devices other than the system mouse or keyboard, use the instance GUID for the device returned by IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics. The instance GUID for a device is always the same. You can allow the user to select a device from a list of those enumerated, then save the GUID to a configuration file and use it again in later sessions.


Device Capabilities

Before you begin asking for input from a device, you need to know something about its capabilities. Does the joystick have a point-of-view hat? Is the mouse currently attached to the user's computer?

DIDEVCAPS  DIMouseCaps;
HRESULT    hr;
BOOLEAN    WheelAvailable;

DIMouseCaps.dwSize = sizeof(DIDEVCAPS);
hr = lpdiMouse->GetCapabilities(&DIMouseCaps);
WheelAvailable = ((DIMouseCaps.dwFlags & DIDC_ATTACHED)
        && (DIMouseCaps.dwAxes > 2));

Another way to check for a button or axis is to call IDirectInputDevice8::GetObjectInfo for that object. If the call returns DIERR_OBJECTNOTFOUND, the object is not present. The following code determines whether there is a z-axis, even if it is not the third axis:

DIDEVICEOBJECTINSTANCE  didoi;

didoi.dwSize = sizeof(DIDEVICEOBJECTINSTANCE);
hr = lpdiMouse->GetObjectInfo(&didoi, DIMOFS_Z, DIPH_BYOFFSET);
    WheelAvailable = SUCCEEDED(hr);


Device Data Formats

If you are not using Action Mapping, setting the data format for a device is an essential step before you can acquire and begin using the device. This is true even if you do not intend to retrieve immediate (state) data from the device. DirectInput uses the data format in many methods to identify particular device objects.

The IDirectInputDevice8::SetDataFormat method tells DirectInput what device objects will be used and how the data will be arranged.

The examples in the reference for the DIDATAFORMAT and DIOBJECTDATAFORMAT structures show how to set up custom data formats for nonstandard devices. Fortunately, this step is not necessary for the joystick, keyboard, and mouse. DirectInput provides five global variables, c_dfDIJoystick, c_dfDIJoystick2, c_dfDIKeyboard, c_dfDIMouse, and c_dfDIMouse2, which can be passed in to IDirectInputDevice8::SetDataFormat to create a standard data format for these devices.

In the following code example, lpdiMouse is an initialized pointer to a DirectInputDevice object:

lpdiMouse->SetDataFormat(&c_dfDIMouse);

Note You cannot change the dwFlags member in the predefined DIDATAFORMAT global variables (for example, to change the property of an axis), because they are const variables. To change properties, use the IDirectInputDevice8::SetProperty method after setting the data format, but before acquiring the device.


Device Object Enumeration

It might be necessary for your application to determine what buttons or axes are available on a given device. To do this, you enumerate the device objects in much the same way as you enumerate devices.

Note Because of limitations imposed by device drivers, enumeration of keyboard keys and indicator lights is not reliable. Objects might falsely be reported as present. You can get basic information about available keys from the device subtype, but there is no way to determine whether extra objects such as the menu key are available, other than asking the user for input.

To some extent, IDirectInputDevice8::EnumObjects overlaps the functionality of IDirectInputDevice8::GetCapabilities. Either method can be used to determine how many buttons or axes are available. However, IDirectInputDevice8::EnumObjects is intended for cataloging all the available objects rather than checking for a particular one.

Like IDirectInput8::EnumDevices, the IDirectInputDevice8::EnumObjects method has a callback function that enables you to do other processing on each object-for example, adding it to a list or creating a corresponding element on a user interface.

The following sample callback extracts the name of each object so that it can be added to a string list or array. This standard callback is documented under the placeholder name DIEnumDeviceObjectsCallback, but you can give it any name you like. Remember, this function is called once for each object enumerated.

char  szName[MAX_PATH];

BOOL CALLBACK DIEnumDeviceObjectsCallback(
                      LPCDIDEVICEOBJECTINSTANCE lpddoi,
                      LPVOID pvRef)
{
  HRESULT hr = StringCchCopy(szName, MAX_PATH, lpddoi->tszName);
  if(SUCCEEDED(hr))
  {
  // Now add szName to a list or array.
  .
  .
  .
  }
  else
  // Handle errors.

  return DIENUM_CONTINUE;

}

The first parameter points to a structure containing information about the object. This structure is created for you by DirectInput.

The second parameter is an application-defined pointer to data, equivalent to the second parameter to IDirectInputDevice8::EnumObjects. In the example, this parameter is not used.

The return value in this case indicates that enumeration is to continue as long as there are objects to be enumerated.

Now here's the call to the IDirectInputDevice8::EnumObjects method, which puts the callback function to work.

lpdiMouse->EnumObjects(DIEnumDeviceObjectsCallback,
                             NULL, DIDFT_ALL);

The first parameter is the address of the callback function. The second parameter can be a pointer to any data you want to use or modify in the callback. The example does not use this parameter and so passes NULL. The third parameter is a flag to indicate which type or types of objects are to be included in the enumeration. In the example, all objects are to be enumerated. To restrict the enumeration, you can use one or more of the other DIDFT_* flags listed at IDirectInputDevice8::EnumObjects.

Note Some of the DIDFT_* flags are combinations of others; for example, DIDFT_AXIS is equivalent to DIDFT_ABSAXIS | DIDFT_RELAXIS.

When an application has exclusive access to the keyboard, DirectInput suppresses all keyboard messages except CTRL+ALT+DEL and, on Microsoft Windows 95 and Windows 98, ALT+TAB. Under Microsoft Windows 2000, no application launched subsequently to the exclusive-mode DirectInput application can get keyboard data.


Device Properties

Properties of DirectInput devices include the size of the data buffer, the range and granularity of values returned from an axis, whether axis data is relative or absolute, and the dead zone and saturation values for a joystick axis. Specialized devices can have other properties as well. For a list of properties defined by DirectInput, see IDirectInputDevice8::GetProperty.

With one exception-the gain property of a force-feedback device-properties can be changed only when the device is in an unacquired state.

Before calling the IDirectInputDevice8::SetProperty or the IDirectInputDevice8::GetProperty method you must set up a property structure that consists of a DIPROPHEADER structure and one or more elements for data. There is potentially a great variety of properties for input devices, and IDirectInputDevice8::SetProperty must be able to work with all sorts of structures defining those properties. The purpose of the DIPROPHEADER structure is to define the size of the property structure and how the data is to be interpreted.

DirectInput includes the following predefined property structures:

  • DIPROPDWORD defines a structure containing a DIPROPHEADER and a DWORD data member for properties that require a single value, such as a buffer size.
  • DIPROPRANGE is for range properties, which require two values (maximum and minimum). It consists of a DIPROPHEADER and two LONG data members.
  • DIPROPGUIDANDPATH is a specialized property structure that enables applications to perform operations on a Human Interface Device (HID) that is not supported by DirectInput. The structure consists of a DIPROPHEADER, a globally unique identifier (GUID), and a Unicode string for the path.
  • DIPROPSTRING is for Unicode string properties. The structure comprises a DIPROPHEADER and a Unicode string.

For IDirectInputDevice8::SetProperty, the data members of the property structure are the values that you want to set. For IDirectInputDevice8::GetProperty, the current value is returned in these members.

Before the call to IDirectInputDevice8::GetProperty or IDirectInputDevice8::SetProperty, the DIPROPHEADER structure must be initialized with the following:

  • The size of the property structure.
  • The size of the DIPROPHEADER structure itself.
  • An object identifier.
  • A value indicating how the object identifier should be interpreted.

When getting or setting properties for a whole device, the object identifier dwObj is 0, and the dwHow member is DIPH_DEVICE. If you want to get or set properties for a device object (for example, a particular axis), the combination of dwObj and dwHow values identifies the object. For details, see DIPROPHEADER.

After setting up the property structure, pass the address of its header into IDirectInputDevice8::GetProperty or IDirectInputDevice8::SetProperty, along with an identifier for the property that you want to obtain or change.

The following values are used to identify the property passed to IDirectInputDevice8::SetProperty and IDirectInputDevice8::GetProperty.

  • DIPROP_BUFFERSIZE. See also Buffered and Immediate Data. The buffer size can also be set by using the IDirectInputDevice8::SetActionMap method.
  • DIPROP_AXISMODE. See also Relative and Absolute Axis Coordinates.
  • DIPROP_CALIBRATIONMODE
  • DIPROP_GRANULARITY
  • DIPROP_FFGAIN
  • DIPROP_FFLOAD
  • DIPROP_AUTOCENTER
  • DIPROP_RANGE
  • DIPROP_DEADZONE
  • DIPROP_SATURATION

For more information about the last three properties, see also Interpreting Joystick Axis Data.

The following code example sets the buffer size for a device to hold up to 10 data items:

DIPROPDWORD  dipdw;
HRESULT      hr;
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = 10;
hr = lpdiDevice->SetProperty(DIPROP_BUFFERSIZE, &d ipdw.diph);


Device Setup

Your application must obtain a DirectInput device object for each device from which it expects input. It must also prepare each device for use, which requires, at the very least, setting the data format and acquiring the device. You might also want to carry out other preparatory tasks such as getting information about the devices and changing their properties.

The following tasks are part of the setup process. Certain steps are always required. Other steps may be necessary if you need further information about devices or need to change default values.

  1. Create the DirectInput device (required). See Creating a DirectInput Device.
  2. Get the device capabilities (optional).
  3. Enumerate the keys, buttons, and axes on the device (optional). See Device Object Enumeration.
  4. Set the cooperative level (highly recommended).
  5. Set the data format (required).
  6. Set the device properties (you must at least set the buffer size if you intend to get buffered data).
  7. When ready to read data, acquire the device (required). See Acquiring Devices.


DirectInput Device Data

This section covers the following basic concepts of getting data from DirectInput devices.

  • Buffered and Immediate Data
  • Time Stamps and Sequence Numbers
  • Polling and Event Notification
  • Relative and Absolute Axis Coordinates

The following topics describe specific details about output data and mouse, keyboard, and joystick input data.

  • Mouse Data
  • Keyboard Data
  • Joystick Data
  • Output Data

DirectInput provides two mechanisms for identifying data retrieved from devices. Using the traditional mechanism, the application identifies the data as coming from a particular device object, such as a the x-axis on a mouse or the F1 key on a keyboard. With the newer system, available for the first time in DirectX 8.0, DirectInput associates application-defined values (for instance, identifiers for particular game actions such as moving or shooting) with the most suitable device objects available. When data is retrieved, the application does not concern itself with the actual device or device object from which the data comes. It acts only on the meaning of that data.


Buffered and Immediate Data

DirectInput supplies two types of data: buffered and immediate. Buffered data is a record of events that are stored until an application retrieves them. Immediate data is a snapshot of the current state of a device.

You might use immediate data in an application that is concerned only with the current state of a device - for example, a flight combat simulation that responds to the current position of the joystick and the state of one or more buttons. Buffered data might be the better choice where events are more important than states - for example, in an application that responds to movement of the mouse and button clicks. You can also use both types of data, as you might, for example, if you wanted to get immediate data for joystick axes but buffered data for the buttons.

Note For devices that do not generate interrupts, such as analog joysticks, DirectInput does not obtain any data until you call the IDirectInputDevice8::Poll method. For more information, see Polling and Event Notification.

For examples of retrieving buffered data, see IDirectInputDevice8::GetDeviceData.

See also:

  • Time Stamps and Sequence Numbers
  • Mouse Data
  • Keyboard Data
  • Joystick Data


Polling and Event Notification

There are two ways to find out whether input data is available: polling and event notification.

Polling a device means regularly getting the current state of the device objects or checking the contents of the event buffer. Polling is typically used by real-time games that are never idle, but instead are constantly updating and rendering the game world.

Polling

In a C++ application, polling would typically be done within the message loop.

Some joysticks and other game devices, or particular objects on them, do not generate hardware interrupts and do not return any data or signal any events until you call the IDirectInputDevice8::Poll method. (This behind-the-scenes polling is not to be confused with the kind of application polling just discussed. IDirectInputDevice8::Poll does not retrieve any data, but merely makes data available.)

To find out whether it is necessary to call IDirectInputDevice8::Poll each time you want to retrieve data, first set the data format for the device, then call the IDirectInputDevice8::GetCapabilities method and check for the DIDC_POLLEDDATAFORMAT flag in the DIDEVCAPS structure.

Do not confuse the DIDC_POLLEDDATAFORMAT flag with the DIDC_POLLEDDEVICE flag. The latter is set if any object on the device requires polling, regardless of data format. You can then find out whether this is the case for a particular object by calling the IDirectInputDevice8::GetObjectInfo method and checking for the DIDOI_POLLED flag in the DIDEVICEOBJECTINSTANCE structure.

The DIDC_POLLEDDEVICE flag describes the worst case for the device, not the actual situation. For example, a Human Interface Device (HID) mouse with software-controllable resolution might be marked as DIDC_POLLEDDEVICE because reading the resolution information requires polling. If you want to retrieve only the standard button and axis data, polling the device under these conditions is not necessary. However, there is no harm in calling the IDirectInputDevice8::Poll method for any input device. If the call is unnecessary, it has no effect and is very fast.

Event Notification

Event notification is suitable for applications that wait for input before doing anything.

To use event notification, set up a thread-synchronization object with the Microsoft Win32 CreateEvent function, and then associate this event with the device by passing its handle to the IDirectInputDevice8::SetEventNotification method. The event is then signaled by Microsoft DirectInput whenever the state of the device changes. Your application can receive notification of the event with a Win32 function such as WaitForSingleObject, and then respond by checking the input buffer to find out what the event was. For code examples, see IDirectInputDevice8::SetEventNotification.


Relative and Absolute Axis Coordinates

Axis coordinates can be returned as relative values-that is, the amount by which they have changed since the application last retrieved the device state or, in the case of buffered input, since the last item was put in the buffer.

Absolute axis coordinates are a running total of all the relative coordinates returned by the system since the device was acquired. In other words, they show the position of the axis in relation to a fixed point.

By default, mouse axes are reported as relative coordinates and joystick axes as absolute coordinates. You can change the coordinate system for a device by setting a property. For more information, see Device Properties.


Time Stamps and Sequence Numbers

When DirectInput input data is buffered (see Buffered and Immediate Data), each DIDEVICEOBJECTDATA structure contains not only information about the type of event and the device object associated with it. It also contains a time stamp and a sequence number.

The dwTimeStamp member contains the system time, in milliseconds, at which the event took place. This is equivalent to the value that would have been returned by the Microsoft Win32 GetTickCount function, but at a higher resolution.

The dwSequence member contains a sequence number assigned by DirectInput. The DirectInput system keeps a single sequence counter, which is incremented by each buffered event from any device. (Simultaneous events on the same device, such as diagonal mouse movements, increment the count only once.) Use this number to compare events from different devices and see which came first. The DISEQUENCE_COMPARE macro, used for comparing DirectInput sequence numbers, takes wraparound into account.

Note Events are always placed in the buffer in chronological order, so you don't need to check the sequence numbers to sort the events from a single device.


Joystick Data

To set up the joystick device for data retrieval, first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIJoystick or the c_dfDIJoystick2 global variable as the parameter value. (See Device Data Formats.).

Because some device drivers do not notify Microsoft DirectInput of changes in state until explicitly asked to do so, you should always call the IDirectInputDevice8::Poll method before attempting to retrieve data from the joystick. For more information, see Polling and Event Notification.

The following sections cover retrieval and interpretation of data from a joystick or other similar input device such as a game pad or steering wheel:

  • Buffered Joystick Data
  • Checking for Lost Joystick Input
  • Immediate Joystick Data
  • Interpreting Joystick Axis Data
  • Using CPOINTs


Buffered Joystick Data

To retrieve buffered data from the joystick, first set the buffer size (see Device Properties) and declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush the buffer at any time with the IDirectInputDevice8::GetDeviceData method.(See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the joystick. For instance, if the user presses button 0 and moves the stick diagonally, the array passed to IDirectInputDevice8::GetDeviceData (if it has at least three elements, and pdwInOut is at least 3) will have three elements filled in-an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis-and the value of pdwInOut will be set to 3.

You can determine which object an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the following values:

  • DIJOFS_X
  • DIJOFS_Y
  • DIJOFS_Z
  • DIJOFS_Rx
  • DIJOFS_Ry
  • DIJOFS_Rz
  • DIJOFS_BUTTON0 to DIJOFS_BUTTON31 or DIJOFS_BUTTON(n)
  • DIJOFS_POV(n)
  • DIJOFS_SLIDER(n)

Each of these values is equivalent to the offset of the data for the object in a DIJOYSTATE structure. For example, DIJOFS_BUTTON0 is equivalent to the offset of rgbButtons[0] in the DIJOYSTATE structure. You can use simple comparisons to determine which device object is associated with an item in the buffer. For example:

DIDEVICEOBJECTDATA  *lpdidod;
int                 n;
.
.
.
/* JoyBuffer is an array of DIDEVICEOBJECTDATA structures
   that has been set by a call to GetDeviceData.
   n is incremented in a loop that examines all filled elements
   in the array. */
lpdidod = &JoyBuffer[n];
if (( (int) lpdidod->dwOfs == DIJOFS_BUTTON0)
   && (lpdidod->dwData & 0x80))
{
 ;  // Do something in response to press of primary button.
}

If the data format was set with c_dfDIJoystick2, you can use the predefined offsets for all the device objects that exist in DIJOYSTATE, but you must supply your own offsets for device objects represented in the extra members of DIJOYSTATE2.

The data for the change of state of the device object is located in the dwData member of the DIDEVICEOBJECTDATA structure. For axes, the coordinate value is returned in this member. For button objects, only the low byte of dwData is significant. The high bit of this byte is set if the button is pressed, and it is clear if the button is released.

For the other members, see Time Stamps and Sequence Numbers.


Checking for Lost Joystick Input

If your application is using the joystick in foreground mode (see Cooperative Levels), it will lose the device when the focus shifts to another application.

Check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or the IDirectInputDevice8::GetDeviceState method and attempt to reacquire the joystick, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the joystick on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would fail again, you would get another DIERR_NOTACQUIRED error, and so on.

Because access to the joystick is not lost except when your application moves to the background - unlike the mouse and keyboard, the joystick is never used by the Windows system - an alternative method is to reacquire the device in response to a WM_ACTIVATE message.


Immediate Joystick Data

To retrieve the current state of the joystick, call the IDirectInputDevice8::GetDeviceState method with a pointer to a DIJOYSTATE or a DIJOYSTATE2 structure, depending on whether the data format was set with c_dfDIJoystick or c_dfDIJoystick2. (See Device Data Formats.) The joystick state returned in the structure includes the coordinates of the axes, the state of the buttons, and the state of the point-of-view controllers.

The first seven members of the DIJOYSTATE structure hold the axis coordinates. The last of these seven, rglSlider, is an array of two values. (See Interpreting Joystick Axis Data.)

The rgdwPOV member contains the position of up to four point-of-view controllers in hundredths of a degree clockwise from north (or forward). The center (neutral) position is reported as -1. For controllers that have only five positions, the position is one of the following values:

  • - 1
  • 0
  • 90 * DI_DEGREES
  • 180 * DI_DEGREES
  • 270 * DI_DEGREES.

Some drivers report a value of 65,535, instead of - 1, for the center position. You should check for a centered POV indicator as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

The rgbButtons member is an array of bytes, one for each of 32 or 128 buttons, depending on the data format. For each button, the high bit is set if the button is down and it is clear if the button is up or not present.

The DIJOYSTATE2 structure has additional members for information about the velocity, acceleration, force, and torque of the axes.

See also

Buffered and Immediate Data


Interpreting Joystick Axis Data

Axis values for the joystick are like those for the mouse. The value returned for the x-axis is greater as the stick moves to the right, and the value for the y-axis increases as the stick moves toward the user.

Data is in arbitrary units determined by the range property of the axis. For example, if the range for the stick's x-axis is from 0 through 10,000, a unit is one ten-thousandth of the stick's left-right travel, and the center position is 5,000. For some axes, the granularity property might be greater than 1. In this case, values are rounded off. For example, if the granularity is 10, values are reported as 0, 10, 20, and so on.

Axis data is also affected by the dead zone, a region around the center position in which motion is ignored. The dead zone provides tolerance for a slight deviation from the true center position for either or both axes of the stick. An axis value within the range of the dead zone is reported as true center.

The saturation property of an axis is a zone of tolerance at the minimum and maximum of the range. An axis value within this zone is reported as the minimum or maximum value. The purpose of the saturation property is to allow for slight differences between, for example, the minimum x-axis value reported at the top-left and bottom-left positions of the stick.

The following illustration shows the effect of the dead zone and the saturation zones. The vertical axis represents the returned axis values, where min and max are the lower and upper limits of the reported range and ctr is the reported center. The horizontal axis shows the physical position of the stick, where pmin and pmax are the extremes of the physical range, pctr is neutral position of the axis, dmin and dmax are the limits of the dead zone, and smin and smax are the boundaries of the lower and upper saturation zones. The lower saturation zone lies between pmin and smin, the upper saturation zone lies between smax and pmax, and the dead zone lies between dmin and dmax.

Graph of dead zone and saturation zones

For more information about joystick properties, see the following:

  • IDirectInputDevice8::GetProperty
  • IDirectInputDevice8::SetProperty
  • DIPROPRANGE
  • DIACTIONFORMAT

Axis coordinates from the joystick can be either relative or absolute. (See Relative and Absolute Axis Coordinates.) Because a joystick is an absolute device - unlike a mouse, it cannot travel infinitely far along any axis - absolute data is returned by default. When the axis mode for the joystick is set to relative, the axis coordinate represents the number of units of movement along the axis since the last value was returned.

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to relative, call the IDirectInputDevice8::SetProperty method with the DIPROP_AXISMODE value in the rguidProp parameter and with DIPROPAXISMODE_REL in the dwData member of the DIPROPDWORD structure.


Using CPOINTs

The CPOINT structure is used to calibrate segments of the response curve of a device axis. Up to eight CPOINTs can be set through the DIPROPCPOINTS structure. Each CPOINT structure contains a raw data value representing the position of the joystick along the axis, and a logical value. When your application receives the raw value, the logical value is used to calculate the returned value that is actually used. Raw values that fall between specific CPOINT raw data values are interpolated to logical values based on a line drawn between the CPOINTs to either side of the value.

The following is an example of the effect of five CPOINTs applied to the response curve of a joystick's x-axis. Before application of the DIPROPCPOINTS structure, the response graph for the example axis would appear as shown below, including saturation and dead zones.

A DIPROPCPOINTS structure is initialized as follows, assuming the physical range to be -500 to 500.

DIPROPCPOINTS dipcp;

dipcp.diph.dwSize = sizeof(DIPROPCPOINTS);
dipcp.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipcp.diph.dwObj = GUID_XAxis;
dipcp.diph.dwHow = DIPH_BYID;
dipcp.dwCPointsNum = 5;
dipcp.cp[0].lP = -500;
dipcp.cp[0].dwLog = 0;
dipcp.cp[1].lP = -300;
dipcp.cp[1].dwLog = 1000;
dipcp.cp[2].lP = -100;
dipcp.cp[2].dwLog = 5000;
dipcp.cp[3].lP = 200;
dipcp.cp[3].dwLog = 9000;
dipcp.cp[4].lP = 500;
dipcp.cp[4].dwLog = 10000;

Note that you do not need to know the actual maximum returned value as the values in the dwLog member of the CPOINT structure are expressed as a percentage of the total, multiplied by 10000 (the number of discrete divisions in the total range). For instance, the example sets the curve so that 10% of the maximum value is returned at the -300 point in the joystick's range. 0.10 * 10000 = 1000, so that value is given to the dwLog member while -300 is assigned to the corresponding lP member.

After applying this DIPROPCPOINTS structure through IDirectInputDevice8::SetProperty, the curve responds as seen below.


Keyboard Data

When using DirectInput, consider the keyboard not as a text input device but as a game pad with many buttons. When your application requires text input, do not use DirectInput methods. It is far easier to retrieve the data from the normal Windows messages, which enable you take advantage of services such as character repeat and translation of physical keys to virtual keys. This is particularly important for languages other than English, which can require special translations of key presses.

To set up the keyboard device for data retrieval, you must first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIKeyboard global variable as the parameter. (See Device Data Formats.)

The following sections give more information about obtaining and interpreting keyboard data:

  • Buffered Keyboard Data
  • Checking for Lost Keyboard Input
  • Immediate Keyboard Data
  • Interpreting Keyboard Data


Buffered Keyboard Data

To retrieve buffered data from the keyboard, you must first set the buffer size (see Device Properties). This step is essential because the default size of the buffer is 0.

You must also declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the keyboard device, you can examine and flush the buffer at any time by using the IDirectInputDevice8::GetDeviceData method. (See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single key-that is, a press or release. Because Microsoft DirectInput gets the data directly from the keyboard, any settings for character repeat in Control Panel are ignored. This means that a keystroke is counted only once, no matter how long the key is held down.

You can determine which key an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the DirectInput Keyboard Device. (See also Interpreting Keyboard Data.)

The data for the change of state of the key is located in the dwData member of the DIDEVICEOBJECTDATA structure. Only the low byte of dwData is significant. The high bit of this byte is set if the key was pressed, and it is clear if it was released. In other words, the key was pressed if (dwData& 0x80) is nonzero.


Checking for Lost Keyboard Input

When you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application, Windows might force your application to unacquire the keyboard. For this reason, you should check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or IDirectInputDevice8::GetDeviceState methods and attempt to reacquire the keyboard, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the keyboard on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would again fail, you would get another DIERR_NOTACQUIRED error, and so on.


Immediate Keyboard Data

To retrieve the current state of the keyboard, call the IDirectInputDevice8::GetDeviceState method with a pointer to an array of 256 bytes that will hold the returned data.

The IDirectInputDevice8::GetDeviceState method behaves in the same way as the Microsoft Win32 GetKeyboardState function. It returns a snapshot of the current state of the keyboard. Each key is represented by a byte in the array of 256 bytes whose address was passed as the lpvData parameter. If the high bit of the byte is set, the key is down. The array is most conveniently indexed with the Microsoft DirectInput Keyboard Device. (See also Interpreting Keyboard Data.)

The following code example calls a function in response to the ESC key being down. Assume that lpdiKeyboard is an acquired DirectInput device.

BYTE  diKeys[256];
if (lpdiKeyboard->GetDeviceState(256, diKeys) == DI_OK)
{
    if (diKeys[DIK_ESCAPE] & 0x80) DoSomething();
}


Interpreting Keyboard Data

This topic covers the identification of keys for which data is reported by the IDirectInputDevice8::GetDeviceState and IDirectInputDevice8::GetDeviceData methods. For more information about interpreting the data from IDirectInputDevice8::GetDeviceData, see Time Stamps and Sequence Numbers.

In one important respect, DirectInput applications read the keyboard differently from the way Windows does. For DirectInput applications, keyboard data refers not to virtual keys but to the actual physical keys - that is, the scan codes. DIK_ENTER, for example, refers only to the ENTER key on the main keyboard, not to the ENTER key on the numerical keypad.

Additionally, differences among keyboards can affect the way DirectInput applications interpret keyboard data. For example, DirectInput defines a constant for each key on the enhanced keyboard, as well as the additional keys on international keyboards. Because NEC keyboards support different scan codes than the PC-enhanced keyboards, DirectInput translates NEC key-scan codes into PC-enhanced scan codes where possible.

Other keyboard differences to consider are:

  • Not all PC-enhanced keyboards have the Windows logo keys (DIK_LWIN, DIK_RWIN, and DIK_APPS), there is no way to determine whether the keys are physically available.
  • Laptops and other small computers often do not implement a full set of keys. Instead, some keys (typically numeric keypad keys) are multiplexed with other keys, which are selected by an auxiliary mode key that does not generate a separate scan code.
  • If the keyboard subtype indicates a PC XT or PC AT keyboard, the following keys are not available: DIK_F11, DIK_F12, and all the extended keys (DIK_* values greater than 0x7F). Furthermore, the PC XT keyboard lacks DIK_SYSRQ.

  • Japanese keyboards, particularly the NEC PC-98 keyboards, contain a substantially different set of keys than U.S. keyboards. For more information, see DirectInput and Japanese Keyboards.


Mouse Data

To set up the mouse device for data retrieval, first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIMouse global variable as the parameter value. Use c_dfDIMouse2 if you want to support more than four mouse buttons.

For maximum performance in a full-screen application, set the cooperative level to DISCL_EXCLUSIVE | DISCL_FOREGROUND. Note that the exclusive setting causes the Microsoft Windows cursor to disappear. The DISCL_FOREGROUND setting causes the application to lose access to the mouse when you switch to a debugging window. Changing to DISCL_BACKGROUND enables you to debug the application more easily, but at a cost in performance.

The following sections give more information about retrieval and interpretation of immediate and buffered mouse data.

  • Buffered Mouse Data
  • Checking for Lost Mouse Input
  • Immediate Mouse Data
  • Interpreting Mouse Axis Data

See Also

Device Data Formats, Cooperative Levels


Buffered Mouse Data

To retrieve buffered data from the mouse, you must first set the buffer size (see Device Properties). The default size of the buffer is 0, so this step is essential.

You must also declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush events in the buffer at any time by using the IDirectInputDevice8::GetDeviceData method. (See Buffered and Immediate Data.) On return, each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the mouse. For example, if the user presses button 0 and moves the mouse diagonally, the array passed to IDirectInputDevice8::GetDeviceData (if it has at least three elements, and pdwInOut is at least 3) will have three elements filled in-an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis-and the value of pdwInOut will be set to 3.

You can determine which object an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the values returned by the following macros:

  • DIMOFS_BUTTON0 to DIMOFS_BUTTON7
  • DIMOFS_X
  • DIMOFS_Y
  • DIMOFS_Z

Each of these values is derived from the offset of the data for the object in a DIMOUSESTATE or DIMOUSESTATE2 structure. For example, DIMOFS_BUTTON0 is equivalent to the offset of rgbButtons[0] in the DIMOUSESTATE structure. DIMOFS_BUTTON4 to DIMOFS_BUTTON7 are supported only for DIMOUSESTATE2. With the macros you can use simple comparisons to determine which device object is associated with an item in the buffer. For example:

DIDEVICEOBJECTDATA  *lpdidod;
int                 n;
.
.
.
/* MouseBuffer is an array of DIDEVICEOBJECTDATA structures
   that has been set by a call to GetDeviceData.
   n is incremented in a loop that examines all filled elements
   in the array. */
lpdidod = &MouseBuffer[n];
if (( (int) lpdidod->dwOfs == DIMOFS_BUTTON0)
      && (lpdidod->dwData & 0x80))
{
 ;  // Do something in response to left button press.
}

The data for the change of state of the device object is located in the dwData member of the DIDEVICEOBJECTDATA structure. For axes, the coordinate value is returned in this member. For button objects, only the low byte of dwData is significant. The high bit of this byte is set if the button was pressed, and it is clear if the button was released. In other words, the button was pressed if (dwData& 0x80) is nonzero.

For more information about the other members of the DIDEVICEOBJECTDATA structure, see Time Stamps and Sequence Numbers.


Checking for Lost Mouse Input

When you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application (or even to the menu in your own application), Windows might force your application to unacquire the mouse. For this reason, you should check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or the IDirectInputDevice8::GetDeviceState method, and attempt to reacquire the mouse if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the mouse on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop - acquisition would again fail, you would get another DIERR_NOTACQUIRED error, and so on.


Immediate Mouse Data

To retrieve the current state of the mouse, call IDirectInputDevice8::GetDeviceState with a pointer to a DIMOUSESTATE or a DIMOUSESTATE2 structure, depending on the data format. The mouse state returned in the structure includes axis data and the state of each of the buttons.

The first three members of the structure hold the axis coordinates. (See Interpreting Mouse Axis Data.)

The rgbButtons member is an array of bytes, one for each of four or eight buttons. For a traditional mouse, the first element in the array is generally the left button, the second is the right button, and the third is the middle button. The high bit is set if the button is down, and it is clear if the button is up or not present.

See also

Buffered and Immediate Data


Interpreting Mouse Axis Data

The data returned for the x-axis and y-axis of a mouse indicates the movement of the mouse itself, not the cursor. The units of measurement are based on the values returned by the mouse hardware and have nothing to do with pixels or any other form of screen measurement. Because DirectInput communicates directly with the mouse driver, the values for mouse speed and acceleration set by the user in Control Panel do not affect this data.

Axis data returned from the mouse can be either relative or absolute. (See Relative and Absolute Axis Coordinates.) Because a mouse is a relative device - unlike a joystick, it does not have a home position - relative data is returned by default.

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to absolute, call IDirectInputDevice8::SetProperty with the DIPROP_AXISMODE value in the rguidProp parameter and with DIPROPAXISMODE_ABS in the dwData member of the DIPROPDWORD structure.

When the axis mode for the mouse is set to relative, the axis coordinate represents the number of units that the device has been moved along the axis since the last value was returned. A negative value indicates that the mouse was moved to the left for the x-axis, or away from the user for the y-axis, or that the z-axis (the wheel) was rotated toward the user. Positive values indicate movement in the opposite direction.

When the axis mode is set to absolute, the coordinates are a running total of all relative motions received by DirectInput. The axis coordinates are not initialized to any particular value when the device is acquired, so your application should treat absolute values as relative to an unknown origin. You can record the current absolute position whenever the device is acquired and save it as the virtual origin. This virtual origin can then be subtracted from subsequent absolute coordinates retrieved from the device to compute the relative distance that the mouse has moved from the point of acquisition.

The data returned for the axis coordinates is also affected by the granularity property of the device. For the x-axis and y-axis of the mouse, granularity is normally 1. In other words, the minimum change in value is 1. For the wheel axis, it might be larger.


Output Data

Some Human Interface Devices both generate input and accept output. The IDirectInputDevice8::SendDeviceData method is used to send packets of data to such devices.

IDirectInputDevice8::SendDeviceData may be viewed as IDirectInputDevice8::GetDeviceData in reverse. As with that method, it uses the DIDEVICEOBJECTDATA structure as the basic unit of data. In this case, however, the dwOfs member contains the instance ID of the device object associated with the data rather than its offset in the data format for the device. (Because offset identifiers exist only for device objects that provide input in the selected data format, an object that accepts only output might not even have an offset.) The dwData member contains whatever data is appropriate for the object. The dwTimeStamp and dwSequence members are not used and must be set to 0.

To send data to the device, set up an array of DIDEVICEOBJECTDATA structures, fill the required number of elements with data, and then pass the array address and the number of elements used to IDirectInputDevice8::SendDeviceData. Data for different device objects is combined into a single packet that is then sent to the device.

The form of the data packet is specific to the device, as is the treatment of unused fields in the packet. Some devices may treat fields as optional. In other words, if no data is supplied, the state of the object remains unchanged. More commonly, all fields are significant, even when you do not specifically supply data for them. For example, if you send data to a single keyboard LED, it is assumed that the data for the other two LEDs is 0 and that they are turned off. However, you can override this behavior by using the DISDD_CONTINUE flag. In this case, the data for the other two LEDs is the value you most recently sent them.

The device object type identifiers are obtained from the dwType member of the DIDEVICEOBJECTINSTANCE structure after passing the HID usage page and usage code to IDirectInputDevice8::GetObjectInfo. For example, the type identifier of the Scroll Lock LED can be obtained by using the following code, where pdev is an IDirectInputDevice8 Interface interface pointer representing the keyboard.

DIDEVICEOBJECTINSTANCE didoi;
DWORD NumLockID;
HRESULT hr = pdev->GetObjectInfo(&didoi,
        DIMAKEUSAGEDWORD(0x07,0x53), DIPH_BYUSAGE);
NumLockID = didoi.dwType;

The following sample function, when called repeatedly, causes the LEDs on the keyboard to flash in a recurring pattern. It is assumed that the high bit of the data byte determines the state of the LED. The DWORDs NumLockID, CapsLockID, and ScrollLockID have all been obtained as shown above.

#define ARRAYSIZE 4
void FlashLEDs(void)
    {
    static int         rgiBits[] = { 1, 2, 4, 2 };
    static int         iLooper = 0;
    DWORD              cdod = 3;                  // Number of items
    DIDEVICEOBJECTDATA rgdod[ARRAYSIZE-1];
    HRESULT            hres;

    // Must clear dwTimeStamp and dwSequence
    ZeroMemory(rgdod, sizeof(rgdod));

    rgdod[0].dwOfs = NumLockID;
    rgdod[1].dwOfs = CapsLockID;
    rgdod[2].dwOfs = ScrollLockID;

    rgdod[0].dwData = (rgiBits[iLooper] & 1) ? 0x80 : 0;
                                           // NumLock light on/off
    rgdod[1].dwData = (rgiBits[iLooper] & 2) ? 0x80 : 0;
                                           // CapsLock light on/off
    rgdod[2].dwData = (rgiBits[iLooper] & 4) ? 0x80 : 0;
                                           // ScrollLock light on/off

    iLooper = (iLooper + 1) % ARRAYSIZE; // Loops from 0 to 3

    hres = pdev->SendDeviceData(sizeof(DIDEVICEOBJECTDATA),
            rgdod, &cdod, 0);
    }


Force Feedback

Force feedback is the generation of push or resistance in an input/output device - for example, by motors mounted in the base of a joystick. DirectInput enables you to generate force-feedback effects for devices that have compatible drivers.

The following sections introduce the elements of force feedback:

  • Basic Concepts of Force Feedback
  • Changing an Effect
  • Creating an Effect
  • Downloading and Unloading Effects
  • Effect Direction
  • Effect Enumeration
  • Effect Object Enumeration
  • Effect Playback
  • Envelopes and Offsets
  • Force-Feedback State
  • Gain
  • Information About a Supported Effect
  • Loading Effects from a File
  • Effect Types


Basic Concepts of Force Feedback

A particular instance of force feedback is called an effect, and the push or resistance is called the force. Most effects fall into one of the following categories:

  • Constant force. A steady force in a single direction.
  • Ramp force. A force that steadily increases or decreases in magnitude.
  • Periodic effect. A force that pulsates according to a defined wave pattern.
  • Condition. A reaction to motion or position along an axis. Two examples are a friction effect that generates resistance to movement of the joystick, and a spring effect that pushes the stick back toward a certain position after it has been moved from that position.

The strength of the force is called its magnitude. Magnitude is measured in units ranging from 0 (no force) through 10,000 (maximum force for the device, defined for C/C++ and Microsoft Visual Basic as DI_FFNOMINALMAX). A negative value indicates force in the opposite direction. Magnitudes are linear: a force of 10,000 is twice as great as one of 5,000.

Ramp forces have a beginning and ending magnitude. For a periodic effect, the basic magnitude is the force at the peak of the wave.

The direction of a force is the direction from which it comes. A positive force on a given axis pushes from the positive toward the negative.

Effects also have duration, measured in microseconds. Periodic effects have a period, or the duration of one cycle, also measured in microseconds. The phase of a periodic effect is the point along the wave at which playback begins.

The following illustration represents a sawtooth periodic effect with a magnitude of 5,000, or half the maximum force for the device. The horizontal axis represents the duration of the effect, and the vertical axis represents the magnitude. Points above the center line represent positive force in the direction defined for the effect, and points below the center line represent negative force, or force in the opposite direction.

Graph of sawtooth force feedback

A force may be further shaped by an envelope. An envelope defines an attack value and a fade value, which modify the beginning and ending magnitude of the effect. Attack and fade also have duration, which determines how long the magnitude takes to reach or fall away from the sustain value, the magnitude in the middle portion of the effect.

The following diagram shows an envelope. The attack level is set to 8,000 and the fade level to 1,000. The sustain level is defined by the basic magnitude of the force to which the envelope is being applied; in the example, it is 5,000. In this case, the attack is greater than the sustain, giving the effect an initial strong kick. Both the attack and the fade level can be either greater or less than the sustain level.

Graph of envelope force feedback

The next diagram shows the result of the envelope being applied to the periodic effect in the first diagram. The envelope is mirrored on the negative side of the magnitude. An attack value of 8,000 means that the initial magnitude of the force in either direction is 80 percent of the maximum possible.

Graph of sawtooth and envelope force feedback

Periodic effects and conditions can also be modified by the addition of an offset, which defines the amount by which the waveform is shifted up or down from the base level. The practical effect of applying a positive offset to the sawtooth example would be to strengthen the positive force and weaken the negative one - in other words, the force would peak more strongly in one direction than in the other.

Finally, the overall magnitude of an effect can be scaled by gain, which is analogous to a volume control in audio. A single gain value can be applied to all effects for a device. You might want to do this to compensate for stronger or weaker forces on different hardware or to accommodate the user's preferences.


Changing an Effect

You can modify the parameters of an effect, in some cases even while the effect is playing. Do this by using the IDirectInputEffect::SetParameters method.

The dwDynamicParams member of the DIEffectInfo structure tells you which effect parameters can be changed while an effect is playing. If you attempt to modify an effect parameter that cannot be modified while the effect is playing, and the effect is still playing, Microsoft DirectInput normally stops the effect, updates the parameters, and restarts the effect. You can override this default behavior by passing the DIEP_NORESTART flag.

The following code example changes the magnitude of the constant force that was set in the example under Creating an Effect.

DIEFFECT        diEffect;           // Parameters for effect
DICONSTANTFORCE diConstantForce;    // Type-specific parameters

diConstantForce.lMagnitude = 5000;
diEffect.dwSize = sizeof(DIEFFECT);
diEffect.cbTypeSpecificParams = sizeof(DICONSTANTFORCE);
diEffect.lpvTypeSpecificParams = &diConstantForce;
hr = lpdiEffect->SetParameters(&diEffect, DIEP_TYPESPECIFICPARAMS);

The DIEP_TYPESPECIFICPARAMS flag ensures that the transfer of data from the DIEFFECT structure is restricted to the relevant members, so that you do not have to initialize the entire structure and so that the minimum possible amount of data needs to be sent to the device.


Creating an Effect

Create an effect object by using the IDirectInputDevice8::CreateEffect method, as in the following code example where g_lpdid points to an instance of the interface. This example creates a very simple effect that pulls the joystick away from the user at full force for half a second.

HRESULT  hr;
LPDIRECTINPUTEFFECT lpdiEffect;  // receives pointer to created effect
DIEFFECT diEffect;               // parameters for created effect
DWORD    dwAxes[2] = { DIJOFS_X, DIJOFS_Y };
LONG     lDirection[2] = { 18000, 0 };
DICONSTANTFORCE diConstantForce;

diConstantForce.lMagnitude = DI_FFNOMINALMAX;   // Full force
diEffect.dwSize          = sizeof(DIEFFECT);
diEffect.dwFlags         = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;
diEffect.dwDuration      = (DWORD)(0.5 * DI_SECONDS);
diEffect.dwSamplePeriod  = 0;                 // = default
diEffect.dwGain          = DI_FFNOMINALMAX;   // No scaling
diEffect.dwTriggerButton = DIEB_NOTRIGGER;    // Not a button response
diEffect.dwTriggerRepeatInterval = 0;         // Not applicable
diEffect.cAxes                   = 2;
diEffect.rgdwAxes                = &dwAxes[0];
diEffect.rglDirection            = &lDirection[0];
diEffect.lpEnvelope              = NULL;
diEffect.cbTypeSpecificParams    = sizeof(DICONSTANTFORCE);
diEffect.lpvTypeSpecificParams   = &diConstantForce;

hr = g_lpdid->CreateEffect(GUID_ConstantForce,
                           &d iEffect,
                           &lpdiEffect,
                           NULL);

In the method call, the first parameter identifies the supported effect with which the created effect is to be associated. The example uses one of the predefined globally unique identifier (GUID)s found in Dinput.h. If you use a predefined GUID, the call fails if the device does not support the effect.

The second parameter sets the parameters as specified in the DIEFFECT structure.

The third parameter receives a pointer to the effect object if the call is successful.

The DIEFF_POLAR flag specifies the type of coordinates used for the direction of the force. (See Effect Direction.) It is combined with DIEFF_OBJECTOFFSETS, which indicates that any buttons or axes used in other members are identified by their offsets within the DIDATAFORMAT structure for the device. The alternative is to use the DIEFF_OBJECTIDS flag, signifying that buttons and axes are identified by the dwType member of the DIDEVICEOBJECTINSTANCE structure returned for the object when it was enumerated with the IDirectInputDevice8::EnumObjects method.

For more information about the members of the DIEFFECT structure, see Effect Direction.


Downloading and Unloading Effects

Before an effect can be played, it must be downloaded to the device. Downloading an effect means telling the driver to prepare the effect for playback. It is entirely up to the driver to determine how this is done. Generally, the driver places the parameters of the effect in hardware memory to minimize the subsequent transfer of data between the device and the system. The consequent reduction in latency is particularly important for conditions and for effects played in response to a trigger, such as a fire button. Ideally the device does not have to communicate with the system at all in order to respond to axis movements and button presses.

Downloading is done automatically when you create an effect, provided the device is not full and is acquired at the exclusive cooperative level. By default, it is also done when you start the effect or change its parameters.

If you specify the DIEP_NODOWNLOAD flag when changing parameters, you must subsequently use the IDirectInputEffect::Download method to download or update the effect.

When the device is unacquired-for example, when it has been acquired with the exclusive foreground cooperative level and the application moves to the background-effects are unloaded and must be downloaded again when the application regains the foreground. This is done automatically when you call the IDirectInputEffect::Start method, but you can choose to download all effects immediately on reacquiring the device. You always have to download effects associated with a trigger button, since the IDirectInputEffect::Start method is not normally called for such effects.

If your application gets the DIERR_DEVICEFULL error when downloading an effect, you must make room for the new effect by unloading an old one. You can remove an effect from the device by calling the IDirectInputEffect::Unload method. You can also remove all effects by resetting the device through a call to the IDirectInputDevice8::SendForceFeedbackCommand method.


Effect Direction

Directions can be defined for one or more axes. As with the mouse and joystick, the x-axis increases from left to right, and the y-axis increases from far to near.

The direction of an effect is the direction from which it comes. An effect with a direction along the negative y-axis tends to push the stick along the positive y-axis (toward the user). If the user must push the stick toward the left to counteract an effect, the effect has a left direction; that is, it lies on the negative x-axis.

Direction can be expressed in polar, spherical, or Cartesian coordinates.

Polar coordinates are expressed as a single angle, in hundredths of a degree clockwise from whatever zero-point, or true north, has been established for the effect. Normally this is the negative y-axis; that is, away from the user. Thus an effect with a polar coordinate of 9,000 has a direction of east, or to the user's right, and the user must exert force to the right to counteract it.

Spherical coordinates are also in hundredths of a degree but can contain two or more angles For each angle, the direction is rotated in the positive direction of the next axis. For a 3D device, the first angle would normally be rotated from the positive x-axis toward the positive y-axis (clockwise from east), and the second angle would be rotated toward the positive z-axis (down). Thus a force with a direction of (0, 0) would be to the user's right and parallel to the tabletop. A direction of 27,000 for the first angle and 4,500 for the second would be directly away from the user (270 degrees clockwise from east) and angling toward the floor (45 degrees downward from the tabletop); to counteract a force with this direction, the user would have to push forward and down.

Cartesian coordinates are similar to 3D vectors. If you draw a straight line on graph paper with an origin of (0, 0) at the center of the page, the direction of the line can be defined by the coordinates of any intersection that it crosses, regardless of the distance from the origin. A direction of (1, - 2) and a direction of (5, - 10) are exactly the same.

Note The coordinates used in creating force-feedback effects define only direction, not magnitude or distance.

When an effect is created or modified, the cAxes, rgdwAxes, and rglDirection members of the DIEFFECT structure are used to specify the direction of the force.

The cAxes member specifies the number of axes involved in the effect. This will also be the number of elements in each of the arrays pointed to by the next two members.

The array pointed to by rgdwAxes identifies the axes to which the effects will be applied. If the DIEFF_OBJECTOFFSETS flag has been set, the axes are identified by the offsets within the data format structure. These offsets are most readily identified by using the DIJOFS_* defines. (For a list of these values, see Joystick Device Constants.)

Finally, the rglDirection member specifies the direction of the force.

Note The cAxes and rgdwAxes members cannot be modified once they have been set. An effect always has the same axis list.

Regardless of whether you are using Cartesian, polar, or spherical coordinates, you must provide exactly as many elements in rglDirection as there are axes in the array pointed to by rgdwAxes.

In the polar coordinate system, north (0 degrees) lies along the vector (0, - 1), where the elements of the vector correspond to the elements in the axis list pointed to by rgdwAxes. Normally those axes are x and y, so north is directly along the negative y-axis; that is, away from the user. The last element of rglDirection must be 0.

In the example in Creating an Effect, the direction of a two-dimensional force is defined in polar coordinates. The force has a south direction - it comes from the direction of the user, so the user has to pull the stick to counteract it. The direction is 180 degrees clockwise from north, and can be assigned as follows:

LONG  lDirection[2] = { 18000, 0 };

For greater clarity, the assignment could also be expressed this way:

LONG  lDirection[2] = { 180 * DI_DEGREES, 0 };

For spherical coordinates, presuming that you are working with a three-axis device, the same direction is assigned as follows:

LONG  lDirection[3] = { 90 * DI_DEGREES, 0, 0 }

The first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1); the second angle is measured in hundredths of a degree toward (0, 0, 1). The elements of the vector notation again correspond to elements in the array pointed to by the rgdwAxes member. Assume that the elements of this array represent the x, y, and z axes, in that order. The point of origin is at x = 1 and y = 0; that is, to the user's right. The direction of rotation is toward the positive y-axis (0, 1); that is, toward the user, or clockwise. The force in the example is 90 degrees clockwise from the right; that is, south. Because the second element of lDirection is 0, there is no rotation on the third axis.

How do you accomplish the same thing with Cartesian coordinates? Presuming that you have used the DIEFF_CARTESIAN flag in the dwFlags member, you would specify the direction like this:

LONG  lDirection[2] = { 0, 1 };

Here again, the elements of the array correspond to the axes listed in the array pointed to by rgdwAxes. The example sets the x-axis to 0 and the y-axis to 1; that is, the direction lies directly along the positive y-axis, or to the south.

The theory of effect directions can be difficult to grasp, but the practice is fairly straightforward.

Examples of Setting Effect Direction

Single-Axis Effects

Setting up the direction for a single-axis effect is easy because there is nothing to specify. Put the DIEFF_CARTESIAN flag in the dwFlags member of the DIEFFECT structure and set rglDirection to point to a single LONG containing the value 0.

The following code example sets up the direction and axis parameters for an x-axis effect:

DIEFFECT eff;
LONG     lZero  = 0;                       // No direction
DWORD    dwAxis = DIJOFS_X;                // X-axis effect

ZeroMemory(&eff, sizeof(eff));
eff.cAxes        = 1;                                     // One axis
eff.dwFlags      = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; // Flags
eff.rglDirection = &lZero;                                // Direction
eff.rgdwAxes     = &dwAxis;                         // Axis for effect

Two-Axis Effects with Polar Coordinates

Setting up the direction for a polar two-axis effect is only a little more complicated. Set the DIEFF_POLAR flag in dwFlags and set rglDirection to point to an array of two LONGs. The first element in this array is the direction from which you want the effect to come. The second element in the array must be 0.

The following example sets up the direction and axis parameters for a two-axis effect coming from the east:

DIEFFECT eff;
LONG     rglDirection[2] = { 90 * DI_DEGREES, 0 };
DWORD    rgdwAxes[2]     = { DIJOFS_X, DIJOFS_Y };   // X- and y-axis

ZeroMemory(&eff, sizeof(eff));
eff.cAxes        = 2;                                  // Two axes
eff.dwFlags      = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;  // Flags
eff.rglDirection = rglDirection;                       // Direction
eff.rgdwAxes     = rgdwAxes;                     // Axis for effect

Two-Axis Effects with Cartesian Coordinates

Setting up the direction for a Cartesian two-axis effect is a bit trickier. Set the DIEFF_CARTESIAN flag in dwFlags, and again set rglDirection to point to an array of two LONGs. This time the first element in the array is the x-coordinate of the direction vector, and the second is the y-coordinate.

The following code example sets up the direction and axis parameters for a two-axis effect coming from the east:

DIEFFECT eff;
LONG     rglDirection[2] = { 1, 0 };            // Positive x = east
DWORD    rgdwAxes[2]     = { DIJOFS_X, DIJOFS_Y };  // X- and y-axis

ZeroMemory(&eff, sizeof(eff));
eff.cAxes = 2;                                       // Two axes
eff.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; // Flags
eff.rglDirection = rglDirection;                     // Direction
eff.rgdwAxes = rgdwAxes;                       // Axis for effect


Effect Enumeration

The IDirectInputDevice8::EnumEffects method returns information about the support offered by the device for various kinds of effects.

It is important to distinguish between supported effects and created effects, or effect objects. A supported effect is a basic type which a device is capable of playing, such as a constant force. However, a constant force by itself has no properties such as magnitude, direction, duration, attack, or fade. These properties are set when you create a specific effect object in your application by shaping the raw effect type with an envelope or setting the values of a DIEFFECT structure. A supported effect can be represented by many effect objects, each with different parameters - for example, several constant forces, each with different duration, magnitude, and direction.

For information about enumerating created effects, see Effect Object Enumeration.

Like other DirectInput enumerations, the IDirectInputDevice8::EnumEffects method requires a callback function. This is documented with the placeholder name DIEnumEffectsCallback, but you can use a different name if you prefer. This function is called for each effect enumerated. Within the function you can obtain the globally unique identifier (GUID) for each effect, get information about the extent of hardware support, and create one or more effect objects whose methods you can use to manipulate the effect.

The following code example sets the enumeration in motion. Assume that g_lpdid is an initialized pointer to the IDirectInputDevice8 Interface interface of the device.

HRESULT hr = g_lpdid->EnumEffects(&DIEnumEffectsCallback,
        g_lpdid, DIEFT_ALL);

A skeletal callback is shown in the following code. The pvRef parameter of the callback could be any 32-bit value, but in this case it is a pointer to the device interface (the global g_lpdid in the previous example), which is used for getting information about effects supported by the device and for creating effect objects.

BOOL CALLBACK DIEnumEffectsCallback(LPCDIEffectInfo pdei,
                                LPVOID pvRef)
{
    HRESULT              hr;
    LPDIRECTINPUTDEVICE8 lpdid = (LPDIRECTINPUTDEVICE8)pvRef;
// Pointer to calling device
    LPDIRECTINPUTEFFECT  lpdiEffect;      // Pointer to created effect
    DIEFFECT             diEffect;        // Params for created effect
    DICONSTANTFORCE      diConstantForce; // Type-specific parameters

    if (DIEFT_GETTYPE(pdei->dwEffType) == DIEFT_CONSTANTFORCE)
    {
       /* Here you can extract information about support for the
          effect type (from pdei), and tailor your effects
          accordingly. For example, the device might not support
          envelopes for this type of effect. */
       .
       .
       .
       // Create one or more constant force effects.
       // For each, you have to initialize a DICONSTANTFORCE
       // and a DIEFFECT structure.
       .
       .
       .
        hr = lpdid->CreateEffect(pdei->guid,
                                &diEffect,
                                &lpdiEffect,
                                NULL);
       .
       .
       .
    }
    // And so on for other types of effect
   .
   .
   .

    return DIENUM_CONTINUE;
    }  // End of callback

For a detailed example of creating an effect, and for more information about how to initialize an effect, see Creating an Effect.


Effect Object Enumeration

When you need to examine or manipulate all the effects you have created, you can use the IDirectInputDevice8::EnumCreatedEffectObjects method. As no flags are currently defined for this method, you cannot restrict the enumeration to particular kinds of effects; all effects will be enumerated.

Note This method enumerates created effects, not effects supported by a device. For more information about the distinction between the two, see Effect Enumeration.

Like other DirectInput enumerations, the IDirectInputDevice8::EnumCreatedEffectObjects method requires a callback function. This standard callback is documented with the placeholder name DIEnumCreatedEffectObjectsCallback, but you can use a different name. The function is called for each effect enumerated. Within the function, you can perform any processing you want. However, it is not safe to create a new effect while enumeration is going on.

The following is a skeletal example of the callback function. The pvRef parameter of the callback can be any 32-bit value; in this case, it is a pointer to the IDirectInputDevice8 Interface interface that is performing the enumeration.

HRESULT  hr;

BOOL CALLBACK DIEnumCreatedEffectObjectsCallback(
                             LPDIRECTINPUTEFFECT peff, LPVOID pvRef);
{
    LPDIRECTINPUTDEVICE pdid = (IDirectInputDevice*)pvRef;
                                        // Pointer to calling device
    DIEFFECT            diEffect;      // Params for created effect

    diEffect.dwSize = sizeof(DIEffectInfo);
    peff->GetParameters(&diEffect, DIEP_ALLPARAMS);
    // Check or set parameters, or do anything else.
    .
    .
    .
    }  // End of callback

Here's the call that sets the enumeration in motion, passing in the DirectInputDevice pointer lpdid:

hr = lpdid->EnumCreatedEffectObjects(
         &DIEnumCreatedEffectObjectsCallback,
         &lpdid, 0);


Effect Playback

There are two principal ways to start playback of an effect: manually by a call to the IDirectInputEffect::Start method, or automatically in response to a button press.

Passing INFINITE in the dwIterations parameter of the IDirectInputEffect::Start method has the effect of playing the effect repeatedly, with the envelope being applied each time. If you want to repeat an effect without repeating the envelope - for example, to begin with a strong kick, then settle down to a steady throb - set dwIterations to 1, and set the dwDuration member of the DIEFFECT structure to INFINITE. (This is the structure passed to the IDirectInputDevice8::CreateEffect method.)

Note Some devices do not support multiple iterations of an effect, and they accept only the value 1 in the dwIterations parameter to the IDirectInputEffect::Start method. Always check the return value from IDirectInputEffect::Start to be sure the effect played successfully.

To associate an effect with a button press, set the dwTriggerButton member of the DIEFFECT structure. Also set the dwTriggerRepeatInterval member to the desired delay between playbacks when the button is held down. This is the interval, in microseconds, between the end of one playback and the start of the next.

Note On some devices, multiple effects cannot be triggered by the same button. If you associate more than one effect with a button, the last effect downloaded is the one triggered. Also, trigger repeat interval might not be supported.

To dissociate an effect from its trigger button, either call the IDirectInputEffect::Unload method or set the parameters for the effect with dwTriggerButton set to DIEB_NOTRIGGER.

Triggered effects, like all others, are lost when the application loses access to the device. To make them active again, download them as soon as the application reacquires the device. See Downloading and Unloading Effects. This step is not necessary for effects not associated with a trigger, because they are automatically downloaded if necessary whenever the IDirectInputEffect::Start method is called.

If an effect has a finite duration and is started by a call to the IDirectInputEffect::Start method, it stops playing when the time has elapsed. If its duration was set to INFINITE, playback ends only when the IDirectInputEffect::Stop method is called. An effect associated with a trigger button starts when the button is pressed and stops when the button is released or the duration has elapsed, whichever comes sooner.


Envelopes and Offsets

You can modify the basic magnitude of some effects by applying an envelope and an offset. For an overview, see Basic Concepts of Force Feedback.

To apply an envelope when creating or modifying an effect, initialize a DIENVELOPE structure and put a pointer to it in the lpEnvelope member of the DIEFFECT structure.

The device driver determines which effects support envelopes. Typically, you can apply an envelope to a constant force, a ramp force, or a periodic effect, but not to a condition. To determine whether a particular effect supports an envelope, call the IDirectInputDevice8::GetEffectInfo method and check for the DIEP_ENVELOPE flag in the dwStaticParams member of the DIEffectInfo structure.

To apply an offset, set the lOffset member of the DIPERIODIC or DICONDITION structure pointed to by the lpvTypeSpecificParams member of the DIEFFECT structure. For periodic effects, the absolute value of the offset plus the magnitude of the effect must not exceed DI_FFNOMINALMAX.

You cannot apply an offset to a constant force or ramp force. In these cases, you can achieve the same effect by altering the magnitude.


Force-Feedback State

The IDirectInputDevice8::SendForceFeedbackCommand method enables you to turn off the device's actuators (effectively causing it to ignore any effects that are being played), pause, stop, or continue playback of effects, and reset the device so that all downloaded effects are removed.

To retrieve the current force-feedback state, use the IDirectInputDevice8::GetForceFeedbackState method. This method returns information about whether the actuators are active, whether playback is paused, and whether the device has been reset. It also retrieves information about various switches and whether the device is currently powered.


Gain

You might want to scale the force of your effects according to the force exerted by different devices. For example, if an application's effects feel right on a device that puts out a maximum force of n newtons on a given axis, you might want to adjust the gain for a device that puts out more force. (You cannot use the gain to increase the maximum force of the axis, so you should set the basic effect magnitudes to values suitable for devices that put out less force.)

Gain can also be used to decrease the magnitude of a hardware-defined effect.

The actual force generated by a device object such as an axis or button is returned in the dwFFMaxForce member of the DIDEVICEOBJECTINSTANCE structure when objects are enumerated. (See Device Object Enumeration.)

You can set the gain for the entire device by using the IDirectInputDevice8::SetProperty method.

You must set the gain for individual effects when creating them by putting a value in the dwGain member of the DIEFFECT structure. (If dwGain is 0, the effect will not be felt.) You can change this value later by using IDirectInputEffect::SetParameters, passing DIEP_GAIN in the dwFlags parameter.

The purpose of setting the device gain is to allow your application to have control over the strength of all effects all at once. For example, you might have a slider control in your application to enable the user to specify how strong the force-feedback effects should be, such as the master volume control on a sound mixer. When the device gain is set, your application does not need to adjust the gain of each individual effect to suit the user's preferences.

A gain value can be in the range from 0 through 10,000, where 10,000 indicates that magnitudes are not to be scaled, 7,500 means that forces are to be scaled to 75 percent of their nominal magnitudes, and so on.


Information About a Supported Effect

The IDirectInputDevice8::GetEffectInfo method can be used to retrieve information about the device's support for an effect whose globally unique identifier (GUID) is known. It retrieves the same information that is returned in the DIEffectInfo structure during enumeration. For more information, see Effect Enumeration.

The following code fetches information about an effect whose GUID is stored in the EffectGuid variable, and determines whether the direction of the effect can be changed without stopping and restarting it:

DIEFFECTINFO diEffectInfo;
diEffectInfo.dwSize = sizeof(DIEFFECTINFO);
g_lpdid->GetEffectInfo(&diEffectInfo, EffectGuid);
if (diEffectInfo.dwDynamicParams & DIEP_DIRECTION)
{
  // Can reset parameter dynamically
}


Loading Effects from a File

To load effects, call the IDirectInputDevice8::EnumEffectsInFile method. By default, the enumeration is limited to the standard Microsoft DirectInput effects, but you can enumerate other effects by setting the DIFEF_INCLUDENONSTANDARD flag. By setting the DIFEF_MODIFYIFNEEDED flag, you can also instruct DirectInput to modify the parameters of effects, if necessary, so that they work on the device. (For example, an effect authored for two axes can be made to work on a single-axis steering wheel.)

In the following code example, the first three standard effects are loaded from a file and created as DirectInputEffect objects.

// g_lpdid is a valid IDirectInputDevice8 pointer to a
// force feedback device.
// The array of effect pointers is declared globally.
LPDIRECTINPUTEFFECT pEff[3];
.
.
.
g_lpdid->EnumEffectsInFile("FEdit1.ffe",
                            EnumEffectsInFileProc,
                            NULL,
                            DIFEF_MODIFYIFNEEDED);
.
.
.

The following callback function is called once for each effect in the file or until it returns DIENUM_STOP. Note that because the DIFEF_MODIFYIFNEEDED flag was passed, the effect parameters may have been modified in lpdife->lpDiEffect. The callback creates the effect with these modified parameters.

BOOL CALLBACK EnumEffectsInFileProc(LPCDIFILEEFFECT lpdife,
        LPVOID pvRef)

{
    HRESULT     hr;
    static int  i;

    hr = g_lpdid->CreateEffect(lpdife->GuidEffect,
                               lpdife->lpDiEffect,
                               &pEff[i],
                               NULL);
    if (FAILED(hr))
    {
        // Error handling
    }
    if (++i > 2) return DIENUM_STOP;
    else return DIENUM_CONTINUE;
}


Effect Types

This section contains information about force-feedback effects.

  • Conditions
  • Constant Forces
  • Custom Forces
  • Device-Specific Effects
  • Periodic Effects
  • Ramp Forces


Conditions

Conditions are forces applied in response to current sensor values within the device. In other words, conditions require information about device motion, such as position or velocity of a joystick handle. In general, conditions are not associated with individual events during a game or other application. They represent ambient phenomena, such as the stiffness or looseness of a flight stick, or the tendency of a steering wheel to return to a straight-ahead position. A condition does not have a predefined magnitude. The magnitude is scaled in proportion to the movement or position of the input object.

DirectInput defines the following types of condition effects:

  • Friction. The force is applied when the axis is moved and depends on the defined friction coefficient.
  • Damper. The force increases in proportion to the velocity with which the user moves the axis.
  • Inertia. The force increases in proportion to the acceleration of the axis.
  • Spring. The force increases in proportion to the distance of the axis from a defined neutral point.

Most hardware devices do not support the application of envelopes to conditions. Conditions have the following type-specific parameters:

Offset | The offset from the zero reading of the appropriate sensor value at which the condition begins to be applied. For a spring effect, the neutral point - that is, the point along the axis at which the spring would be considered at rest - would be defined by the offset for the condition. For a damper, the offset would define the greatest velocity value for which damping force is zero. Offset is not normally used for inertia or friction effects.
Coefficient | A multiplier that scales the effect. For some devices, you can set separate coefficients for the positive and negative direction along the axis associated with the condition. For example, a flight stick controlling a damaged aircraft might move more easily to the right than to the left.
Saturation | In force feedback, saturation is an expression of the maximum possible force for an effect. For example, suppose a flight stick has a spring condition on the x-axis. The offset is 0 and the coefficient is 10,000, so the maximum force is normally exerted when the stick is furthest from the center. But if you define a positive and negative saturation of 5,000, the force does not increase after the stick has been moved halfway to the right or left. Not all devices support saturation.
Deadband | The deadband is a zone around the offset of an axis at which the condition is not active. In the case of a spring that is at rest in the middle of an axis, the deadband enlarges this area of rest. Not all devices support deadband.

Conditions can have duration, although in most cases you would probably want to set the duration to infinite ( - 1) and stop the effect only in response to some event in the application.

To create a condition, pass one of the following values in the rguid parameter of the IDirectInputDevice8::CreateEffect method:

  • GUID_Spring
  • GUID_Damper
  • GUID_Inertia
  • GUID_Friction

You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEffectInfo structure is equal to DIEFT_CONDITION. In this way, you can use hardware-specific conditions designed by the manufacturer.

The type-specific structure for conditions is DICONDITION. For multiple-axis conditions, you can provide an array of such structures, one for each axis, or a single structure that defines the condition in the specified direction. In either case, you must set the cbTypeSpecificParams member of the DIEFFECT structure to the number of bytes used; that is, to sizeof(DICONDITION) * n, where n is the number of structures provided.

An application should call the IDirectInputDevice8::GetEffectInfo method or the IDirectInputDevice8::EnumEffects method and examine the dwEffType member of the DIEffectInfo structure to determine whether both a positive and a negative coefficient and saturation for the effect are supported on the device. If the effect does not return the DIEFT_POSNEGCOEFFICIENTS flag, it ignores the value in the lNegativeCoefficient member, and the value in lPositiveCoefficient is applied to the entire axis. Likewise, if the effect does not return the DIEFT_POSNEGSATURATION flag, it ignores the value in dwNegativeSaturation, and the value in dwPositiveSaturation is used as the negative saturation level. Finally, if the effect does not return the DIEFT_SATURATION flag, it ignores both the dwPositiveSaturationdwNegativeSaturation values, and no saturation is applied.

You should also check DIEffectInfo. dwEffType for the DIEFT_DEADBAND flag, to see if deadband is supported for the condition. If it is not supported, the value in the lDeadBand member of the DICONDITION structure will be ignored.

You can set a coefficient to a negative value, and this has the effect of generating the force in the opposite direction. For example, for a spring effect, it would cause the spring to push away from the offset point rather than pulling toward it.


Constant Forces

A constant force is a force with a defined magnitude and duration.

You can apply an envelope to a constant force to give it shape. For example, suppose you have an effect with a nominal magnitude of 2,000 and a duration of 2 seconds. Then you apply an envelope with the following values:

Parameter | Value
Attack time | 0.5 second
Initial attack level | 5,000
Fade time | 1 second
Fade level | 0

When you play the effect, you get the following:

Elapsed time | Magnitude
0.0 | 5,000
0.1 | 4,400
0.2 | 3,800
0.3 | 3,200
0.4 | 2,600
0.5 | 2,000
(Duration of sustain) | 2,000
1.0: | 2,000
1.1 | 1,800
1.2 | 1,600
1.3 | 1,400
1.4 | 1,200
1.5 | 1,000
1.6 | 800
1.7 | 600
1.8 | 400
1.9 | 200
2.0 | 0

You cannot apply an offset to a constant force.

To create a constant force, pass GUID_ConstantForce to the IDirectInputDevice8::CreateEffect method. You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEffectInfo structure (DIDFT_GETTYPE(dwEffType)) is equal to DIEFT_CONSTANTFORCE. In this way, you can use hardware-specific forces designed by the manufacturer such as a "constant" force that actually varies in magnitude in a seemingly random fashion to simulate turbulence.

A constant force uses a DICONSTANTFORCE structure to define the magnitude. A negative magnitude has the effect of reversing the direction of the force.


Custom Forces

Application writers can create their own effects by creating a custom force. A custom force is an array of constant force values played back by the device.

The type-specific structure for custom waveform effects is DICUSTOMFORCE.

Set the dwSamplePeriod member of the DICUSTOMFORCE structure and the dwSamplePeriod member of the DIEFFECT structure to the same value. This is the time, in milliseconds, for which each element in the array of forces is played.

The custom force is played repeatedly until the time set in the dwDuration member of the DIEFFECT structure has elapsed.


Device-Specific Effects

Hardware drivers can support special effects that do not fit into the categories defined by DirectInput. The type-specific parameters for these effects may be either hard-coded or modifiable by the application.

If type-specific parameters are modifiable, the application developer must obtain a header file declaring the data structure required by the effect.

The hardware vendor must provide a globally unique identifier (GUID) identifying the device-specific effect and might provide a custom structure for the type-specific parameters of the effect. Your application then must initialize a DIEFFECT structure and a type-specific structure, as with any other effect. You then call the IDirectInputDevice8::CreateEffect method, passing the device-specific GUID and a pointer to the DIEFFECT structure.

When you obtain information about a device-specific effect in a DIEffectInfo structure, the low byte of the dwEffType member (DIDFT_GETTYPE(dwEffType)) indicates into which of the predefined DirectInput effect categories (constant force, ramp force, periodic, or condition) the effect falls. If it does not fall into any of the predefined categories, the value is DIEFT_HARDWARE.

If a device-specific effect falls into one of the predefined categories, the lpvTypeSpecificParams member of the DIEFFECT structure must point to the corresponding DICONSTANTFORCE, DIRAMPFORCE, DIPERIODIC, or DICONDITION structure, and the cbTypeSpecificParams member must be equal to the size of that structure.

If (DIDFT_GETTYPE(dwEffType) == DIEFT_HARDWARE), the values of the lpvTypeSpecificParams and cbTypeSpecificParams members depend on whether the effect requires custom type-specific parameters. If it does, these values must refer to the appropriate structure defined in the manufacturer's header file and declared and initialized by your application. If the effect does not require custom parameters-that is, if the dwStaticParams member of the DIEFFECTINFO structure for the hardware effect does not have the DIEP_TYPESPECIFICPARAMS flag-lpvTypeSpecificParams must be NULL and cbTypeSpecificParams must be 0.

DirectInput passes the GUID and the DIEFFECT structure to the device driver for verification. If the GUID is unknown, the device returns DIERR_DEVICENOTREG. If the GUID is known but the type-specific data is incorrect for that effect, the device returns DIERR_INVALIDPARAM.


Periodic Effects

Periodic effects are waveform effects. DirectInput defines the following waveforms.

  • Square.
  • Sine.
  • Cosine.
  • Triangle.
  • SawtoothUp. The waveform drops vertically after it reaches maximum positive force. See Basic Concepts of Force Feedback for an example.
  • SawtoothDown. The waveform rises vertically after it reaches maximum negative force.

An envelope can be applied to periodic effects. See the example in Basic Concepts of Force Feedback.

The phase of a periodic effect is the point along the waveform where the effect begins. Phase is measured in hundredths of a degree, from 0 to 35,999. The following table indicates where selected phase values (in degrees) lie along the various waveforms. Max is the top (+) or bottom ( - ) of the wave, and Mid is the midpoint, where no force is applied in either direction.

Waveform | 0 | 90 | 180 | 270
Square | +Max | +Max | - Max | - Max
Sine | Mid | +Max | Mid | - Max
Triangle | +Max | Mid | - Max | Mid
SawtoothUp | - Max | - Max/2 | Mid | +Max/2 (reaches +Max just before the cycle repeats)
SawtoothDown | +Max | +Max/2 | Mid | - Max/2 (reaches - Max just before the cycle repeats)

A driver may round off a phase value to the nearest supported value. For example, for a sine effect some drivers support only values of 0 and 9,000 (to create a cosine); for other effects, only values of 0 and 18,000 are supported.

  • GUID_Square
  • GUID_Sine
  • GUID_Triangle
  • GUID_SawtoothUp
  • GUID_SawtoothDown

You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEffectInfo structure (DIDFT_GETTYPE(dwEffType)) is equal to DIEFT_PERIODIC. In this way, you can use hardware-specific forces designed by the manufacturer. For example, a hardware device might support a periodic effect that rotates the stick in a small circle.

The type-specific structure for periodic effects is DIPERIODIC.

Do not confuse the period of a periodic effect (DIPERIODIC.dwPeriod) with the sample period (DIEFFECT.dwSamplePeriod). The period is the time that it takes to go through a complete wave cycle. The sample period, as for all effects, is the minimum time between actual adjustments of magnitude.


Ramp Forces

A ramp force is a force with defined starting and ending magnitudes and a finite duration. A ramp force can continue in a single direction, or it can start as a strong push in one direction, weaken, stop, and then strengthen in the opposite direction.

The following illustration shows a ramp force that starts at a magnitude of -5,000 and ends at 5,000:

You can apply an envelope to a ramp force to shape it further. The following diagram shows the effect of applying an envelope, shown in green, to the ramp force in the previous diagram.

Note that during the sustain portion of the envelope, the magnitude of the effect follows the same straight line as before the envelope was applied. For the duration of the attack and fade, the slope of the ramp is modified by the attack and fade levels.

You cannot apply an offset to a ramp force.

To create a ramp force, pass GUID_RampForce to the IDirectInputDevice8::CreateEffect method. You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEffectInfo structure (DIEFT_GetType(dwEffType)) is equal to DIEFT_RAMPFORCE. In this way, you can use hardware-specific ramp forces designed by the manufacturer.

A ramp force uses a DIRAMPFORCE structure to define the starting and ending magnitude of the force, whereas the duration is taken from the DIEFFECT structure. Duration must never be set to INFINITE.


Programming Tips and Tools

This topic covers the following specialized programming tips.

  • Designing for Previous Versions of DirectInput
  • Preventing Response Delays During Debugging
  • Avoiding Duplicate Registry Keys

Designing for Previous Versions of DirectInput

In the DirectInput8Create, IDirectInput8::Initialize, IDirectInputDevice8::Initialize, and IDirectInputEffect::Initialize methods, you are required to pass the DirectInput version number. This parameter specifies which version of DirectX the DirectInput subsystem should emulate.

Applications designed for the latest version of DirectInput should pass the value DIRECTINPUT_VERSION as defined in Dinput.h.

Applications designed to run under previous versions should pass a value corresponding to the version of DirectInput for which they were designed, with the main version number in the high-order byte. For example, an application designed to run on DirectInput 3.0 should pass a value of 0x0300.

If you define DIRECTINPUT_VERSION as 0x0300 before including the Dinput.h header file, the header file generates structure definitions compatible with DirectInput 3.0.

If you do not define DIRECTINPUT_VERSION before including the Dinput.h header file, the header file generates structure definitions compatible with the current version of DirectInput. However, the DirectX 3-compatible structures are available under the same names with "_DX3" appended. For example, the DirectX 3-compatible DIDEVCAPS structure is called DIDEVCAPS_DX3.

You must also use the appropriate versions of the DirectInput and DirectInputDevice interfaces. For versions of DirectX prior to DirectX 7.0, you must use IDirectInput and either IDirectInputDevice or IDirectInputDevice2 (the latter is available for DirectX 5.0 or later.)

Preventing Response Delays During Debugging

When using the keyboard or mouse with DirectInput under Microsoft Windows 2000, you might notice short delays in response when you step through code during a debugging session. This behavior occurs only in debug mode, so it is not seen by your application's end users. However, this behavior can be eliminated in debug mode as well by adding the emulation value to the following registry key.

HKEY_LOCAL_MACHINE
    SOFTWARE
        Microsoft
            DirectInput

Name | Type | Data
Emulation | DWORD | 0x08 (for the keyboard) 0x10 (for the mouse) 0x18 (for both)

You can also switch to use emulation from the DirectX control panel by following these steps.

  1. Open the Windows control panel
  2. Open the DirectX control panel. Note that if you are using Microsoft Windows XP, you might need to click Switch to Classic View to see the DirectX icon.
  3. Select the DirectInput tab.
  4. In the Debug Input Device Emulation section, you can check the Emulate Keyboard and Emulate Mouse boxes.

Without changing how DirectInput returns data, this value invokes an emulation mode that is not susceptible to those delays. These settings are global and affect all DirectInput clients. Performance only improves when using the debug binaries and only for applications that employ foreground exclusive device access. Some features, such as masking the Windows keys, are not available when devices are emulated so emulation is recommended only for debugging.

Note If you are using earlier versions of DirectX, you must do a debug software development kit (SDK) install in order to get the correct debug DLL onto your computer.

Avoiding Duplicate Registry Keys

For every application that uses DirectInput 8.0 or later versions, DirectInput creates a key in the following registry.

HKEY_CURRENT_USER
    SOFTWARE
        Microsoft
            DirectInput

This allows the independent hardware vendors (IHVs) to turn off their own device mapping for certain applications. During debugging, however, each build will generate a new key which contains a time stamp and the file size. To avoid generating multiple keys in the registry, use the binary value, AppIdFlag.

The following table lists the possible values for AppIdFlag.

1 | The time stamp is ignored when generating the key.
2 | The file size is ignored when generating the key.
3 | Both the time stamp and file size are ignored when generating the key.

If AppIdFlag is set to 3, all builds of applications with the same file name will use the same key.

Note The AppIdFlag value should only be set on test computers to avoid the possibility of two applications that ship with the same file name interfering with each other's input control mappings.


DirectInput Tutorials

This section contains five tutorials, each providing step-by-step instructions for implementing basic Microsoft DirectInput functionality in a C or C++ application.

Tutorials

  • Tutorial 1: Using the Keyboard
  • Tutorial 2: Using the Mouse
  • Tutorial 3: Using the Joystick
  • Tutorial 4: Using Force Feedback
  • Tutorial 5: Using Action Mapping

Note These tutorials are written using C++ style function calls. For instructions on writing Microsoft DirectX function calls in a C environment, see Using C to Access COM Objects.


Tutorial 1: Using the Keyboard

To prepare for keyboard input, first create an instance of a DirectInput object. You then use the IDirectInput8::CreateDevice method to create an instance of an IDirectInputDevice8 Interface interface. The IDirectInputDevice8 Interface interface methods are used to manipulate the device, set its behavior, and retrieve data.

This tutorial divides the required tasks into the following steps.

  • Step 1: Creating the DirectInput Object
  • Step 2: Creating the DirectInput Keyboard Device
  • Step 3: Setting the Keyboard Data Format
  • Step 4: Setting the Keyboard Behavior
  • Step 5: Gaining Access to the Keyboard
  • Step 6: Retrieving Data from the Keyboard
  • Step 7: Closing Down the DirectInput System

Adding DirectInput keyboard support to an application is relatively simple, so this tutorial is not based on the complete Keyboard Sample application. All of the tutorial steps are illustrated by code fragments within the text. All related steps for initializing the system are gathered in Tutorial 1 Samples. Another function, Tutorial 1 Samples, is called whenever the system needs to be closed down. Much of the content of these functions are reused in subsequent tutorials.


Step 1: Creating the DirectInput Object

The first step in setting up the DirectInput system is to create a single DirectInput object as overall manager. This is done with a call to the DirectInput8Create function.

// HINSTANCE  g_hinst; // initialized earlier
HRESULT         hr;
LPDIRECTINPUT8  g_lpDI;

hr = DirectInput8Create(g_hinst, DIRECTINPUT_VERSION,
        IID_IDirectInput8, (void**)&g_lpDI, NULL);
if FAILED(hr)
{
        // DirectInput not available; take appropriate action
}

The first parameter for DirectInput8Create is the instance handle to the application or DLL that is creating the object.

The second parameter tells the DirectInput object which version of the DirectInput system should be used. You can design your application to be compatible with earlier versions of DirectInput. For more information, see Programming Tips and Tools.

The third parameter determines which interface is returned. Most applications obtain the most recent version, by passing IID_IDirectInput8.

The fourth parameter is the address of a variable that is initialized with a valid interface pointer if the call succeeds.

The last parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

After creating a single DirectInput object as overall manager, go to Step 2: Creating the DirectInput Keyboard Device.


Step 2: Creating the DirectInput Keyboard Device

After creating the DirectInput object, your application must create the keyboard object - the device - and retrieve a pointer to an IDirectInputDevice8 Interface interface. The device performs most of the keyboard-related tasks, using the methods of the interface.

To do this your application must call the IDirectInput8::CreateDevice method, as shown in Tutorial 1 Samples. IDirectInput8::CreateDevice accepts three parameters.

The first parameter is the globally unique identifier (GUID) for the device being created. Because the system keyboard is used, your application should pass the GUID_SysKeyboard predefined global variable.

The second parameter is the address of a variable that is initialized with the interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

The following example attempts to retrieve a pointer to an IDirectInputDevice8 Interface interface. If this fails, it calls the DI_Term application-defined sample function to deallocate existing DirectInput objects, if any.

Note In all the examples, g_lpdi is the initialized pointer to the DirectInput object.

HRESULT               hr;
LPDIRECTINPUTDEVICE8  g_lpDIDevice

hr = g_lpDI->CreateDevice(GUID_SysKeyboard, &g_lpDIDevice, NULL);
if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After creating the DirectInput keyboard device, go to Step 3: Setting the Keyboard Data Format.


Step 3: Setting the Keyboard Data Format

After retrieving an IDirectInputDevice8 Interface pointer, your application must set the device's data format, as shown in Tutorial 1 Samples. For keyboards, this is a very simple task. Call the IDirectInputDevice8::SetDataFormat method, specifying the data format provided by DirectInput in the c_dfDIKeyboard global variable.

The following example attempts to set the data format. If this fails, it calls the DI_Term sample function to deallocate existing DirectInput objects, if any.

hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard);

if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After setting the keyboard data format, go to Step 4: Setting the Keyboard Behavior.


Step 4: Setting the Keyboard Behavior

Before your application can gain access to the keyboard, it must set the device's behavior using the IDirectInputDevice8::SetCooperativeLevel method, as shown in Tutorial 1 Samples. This method accepts the handle to the window to be associated with the device and a combination of flags that determine the cooperative level. In this case the application is requesting foreground, nonexclusive access.

The following example attempts to set the device's cooperative level. If this fails, it calls the DI_Term application-defined sample function to deallocate existing DirectInput objects, if any.

// Set the cooperative level

hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
        DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);

 if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After setting the keyboard behavior, go to Step 5: Gaining Access to the Keyboard.


Step 5: Gaining Access to the Keyboard

After your application sets the keyboard's behavior, it can acquire access to the device by calling the IDirectInputDevice8 Interface method. The application must acquire the device before retrieving data from it. The IDirectInputDevice8 Interface method accepts no parameters.

The following line of sample code acquires the keyboard device that was created in Step 2: Creating the DirectInput Keyboard Device.

if (g_lpDIDevice) g_lpDIDevice->Acquire();

Now that your application has acquired access to the keyboard, go to Step 6: Retrieving Data from the Keyboard.


Step 6: Retrieving Data from the Keyboard

After a device is acquired, your application can start retrieving data from it. The simplest way to do this is to call the IDirectInputDevice8::GetDeviceState method, which takes a snapshot of the device's state at the time of the call.

The IDirectInputDevice8::GetDeviceState method accepts two parameters: the size of a buffer to be filled with device state data, and a pointer to that buffer. For keyboards, always declare a buffer of 256 unsigned bytes.

The following sample attempts to retrieve the state of the keyboard. If this fails, it calls an application-defined sample function to deallocate existing DirectInput objects, if any. For more information, see Tutorial 1 Samples.

After retrieving the keyboard's current state, your application can respond to specific keys that were pressed down at the time of the call. Each element in the buffer represents a key. If an element's high bit is 1, the key was down at the moment of the call; otherwise, the key was up. To check the state of a given key, use the DirectInput Keyboard Device to index the buffer for a given key.

The following skeleton function, called from the main loop of a hypothetical spaceship game, uses the IDirectInputDevice8::GetDeviceState method to poll the keyboard. It then checks to see if the LEFT ARROW, RIGHT ARROW, UP ARROW or DOWN ARROW keys were pressed when the device state was retrieved. This is accomplished with the KEYDOWN macro defined in the body of the function. The macro accepts a buffer's variable name and an index value, and then checks the byte at the specified index to see if the high bit is set and returns TRUE if it is.

void WINAPI ProcessKBInput()
{
    #define KEYDOWN(name, key) (name[key] & 0x80)

    char     buffer[256];
    HRESULT  hr;
    hr = g_lpDIDevice->GetDeviceState(sizeof(buffer),(LPVOID)&buffer);
    if FAILED(hr)
    {
        // If it failed, the device has probably been lost.
        // Check for (hr == DIERR_INPUTLOST)
        // and attempt to reacquire it here.
        return;
    }

    // Turn the spaceship right or left
    if (KEYDOWN(buffer, DIK_RIGHT));
        // Turn right.
    else if(KEYDOWN(buffer, DIK_LEFT));
        // Turn left.

    // Thrust or stop the spaceship
    if (KEYDOWN(buffer, DIK_UP)) ;
        // Move the spaceship forward.
    else if (KEYDOWN(buffer, DIK_DOWN));
        // Stop the spaceship.
}

Now that your application can retrieve data from the keyboard, go to Step 7: Closing Down the DirectInput System.


Step 7: Closing Down the DirectInput System

When an application is about to close, it should destroy all DirectInput objects. This is a three-step process.

  • Release access to all DirectInput devices (IDirectInputDevice8 Interface).
  • Release all DirectInput devices (IDirectInputDevice8::Release ).
  • Release the DirectInput object (IDirectInput8::Release ).

For a sample function that closes down the DirectInput system, see Tutorial 1 Samples.


Tutorial 1 Samples

Sample Function 1: DI_Init

This application-defined sample function creates a Microsoft DirectInput object, initializes it, and retrieves the necessary interface pointers, assigning them to global variables. When initialization is complete, it acquires the device.

If any part of the initialization fails, this function calls the DI_Term application-defined sample function to deallocate DirectInput objects and interface pointers in preparation for terminating the program. For more information, see Sample Function 2: DI_Term.

In addition to creating the DirectInput object, the DI_Init function performs the tasks discussed in the following tutorial steps.

  • Step 2: Creating the DirectInput Keyboard Device
  • Step 3: Setting the Keyboard Data Format
  • Step 4: Setting the Keyboard Behavior
  • Step 5: Gaining Access to the Keyboard

The following is the DI_Init function.

/* The following variables are presumed to be initialized:
HINSTANCE             g_hinst;    // application instance
HWND                  g_hwndMain; // application window
*/

LPDIRECTINPUT8        g_lpDI;
LPDIRECTINPUTDEVICE8  g_lpDIDevice;

BOOL WINAPI DI_Init()
{
    HRESULT hr;

    // Create the DirectInput object.
    hr = DirectInput8Create(g_hinst, DIRECTINPUT_VERSION,
                            IID_IDirectInput8, (void**)&g_lpDI, NULL);

    if FAILED(hr) return FALSE;

    // Retrieve a pointer to an IDirectInputDevice8 interface
    hr = g_lpDI->CreateDevice(GUID_SysKeyboard, &g_lpDIDevice, NULL);

    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Now that you have an IDirectInputDevice8 interface, get
    // it ready to use.

    // Set the data format using the predefined keyboard data
    // format provided by the DirectInput object for keyboards.

    hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard);

    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Set the cooperative level
    hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                             DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Get access to the input device.
    hr = g_lpDIDevice->Acquire();
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    return TRUE;

Sample Function 2: DI_Term

This application-defined sample function deallocates existing DirectInput interface pointers in preparation for program shutdown or in the event of a failure to properly initialize a device.

/* The following variables are presumed initialized:
LPDIRECTINPUT8        g_lpDI;
LPDIRECTINPUTDEVICE8  g_lpDIDevice;
*/

void WINAPI DI_Term()
{
    if (g_lpDI)
    {
        if (g_lpDIDevice)
        {
        // Always unacquire device before calling Release().
            g_lpDIDevice->Unacquire();
            g_lpDIDevice->Release();
            g_lpDIDevice = NULL;
        }
        g_lpDI->Release();
        g_lpDI = NULL;
    }
}

For additional DirectInput tutorials, see DirectInput Tutorials.


Tutorial 2: Using the Mouse

This tutorial guides you through the process of setting up a mouse device and retrieving buffered input data.

To prepare for mouse input, you first create an instance of a Microsoft DirectInput object. Then you use the IDirectInput8::CreateDevice method to create an instance of an IDirectInputDevice8 Interface interface. The IDirectInputDevice8 interface methods are used to manipulate the device, set its behavior, and retrieve data.

The first step of setting up the DirectInput system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard.

This tutorial divides the required tasks into the following steps.

  • Step 1: Creating the DirectInput Mouse Device
  • Step 2: Setting the Mouse Data Format
  • Step 3: Setting the Mouse Behavior
  • Step 4: Preparing for Buffered Input from the Mouse
  • Step 5: Managing Access to the Mouse
  • Step 6: Retrieving Buffered Data from the Mouse

Note When an application acquires the mouse at the exclusive cooperative level, Microsoft Windows does not show a pointer on the screen. For this, your application needs a simple sprite engine. The Scrawl sample application uses the Microsoft Win32 function DrawIcon to display a crosshair cursor.


Step 1: Creating the DirectInput Mouse Device

After creating the DirectInput object, your application should retrieve a pointer to an IDirectInputDevice8 Interface interface, which is used to perform most mouse-related tasks. To do this, call the IDirectInput8::CreateDevice method.

The first parameter of IDirectInput8::CreateDevice is the globally unique identifier (GUID) for the device your application is creating. In this case, because the system mouse is used, your application should pass the predefined global variable GUID_SysMouse.

The second parameter is the address of a variable that is initialized with a valid IDirectInputDevice8 Interface interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown for use in COM aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

The following sample code attempts to retrieve a pointer to an IDirectInputDevice8 Interface interface. If the call fails, FALSE is returned. It is assumed that g_pDI is a valid pointer to IDirectInput8 Interface.

LPDIRECTINPUTDEVICE8 g_pMouse;
HRESULT             hr;

hr = g_pDI->CreateDevice(GUID_SysMouse, &g_pMouse, NULL);

if (FAILED(hr)) {
    return FALSE;
}

After creating the DirectInput mouse device, go to Step 2: Setting the Mouse Data Format.


Step 2: Setting the Mouse Data Format

After retrieving an IDirectInputDevice8 Interface pointer, your application must set the device's data format. For mouse devices, this is a very simple task. Call the IDirectInputDevice8::SetDataFormat method, specifying the data format provided for your convenience by DirectInput in the c_dfDIMouse global variable.

The following code fragment attempts to set the device's data format. If the call fails, FALSE is returned.

hr = g_pMouse->SetDataFormat(&c_dfDIMouse);

if (FAILED(hr)) {
    return FALSE;
}

After setting the mouse data format, go to Step 3: Setting the Mouse Behavior.


Step 3: Setting the Mouse Behavior

Before it can gain access to the mouse, your application must set the mouse device's behavior using the IDirectInputDevice8::SetCooperativeLevel method. This method accepts the handle to the window to be associated with the device. In Scrawl, the DISCL_EXCLUSIVE flag is included to ensure that this application is the only one that can have exclusive access to the device. This flag is combined with DISCL_FOREGROUND because Scrawl should not allow data input when another application is in the foreground.

The following code sample attempts to set the device's cooperative level. If this attempt fails, FALSE is returned. It is assumed that hWnd is a valid window handle.

hr = g_pMouse->SetCooperativeLevel(hWnd,
               DISCL_EXCLUSIVE | DISCL_FOREGROUND);

if (FAILED(hr)) {
    return FALSE;
}

After setting the mouse behavior, go to Step 4: Preparing for Buffered Input from the Mouse.


Step 4: Preparing for Buffered Input from the Mouse

The Scrawl application demonstrates how to use event notification to find out about mouse activity, and how to read buffered input from the mouse. Both of these techniques require some setup. You can perform these steps at any time after creating the mouse device and before acquiring it.

First, create an event and associate it with the mouse device. You are instructing DirectInput to notify the mouse device object whenever a hardware interrupt indicates that new data is available.

This is how it is done in Scrawl, where g_hevtMouse is a global HANDLE.

g_hMouseEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

if (g_hMouseEvent == NULL) {
    return FALSE;
}

hr = g_pMouse->SetEventNotification(g_hMouseEvent);

if (FAILED(hr)) {
    return FALSE;
}

Now set the buffer size so that DirectInput can store any input data until you are ready to view it. Note that by default the buffer size is zero, so this step is essential if you want to use buffered data.

It is not necessary to used buffered data with event notification. If you prefer, you can retrieve immediate data when an event is signaled.

To set the buffer size, initialize a DIPROPDWORD structure with information about itself and about the property you want to set. Most of the values are boilerplate. The key value is the last one, dwData, which is initialized with the number of items you want the buffer to hold.

#define SAMPLE_BUFFER_SIZE  16

DIPROPDWORD dipdw;
    // the header
    dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
    dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    dipdw.diph.dwObj        = 0;
    dipdw.diph.dwHow        = DIPH_DEVICE;
    // the data
    dipdw.dwData            = SAMPLE_BUFFER_SIZE;

You then pass the address of the header (the DIPROPHEADER structure within the DIPROPDWORD structure ), along with the identifier of the property you want to change, to the IDirectInputDevice8::SetProperty method, as follows:

hr = g_pMouse->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);

if (FAILED(hr)) {
    return FALSE;
}

The setup is now complete, and you are ready to acquire the mouse and start collecting data.

After preparing your application for buffered input from the mouse, go to Step 5: Managing Access to the Mouse.


Step 5: Managing Access to the Mouse

DirectInput provides the IDirectInputDevice8 Interface and IDirectInputDevice8 Interface methods to manage device access. Your application must call the IDirectInputDevice8 Interface method to gain access to the device before requesting mouse information with the IDirectInputDevice8::GetDeviceState and IDirectInputDevice8::GetDeviceData methods.

Most of the time your application has the device in an acquired state. However, if you have only foreground access, the mouse is automatically unacquired whenever your application moves to the background. You are responsible for reacquiring it when you get the focus back again. This can be done in response to a WM_ACTIVATE message.

Scrawl handles this message by setting a global variable, g_bActive, according to whether the application is gaining or losing the focus. It then calls a helper function, SetAcquire, which acquires the mouse if g_bActive is TRUE and unacquires it otherwise.

case WM_ACTIVATE:
    if (WA_INACTIVE == wParam)
        g_bActive = FALSE;
    else
        g_bActive = TRUE;

    // Set exclusive mode access to the mouse based on active state
    SetAcquire();
    return 0;

If you have exclusive access, your application might need to unacquire the mouse to enable the user to interact with Windows - for example, to access a menu or a dialog box. In Scrawl this can happen when the user opens the system menu with ALT+SPACEBAR.

The Scrawl window procedure has a handler for WM_ENTERMENULOOP that responds by setting the global variable g_bActive to FALSE and calling the SetAcquire function. This handler enables Windows to have the mouse and display its own cursor.

When the user is done using a menu, Windows sends the application a WM_EXITSIZEMOVE message. In this case, the Scrawl window process sets g_bActive appropriately and calls SetAcquire.

Scrawl also unacquires the mouse in response to a right-button click, which displays a shortcut menu. Although the mouse would get unacquired later, in the WM_ENTERMENULOOP handler, it is unacquired here first so that the position of the Windows cursor can be set before the menu appears.

Finally, Scrawl tries to reacquire the mouse if it receives a DIERR_INPUTLOST error after an attempt to retrieve data. This is in case the device has been unacquired by some mechanism not covered elsewhere; for instance, if the user has pressed CTRL+ALT+DEL.

In summary, your application needs to acquire the mouse before it can get data from it. This needs to be done only once, as long as nothing happens to force your application to surrender access to it. In exclusive mode, you are responsible for giving up control of the mouse when Windows needs it. You are also responsible for reacquiring the mouse whenever your program needs access to it after losing it to Windows or another application.

Once your application can manage access to the mouse, go to Step 6: Retrieving Buffered Data from the Mouse.


Step 6: Retrieving Buffered Data from the Mouse

Once the mouse is acquired, your application can begin to retrieve data from it.

In the Scrawl sample, retrieval is triggered by a signaled event. In the WinMain function, the application sleeps until MsgWaitForMultipleObjects indicates that there is either a signal or a message. If there is a signal associated with the mouse, the OnMouseInput function is called. This function is a good illustration of how buffered input is handled, as shown in the following process.

First, the function makes sure that the old cursor position is cleaned up. Note that Scrawl is maintaining its own cursor and is wholly responsible for drawing and erasing it.

VOID OnMouseInput(HWND hWnd)
{
    /* Invalidate the old cursor so that it will be erased */
    InvalidateCursorRect(hWnd);

Next, the function enters a loop to read and respond to the entire contents of the buffer. Because it retrieves just one item at a time, it needs only a single DIDEVICEOBJECTDATA structure to hold the data.

    while (!bDone) {
        DIDEVICEOBJECTDATA od;
        DWORD dwElements = 1;   // number of items to be retrieved

Note Another way to go about handling input would be to read the entire buffer at once and then loop through the retrieved items, responding to each one in turn. In that case, dwElements would be the size of the buffer, and od would be an array with the same number of elements.

The application calls the IDirectInputDevice8::GetDeviceData method in order to fetch the data. The second parameter tells DirectInput where to put the data, and the third tells it how many items are wanted. The final parameter would be DIGDD_PEEK if the data was to be left in the buffer, but in this case the data is not needed again, and so it is removed.

        hr = g_pMouse->GetDeviceData(sizeof(DIDEVICEOBJECTDATA),
                                     &od, &dwElements, 0);

Next, the application checks to see if access to the device has been lost and, if so, attempts to reacquire the mouse at the first opportunity. This step was discussed in Step 5: Managing Access to the Mouse.

        if (hr == DIERR_INPUTLOST)
        {
            SetAcquire();
            break;
        }

Next, the application makes sure the call to the IDirectInputDevice8::GetDeviceData method succeeded and that there was actually data to be retrieved. Note that after the call to IDirectInputDevice8::GetDeviceData the dwElements variable shows how many items were actually retrieved.

        /* Unable to read data or no data available */

        if (FAILED(hr) || dwElements == 0)
        {
            break;
        }

If execution has proceeded to this point, the call succeeded and there is an item of data in the buffer. Now the application looks at the dwOfs member of the DIDEVICEOBJECTDATA structure to determine which object on the device reported a change of state, and it calls helper functions to respond appropriately. The value of the dwData member, which contains information about what occurred with the device object, is passed to these functions.

        /* View the element to see what occurred */

        switch (od.dwOfs)
        {
            // Mouse horizontal motion
            case DIMOFS_X:
                UpdateCursorPosition(od.dwData, 0);
                break;

            // Mouse vertical motion
            case DIMOFS_Y:
                UpdateCursorPosition(0, od.dwData);
                break;

            // DIMOFS_BUTTON1: Right button pressed or released
            case DIMOFS_BUTTON1:

            // DIMOFS_BUTTON0: Left button pressed or released
            case DIMOFS_BUTTON0:
                // Is the right button or a swapped left button down?
                if((g_bSwapMouseButtons &&
                               DIMOFS_BUTTON1 == od.dwOfs) ||
                   (!g_bSwapMouseButtons &&
                               DIMOFS_BUTTON0 == od.dwOfs))
                {
                    if (od.dwData & 0x80)  // Left button pressed, so
                                                // go into button-down mode
                    {
                        bDone = TRUE;
                        OnLeftButtonDown(hWnd);
                    }
                // Is the left button or a swapped right button down?
                if((g_bSwapMouseButtons &&
                               DIMOFS_BUTTON0 == od.dwOfs) ||
                   (!g_bSwapMouseButtons &&
                               DIMOFS_BUTTON1 == od.dwOfs))
                {
                    if(!(od.dwData & 0x80))  // button release, so
                                             // check shortcut menu
                    {
                        bDone = TRUE;
                        OnRightButtonUp(hWnd);
                    }
                }
                break;
        }

Finally, in the event that the cursor has been moved by one of the helper functions, the OnMouseInput sample function invalidates the screen rectangle occupied by the cursor.

    // Invalidate the new cursor so that it will be drawn
    InvalidateCursorRect(hWnd);
}

Scrawl also collects mouse data in the OnLeftButtonDown function. This is where the application keeps track of mouse movements while the primary button is being held down - that is, while the user is drawing. This function does not rely on event notification, but repeatedly polls the DirectInput buffer until the button is released.

Note that in the OnLeftButtonDown function no drawing is done until all pending data has been read. This is because each horizontal or vertical movement of the mouse is reported as a separate event. (Both events are, however, placed in the buffer at the same time. ) If a line were immediately drawn in response to each separate axis movement, a diagonal mouse movement would produce two lines at right angles.

Another way you can be sure that the movement in both axes is taken into account before responding in your application is to check the sequence numbers of the x-axis item and the y-axis item. If the numbers are the same, the two events took place simultaneously. For more information, see Time Stamps and Sequence Numbers.

For additional DirectInput tutorials, see DirectInput Tutorials.


Tutorial 3: Using the Joystick

This tutorial shows you how to enumerate a joystick attached to a system and set it up for input. Code samples are based on the Joystick Sample.

The first step of setting up the Microsoft DirectInput system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard.

The first step in this tutorial is to enumerate devices; that is, to see what joysticks are available. As part of this process you initialize each joystick device and set its desired characteristics. You then use the IDirectInputDevice8 Interface interface methods to retrieve data from each joystick.

This tutorial divides the required tasks into the following steps.

Steps

  • Step 1: Enumerating the Joysticks
  • Step 2: Creating the DirectInput Joystick Device
  • Step 3: Setting the Joystick Data Format
  • Step 4: Setting the Joystick Behavior
  • Step 5: Gaining Access to the Joystick
  • Step 6: Retrieving Data from the Joystick


Step 1: Enumerating the Joysticks

After creating the DirectInput system, call the IDirectInput8::EnumDevices method to enumerate the joysticks, as in the following sample code.

//g_pDI is an initialized pointer to IDirectInput8
g_pDI->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback,
                       NULL, DIEDFL_ATTACHEDONLY)

The DI8DEVCLASS_GAMECTRL constant, passed as the first parameter, specifies the class of device to be enumerated.

EnumJoysticksCallback is the address of a callback function to be called each time a joystick is found. This is where the individual devices are created in Step 2: Creating the DirectInput Joystick Device.

The third parameter can be any 32-bit value that you want to make available to the callback function. In this case, nothing is being sent.

The last parameter, DIEDFL_ATTACHEDONLY, is a flag that restricts enumeration to devices that are attached to the computer.

When your application can enumerate the joysticks, go to Step 2: Creating the DirectInput Joystick Device.


Step 2: Creating the DirectInput Joystick Device

After creating the DirectInput object, the application must retrieve a pointer to an IDirectInputDevice8 Interface interface, which is used to perform most joystick-related tasks. In the Joystick Sample, this is done in the callback function EnumJoysticksCallback, which is called each time a joystick is enumerated.

The following sample code is the first part of the callback function.

BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE*
                                       pdidInstance, VOID* pContext)
{
    HRESULT hr;

    // Obtain an interface to the enumerated joystick.
    hr = g_pDI->CreateDevice(pdidInstance->guidInstance,
                                &g_pJoystick, NULL);
    if(FAILED(hr))
        return DIENUM_CONTINUE;

    return DIENUM_STOP;

The EnumJoysticksCallback callback function parameters are as follows:

  • A pointer to the device instance, supplied by the DirectInput system when the device is enumerated.
  • A pointer to a 32-bit value that you supplied as a parameter to IDirectInput8::EnumDevices. This parameter could be any 32-bit value such as a pointer to an interface so that you could use its methods. In this case, however, NULL was passed.

The first task of the callback function is to create the device. The IDirectInput8::CreateDevice method accepts three parameters.

The first parameter is a reference to the globally unique identifier (GUID) for the instance of the device. In this case, the GUID is taken from the DIDEVICEINSTANCE structure supplied by DirectInput when it enumerated the device.

The second parameter is the address of the variable that is initialized with a valid interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown for use in COM aggregation. The Joystick Sample does not use aggregation, so the parameter is NULL.

Note that if the device interface cannot be created, DIENUM_CONTINUE is returned from the callback function. This flag instructs DirectInput to keep enumerating as long as there are devices to be enumerated.

After creating the DirectInput joystick device, go to Step 3: Setting the Joystick Data Format.


Step 3: Setting the Joystick Data Format

Now that the application has a pointer to a DirectInput device, it can call the IDirectInputDevice8 Interface methods to manipulate that device. The first step, which is essential, is to set the data format for the joystick. This step tells DirectInput how to format the input data.

if (FAILED(hr = g_pJoystick->SetDataFormat(&c_dfDIJoystick2)))
    return hr;

The IDirectInputDevice8::SetDataFormat method takes one parameter, a pointer to a DIDATAFORMAT structure containing information about how the data for the device is to be formatted. For the joystick, you can use the predefined global variable c_dfDIJoystick2, which signifies use of the DIJOYSTATE2 structure to retrieve data.

After setting the joystick data format, go to Step 4: Setting the Joystick Behavior.


Step 4: Setting the Joystick Behavior

The joystick device has been created, and its data format has been set. The next step is to set its cooperative level. As in the previous step, g_pJoystick is a pointer to the device interface.

if (FAILED(hr = g_pJoystick->SetCooperativeLevel(hDlg,
                    DISCL_EXCLUSIVE | DISCL_FOREGROUND)))
    return hr;

The first parameter to IDirectInputDevice8::SetCooperativeLevel is a window handle. In this case, the handle to the dialog box serving as the main program window is passed to the function.

The final parameter is a combination of flags describing the desired cooperative level. The Joystick sample requires input from the joystick only when it is the foreground application. Also, when the joystick sample is in the foreground, it should be the only application with exclusive access to the joystick. Therefore, the flags are set to DISCL_EXCLUSIVE | DISCL_FOREGROUND. See Cooperative Levels for a full explanation of these flags.

The next step is to gather information about the capabilities of the joystick. This information includes the number of axes, buttons, and other controllers, whether the device supports force feedback, and other details about the joystick's behavior and supported options.

A DIDEVCAPS structure is used to hold the capability information. The dwSize member of the DIDEVCAPS structure must first be initialized, then the address of the structure sent to IDirectInputDevice8::GetCapabilities. In the example below, g_diDevCaps is a previously declared DIDEVCAPS structure.

g_diDevCaps.dwSize = sizeof(DIDEVCAPS);
if (FAILED(hr = g_pJoystick->GetCapabilities(&g_diDevCaps)))
    return hr;

At this point, you could proceed using the device defaults or you could customize the device properties. The Joystick sample enumerate the axes on the joystick and sets a range for each by calling IDirectInputDevice8::EnumObjects.

if (FAILED(hr = g_pJoystick->EnumObjects(EnumAxesCallback,
                                       (VOID*)hDlg, DIDFT_AXIS)))
    return hr;

The first parameter to the IDirectInputDevice8::EnumObjects method, EnumAxesCallback, is the address of a callback function which processes the enumerated objects as desired.

The second parameter can be any 32-bit value that you might want to provide to the callback function. Here, the handle to the main dialog window is passed so that it can update the display to indicate which axes are found on the joystick.

The last parameter, DIDFT_AXIS, tells the callback function to enumerate only device axes.

In the sample, the properties changed will be the range for any axis or slider detected (a slider is considered an axis ).

By setting the range, you are telling DirectInput what maximum and minimum values you want returned for an axis. If you set a range of -1,000 to +1,000 for the x-axis, as in the example, you are asking that a value of -1,000 be returned when the stick is at the extreme left, +1,000 when it is at the extreme right, and zero when it is in the middle.

The following sample code sets the range of an enumerated axis. The pdidoi variable is the address of a DIDEVICEOBJECTINSTANCE structure passed by the system to the callback function. This variable contains information about the object currently being enumerated.

DIPROPRANGE diprg;

diprg.diph.dwSize       = sizeof(DIPROPRANGE);
diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER);
diprg.diph.dwHow        = DIPH_BYID;
diprg.diph.dwObj        = pdidoi->dwType;
diprg.lMin              = -1000;
diprg.lMax              = +1000;
.
.
hr = g_pJoystick->SetProperty(DIPROP_RANGE, &diprg.diph);
if (FAILED(hr))
    return DIENUM_STOP;

The first task here is to set up the DIPROPRANGE structure diprg, whose address is passed into the IDirectInputDevice8::SetProperty method. Note that it is not the address of the structure itself that is passed but rather the address of its first member, which is a DIPROPHEADER structure. For more information, see Device Properties.

The property header is initialized with the following values.

  • The size of the property structure
  • The size of the header structure
  • A flag to indicate how the dwObj member is to be interpreted.
  • The value found in the dwType member of the DIDEVICEOBJECTINSTANCE structure indicating the object whose property is being changed.

The lmin and lmax members of the DIPROPRANGE structure are assigned the desired range values.

The application now calls the IDirectInputDevice8::SetProperty method. The first parameter is a flag indicating which property is being changed. The second parameter is the address of the DIPROPHEADER member of the property structure.

After setting the joystick behavior, go to Step 5: Gaining Access to the Joystick.


Step 5: Gaining Access to the Joystick

After your application sets a joystick's behavior, it can acquire access to the device by calling the IDirectInputDevice8 Interface method. The application must acquire the device before retrieving data from it. The IDirectInputDevice8 Interface method accepts no parameters.

The Joystick sample performs initial acquisition in the message loop as the application is activated. This loop also automatically reacquires the device whenever the application regains focus after having lost it. Acquisition is also performed if access to the joystick is lost or a DIERR_INPUTLOST error is returned when the application attempts to get input data. This is shown in the following code sample.

hr = g_pJoystick->Poll();
if (FAILED(hr))
{
    hr = g_pJoystick->Acquire();
    while(hr == DIERR_INPUTLOST)
        hr = g_pJoystick->Acquire();
    return S_OK;
}

Once your application can gain access to the joystick go to Step 6: Retrieving Data from the Joystick.


Step 6: Retrieving Data from the Joystick

Because your application is more likely concerned with the position of the joystick axes than with their movement, you probably want to retrieve immediate rather than buffered data from the device. You can do this by polling with IDirectInputDevice8::GetDeviceState. Note that not all device drivers notify DirectInput when the state of the device changes. Therefore, it is always good policy to call the IDirectInputDevice8 Interface method before checking the device state.

The Joystick application calls the following function from the Windows message loop.

HRESULT UpdateInputState(HWND hDlg)
{
    HRESULT     hr;
    CHAR        strText[128]; // Device state text
    DIJOYSTATE2 js;           // Direct Input joystick state
    CHAR*       str;

    if (NULL == g_pJoystick)
        return S_OK;

    // Poll the device to read the current state
    hr = g_pJoystick->Poll();
    if (FAILED(hr))
    {
        // Attempt to reacquire joystick
    }
    hr = g_pJoystick->GetDeviceState(sizeof(DIJOYSTATE2), &js);
    if (FAILED(hr))
        return hr;

Note the call to IDirectInputDevice8::GetDeviceState. The first parameter is the size of the structure in which the data is returned, and the second parameter is the address of this structure, which is of type DIJOYSTATE2. This structure holds data for up to six axes, 128 buttons, and four point-of-view hats. The sample program proceeds to view the state of all axes and buttons, and one slider. This information is then displayed in the main dialog window.

Joystick buttons work just like keys or mouse buttons. If the high bit of the returned byte is 1, the button is pressed.

For additional DirectInput tutorials, see DirectInput Tutorials.


Tutorial 4: Using Force Feedback

This tutorial takes you through the process of creating, playing, and modifying a simple effect on a force-feedback joystick. The effect is based on the feel of running a chain saw. Effects are created that simulate a chain saw starting with some difficulty, running normally, and cutting into wood.

The first step of setting up the Microsoft DirectInput system and the final step of closing it down are essentially the same for any application and are covered in Tutorial 1: Using the Keyboard. However, when closing down the DirectInput force-feedback system, you are required to take the additional step of releasing any effects you have created.

This tutorial divides the required tasks into the following steps.

  • Step 1: Enumerating Force-Feedback Devices
  • Step 2: Creating the DirectInput Force-Feedback Device
  • Step 3: Enumerating Supported Effects
  • Step 4: Creating an Effect
  • Step 5: Playing an Infinite Effect
  • Step 6: Changing an Effect


Step 1: Enumerating Force-Feedback Devices

The first step is to ensure that a force-feedback device is available on the system. You do this by calling the IDirectInput8::EnumDevices method. In the following example, the global pointer to the game device interface is initialized only if the enumeration has succeeded in finding at least one suitable device:

LPDIRECTINPUTDEVICE8  g_lpDIDevice = NULL;

hr = g_lpDI->EnumDevices(DI8DEVCLASS_GAMECTRL,
                         DIEnumDevicesProc,
                         NULL,
                         DIEDFL_FORCEFEEDBACK | DIEDFL_ATTACHEDONLY);
if (FAILED(hr))
{
  // No force-feedback joystick available; take appropriate action.
}

In the example, g_lpDI is an initialized pointer to the IDirectInput8 Interface interface. The first parameter to IDirectInput8::EnumDevices restricts the enumeration to joystick-type devices. The second parameter is the callback function that is called whenever DirectInput identifies a device that qualifies for enumeration. The third parameter is for user-defined data to be passed in or out of the callback function; in this case it is not used. Finally, the flags further restrict the enumeration to devices attached to the system that support force feedback.

The callback function is a convenient place to initialize the device as soon as it has been found. (It is assumed that the first device found is the one you want to use.) You do this in Step 2: Creating the DirectInput Force-Feedback Device.


Step 2: Creating the DirectInput Force-Feedback Device

To have DirectInput enumerate devices, create a callback function of the same type as DIEnumDevicesCallback. In Step 1 you passed the address of this function to the IDirectInput8::EnumDevices method.

DirectInput passes into the callback, as the first parameter, a pointer to a DIDEVICEINSTANCE structure that tells you what you need to know about the device. The structure member of most interest in the example is guidInstance, the unique identifier for the particular piece of hardware on the user's system. You must pass this globally unique identifier (GUID) to the IDirectInput8::CreateDevice method.

The following code fragment is the first part of the callback, which extracts the globally unique identifier (GUID) and creates the device object.

BOOL CALLBACK DIEnumDevicesProc( LPCDIDEVICEINSTANCE lpddi,
                                 LPVOID pvRef )
{
    HRESULT hr;
    GUID DeviceGuid = lpddi->guidInstance;

    // Create game device.

    hr = g_lpDI->CreateDevice(DeviceGuid, &g_lpDIDevice, NULL);

    if (FAILED(hr))
        // Continue enumerating until successful or finished
        return DIENUM_CONTINUE;

The next steps of the callback function are similar to those for setting up any input device. Note that you need the exclusive cooperative level for any force-feedback device.

    // Set cooperative level.
    hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                                  DISCL_EXCLUSIVE | DISCL_FOREGROUND);
    if (FAILED(hr))
        return hr;

    // set game data format
    hr = g_lpDIDevice->SetDataFormat(&c_dfDIJoystick);
    if (FAILED(hr))
        return hr;

Finally, you might want to turn off the device's autocenter feature. Autocenter is essentially a condition effect that uses the motors to simulate the springs in a standard joystick. It is a good idea to turn it off so that it does not interfere with other effects.

    DIPROPDWORD DIPropAutoCenter;

    DIPropAutoCenter.diph.dwSize       = sizeof(DIPropAutoCenter);
    DIPropAutoCenter.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    DIPropAutoCenter.diph.dwObj        = 0;
    DIPropAutoCenter.diph.dwHow        = DIPH_DEVICE;
    DIPropAutoCenter.dwData            = DIPROPAUTOCENTER_OFF;

    hr = g_lpDIDevice->SetProperty(DIPROP_AUTOCENTER,
                                   &DIPropAutoCenter.diph);
    if (FAILED(hr))
    {
        // Handle the failure as appropriate
    }

    return DIENUM_STOP;   // One is enough.
}   // end DIEnumDevicesProc

Before using the device, you must acquire it. See Step 5: Gaining Access to the Joystick in Tutorial 3: Using the Joystick for an example of how to handle acquisition. Note that unlike other property changes, force-feedback effects can be downloaded to a device when it is in an acquired state.

After you have created the DirectInput force-feedback device, go to Step 3: Enumerating Supported Effects.


Step 3: Enumerating Supported Effects

Now that you have successfully enumerated and created a force-feedback device, you can enumerate the effect types it supports.

Effect enumeration is not strictly necessary if you want to create only standard effects that will be available on any device, such as constant forces. When creating the effect object, you can identify the desired effect type by using one of the predefined GUIDs, such as GUID_ConstantForce. For a complete list of these identifiers, see IDirectInputDevice8::CreateEffect.

Another more flexible approach is to enumerate supported effects of a particular type, then obtain the globally unique identifier (GUID) for the effect from the callback function. You could use the callback to obtain more information about the device's support for the effect - for example, whether it supports an envelope - but in this tutorial you obtain only the effect GUID.

First, create the callback function that DirectInput calls for each effect enumerated. For information about this standard callback, see DIEnumEffectsCallback. You can give the function any name you like.

BOOL  EffectFound = FALSE;  // global flag
BOOL CALLBACK DIEnumEffectsProc(LPCDIEffectInfo pei, LPVOID pv)
{
    *((GUID *)pv) = pei->guid;
    EffectFound = TRUE;
    return DIENUM_STOP;  // one is enough
}

The GUID variable pointed to by the application-defined value pv is assigned the value passed in the DIEffectInfo structure created by DirectInput for the effect.

To obtain the effect GUID, set the callback in motion by calling the IDirectInputDevice8::EnumEffects method, as follows:

HRESULT  hr;
GUID     guidEffect;
hr = g_lpDIDevice->EnumEffects(
                         (LPDIENUMEFFECTSCALLBACK) DIEnumEffectsProc,
                         &guidEffect,
                         DIEFT_PERIODIC);
if (FAILED(hr))
{
    // Note that success does not mean that any effects were found,
    // only that the process went smoothly.
}

Note that you pass the address of a GUID variable, guidEffect, to the IDirectInputDevice8::EnumEffects method. This address is passed in turn to the callback as the pv parameter. You also restrict the enumeration to periodic effects by setting the flag DIEFT_PERIODIC.

Once your application can enumerate supported effects, go to Step 4: Creating an Effect.


Step 4: Creating an Effect

If the EffectFound value is no longer FALSE after effect enumeration, you can safely assume that DirectInput has found support for at least one effect of the periodic type you requested by passing the DIEFT_PERIODIC flag. Knowing the effect globally unique identifier (GUID), you can now create the effect object.

Before calling the IDirectInputDevice8::CreateEffect method, you set up the following arrays and structures.

  • An array of axes that will be involved in the effect. For a joystick, this array normally consists of the identifiers for the x-axis and the y-axis.
  • An array of values for setting the direction. The values differ according to both the number of axes and whether you want to use polar, spherical, or Cartesian coordinates. For a full explanation, see Effect Direction.
  • A structure of type-specific parameters. In the example, because you are creating a periodic effect, this is of type DIPERIODIC.
  • A DIENVELOPE structure for defining an envelope to be applied to the effect.
  • A DIEFFECT structure to contain the basic parameters for the effect.

Arrays can be initialized when they, along with the structures, are declared.

DWORD      dwAxes[2] = {DIJOFS_X, DIJOFS_Y};
LONG       lDirection[2] = {0, 0};

DIPERIODIC diPeriodic;      // type-specific parameters
DIENVELOPE diEnvelope;      // envelope
DIEFFECT   diEffect;        // general parameters

Next, initialize the type-specific parameters. The values in this example create a full-force periodic effect with a period of one-twentieth of a second.

diPeriodic.dwMagnitude = DI_FFNOMINALMAX;
diPeriodic.lOffset = 0;
diPeriodic.dwPhase = 0;
diPeriodic.dwPeriod = (DWORD)(0.05 * DI_SECONDS);

To produce an effect of the chain-saw motor trying to start, briefly coughing into life, and then slowly dying, you set an envelope with an attack time of one-half second and a fade time of one second.

diEnvelope.dwSize = sizeof(DIENVELOPE);
diEnvelope.dwAttackLevel = 0;
diEnvelope.dwAttackTime = (DWORD)(0.5 * DI_SECONDS);
diEnvelope.dwFadeLevel = 0;
diEnvelope.dwFadeTime = (DWORD)(1.0 * DI_SECONDS);

Next, set up the basic effect parameters. These include flags to determine how the directions and device objects (buttons and axes) are identified, the sample period and gain for the effect, and pointers to the other data that you have just prepared. You also associate the effect with the joystick's fire button so that it is automatically played whenever that button is pressed.

diEffect.dwSize = sizeof(DIEFFECT);
diEffect.dwFlags = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;
diEffect.dwDuration = (DWORD)(2 * DI_SECONDS);

diEffect.dwSamplePeriod = 0;               // = default
diEffect.dwGain = DI_FFNOMINALMAX;         // no scaling
diEffect.dwTriggerButton = DIJOFS_BUTTON0;
diEffect.dwTriggerRepeatInterval = 0;
diEffect.cAxes = 2;
diEffect.rgdwAxes = dwAxes;
diEffect.rglDirection = &lDirection[0];
diEffect.lpEnvelope = &diEnvelope;
diEffect.cbTypeSpecificParams = sizeof(diPeriodic);
diEffect.lpvTypeSpecificParams = &diPeriodic;

Finally, you can create the effect.

LPDIRECTINPUTEFFECT  g_lpdiEffect;  // global effect object

hr = g_lpDIDevice->CreateEffect(
                     guidEffect,     // GUID from enumeration
                     &diEffect,      // where the data is
                     &g_lpdiEffect,  // where to put interface pointer
                     NULL);          // no aggregation
if (FAILED(hr))
{
    return hr;
}

Note that, by default, the effect is downloaded to the device as soon as it has been created, provided that the device is in an acquired state at the exclusive cooperative level. You should now be able to compile, run, press the fire button, and feel the sputtering of a chain saw that's out of gas.

After creating an effect object, go to Step 5: Playing an Infinite Effect.


Step 5: Playing an Infinite Effect

The effect created in the previous step starts in response to the press of a button. To create an effect that is to be played in response to an explicit call, return to Step 4: Creating an Effect and modify the dwTriggerButton member of the DIEFFECT structure as follows:

diEffect.dwTriggerButton = DIEB_NOTRIGGER;

To make a chain saw that starts and keeps going, change the dwDuration member as follows:

diEffect.dwDuration = INFINITE;

Next, start the effect.

g_lpdiEffect->Start(1, 0);

The effect keeps running until you stop it.

g_lpdiEffect->Stop();

Note that it is not necessary to change the envelope you created in the previous step. The attack is played as the effect starts, but the fade value is ignored.

Once your application can play an infinite effect, go to Step 6: Changing an Effect.


Step 6: Changing an Effect

Next, you modify the effect to simulate the slowing down of the engine as the saw bites into wood. DirectInput enables you to modify the parameters of an effect while it is playing.

To change the effect, set up a new DIEFFECT structure or have access to the one you used to create the effect. If you are setting up a new structure with local scope, initialize only the dwSize member and any members that contain or point to data that is to be changed.

In this case, you want to change a type-specific parameter - the period of the effect - so you need to have access to the DIPERIODIC structure you used when creating the effect. Alternatively, you can create a local copy with all members initialized. Make sure that the address of the DIPERIODIC structure is in the lpvTypeSpecificParams member of the DIEFFECT structure.

First, set the new period of the effect.

diPeriodic.dwPeriod = (DWORD)(0.08 * DI_SECONDS);

Next, call the IDirectInputEffect::SetParameters method to make the changes.

hr = g_lpdiEffect->SetParameters(&diEffect, DIEP_TYPESPECIFICPARAMS);

Note the DIEP_TYPESPECIFICPARAMS flag that restricts the changes to a single member of the DIEFFECT structure.

You can control the way changes are handled by using other flags. For example, by using the DIEP_NODOWNLOAD flag you could change the parameters immediately after starting the effect but delay the implementation until a specific call to the IDirectInputEffect::Download method. For more information concerning use of the various control flags, see IDirectInputEffect::SetParameters.

For additional DirectInput tutorials, see DirectInput Tutorials.


Tutorial 5: Using Action Mapping

This tutorial guides you through the setup, modification, and application of an action map. Examples are based written as though they were to be used in a space combat game.

The first step of setting up the Microsoft DirectInput system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard. The keyboard, a mouse, and a joystick are all used in the sample, so each of those devices needs to be set up.

This tutorial divides the required tasks into the following steps.

  • Step 1: Defining the Game Actions
  • Step 2: Defining the Action Map
  • Step 3: Mapping Actions to Devices
  • Step 4: Configuring and Applying the Action Map
  • Step 5: Displaying the Action Map
  • Step 6: User Configuration of the Action Map
  • Step 7: Retrieval of Action Mapped Data


Step 1: Defining the Game Actions

The first step toward creating an action map is the definition of the game actions. These actions are specific to the application and are defined by the developer. In the case of this example, the actions chosen reflect its needs as a space combat simulator. These values can be defined in many ways as the developer sees fit. They could be defined as an enumeration, or they could be defined as constants as in this code fragment.

#define INPUT_LEFTRIGHT_AXIS   1L
#define INPUT_UPDOWN_AXIS      2L
#define INPUT_TURNLEFT         3L
#define INPUT_TURNRIGHT        4L
#define INPUT_FORWARDTHRUST    5L
#define INPUT_REVERSETHRUST    6L
#define INPUT_FIREWEAPONS      7L
#define INPUT_ENABLESHIELD     8L
#define INPUT_DISPLAYGAMEMENU  9L
#define INPUT_QUITGAME        10L

Once these values are defined, they can be assigned to genre-specific action-mapping constants. This is done in Step 2: Defining the Action Map.


Step 2: Defining the Action Map

Next, each game action should be assigned to at least one virtual control or device object. These controls are defined as action-mapping constants and are defined by genre and subgenre. In this case, the best choice is the Space Combat subgenre of the flight-games genre. This subgenre makes the following constants available.

Priority 1 Controls
DIAXIS_SPACESIM_LATERAL, DIAXIS_SPACESIM_MOVE, DIAXIS_SPACESIM_THROTTLE, DIBUTTON_SPACESIM_FIRE, DIBUTTON_SPACESIM_MENU, DIBUTTON_SPACESIM_TARGET, DIBUTTON_SPACESIM_WEAPONS
Priority 2 Controls
DIAXIS_SPACESIM_CLIMB, DIAXIS_SPACESIM_ROTATE, DIBUTTON_SPACESIM_BACKWARD_LINK, DIBUTTON_SPACESIM_DEVICE, DIBUTTON_SPACESIM_DISPLAY, DIBUTTON_SPACESIM_FASTER_LINK, DIBUTTON_SPACESIM_FIRESECONDARY, DIBUTTON_SPACESIM_FORWARD_LINK, DIBUTTON_SPACESIM_GEAR, DIBUTTON_SPACESIM_GLANCE_DOWN_LINK, DIBUTTON_SPACESIM_GLANCE_LEFT_LINK, DIBUTTON_SPACESIM_GLANCE_RIGHT_LINK, DIBUTTON_SPACESIM_GLANCE_UP_LINK, DIBUTTON_SPACESIM_LEFT_LINK, DIBUTTON_SPACESIM_LOWER, DIBUTTON_SPACESIM_PAUSE, DIBUTTON_SPACESIM_RAISE, DIBUTTON_SPACESIM_RIGHT_LINK, DIBUTTON_SPACESIM_SLOWER_LINK, DIBUTTON_SPACESIM_TURN_LEFT_LINK, DIBUTTON_SPACESIM_TURN_RIGHT_LINK, DIBUTTON_SPACESIM_VIEW, DIHATSWITCH_SPACESIM_GLANCE

Priority 1 controls are those controls that, at the minimum, should be mapped to a device object if possible. Priority 2 controls are less critical to basic game operation and may be mapped as needed.

Game actions are assigned to action-mapping constant controls in an array of DIACTION structures. Each DIACTION structure contains at least one game action, its associated action-mapping constant, any necessary flags, and either a friendly name or ID string for the action. The remaining DIACTION members are not used at this point. The following code sample shows definition of the array of DIACTION structures.

#define NUMBER_OF_ACTIONS 18

DIACTION g_rgGameAction[NUMBER_OF_ACTIONS] =
{
    // Device input pre-defined by DirectInput, according to genre
    {INPUT_LEFTRIGHT_AXIS, DIAXIS_SPACESIM_LATERAL, 0, "Turn",},
    {INPUT_UPDOWN_AXIS, DIAXIS_SPACESIM_MOVE, 0, "Move",},
    {INPUT_FIREWEAPONS, DIBUTTON_SPACESIM_FIRE, 0, "Shoot",},
    {INPUT_ENABLESHIELD, DIBUTTON_SPACESIM_GEAR, 0, "Shield",},
    {INPUT_DISPLAYGAMEMENU, DIBUTTON_SPACESIM_DISPLAY, 0, "Display",},
    {INPUT_QUITGAME, DIBUTTON_SPACESIM_MENU, 0, "Quit Game",},

    // Keyboard input mappings
    {INPUT_TURNLEFT, DIKEYBOARD_LEFT, 0, "Turn left", },
    {INPUT_TURNRIGHT, DIKEYBOARD_RIGHT, 0, "Turn right", },
    {INPUT_FORWARDTHRUST, DIKEYBOARD_UP, 0, "Forward thrust", },
    {INPUT_REVERSETHRUST, DIKEYBOARD_DOWN, 0, "Reverse thrust", },
    {INPUT_FIREWEAPONS, DIKEYBOARD_F, 0, "Fire weapons", },
    {INPUT_ENABLESHIELD, DIKEYBOARD_S, 0, "Enable shields", },
    {INPUT_DISPLAYGAMEMENU, DIKEYBOARD_D, DIA_APPFIXED,
    "Display game menu"), },
    {INPUT_QUITGAME, DIKEYBOARD_ESCAPE, DIA_APPFIXED, "Quit game", },

    // Mouse input mappings
    {INPUT_LEFTRIGHT_AXIS, DIMOUSE_XAXIS, 0, "Turn", },
    {INPUT_UPDOWN_AXIS, DIMOUSE_YAXIS, 0, "Move", },
    {INPUT_FIREWEAPONS, DIMOUSE_BUTTON0, 0, "Fire weapons", },
    {INPUT_ENABLESHIELD, DIMOUSE_BUTTON1, 0, "Enable shields", },
};

A DIACTIONFORMAT structure is then initialized to contain the DIACTION array g_rgGameAction defined above. The DIACTIONFORMAT structure also defines the genre, buffer size, axis scaling, and a friendly name for the action map. The g_AppGuid value is a globally unique identifier (GUID) defined in the application to identify the action map. For more information about creating GUIDs, see COM Object Overview.

DIACTIONFORMAT diaf;
diaf.dwSize        = sizeof(DIACTIONFORMAT);
diaf.dwActionSize  = sizeof(DIACTION);
diaf.dwDataSize    = NUMBER_OF_ACTIONS * sizeof(DWORD);
diaf.dwNumActions  = NUMBER_OF_ACTIONS;
diaf.guidActionMap = g_AppGuid;
diaf.dwGenre       = DIVIRTUAL_SPACESIM;
diaf.rgoAction     = g_rgGameAction;
diaf.dwBufferSize  = 16;
diaf.lAxisMin      = -100;
diaf.lAxisMax      = 100;
diaf.tszActionMap  = "DI Test";

This DIACTIONFORMAT structure is matched against enumerated devices to find the best match in Step 3: Mapping Actions to Devices.


Step 3: Mapping Actions to Devices

Once the desired mapping has been defined, it must be applied to physical devices. IDirectInput8::EnumDevicesBySemantics begins this process in the following code fragment, where m_pDI is a previously defined IDirectInput8 object.

HRESULT hr;

hr = m_pDI->EnumDevicesBySemantics(m_strUserName, &m_diaf,
                                EnumSuitableDevicesCB, this, 0L);

The first parameter, m_strUserName is useful in the case of multiple users who might have different mapping preferences. However, in the case of this example, this value is NULL, indicating the user currently logged onto the system.

The second parameter is the address of the DIACTIONFORMAT structure containing the mapping information.

The third parameter is the address of a callback function that is called for each device found on the system. The function used in the sample is based on the DIEnumDevicesBySemanticsCallback function.

The fourth parameter could be any 32-bit value that you want to make available to the callback function. Here, this is a this pointer to the class object used by the MultiMapper sample for the various action-mapping setup and manipulation functions. This gives the callback function access to the class' functions.

The final parameter is used for flags. None are used in this example.

The EnumSuitableDevicesCB callback function calls the application-defined function AddDevices, which in turn calls the IDirectInputDevice8::BuildActionMap function on the device pdidDevice currently being enumerated. This call is shown in the following code fragment.

hr = pdidDevice->BuildActionMap( &m_diaf, m_strUserName, 0L );

The first parameter is once again the address of the DIACTIONFORMAT structure containing the action map.

The second parameter is again the name of the user if desired, though NULL in this case.

The final parameter holds control flags, with none being passed in this case.

IDirectInputDevice8::BuildActionMap takes the list of control assignments specified in the DIACTIONFORMAT structure and attempts to map them to specific device objects on the device being enumerated. The results of the mapping are returned in the same structure. Each pass maps different controls depending on the nature of the currently enumerated device. A keyboard, for instance, maps controls that specify a mapping to a particular key, but leaves controls that specify buttons, sliders, or axes unmapped. If a joystick is enumerated next, IDirectInputDevice8::BuildActionMap ignores those controls mapped to keyboard keys, but it attempts to map the buttons, sliders, and axes to the joystick's device objects.

The results of this default mapping can be examined and manipulated. This is done in Step 4: Configuring and Applying the Action Map.


Step 4: Configuring and Applying the Action Map

Once the mapping has been returned in the DIACTIONFORMAT structure, it can be manipulated before being applied by IDirectInputDevice8::SetActionMap.

The dwHow member of each DIACTIONFORMAT structure might be examined at this point to determine both whether the mapping was successful and what the criteria were in selecting the device object to which that action was mapped. For instance, you can determine if the mapping was specified by the hardware manufacturer or requested by the user.

The actual mapping itself may be changed as well by editing the dwSemantic member of the appropriate DIACTIONFORMAT structure returned in the default mapping. You can choose to make those changes, but it is not recommended that you do so.

Once the action map configuration is finalized, it must be applied to the device to bind the physical controls to the game actions. This is done by calling IDirectInputDevice8::SetActionMap as follows:

    hr = pdidDevice->SetActionMap( &m_diaf, m_strUserName, 0L );

Action maps, once created, can be displayed for and easily altered by the user. This is explained in Step 5: Displaying the Action Map.


Step 5: Displaying the Action Map

In addition to the advantage of action mapping in enabling the developer to define game actions independently of specific controller hardware, action mapping also benefits the user by providing a user interface (UI) for easy reconfiguration.

The UI can be displayed in two forms, text-only or graphics. In addition, each of those two options can be viewed in two modes: view-only or edit.

To display the UI, some initial setup is involved. First, a DICOLORSET structure is declared and initialized. This structure, as its name implies, describes the color set used to display the UI. The following code fragment shows the setup of this structure.

DICOLORSET dics;
ZeroMemory(&dics, sizeof(DICOLORSET));
dics.dwSize = sizeof(DICOLORSET);

By using the ZeroMemory function to set the memory block to zeroes, it indicates that the default color scheme should be used. Beyond this, the only element that requires initialization is the dwSize member, which is set equal to the size of the DICOLORSET structure.

The DICOLORSET structure is then included as part of a larger DICONFIGUREDEVICESPARAMS structure as seen in this code fragment.

DICONFIGUREDEVICESPARAMS dicdp;
ZeroMemory(&dicdp, sizeof(dicdp));
dicdp.dwSize = sizeof(dicdp);
dicdp.dwcUsers       = 1;
dicdp.lptszUserNames = m_strUserName;

dicdp.dwcFormats     = 1;
dicdp.lprgFormats    = &m_diaf;
dicdp.hwnd           = m_hWnd;
dicdp.lpUnkDDSTarget = NULL;

The DICONFIGUREDEVICESPARAMS structure is declared and its allotted memory is set to contain nothing but zeroes. Once again, the dwSize member is set to the size of the structure. Only the currently logged user is being used in this example, so dwcUsers is set to 1. Recall that the m_strUserName variable is set to NULL so that the user's name is the name of the user currently logged onto the system.

Only one DIACTIONFORMAT structure containing the action map is being passed, so dwcFormats is set to 1 and the address of the DIACTIONFORMAT structure is passed as lprgFormats.

The hwnd variable is assigned the handle of the application window and the lpUnkDDSTarget is set to NULL to indicate that the Windows Graphics Device Interface (GDI) functions should be used to draw the configuration user interface image.

The initialized DICONFIGUREDEVICESPARAMS structure is then passed to IDirectInput8::ConfigureDevices as illustrated in this code fragment.

hr = m_pDI->ConfigureDevices(NULL, &dicdp, dwFlags, NULL);

The first and last parameters, which are used with an optional callback function, are set to NULL as they are not used in this sample.

The second parameter is the address of the DICONFIGUREDEVICESPARAMS structure containing the data to be displayed and other auxiliary information.

The third parameter is used for flags that determine whether the display is in read-only or edit mode. If you want to display the configuration for informational purposes without giving the user the option of changing it, you use the DICD_DEFAULT flag in this parameter. However, in this sample the dwFlags variable had been set earlier to DICD_EDIT, so the display allows user configuration. This is discussed in Step 6: User Configuration of the Action Map.


Step 6: User Configuration of the Action Map

At this point, the user configuration interface is displayed. If the device manufacturer has provided a graphic, users see an image of the device with labels indicating the action assigned to each device object. If no graphic is available, a simple text list of available device objects with their associated actions is displayed. An example of the former is shown here.

Graphical user interface for configuring the action map

Users can now reassign controllers to actions as they see fit. Any changes made will be reflected in the DIACTIONFORMAT structure. When the user interface is closed, the new action map must be sent to IDirectInputDevice8::SetActionMap before it can be implemented.

Using the data associated with the controls in an action map is described in Step 7: Retrieval of Action Mapped Data.


Step 7: Retrieval of Action Mapped Data

Action mapping was designed with buffered data in mind and will most often be used in that manner. The only difference between retrieving data from an action-mapped device and a device with no mapping is where you get it. Without action mapping, you would look to the dwOfs member of the DIDEVICEOBJECTDATA structure to determine which device object reported a change. However, with action mapping, you look to the uAppData member. Data is found in the dwData member.


DirectInput Samples

The following sample programs demonstrate the use and capabilities of DirectInput.

  • CustomFormat Sample
  • FFConst Sample
  • Joystick Sample
  • Keyboard Sample
  • Mouse Sample

Although DirectX samples include Microsoft Visual C++ project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly.


CustomFormat Sample

Description

This sample illustrates the use of a custom data format.

Path

Source: | (SDK root)\Samples\C++\DirectInput\CustomFormat
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\CustomFormat.exe

User's Guide

After you have started the sample, the sample displays the mouse location and which mouse button is clicked.

Note If your mouse has more than four buttons, not all of the buttons will be used by this sample.

Programming Notes

The comments in CustomFormat.cpp explain how to create, initialize, and retrieve data with a custom data format. You might want to use a custom data format for adding support for a non-standard input device. By enumerating the device objects, you can determine exactly what data is available. The data format you create specifies how the data you are interested in will be stored.

For compatibility, this sample creates a new format to store mouse data. Usually, you would want to use one of the provided c_dfDIMouse types, but the steps taken to create the custom format will be the same for any hardware device. For more information, see IDirectInputDevice8::SetDataFormat.


FFConst Sample

Description

The FFConst sample program applies raw forces to a force-feedback input device, illustrating how a simulator-type application can use force feedback to generate forces computed by a physics engine.

You must have a force-feedback device connected to your system in order to run the application.

Path

Source: | (SDK root)\Samples\C++\DirectInput\FFConst
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\FFConst.exe

User's Guide

When you run the application, it displays a window with a crosshair and a black spot in it. Click anywhere within the window's client area to move the black spot. (Note that moving the device itself does not do anything.) FFConst exerts a constant force on the device from the direction of the spot, in proportion to the distance from the crosshair. You can also hold down the mouse button and move the spot continuously.

Programming Notes

This sample program enumerates the input devices and acquires the first force-feedback device that it finds. If none are detected, it displays a message and terminates.

When the user moves the black spot, joySetForcesXY function converts the cursor coordinates to a force direction and magnitude. This data is used to modify the parameters of the constant force effect.


Joystick Sample

Description

The Joystick sample program obtains and displays joystick data.

Path

Source: | (SDK root)\Samples\C++\DirectInput\Joystick
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\Joystick.exe

User's Guide

Observe how the displayed data changes when you move and twist the stick, rotate the throttle wheel, and press buttons in various combinations.

Programming Notes

The application polls the joystick for immediate data in response to a timer set inside the dialog procedure.


Keyboard Sample

Description

The Keyboard sample program enables the exploration of Foreground versus Background and Exclusive versus Non-Exclusive cooperative levels, and Buffered versus Immediate data retrieval from the keyboard.

Path

Source: | (SDK root)\Samples\C++\DirectInput\Keyboard
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\Keyboard.exe

User's Guide

Through the user interface, any combination of cooperative level and data styles can be created and the resulting keyboard behavior observed. Each setting is explained as it is selected, and the expected behavior is predicted when the device is created.

Programming Notes

Note that holding down a key in immediate mode holds that key indefinitely as subsequent snapshots of the keyboard are taken by DirectInput. This is an optical illusion because DirectInput is taking individual snapshots at the rate of twelve times a second, but it demonstrates that, in immediate mode, only the state of the keyboard at that time is considered, while anything that has happened between snapshots is ignored.

Holding down a key in buffered mode briefly displays the data indicating that the key has been pressed, then quickly clears that data as it is flushed from the buffer. Releasing the key generates another briefly displayed key-up event. This is a significant difference from immediate mode.


Mouse Sample

Description

The Mouse sample program enables the exploration of Foreground versus Background and Exclusive versus Non-Exclusive cooperative levels, and Buffered versus Immediate data retrieval from the mouse.

Path

Source: | (SDK root)\Samples\C++\DirectInput\Mouse
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\Mouse.exe

User's Guide

Through the user interface, any combination of cooperative level and data styles can be created and the resulting keyboard behavior observed. Each setting is explained as it is selected, and the expected behavior is predicted when the device is created.

To release the mouse, press ENTER.

Programming Notes

Note that in immediate mode, all device objects are visible and you can see the data change as the mouse is moved. This is an optical illusion because DirectInput is taking individual snapshots at the rate of twelve times a second, but it demonstrates that, in immediate mode, only the state of the device at that time is considered, while anything that has happened between device snapshots is ignored.

Holding down a button in buffered mode briefly displays the data indicating that the button has been pressed, then quickly clears that data as it is flushed from the buffer. Releasing the button generates another briefly displayed button up event. This is a significant difference from immediate mode.


DirectInput C/C++ Reference

Reference material for the DirectInput C/C++ API is divided into the following categories.

  • DirectInput Interfaces
  • Callback Functions
  • DirectInput Functions
  • Macros
  • DirectInput Structures
  • Device Constants
  • Action Mapping Constants
  • Return Values


DirectInput Interfaces

This section contains references for methods of the following DirectInput interfaces.

  • IDirectInput8 Interface
  • IDirectInputDevice8 Interface
  • IDirectInputEffect Interface

Note All DirectInput methods have corresponding macros that expand to C or C++ syntax depending on which language is defined. These macros are found in the Dinput.h header file and are not documented separately.


IDirectInput8 Interface

Applications use the methods of the IDirectInput8 interface to enumerate, create, and retrieve the status of Microsoft DirectInput devices, initialize the DirectInput object, and invoke an instance of the Microsoft Windows Control Panel.

IDirectInput8 Members

Method | Description
IDirectInput8::ConfigureDevices | Displays property pages for connected input devices and enables the user to map actions to device controls.
IDirectInput8::CreateDevice | Creates and initializes an instance of a device based on a given globally unique identifier (GUID), and obtains an IDirectInputDevice8 Interface interface.
IDirectInput8::EnumDevices | Enumerates available devices.
IDirectInput8::EnumDevicesBySemantics | Enumerates devices that most closely match the application-specified action map.
IDirectInput8::FindDevice | Retrieves the instance globally unique identifier (GUID) of a device that has been newly attached to the system. It is called in response to a Microsoft Win32 device management notification.
IDirectInput8::GetDeviceStatus | Retrieves the status of a specified device.
IDirectInput8::Initialize | Initializes a DirectInput object. Applications normally do not need to call this method. The DirectInput8Create function automatically initializes the DirectInput object after creating it.
IDirectInput8::RunControlPanel | Runs Control Panel to enable the user to install a new input device or modify configurations.

Remarks

IDirectInput8 supersedes the IDirectInput, IDirectInput2, and IDirectInput7 interfaces used in earlier versions of Microsoft DirectX.

IDirectInput8 is an interface to a new class of object, represented by the class identifier CLSID_DirectInput8, and cannot be obtained by calling QueryInterface on an interface to objects of class CLSID_DirectInput. Instead, obtain the IDirectInput8 interface by using the DirectInput8Create function.

The LPDIRECTINPUT8 type is defined as a pointer to the IDirectInput8 interface:

typedef struct IDirectInput8    *LPDIRECTINPUT8;


IDirectInput8::ConfigureDevices

Displays property pages for connected input devices and enables the user to map actions to device controls.

HRESULT ConfigureDevices(
  LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
  LPDICONFIGUREDEVICESPARAMS lpdiCDParams,
  DWORD dwFlags,
  LPVOID pvRefData
);

Parameters

lpdiCallback
Address of a callback function to be called each time the contents of the surface change. See DIConfigureDevicesCallback. Pass NULL if the application does not handle the display of the property sheet. In this case, DirectInput displays the property sheet and returns control to the application when the user closes the property sheet. If you supply a callback pointer, you must also supply a valid surface pointer in the lpUnkDDSTarget member of the DICONFIGUREDEVICESPARAMS structure.
lpdiCDParams
Address of a DICONFIGUREDEVICESPARAMS structure that contains information about users and genres for the game, as well as information about how the user interface is displayed.
dwFlags
DWORD value that specifies the mode in which the control panel should be invoked. The dwFlags parameter must be one of the following values.
DICD_DEFAULT
Open the property sheet in view-only mode.
DICD_EDIT
Open the property sheet in edit mode. This mode enables the user to change action-to-control mappings. After the call returns, the application should assume current devices are no longer valid, release all device interfaces, and reinitialize them by calling IDirectInput8::EnumDevicesBySemantics.
pvRefData
Application-defined value to pass to the callback function.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following: DIERR_INVALIDPARAM, DIERR_OUTOFMEMORY.

Remarks

IDirectInput8::ConfigureDevices is deprecated. This method always fails on Windows Vista and later versions of Windows.

Hardware vendors provide bitmaps and other display information for their device.

Before calling the method, an application can modify the text labels associated with each action by changing the value in the lptszActionName member of the DIACTION structure.

Configuration is stored for each user of each device for each game. The information can be retrieved by the IDirectInputDevice8::BuildActionMap method.

By default, acceleration is supported for these pixel formats:

  • A1R5G5B5

    16-bit pixel format with 5 bits reserved for each color and 1 bit reserved for alpha (transparent texel).

  • A8R8G8B8

    32-bit ARGB pixel format with alpha.

  • R9G8B8

    24-bit RGB pixel format.

  • X1R5G5B5

    16-bit pixel format with 5 bits reserved for each color.

  • X8R8G8B8

    32-bit RGB pixel format with 8 bits reserved for each color.

Other formats will result in color conversion and dramatically slow the frame rate.

Note Even if the cooperative level for the application is disabling the Windows logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping user interface (UI) is displayed.

Requirements

Header: Declared in Dinput.h.


IDirectInput8::CreateDevice

Creates and initializes an instance of a device based on a given globally unique identifier (GUID), and obtains an IDirectInputDevice8 Interface interface.

HRESULT CreateDevice(
  REFGUID rguid,
  LPDIRECTINPUTDEVICE * lplpDirectInputDevice,
  LPUNKNOWN pUnkOuter
);

Parameters

rguid
Reference to the GUID for the desired input device (see Remarks). The GUID is retrieved through the IDirectInput8::EnumDevices method, or it can be one of the predefined GUIDs listed below. For the following GUID values to be valid, your application must define INITGUID before all other preprocessor directives at the beginning of the source file, or link to Dxguid.lib.
GUID_SysKeyboard
The default system keyboard.
GUID_SysMouse
The default system mouse.
lplpDirectInputDevice
Address of a variable to receive the IDirectInputDevice8 Interface interface pointer if successful.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation, or NULL if the interface is not aggregated. Most calling applications pass NULL.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following: DIERR_DEVICENOTREG, DIERR_INVALIDPARAM, DIERR_NOINTERFACE, DIERR_NOTINITIALIZED, DIERR_OUTOFMEMORY.

Remarks

Calling this method with pUnkOuter = NULL is equivalent to creating the object by CoCreateInstance (&CLSID_DirectInputDevice, NULL, CLSCTX_INPROC_SERVER, riid, lplpDirectInputDevice) and then initializing it with Initialize.

Calling this method with pUnkOuter != NULL is equivalent to creating the object by CoCreateInstance (&CLSID_DirectInputDevice, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInputDevice). The aggregated object must be initialized manually.

Requirements

Header: Declared in Dinput.h.


IDirectInput8::EnumDevices

Enumerates available devices.

HRESULT EnumDevices(
  DWORD dwDevType,
  LPDIENUMDEVICESCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

dwDevType

Device type filter.

To restrict the enumeration to a particular type of device, set this parameter to a DI8DEVTYPE_* value. See DIDEVICEINSTANCE.

To enumerate a class of devices, use one of the following values.

DI8DEVCLASS_ALL
All devices.
DI8DEVCLASS_DEVICE
All devices that do not fall into another class.
DI8DEVCLASS_GAMECTRL
All game controllers.
DI8DEVCLASS_KEYBOARD
All keyboards. Equivalent to DI8DEVTYPE_KEYBOARD.
DI8DEVCLASS_POINTER
All devices of type DI8DEVTYPE_MOUSE and DI8DEVTYPE_SCREENPOINTER.
lpCallback
Address of a callback function to be called once for each device enumerated. See DIEnumDevicesCallback.
pvRef
Application-defined 32-bit value to be passed to the enumeration callback each time it is called.
dwFlags
Flag value that specifies the scope of the enumeration. This parameter can be one or more of the following values:
DIEDFL_ALLDEVICES
All installed devices are enumerated. This is the default behavior.
DIEDFL_ATTACHEDONLY
Only attached and installed devices.
DIEDFL_FORCEFEEDBACK
Only devices that support force feedback.
DIEDFL_INCLUDEALIASES
Include devices that are aliases for other devices.
DIEDFL_INCLUDEHIDDEN
Include hidden devices. For more information about hidden devices, see DIDEVCAPS.
DIEDFL_INCLUDEPHANTOMS
Include phantom (placeholder) devices.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED.

Remarks

All installed devices can be enumerated, even if they are not present. For example, a flight stick might be installed on the system but not currently plugged into the computer. Set the dwFlags parameter to indicate whether only attached or all installed devices should be enumerated. If the DIEDFL_ATTACHEDONLY flag is not present, all installed devices are enumerated.

A preferred device type can be passed as a dwDevType filter so that only the devices of that type are enumerated.

On Microsoft Windows XP, DirectInput enumerates only one mouse and one keyboard device, referred to as the system mouse and the system keyboard. These devices represent the combined output of all mice and keyboards respectively on a system. For information about how to read from multiple mice or keyboards individually on Windows XP, see the WM_INPUT documentation.

Note The order in which devices are enumerated by DirectInput is not guaranteed.

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInput8::EnumDevicesBySemantics


IDirectInput8::EnumDevicesBySemantics

Enumerates devices that most closely match the application-specified action map.

HRESULT EnumDevicesBySemantics(
  LPCTSTR ptszUserName,
  LPDIACTIONFORMAT lpdiActionFormat,
  LPDIENUMDEVICESBYSEMANTICSCB lpCallback,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

ptszUserName
String identifying the current user, or NULL to specify the user logged onto the system. The user name is taken into account when enumerating devices. A device with user mappings is preferred to a device without any user mappings. By default, devices in use by other users are not enumerated for this user.
lpdiActionFormat
Address of a DIACTIONFORMAT structure that specifies the action map for which suitable devices are enumerated.
lpCallback
Address of a callback function to be called once for each device enumerated. See DIEnumDevicesBySemanticsCallback.
pvRef
Application-defined 32-bit value to pass to the enumeration callback each time it is called.
dwFlags
Flag value that specifies the scope of the enumeration. This parameter can be one or more of the following values.
DIEDBSFL_ATTACHEDONLY
Only attached and installed devices are enumerated.
DIEDBSFL_AVAILABLEDEVICES
Only unowned, installed devices are enumerated.
DIEDBSFL_FORCEFEEDBACK
Only devices that support force feedback are enumerated.
DIEDBSFL_MULTIMICEKEYBOARDS
Only secondary (non-system) keyboard and mouse devices.
DIEDBSFL_NONGAMINGDEVICES
Only HID-compliant devices whose primary purpose is not as a gaming device. Devices such as USB speakers and multimedia buttons on some keyboards would fall within this value.
DIEDBSFL_THISUSER
All installed devices for the user identified by ptszUserName, and all unowned devices, are enumerated.
DIEDBSFL_VALID
DIEDBSFL_VALID is also defined in Dinput.h, but is not used by applications.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED.

Remarks

The keyboard and mouse are enumerated last.

Note The order in which devices are enumerated by DirectInput is not guaranteed.

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInput8::EnumDevices


IDirectInput8::FindDevice

Retrieves the instance globally unique identifier (GUID) of a device that has been newly attached to the system. It is called in response to a Microsoft Win32 device management notification.

HRESULT FindDevice(
  REFGUID rguidClass,
  LPCTSTR ptszName,
  LPGUID pguidInstance
);

Parameters

rguidClass
Unique identifier of the device class for the device that the application is to locate. The application obtains the class GUID from the device arrival notification. For more information, see the documentation on the DBT_DEVICEARRIVAL event in the Microsoft Platform Software Development Kit (SDK).
ptszName
Name of the device. The application obtains the name from the device arrival notification.
pguidInstance
Address of a variable to receive the instance GUID for the device, if the device is found. This value can be passed to IDirectInput8::CreateDevice.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be DIERR_DEVICENOTREG. Failure results if the GUID and name do not correspond to a device class that is registered with DirectInput. For example, they might refer to a storage device, rather than an input device.

Requirements

Header: Declared in Dinput.h.


IDirectInput8::GetDeviceStatus

Retrieves the status of a specified device.

HRESULT GetDeviceStatus(
  REFGUID rguidInstance
);

Parameters

rguidInstance
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the instance of the device whose status is being checked.

Return Values

If the method succeeds, the return value is DI_OK if the device is attached to the system, or DI_NOTATTACHED otherwise. If the method fails, the return value can be one of the following error values: DIERR_GENERIC, DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED.

Requirements

Header: Declared in Dinput.h.


IDirectInput8::Initialize

Initializes a DirectInput object. Applications normally do not need to call this method. The DirectInput8Create function automatically initializes the DirectInput object after creating it.

HRESULT Initialize(
  HINSTANCE hinst,
  DWORD dwVersion
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility. It is an error for a DLL to pass the handle of the parent application. For example, a Microsoft ActiveX control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle of the browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_BETADIRECTINPUTVERSION, DIERR_OLDDIRECTINPUTVERSION.

Requirements

Header: Declared in Dinput.h.


IDirectInput8::RunControlPanel

Runs Control Panel to enable the user to install a new input device or modify configurations.

HRESULT RunControlPanel(
  HWND hwndOwner,
  DWORD dwFlags
);

Parameters

hwndOwner
Handle of the window to be used as the parent window for the subsequent user interface. If this parameter is NULL, no parent window is used.
dwFlags
Currently not used and must be set to 0.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED.

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::RunControlPanel


IDirectInputDevice8 Interface

Applications use the methods of the IDirectInputDevice8 interface to gain and release access to Microsoft DirectInput devices, manage device properties and information, set behavior, perform initialization, create and play force-feedback effects, and invoke a device's control panel.

IDirectInputDevice8 Members

Method | Description
IDirectInputDevice8::Acquire | Obtains access to the input device.
IDirectInputDevice8::BuildActionMap | Builds an action map for the device and retrieves information about it.
IDirectInputDevice8::CreateEffect | Creates and initializes an instance of an effect identified by the effect globally unique identifier (GUID).
IDirectInputDevice8::EnumCreatedEffectObjects | Enumerates all the currently created effects for this device.
IDirectInputDevice8::EnumEffects | Enumerates all the effects supported by the force-feedback system on the device.
IDirectInputDevice8::EnumEffectsInFile | Enumerates all the effects in a file created by the Force Editor utility or another application using the same file format.
IDirectInputDevice8::EnumObjects | Enumerates the input and output objects available on a device.
IDirectInputDevice8::Escape | Sends a hardware-specific command to the force-feedback driver.
IDirectInputDevice8::GetCapabilities | Obtains the capabilities of the DirectInputDevice object.
IDirectInputDevice8::GetDeviceData | Retrieves buffered data from the device.
IDirectInputDevice8::GetDeviceInfo | Obtains information about the device's identity.
IDirectInputDevice8::GetDeviceState | Retrieves immediate data from the device.
IDirectInputDevice8::GetEffectInfo | Obtains information about an effect.
IDirectInputDevice8::GetForceFeedbackState | Retrieves the state of the device's force-feedback system.
IDirectInputDevice8::GetImageInfo | Retrieves information about a device image for use in a configuration property sheet.
IDirectInputDevice8::GetObjectInfo | Retrieves information about a device object, such as a button or axis.
IDirectInputDevice8::GetProperty | Retrieves information about the input device.
IDirectInputDevice8::Initialize | Initializes a DirectInputDevice object.
IDirectInputDevice8::Poll | Retrieves data from polled objects on a DirectInput device.
IDirectInputDevice8::RunControlPanel | Runs the DirectInput control panel associated with this device.
IDirectInputDevice8::SendDeviceData | Sends data to a device that accepts output.
IDirectInputDevice8::SendForceFeedbackCommand | Sends a command to the device's force-feedback system.
IDirectInputDevice8::SetActionMap | Sets the data format for a device and maps application-defined actions to device objects.
IDirectInputDevice8::SetCooperativeLevel | Establishes the cooperative level for this instance of the device.
IDirectInputDevice8::SetDataFormat | Sets the data format for the DirectInput device.
IDirectInputDevice8::SetEventNotification | Specifies an event that is to be set when the device state changes.
IDirectInputDevice8::SetProperty | Sets properties that define the device behavior.
IDirectInputDevice8::Unacquire | Releases access to the device.
IDirectInputDevice8::WriteEffectToFile | Saves information about one or more force-feedback effects to a file that can be read by using EnumEffectsInFile.

Remarks

The IDirectInputDevice8 interface is obtained by using the IDirectInput8::CreateDevice method. For an example, see Creating a DirectInput Device.

IDirectInputDevice8 supersedes the IDirectInputDevice, IDirectInputDevice2, and IDirectInputDevice7 interfaces used in previous versions of Microsoft DirectX, but does not inherit from them. Methods that share names with those from older interfaces perform similar services, but may not have exactly the same functionality or behavior. You cannot obtain the earlier interfaces by using QueryInterface.

The LPDIRECTINPUTDEVICE8 type is defined as a pointer to the IDirectInputDevice8 interface:

typedef struct IDirectInputDevice8    *LPDIRECTINPUTDEVICE8;


IDirectInputDevice8::Acquire

Obtains access to the input device.

HRESULT Acquire();

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK, or S_FALSE if the device was already acquired. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED, DIERR_OTHERAPPHASPRIO.

Remarks

Before a device can be acquired, a data format must be set by using the IDirectInputDevice8::SetDataFormat method or IDirectInputDevice8::SetActionMap method. If the data format has not been set, IDirectInputDevice8 Interface returns DIERR_INVALIDPARAM.

Devices must be acquired before calling the IDirectInputDevice8::GetDeviceState or IDirectInputDevice8::GetDeviceData methods for that device.

Device acquisition does not use a reference count. Therefore, if an application calls the IDirectInputDevice8 Interface method twice, then calls the IDirectInputDevice8 Interface method once, the device is unacquired.

If IDirectInputDevice8::BuildActionMap succeeds but no actions have been mapped, a subsequent call to IDirectInputDevice8::SetActionMap will return DI_OK but a call to IDirectInputDevice8 Interface will fail with DIERR_INVALIDPARAM.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::BuildActionMap

Builds an action map for the device and retrieves information about it.

HRESULT BuildActionMap(
  LPDIACTIONFORMAT lpdiaf,
  LPCTSTR lpszUserName,
  DWORD dwFlags
);

Parameters

lpdiaf
Address of a DIACTIONFORMAT structure that receives information about the action map.
lpszUserName
Pointer to a string that specifies the name of the user for whom mapping is requested. When using ANSI compiler settings, pass NULL and DirectInput will assume the current user name. When using Unicode compiler settings, do not pass NULL because the mappings will not be saved.
dwFlags
Flags to control the mapping. This can be one of the following values.
DIDBAM_DEFAULT
Overwrite all mappings except application-specified mappings; that is, mappings that have the DIA_APPMAPPED flag in the DIACTION structure.
DIDBAM_HWDEFAULTS
Overwrite all mappings, including application-specified mappings. This flag is similar to DIDBAM_INITIALIZE, but automatically overrides user-mapped actions with the defaults specified by the device driver or DirectInput.
DIDBAM_INITIALIZE
Overwrite all mappings, including application-specified mappings.
DIDBAM_PRESERVE
Preserve current mappings assigned for this device or any other configured device.

Return Values

If the method succeeds, the return value is DI_OK, DI_NOEFFECT, or DI_WRITEPROTECT>. See Remarks. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_MAPFILEFAIL.

Remarks

The method returns DI_NOEFFECT if no mappings were created for the device. For example, a keyboard or mouse will not provide mappings for genre-specific actions.

If DIERR_INVALIDPARAM is returned, one or more of the mappings was not valid. The dwHow member of the DIACTION structure is set to DIAH_ERROR. The application can iterate through the action map to find and correct errors.

If DIEFF_MAPFILEFAIL is returned, an error has occurred either reading the vendor supplied file for the device or reading or writing the user configuration file for the device.

DI_WRITEPROTECT> is returned if the mappings were not configurable. For example, the buttons on a voice controller cannot be reconfigured because each button causes a specific hardware action to occur. DI_WRITEPROTECT> overrides other success codes, so a check of the return codes will not reveal if any actions have been mapped.

If IDirectInputDevice8::BuildActionMap succeeds but no actions have been mapped, a subsequent call to IDirectInputDevice8::SetActionMap will return DI_OK but a call to IDirectInputDevice8 Interface will fail with DIERR_INVALIDPARAM.

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::SetActionMap, IDirectInputDevice8::SetDataFormat


IDirectInputDevice8::CreateEffect

Creates and initializes an instance of an effect identified by the effect globally unique identifier (GUID).

HRESULT CreateEffect(
  REFGUID rguid,
  LPCDIEFFECT lpeff,
  LPDIRECTINPUTEFFECT * ppdeff,
  LPUNKNOWN punkOuter
);

Parameters

rguid
Reference to (C++) or address of (C) the GUID identifying the effect to be created. This can be a predefined effect GUID, or it can be a GUID obtained from IDirectInputDevice8::EnumEffects. The following standard effect GUIDs are defined:
  • GUID_ConstantForce
  • GUID_RampForce
  • GUID_Square
  • GUID_Sine
  • GUID_Triangle
  • GUID_SawtoothUp
  • GUID_SawtoothDown
  • GUID_Spring
  • GUID_Damper
  • GUID_Inertia
  • GUID_Friction
  • GUID_CustomForce
lpeff
DIEFFECT structure that provides parameters for the created effect. This parameter is optional. If it is NULL, the effect object is created without parameters. The application must then call the IDirectInputEffect::SetParameters method to set the parameters of the effect before it can download the effect.
ppdeff
Address of a variable to receive a pointer to the IDirectInputEffect Interface interface if successful.
punkOuter
Controlling unknown for COM aggregation. The value is NULL if the interface is not aggregated. Most calling applications pass NULL.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_DEVICEFULL, DIERR_DEVICENOTREG, DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED.

Remarks

If the return value is S_OK, the effect was created, and the parameters of the effect were updated, but the effect was not necessarily downloaded. For it to be downloaded, the device must be acquired in exclusive mode.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::EnumCreatedEffectObjects

Enumerates all the currently created effects for this device. Effects created by IDirectInputDevice8::CreateEffect are enumerated.

HRESULT EnumCreatedEffectObjects(
  LPDIENUMCREATEDEFFECTOBJECTSCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD fl
);

Parameters

lpCallback
Address of an application-defined callback function. DirectInput provides the prototype function DIEnumCreatedEffectObjectsCallback.
pvRef
Reference data (context) for callback.
fl
No flags are currently defined. This parameter must be 0.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED.

Remarks

The results are unpredictable if you create or destroy an effect while an enumeration is in progress. However, the callback function can safely release the effect passed to it.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::EnumEffects

Enumerates all the effects supported by the force-feedback system on the device. The enumerated GUIDs can represent predefined effects, as well as effects peculiar to the device manufacturer.

HRESULT EnumEffects(
  LPDIENUMEFFECTSCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD dwEffType
);

Parameters

lpCallback
Address of an application-defined callback function. The declaration of this function must conform to that of the DIEnumEffectsCallback prototype.
pvRef
A 32-bit application-defined value to be passed to the callback function. This parameter can be any 32-bit type; it is declared as LPVOID for convenience.
dwEffType
Effect type filter. Use one of the DIEFT_* values to indicate the effect type to be enumerated, or DIEFT_ALL to enumerate all effect types. For a list of these values, see DIEffectInfo.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM DIERR_NOTINITIALIZED

Remarks

If the callback stops the enumeration prematurely, the enumeration is considered to have succeeded.

An application can use the dwEffType member of the DIEffectInfo structure to obtain general information about the effect, such as its type and which envelope and condition parameters are supported by the effect.

To exploit an effect to its fullest, contact the device manufacturer to obtain information about the semantics of the effect and its effect-specific parameters.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::EnumEffectsInFile

Enumerates all the effects in a file created by the Force Editor utility or another application using the same file format.

HRESULT EnumEffectsInFile(
  LPCSTR lpszFileName,
  LPENUMEFFECTSINFILECALLBACK pec,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

lpszFileName
Name of the RIFF file.
pec
Address of an application-defined callback function. The declaration of this function must conform to that of the DIEnumEffectsInFileCallback prototype.
pvRef
Application-defined value to be passed to the callback function. This parameter can be any 32-bit type.
dwFlags
Can be DIFEF_DEFAULT ( = 0) or one or both of the following values:
DIFEF_INCLUDENONSTANDARD
Include effect types that are not defined by DirectInput.
DIFEF_MODIFYIFNEEDED
Instruct DirectInput to modify the authored effect, if necessary, so that it plays on the current device. For example, by default, an effect authored for two axes does not play on a single-axis device. Setting this flag allows the effect to play on a single axis. The parameters are modified in the DIEFFECT structure pointed to by the lpDiEffect member of the DIFILEEFFECT structure passed to the callback.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM DIERR_NOTINITIALIZED

Remarks

If the callback stops the enumeration prematurely, the enumeration is considered to have succeeded.

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::WriteEffectToFile, Loading Effects from a File


IDirectInputDevice8::EnumObjects

Enumerates the input and output objects available on a device.

HRESULT EnumObjects(
  LPDIENUMDEVICEOBJECTSCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

lpCallback
Address of a callback function that receives DirectInputDevice objects. DirectInput provides a prototype of this function as DIEnumDeviceObjectsCallback.
pvRef
Reference data (context) for callback.
dwFlags
Flags that specify the types of object to be enumerated. Each of the following values restricts the enumeration to objects of the described type:
DIDFT_ABSAXIS
An absolute axis.
DIDFT_ALIAS
Controls identified by a Human Interface Device (HID) usage alias. This flag applies only to HID-compliant USB devices.
DIDFT_ALL
All objects.
DIDFT_AXIS
An axis, either absolute or relative.
DIDFT_BUTTON
A push button or a toggle button.
DIDFT_COLLECTION
A HID link collection. HID link collections do not generate data of their own.
DIDFT_ENUMCOLLECTION(n)
An object that belongs to HID link collection number n.
DIDFT_FFACTUATOR
An object that contains a force-feedback actuator. In other words, forces can be applied to this object.
DIDFT_FFEFFECTTRIGGER
An object that can be used to trigger force-feedback effects.
DIDFT_NOCOLLECTION
An object that does not belong to any HID link collection; in other words, an object for which the wCollectionNumber member of the DIDEVICEOBJECTINSTANCE structure is 0.
DIDFT_NODATA
An object that does not generate data.
DIDFT_OUTPUT
An object that supports output. For details, see Remarks in IDirectInputDevice8::SendDeviceData.
DIDFT_POV
A point-of-view controller.
DIDFT_PSHBUTTON
A push button. A push button is reported as down when the user presses it, and as up when the user releases it.
DIDFT_RELAXIS
A relative axis.
DIDFT_TGLBUTTON
A toggle button. A toggle button is reported as down when the user presses it and remains so until the user presses the button a second time.
DIDFT_VENDORDEFINED
An object of a type defined by the manufacturer.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values:.

DIERR_INVALIDPARAM DIERR_NOTINITIALIZED

Remarks

The DIDFT_FFACTUATOR and DIDFT_FFEFFECTTRIGGER flags in the dwFlags parameter restrict enumeration to objects that meet all the criteria defined by the included flags. For all the other flags, an object is enumerated if it meets the criterion defined by any included flag in this category. For example, (DIDFT_FFACTUATOR | DIDFT_FFEFFECTTRIGGER) restricts enumeration to force-feedback trigger objects, and (DIDFT_FFEFFECTTRIGGER | DIDFT_TGLBUTTON | DIDFT_PSHBUTTON) restricts enumeration to buttons of any kind that can be used as effect triggers.

Applications should not rely on this method to determine whether certain keyboard keys or indicator lights are present, as these objects might be enumerated even though they are not present. Although the basic set of available objects can be determined from the device subtype, there is no reliable way of determining whether extra objects such as the menu key are available.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::Escape

Sends a hardware-specific command to the force-feedback driver.

HRESULT Escape(
  LPDIEFFESCAPE pesc
);

Parameters

pesc
DIEFFESCAPE structure that describes the command to be sent. On success, the cbOutBuffer member contains the number of bytes of the output buffer actually used.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_DEVICEFULL, DIERR_NOTINITIALIZED.

Remarks

Other device-specific error codes are also possible. Ask the hardware manufacturer for details.

Because each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the DIDEVICEINSTANCE structure against the value the application is expecting.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::GetCapabilities

Obtains the capabilities of the DirectInputDevice object.

HRESULT GetCapabilities(
  LPDIDEVCAPS lpDIDevCaps
);

Parameters

lpDIDevCaps
Address of a DIDEVCAPS structure to be filled with the device capabilities. The dwSize member of this structure must be initialized before calling this method.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED, E_POINTER.

Remarks

For compatibility with DirectX 3, it is also valid to pass a DIDEVCAPS_DX3 structure with the dwSize member initialized to sizeof(DIDEVCAPS_DX3).

The number of objects returned in the DIDEVCAPS structure is the maximum number of objects that could be enumerated. However, all of these objects are not necessarily returned during a call to IDirectInputDevice8::EnumObjects.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::GetDeviceData

Retrieves buffered data from the device.

HRESULT GetDeviceData(
  DWORD cbObjectData,
  LPDIDEVICEOBJECTDATA rgdod,
  LPDWORD pdwInOut,
  DWORD dwFlags
);

Parameters

cbObjectData
Size of the DIDEVICEOBJECTDATA structure, in bytes.
rgdod
Array of DIDEVICEOBJECTDATA structures to receive the buffered data. The number of elements in this array must be equal to the value of the pdwInOut parameter. If this parameter is NULL, the buffered data is not stored anywhere, but all other side effects take place.
pdwInOut
On entry, the number of elements in the array pointed to by the rgdod parameter. On exit, the number of elements actually obtained.
dwFlags
Flags that control the manner in which data is obtained. This value can be 0 or the following flag.
DIGDD_PEEK
Do not remove the items from the buffer. A subsequent IDirectInputDevice8::GetDeviceData call will read the same data. Normally, data is removed from the buffer after it is read.

Return Values

If the method succeeds, the return value is DI_OK or DI_BUFFEROVERFLOW. If the method fails, the return value can be one of the following error values: DIERR_INPUTLOST, DIERR_INVALIDPARAM, DIERR_NOTACQUIRED, DIERR_NOTBUFFERED, DIERR_NOTINITIALIZED.

Remarks

Note If the method returns DI_BUFFEROVERFLOW, the data in the rgdod array has been truncated.

In the debug version of DirectInput, if a call is made to IDirectInputDevice8::GetDeviceData and the device has been unacquired, then random bytes will be sent to the device data buffer. To make sure you are not using random device data, always check for the DIERR_UNACQUIRED return code.

Before device data can be obtained, you must set the data format and the buffer size by using the IDirectInputDevice8::SetDataFormat and IDirectInputDevice8::SetProperty methods, or by using the IDirectInputDevice8::SetActionMap method. You must also acquire the device by using the IDirectInputDevice8 Interface method.

The maximum number of events that the buffer will hold is one less than the buffer size set with the IDirectInputDevice8::SetProperty method.

The following code example reads up to ten buffered data elements, removing them from the device buffer as they are read.

DIDEVICEOBJECTDATA rgdod[10];
DWORD dwItems = 10;
hres = idirectinputdevice9_GetDeviceData(
    sizeof(DIDEVICEOBJECTDATA),
    rgdod,
    &dwItems,
    0);
if (SUCCEEDED(hres)) {
    // dwItems = Number of elements read (could be zero).
    if (hres == DI_BUFFEROVERFLOW) {
    // Buffer had overflowed.
    }
}

Your application can flush the buffer and retrieve the number of flushed items by specifying NULL for the rgdod parameter and a pointer to a variable containing INFINITE for the pdwInOut parameter. The following code example illustrates how this can be done.

dwItems = INFINITE;
hres = idirectinputdevice9_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            0);
if (SUCCEEDED(hres)) {
    // Buffer successfully flushed.
    // dwItems = Number of elements flushed.
    if (hres == DI_BUFFEROVERFLOW) {
        // Buffer had overflowed.
    }
}

Your application can query for the number of elements in the device buffer by setting the rgdod parameter to NULL, setting pdwInOut to INFINITE and setting dwFlags to DIGDD_PEEK. The following code example illustrates how this can be done.

dwItems = INFINITE;
hres = idirectinputdevice9_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            DIGDD_PEEK);
if (SUCCEEDED(hres)) {
    // dwItems = Number of elements in buffer.
    if (hres == DI_BUFFEROVERFLOW) {
        // Buffer overflow occurred; not all data
        //   was successfully captured.
    }
}

To query about whether a buffer overflow has occurred, set the rgdod parameter to NULL and the pdwInOut parameter to 0. The following code example illustrates how this can be done.

dwItems = 0;
hres = idirectinputdevice9_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            0);
if (hres == DI_BUFFEROVERFLOW) {
    // Buffer overflow occurred.
}

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::Poll, Polling and Event Notification


IDirectInputDevice8::GetDeviceInfo

Obtains information about the device's identity.

HRESULT GetDeviceInfo(
  LPDIDEVICEINSTANCE pdidi
);

Parameters

pdidi
Address of a DIDEVICEINSTANCE structure to be filled with information about the device's identity. An application must initialize the structure's dwSize member before calling this method.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED, E_POINTER.

Remarks

For compatibility with DirectX 3, it is also valid to pass a DIDEVICEINSTANCE_DX3 structure with the dwSize member initialized to sizeof(DIDEVICEINSTANCE_DX3).

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::GetDeviceState

Retrieves immediate data from the device.

HRESULT GetDeviceState(
  DWORD cbData,
  LPVOID lpvData
);

Parameters

cbData
Size of the buffer in the lpvData parameter, in bytes.
lpvData
Address of a structure that receives the current state of the device. The format of the data is established by a prior call to the IDirectInputDevice8::SetDataFormat method.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INPUTLOST, DIERR_INVALIDPARAM, DIERR_NOTACQUIRED, DIERR_NOTINITIALIZED, E_PENDING.

Remarks

Before device data can be obtained, set the cooperative level by using the IDirectInputDevice8::SetCooperativeLevel method, then set the data format by using IDirectInputDevice8::SetDataFormat, and acquire the device by using the IDirectInputDevice8 Interface method.

The five predefined data formats require corresponding device state structures according to the following table:

Data format | State structure
c_dfDIMouse | DIMOUSESTATE
c_dfDIMouse2 | DIMOUSESTATE2
c_dfDIKeyboard | array of 256 bytes
c_dfDIJoystick | DIJOYSTATE
c_dfDIJoystick2 | DIJOYSTATE2

For example, if you passed the c_dfDIMouse format to the IDirectInputDevice8::SetDataFormat method, you must pass a DIMOUSESTATE structure to the IDirectInputDevice8::GetDeviceState method.

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::Poll, Polling and Event Notification, Buffered and Immediate Data


IDirectInputDevice8::GetEffectInfo

Obtains information about an effect.

HRESULT GetEffectInfo(
  LPDIEffectInfo pdei,
  REFGUID rguid
);

Parameters

pdei
DIEffectInfo structure that receives information about the effect. The calling application must initialize the dwSize member of the structure before calling this method.
rguid
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the effect for which information is being requested.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_DEVICENOTREG, DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED, E_POINTER.

Remarks

Note If this method is called on an non-Force Feedback device, E_POINTER will be returned.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::GetForceFeedbackState

Retrieves the state of the device's force-feedback system.

HRESULT GetForceFeedbackState(
  LPDWORD pdwOut
);

Parameters

pdwOut

Location for flags that describe the current state of the device's force-feedback system.

The value is a combination of the following constants.

DIGFFS_ACTUATORSOFF
The device's force-feedback actuators are disabled. If the device cannot report the actuator state, neither DIGFFS_ACTUATORSON nor DIGFFS_ACTUATORSOFF is returned.
DIGFFS_ACTUATORSON
The device's force-feedback actuators are enabled. If the device cannot report the actuator state, neither DIGFFS_ACTUATORSON nor DIGFFS_ACTUATORSOFF is returned.
DIGFFS_DEVICELOST
The device suffered an unexpected failure and is in an indeterminate state. It must be reset either by unacquiring and reacquiring the device, or by sending a DISFFC_RESET command.
DIGFFS_EMPTY
The device has no downloaded effects.
DIGFFS_PAUSED
Playback of all active effects has been paused.
DIGFFS_POWEROFF
The force-feedback system is not currently available. If the device cannot report the power state, neither DIGFFS_POWERON nor DIGFFS_POWEROFF is returned.
DIGFFS_POWERON
Power to the force-feedback system is currently available. If the device cannot report the power state, neither DIGFFS_POWERON nor DIGFFS_POWEROFF is returned.
DIGFFS_SAFETYSWITCHOFF
The safety switch is currently off; that is, the device cannot operate. If the device cannot report the state of the safety switch, neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF is returned.
DIGFFS_SAFETYSWITCHON
The safety switch is currently on; that is, the device can operate. If the device cannot report the state of the safety switch, neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF is returned.
DIGFFS_STOPPED
No effects are playing, and the device is not paused.
DIGFFS_USERFFSWITCHOFF
The user force-feedback switch is currently off; that is, the device cannot operate. If the device cannot report the state of the user force-feedback switch, neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF is returned.
DIGFFS_USERFFSWITCHON
The user force-feedback switch is currently on; that is, the device can operate. If the device cannot report the state of the user force-feedback switch, neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF is returned.

Applications should ignore any flags that are not currently defined.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INPUTLOST, DIERR_INVALIDPARAM, DIERR_NOTEXCLUSIVEACQUIRED, DIERR_NOTINITIALIZED, DIERR_UNSUPPORTED.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

The DIGFFS_PAUSED and DIGFFS_STOPPED flags may not always be reported correctly because there is no mechanism for the drivers to report that they support these flags.

Note When calling IDirectInputDevice8::GetForceFeedbackState, it is possible for the state of the device returned not to match the expected state. This might happen if commands recently sent by IDirectInputDevice8::SendForceFeedbackCommand are still pending. Wait a short time and then check the device state again.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::GetImageInfo

Retrieves information about a device image for use in a configuration property sheet.

HRESULT GetImageInfo(
  LPDIDEVICEIMAGEINFOHEADER lpdiDevImageInfoHeader
);

Parameters

lpdiDevImageInfoHeader
Address of a DIDEVICEIMAGEINFOHEADER structure that receives information about the device image.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_MAPFILEFAIL, DIERR_MOREDATA, DIERR_NOTINITIALIZED, DIERR_OBJECTNOTFOUND.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::GetObjectInfo

Retrieves information about a device object, such as a button or axis.

HRESULT GetObjectInfo(
  LPDIDEVICEOBJECTINSTANCE pdidoi,
  DWORD dwObj,
  DWORD dwHow
);

Parameters

pdidoi
Address of a DIDEVICEOBJECTINSTANCE structure to be filled with information about the object. The structure's dwSize member must be initialized before this method is called.
dwObj
Value that identifies the object whose information is to be retrieved. The value set for this parameter depends on the value specified in the dwHow parameter.
dwHow
Value that specifies how the dwObj parameter should be interpreted. The dwHow value can be one of the following:
DIPH_BYOFFSET
The dwObj parameter is the offset into the current data format of the object whose information is being accessed.
DIPH_BYID
The dwObj parameter is the object type/instance identifier. This identifier is returned in the dwType member of the DIDEVICEOBJECTINSTANCE structure returned from a previous call to the IDirectInputDevice8::EnumObjects method.
DIPH_BYUSAGE
The dwObj parameter contains the HID Usage Page and Usage values of the object, combined by the DIMAKEUSAGEDWORD macro.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED, DIERR_OBJECTNOTFOUND, E_POINTER.

Remarks

For compatibility with DirectX 3, it is also valid to pass a DIDEVICEOBJECTINSTANCE_DX3 structure with the dwSize member initialized to sizeof(DIDEVICEOBJECTINSTANCE_DX3).

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::GetProperty

Retrieves information about the input device.

HRESULT GetProperty(
  REFGUID rguidProp,
  LPDIPROPHEADER pdiph
);

Parameters

rguidProp
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the property to be retrieved. This can be one of the predefined values or a pointer to a GUID that identifies the property. The following properties are predefined for an input device.
DIPROP_APPDATA
Retrieves the application-defined value associated with an in-game action, as a DIPROPPOINTER.
DIPROP_AUTOCENTER
Determines whether device objects are self centering. The value returned can be DIPROPAUTOCENTER_OFF or DIPROPAUTOCENTER_ON. See IDirectInputDevice8::SetProperty for more information.
DIPROP_AXISMODE
Retrieves the axis mode. The retrieved value can be DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL.
DIPROP_BUFFERSIZE
Retrieves the input buffer size. The buffer size determines the amount of data that the buffer can hold between calls to the IDirectInputDevice8::GetDeviceData method before data is lost. You can set this value to 0 to indicate that the application does not read buffered data from the device. If the buffer size in the dwData member of the DIPROPDWORD structure is too large for the device to support it, then the largest possible buffer size is set. However, this property always returns the buffer size set using the IDirectInputDevice8::SetProperty method, even if the buffer cannot be supported because it is too large.
DIPROP_CALIBRATION

Predefined property that allows the application to access the information that DirectInput uses to manipulate axes that require calibration. This property exists primarily for applications of the control panel type. Normal applications should not need to deal with calibration information.

You can access the calibration mode property for a particular axis by setting the dwHow member of the DIPROPHEADER structure to DIPH_BYID or to DIPH_BYOFFSET and setting the dwObj member to the object ID or offset, respectively.

Control panel applications that set new calibration data must also invoke the IDirectInputJoyConfig::SendNotify method to notify other applications of the change in calibration. For more information about IDirectInputJoyConfig::SendNotify, see the DirectInput Driver Development Kit (DDK).

DIPROP_CALIBRATIONMODE
For use by device drivers; not used by applications.
DIPROP_CPOINTS
This property is unsupported. Retrieves calibration points used for the adjustment of incoming raw data as a DIPROPCPOINTS structure.
DIPROP_DEADZONE
Retrieves a value for the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range.
DIPROP_FFGAIN
Retrieves the gain of the device. This property always returns DI_OK even if the device does not support force feedback. See IDirectInputDevice8::SetProperty for more information.
DIPROP_FFLOAD
Retrieves the memory load for the device. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE. The retrieved value is in the range from 0 through 100, indicating the percentage of device memory in use. The device must be acquired in exclusive mode. If it is not, the method will fail with a return value of DIERR_NOTEXCLUSIVEACQUIRED.
DIPROP_GETPORTDISPLAYNAME
Retrieves the human-readable display name of the port to which this device is connected. Not generally used by applications.
DIPROP_GRANULARITY
Retrieves the input granularity. Granularity represents the smallest distance over which the object reports movement. Most axis objects have a granularity of one; that is, all values are possible. Some axes have a larger granularity. For example, the wheel axis on a mouse can have a granularity of 20; that is, all reported changes in position are multiples of 20. In other words, when the user turns the wheel slowly, the device reports a position of 0, then 20, then 40, and so on. This is a read-only property.
DIPROP_GUIDANDPATH
Retrieves the class GUID and device interface (path) for the device. This property lets advanced applications perform operations on a human interface device that are not supported by DirectInput. For more information, see the DIPROPGUIDANDPATH structure.
DIPROP_INSTANCENAME
Retrieves the friendly instance name of the device. For more information, see IDirectInputDevice8::SetProperty.
DIPROP_JOYSTICKID
Retrieves the instance number of a joystick. This property is not implemented for the mouse or keyboard.
DIPROP_KEYNAME
Retrieves the localized key name for a keyboard key, as a DIPROPSTRING. Using this property on devices other than a keyboard will return unexpected names.
DIPROP_LOGICALRANGE
Retrieves the range of the raw data returned for axes on a human interface device. Devices can return negative values.
DIPROP_PHYSICALRANGE
Retrieves the range of data for axes as suggested by the manufacturer of a human interface device. Values can be negative. Normally DirectInput returns values from 0 through 0xFFFF, but the range can be made to conform to the manufacturer's suggested range by using DIPROP_RANGE.
DIPROP_PRODUCTNAME
Retrieves the friendly product name of the device. For more information, see IDirectInputDevice8::SetProperty.
DIPROP_RANGE
Retrieves the range of values an object can possibly report. For some devices, this is a read-only property.
DIPROP_SATURATION
Retrieves a value for the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone).
DIPROP_SCANCODE
Retrieves the scan code for a keyboard key, as a DIPROPDWORD. If successful, S_OK is returned. E_FAIL is returned if the property cannot resolve specialized keys on USB keyboards because they do not exist in scan code form. For all other failures, E_INVALIDARG is returned.
DIPROP_TYPENAME
Predefined property that retrieves the type name of a device. For most game controllers, this is the registry key name under REGSTR_PATH_JOYOEM from which static device settings can be retrieved, but predefined joystick types have special names consisting of a number sign (&Sharp;) followed by a character dependent on the type. This value might not be available for all devices.
DIPROP_USERNAME
Retrieves the user name for a user currently assigned to a device, as a DIPROPSTRING. User names are set by calling IDirectInputDevice8::SetActionMap. If no user name is set, the method returns S_FALSE.
DIPROP_VIDPID
Read-only device property that retrieves the vendor identity (ID) and product ID of a HID device. This property is of type DIPROPDWORD and contains both values. These two WORD values are combined in the dwData member of the DIPROPDWORD structure. See Examples. This property applies to the entire device, rather than to any particular object, so the dwHow member of the DIPROPHEADER structure must be set to DIPH_DEVICE.
pdiph
Address of the DIPROPHEADER portion of a larger property-dependent structure that contains the DIPROPHEADER structure as a member. The following structures are used for properties:
  • DIPROPDWORD is used for properties represented by a single numerical value.
  • DIPROPGUIDANDPATH is used for DIPROP_GUIDANDPATH.
  • DIPROPRANGE is used for properties represented by a pair of numerical values. Currently, the only such property is DIPROP_RANGE.
  • DIPROPSTRING is used for string properties.

Return Values

If the method succeeds, the return value is DI_OK or S_FALSE. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_NOTEXCLUSIVEACQUIRED, DIERR_NOTINITIALIZED, DIERR_OBJECTNOTFOUND, DIERR_UNSUPPORTED.

Remarks

If rguidProp is set to DIPROP_APPDATA, the dwHow member of the DIPROPHEADER structure should only be set to DIPH_BYUSAGE when getting information about input controls, such as buttons or axes. Setting DIPH_BYUSAGE for other device objects such as a physical interface device (PID) or LED devices can lead to unpredictable results.

S_FALSE is always returned when IDirectInputDevice8::GetProperty is called with rguidProp set to DIPROP_GETPORTDISPLAYNAME, even if the method succeeds.

The scan codes reported in Microsoft DirectX 8.1 are different from the ones reported in DirectX 8.0. In DirectX 8.0, the property actually reported the single byte DIK_* constant associated with the key, not the scan code. In DirectX 8.1 and later releases, the property reports the make scan code as would be reported by a PS/2 keyboard. In some cases, scan codes are multiple bytes, in which case the scan code bytes are ordered with the first byte in the least significant byte of the DWORD retrieved by the property.

Example

The following C example shows how to obtain the value of the DIPROP_BUFFERSIZE property.

DIPROPDWORD dipdw;  // DIPROPDWORD contains a DIPROPHEADER structure.
HRESULT hr;
dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj        = 0; // device property
dipdw.diph.dwHow        = DIPH_DEVICE;

hr = idirectinputdevice9_GetProperty(pdid, DIPROP_BUFFERSIZE, &dipdw.diph);
if (SUCCEEDED(hr)) {
    // The dipdw.dwData member contains the buffer size.
}

The following example shows how to extract the two WORD values from the dwData member of the DIPROPDWORD structure using the DIPROP_VIDPID property:

wVendorID  = LOWORD(DIPROPDWORD.dwData);
wProductID = HIWORD(DIPROPDWORD.dwData);

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::SetProperty


IDirectInputDevice8::Initialize

Initializes a DirectInputDevice object. The IDirectInput8::CreateDevice method automatically initializes a device after creating it; applications normally do not need to call this method.

HRESULT Initialize(
  HINSTANCE hinst,
  DWORD dwVersion,
  REFGUID rguid
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInputDevice object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility. It is an error for a DLL to pass the handle to the parent application. For example, a Microsoft ActiveX control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that may be necessary.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.
rguid
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the instance of the device with which the interface should be associated. The IDirectInput8::EnumDevices method can be used to determine which instance GUIDs are supported by the system.

Return Values

If the method succeeds, the return value is DI_OK or S_FALSE. If the method returns S_FALSE, the device had already been initialized with the instance GUID passed in though rGUID. If the method fails, the return value can be one of the following error values: DIERR_ACQUIRED, DIERR_DEVICENOTREG.

Remarks

If this method fails, the underlying object should be considered to be in an indeterminate state and must be reinitialized before use.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::Poll

Retrieves data from polled objects on a DirectInput device. If the device does not require polling, calling this method has no effect. If a device that requires polling is not polled periodically, no new data is received from the device. Calling this method causes DirectInput to update the device state, generate input events (if buffered data is enabled), and set notification events (if notification is enabled).

HRESULT Poll();

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK, or DI_NOEFFECT if the device does not require polling. If the method fails, the return value can be one of the following error values: DIERR_INPUTLOST, DIERR_NOTACQUIRED, DIERR_NOTINITIALIZED.

Remarks

Before a device data can be polled, the data format must be set by using the IDirectInputDevice8::SetDataFormat or IDirectInputDevice8::SetActionMap method, and the device must be acquired by using the IDirectInputDevice8 Interface method.

Requirements

Header: Declared in Dinput.h.

See Also

Polling and Event Notification


IDirectInputDevice8::RunControlPanel

Runs the DirectInput control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.

HRESULT RunControlPanel(
  HWND hwndOwner,
  DWORD dwFlags
);

Parameters

hwndOwner
Parent window handle. If this parameter is NULL , no parent window is used.
dwFlags
Not currently used. Zero is the only valid value.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM DIERR_NOTINITIALIZED

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::SendDeviceData

Sends data to a device that accepts output.

Note There are no devices that accept output from IDirectInputDevice8::SendDeviceData. See Remarks.

HRESULT SendDeviceData(
  DWORD cbObjectData,
  LPCDIDEVICEOBJECTDATA rgdod,
  LPDWORD pdwInOut,
  DWORD fl
);

Parameters

cbObjectData
Size, in bytes, of a single DIDEVICEOBJECTDATA structure.
rgdod
Array of DIDEVICEOBJECTDATA structures containing the data to send to the device.
pdwInOut
On entry, the variable pointed to by this parameter contains the number of elements in the array pointed to by rgdod. On exit, it contains the number of elements sent to the device.
fl
Flags controlling the manner in which data is sent. This can be 0 or the following value.
DISDD_CONTINUE
The device data sent is overlaid on the previously sent device data.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INPUTLOST, DIERR_NOTACQUIRED, DIERR_REPORTFULL, DIERR_UNPLUGGED.

Remarks

Applications should not use IDirectInputDevice8::SendDeviceData. Force Feedback is the recommended way to send data to a device. If you want to send other data to a device, such as changing LED or internal device states, the HID application programming interface (API) is the recommended way.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::SendForceFeedbackCommand

Sends a command to the device's force-feedback system.

HRESULT SendForceFeedbackCommand(
  DWORD dwFlags
);

Parameters

dwFlags
Single value indicating the desired change in state. The value can be one of the following.
DISFFC_CONTINUE
Paused playback of all active effects is to be continued. It is an error to send this command when the device is not in a paused state.
DISFFC_PAUSE
Playback of all active effects is to be paused. This command also stops the clock-on effects so that they continue playing to their full duration when restarted.

While the device is paused, new effects cannot be started, and existing ones cannot be modified. Doing so can cause the subsequent DISFFC_CONTINUE command to fail to perform properly.

To abandon a pause and stop all effects, use the DISFFC_STOPALL or DISFCC_RESET commands.

DISFFC_RESET
The device's force-feedback system is to be put in its startup state. All effects are removed from the device, are no longer valid, and must be re-created if they are to be used again. The device's actuators are disabled.
DISFFC_SETACTUATORSOFF
The device's force-feedback actuators are to be disabled. While the actuators are off, effects continue to play but are ignored by the device. Using the analogy of a sound playback device, they are muted, rather than paused.
DISFFC_SETACTUATORSON
The device's force-feedback actuators are to be enabled.
DISFFC_STOPALL
Playback of any active effects is to be stopped. All active effects are reset, but are still being maintained by the device and are still valid. If the device is in a paused state, that state is lost. This command is equivalent to calling the IDirectInputEffect::Stop method for each effect playing.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INPUTLOST, DIERR_INVALIDPARAM, DIERR_NOTEXCLUSIVEACQUIRED, DIERR_NOTINITIALIZED, DIERR_UNSUPPORTED.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Note When calling IDirectInputDevice8::GetForceFeedbackState, it is possible for the state of the device returned not to match the expected state. This might happen if commands recently sent by IDirectInputDevice8::SendForceFeedbackCommand are still pending. Wait a short time and then check the device state again.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::SetActionMap

Sets the data format for a device and maps application-defined actions to device objects. It also sets the buffer size for buffered data.

HRESULT SetActionMap(
  LPCDIACTIONFORMAT lpdiActionFormat,
  LPCTSTR lptszUserName,
  DWORD dwFlags
);

Parameters

lpdiActionFormat
Address of a DIACTIONFORMAT structure containing information about the action map to be applied.
lptszUserName
Unicode string that specifies the name of the user for which the action map is being set. A value of NULL specifies the user currently logged into the system.
dwFlags
DWORD value that specifies how the action map is applied. This can be one of the following values.
DIDSAM_DEFAULT
Set the action map for this user. If the map differs from the current map, the new settings are saved to disk.
DIDSAM_FORCESAVE
Always save the configuration to disk.
DIDSAM_NOUSER
Reset user ownership for this device in the default configuration property sheet. Resetting user ownership does not remove the current action map.

Return Values

If the method succeeds, the return value can be one of the following error values: DI_OK, DI_SETTINGSNOTSAVED, or DI_WRITEPROTECT. If the method fails, the return value can be one of the following error values: DIERR_ACQUIRED or DIERR_INVALIDPARAM, DI_SETTINGSNOTSAVED, DI_WRITEPROTECT, DIERR_ACQUIRED, DIERR_INVALIDPARAM.

Remarks

This method provides the mechanism to change action-to-control mapping from the device defaults. An application must use this method to map its in-game actions to virtual controls.

The user name passed to this method binds a set of action mappings for a device to a specific user. Settings are automatically saved to disk when they differ from the currently applied map. Applications that accept input from multiple users should be very careful when applying action maps to the system mouse or keyboard, as the action maps for each user may conflict.

The method can be called only when the device is not acquired.

If IDirectInputDevice8::BuildActionMap succeeds but no actions have been mapped, a subsequent call to IDirectInputDevice8::SetActionMap will return DI_OK but a call to IDirectInputDevice8 Interface will fail with DIERR_INVALIDPARAM.

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::BuildActionMap


IDirectInputDevice8::SetCooperativeLevel

Establishes the cooperative level for this instance of the device. The cooperative level determines how this instance of the device interacts with other instances of the device and the rest of the system.

HRESULT SetCooperativeLevel(
  HWND hwnd,
  DWORD dwFlags
);

Parameters

hwnd
Window handle to be associated with the device. This parameter must be a valid top-level window handle that belongs to the process. The window associated with the device must not be destroyed while it is still active in a DirectInput device.
dwFlags
Flags that describe the cooperative level associated with the device. The following flags are defined:
DISCL_BACKGROUND
The application requires background access. If background access is granted, the device can be acquired at any time, even when the associated window is not the active window.
DISCL_EXCLUSIVE
The application requires exclusive access. If exclusive access is granted, no other instance of the device can obtain exclusive access to the device while it is acquired. However, nonexclusive access to the device is always permitted, even if another application has obtained exclusive access. An application that acquires the mouse or keyboard device in exclusive mode should always unacquire the devices when it receives WM_ENTERSIZEMOVE and WM_ENTERMENULOOP messages. Otherwise, the user cannot manipulate the menu or move and resize the window.
DISCL_FOREGROUND
The application requires foreground access. If foreground access is granted, the device is automatically unacquired when the associated window moves to the background.
DISCL_NONEXCLUSIVE
The application requires nonexclusive access. Access to the device does not interfere with other applications that are accessing the same device.
DISCL_NOWINKEY
Disable the Windows logo key. Setting this flag ensures that the user cannot inadvertently break out of the application. Note, however, that DISCL_NOWINKEY has no effect when the default action mapping user interface (UI) is displayed, and the Windows logo key will operate normally as long as that UI is present.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED, E_HANDLE.

Remarks

Applications must specify either DISCL_FOREGROUND or DISCL_BACKGROUND; it is an error to specify both or neither. Similarly, applications must specify either DISCL_EXCLUSIVE or DISCL_NONEXCLUSIVE.

If the system mouse is acquired in exclusive mode, the pointer is removed from the screen until the device is unacquired. This applies only to a mouse created by passing GUID_SysMouse to IDirectInput8::CreateDevice.

Applications that select the background exclusive mode cooperative level are not guaranteed to retain access to the device if another application requests exclusive access. When a background exclusive mode application loses access, calls to DirectInput device methods will fail and return DIERR_NOTACQUIRED. The application can regain access to the device by manually unacquiring the device and reaquiring it.

Applications must call this method before acquiring the device by using the IDirectInputDevice8 Interface method.

Requirements

Header: Declared in Dinput.h.

See Also

Cooperative Levels


IDirectInputDevice8::SetDataFormat

Sets the data format for the DirectInput device.

HRESULT SetDataFormat(
  LPCDIDATAFORMAT lpdf
);

Parameters

lpdf
Address of a structure that describes the format of the data that the DirectInputDevice should return. An application can define its own DIDATAFORMAT structure or use one of the following predefined global variables:
  • c_dfDIKeyboard
  • c_dfDIMouse
  • c_dfDIMouse2
  • c_dfDIJoystick
  • c_dfDIJoystick2

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_ACQUIRED, DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED.

Remarks

The data format must be set before the device can be acquired by using the IDirectInputDevice8 Interface method. It is necessary to set the data format only once. The data format cannot be changed while the device is acquired.

If the application is using action mapping, the data format is set instead by the call to IDirectInputDevice8::SetActionMap.

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::GetDeviceState


IDirectInputDevice8::SetEventNotification

Specifies an event that is to be set when the device state changes. It is also used to turn off event notification.

HRESULT SetEventNotification(
  HANDLE hEvent
);

Parameters

hEvent
Handle to the event that is to be set when the device state changes. DirectInput uses the Microsoft Win32 SetEvent function on the handle when the state of the device changes. If the hEvent parameter is NULL, notification is disabled.

The application can create the handle as either a manual-reset or autoreset event by using the Win32 CreateEvent function. If the event is created as an autoreset event, the operating system automatically resets the event when a wait has been satisfied. If the event is created as a manual-reset event, it is the application's responsibility to call the Win32 ResetEvent function to reset it. DirectInput does not call the Win32 ResetEvent function for event notification handles. Most applications create the event as an automatic-reset event.

Return Values

If the method succeeds, the return value is DI_OK or DI_POLLEDDEVICE. If the method fails, the return value can be one of the following error values: DIERR_ACQUIRED, DIERR_HANDLEEXISTS, DIERR_INVALIDPARAM, DIERR_NOTINITIALIZED.

Remarks

A device state change is defined as any of the following:

  • A change in the position of an axis
  • A change in the state (pressed or released) of a button
  • A change in the direction of a POV control
  • Loss of acquisition

Do not call the Win32 CloseHandle function on the event while it has been selected into a DirectInputDevice object. You must call this method with the hEvent parameter set to NULL before closing the event handle.

The event notification handle cannot be changed while the device is acquired. If the function is successful, the application can use the event handle like any other Win32 event handle.

Examples

The following code example checks whether the handle is currently set without blocking:

dwResult = WaitForSingleObject(hEvent, 0);
if (dwResult == WAIT_OBJECT_0) {
    // Event is set. If the event was created as
    // autoreset, it has also been reset.
}

The following code example illustrates blocking indefinitely until the event is set. This behavior is strongly discouraged because the thread does not respond to the system until the wait is satisfied. In particular, the thread does not respond to Microsoft Windows messages.

dwResult = WaitForSingleObject(hEvent, INFINITE);
if (dwResult == WAIT_OBJECT_0) {
    // Event has been set. If the event was created
    // as autoreset, it has also been reset.
}

The following code example illustrates a typical application loop for a non-message-based application that uses two events:

HANDLE ah[2] = { hEvent1, hEvent2 };

while (TRUE) {

    dwResult = MsgWaitForMultipleObjects(2, ah, FALSE,
                        INFINITE, QS_ALLINPUT);
    switch (dwResult) {
    case WAIT_OBJECT_0:
        // Event 1 has been set. If the event was created as
        // autoreset, it has also been reset.
        ProcessInputEvent1();
        break;

    case WAIT_OBJECT_0 + 1:
        // Event 2 has been set. If the event was created as
        // autoreset, it has also been reset.
        ProcessInputEvent2();
        break;

    case WAIT_OBJECT_0 + 2:
        // A Windows message has arrived. Process
        // messages until there aren't any more.
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
            if (msg.message == WM_QUIT) {
                goto exitapp;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        break;

    default:
        // Unexpected error.
        Panic();
        break;
    }
}

The following code example illustrates a typical message loop for a message-based application that uses two events:

HANDLE ah[2] = { hEvent1, hEvent2 };
DWORD dwWait = 0;

while (TRUE) {

    dwResult = MsgWaitForMultipleObjects(2, ah, FALSE,
                                         dwWait, QS_ALLINPUT);
    dwWait = 0;

    switch (dwResult) {
    case WAIT_OBJECT_0:
        // Event 1 has been set. If the event was
        // created as autoreset, it has also
        // been reset.
        ProcessInputEvent1();
        break;

    case WAIT_OBJECT_0 + 1:
        // Event 2 has been set. If the event was
        // created as autoreset, it has also
        // been reset.
        ProcessInputEvent2();
        break;

    case WAIT_OBJECT_0 + 2:
        // A Windows message has arrived. Process
        // messages until there aren't any more.
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
            if (msg.message == WM_QUIT) {
                goto exitapp;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        break;

    default:
        // No input or messages waiting.
        // Do a frame of the game.
        // If the game is idle, tell the next wait
        // to wait indefinitely for input or a message.
        if (!DoGame()) {
            dwWait = INFINITE;
        }
        break;
    }
}

Requirements

Header: Declared in Dinput.h.

See Also

Polling and Event Notification


IDirectInputDevice8::SetProperty

Sets properties that define the device behavior. These properties include input buffer size and axis mode.

HRESULT SetProperty(
  REFGUID rguidProp,
  LPCDIPROPHEADER pdiph
);

Parameters

rguidProp
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the property to be set. This can be one of the predefined values, or a pointer to a GUID that identifies the property. The following property values are predefined for an input device:
DIPROP_APPDATA
Sets the application-defined value associated with an in-game action, as a DIPROPPOINTER.
DIPROP_AUTOCENTER

Specifies whether device objects are self centering. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member can be one of the following values.

DIPROPAUTOCENTER_OFF: The device should not automatically center when the user releases the device. An application that uses force feedback should disable autocentering before playing effects.

DIPROPAUTOCENTER_ON: The device should automatically center when the user releases the device.

Not all devices support the autocenter property.

DIPROP_AXISMODE
Sets the axis mode. The value being set (DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL) must be specified in the dwData member of the associated DIPROPDWORD structure. See the description of the pdiph parameter for more information. This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.
DIPROP_BUFFERSIZE
Sets the input buffer size. The value being set must be specified in the dwData member of the associated DIPROPDWORD structure. See Remarks. This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.
DIPROP_CALIBRATION

Predefined property that allows the application to access the information that DirectInput uses to manipulate axes that require calibration. This property exists primarily for applications of the control panel type. Normal applications should not need to deal with calibration information.

You can access the calibration mode property for an axis by setting the dwHow member of the DIPROPHEADER structure to DIPH_BYID or to DIPH_BYOFFSET and setting the dwObj member to the object ID or offset, respectively.

Control panel applications that set new calibration data must also invoke the IDirectInputJoyConfig::SendNotify method to notify other applications of the change in calibration. For more information about IDirectInputJoyConfig::SendNotify, see the DirectX Driver Development Kit (DDK).

DIPROP_CALIBRATIONMODE

Enables the application to specify whether DirectInput should retrieve calibrated or uncalibrated data from an axis. By default, DirectInput retrieves calibrated data.

Setting the calibration mode for the entire device is equivalent to setting it for each axis individually.

The dwData member of the DIPROPDWORD structure can be one of the following values:

DIPROPCALIBRATIONMODE_COOKED: DirectInput should return data after applying calibration information. This is the default mode.

DIPROPCALIBRATIONMODE_RAW: DirectInput should return raw, uncalibrated data. This mode is typically used only by applications of the control panel type. Note that raw data might include negative values.

Setting a device into raw mode causes the dead zone, saturation, and range settings to be ignored.

DIPROP_CPOINTS
This property is unsupported. Sets calibration points used for the adjustment of incoming raw data. The values being set must be specified as CPOINT types in the cp array of the associated DIPROPCPOINTS structure. This setting applies to individual device objects, so the dwHow member of the associated DIPROPHEADER structure must be set to either DIPH_BYID or DIPH_BYOFFSET.
DIPROP_DEADZONE
Sets the value for the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range. This setting can be applied to either the entire device or to a specific axis.
DIPROP_FFGAIN
Sets the gain for the device. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member contains a gain value that is applied to all effects created on the device. The value is an integer in the range from 0 through 10,000, specifying the amount by which effect magnitudes should be scaled for the device. For example, a value of 10,000 indicates that all effect magnitudes are to be taken at face value. A value of 9,000 indicates that all effect magnitudes are to be reduced to 90 percent of their nominal magnitudes.

DirectInput always checks the gain value before setting the gain property. If the gain is outside of the range (less than zero or greater than 10,000), IDirectInputDevice8::SetProperty will return DIERR_INVALIDPARAM. Otherwise, if successful, it will return DI_OK, even if the device does not support force feedback.

Setting a gain value is useful when an application wants to scale down the strength of all force-feedback effects uniformly, based on user preferences.

Unlike other properties, the gain can be set when the device is in an acquired state.

DIPROP_INSTANCENAME

This property exists for advanced applications that want to change the friendly instance name of a device (as returned in the tszInstanceName member of the DIDEVICEINSTANCE structure) to distinguish it from similar devices that are plugged in simultaneously. Most applications should have no need to change the friendly name.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

The pdiph parameter must be a pointer to the diph member of a DIPROPSTRING structure.

DIPROP_PRODUCTNAME

This property exists for advanced applications that want to change the friendly product name of a device (as returned in the tszProductName member of the DIDEVICEINSTANCE structure) to distinguish it from similar devices which are plugged in simultaneously. Most applications should have no need to change the friendly name.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

The pdiph parameter must be a pointer to the diph member of a DIPROPSTRING structure.

Setting the product name is only useful for changing the user-defined name of an analog joystick on Microsoft Windows 98, Windows 2000, and Windows Millennium Edition (Windows Me) computers. In other cases, attempting to set this property will still return DI_OK. However, the name is not stored in a location used by IDirectInputDevice8::GetProperty.

DIPROP_RANGE
Sets the range of values an object can possibly report. The minimum and maximum values are taken from the lmin and lmax members of the associated DIPROPRANGE structure.

For some devices, this is a read-only property.

You cannot set a reverse range; lmax must be greater than lmin.

DIPROP_SATURATION
Sets the value for the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone). This setting can be applied to either the entire device or a specific axis.
pdiph
Address of the DIPROPHEADER structure contained within the type-specific property structure.

Return Values

If the method succeeds, the return value is DI_OK or DI_PROPNOEFFECT. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM DIERR_NOTINITIALIZED, DIERR_OBJECTNOTFOUND, DIERR_UNSUPPORTED.

Remarks

The buffer size determines the amount of data that the buffer can hold between calls to the IDirectInputDevice8::GetDeviceData method before data is lost. This value may be set to 0 to indicate that the application does not read buffered data from the device. If the buffer size in the dwData member of the DIPROPDWORD structure is too large for the device to support it, then the largest possible buffer size is set.

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::GetProperty


IDirectInputDevice8::Unacquire

Releases access to the device.

HRESULT Unacquire();

Parameters

None.

Return Values

The return value is DI_OK is the device was unacquired, or DI_NOEFFECT if the device was not in an acquired state.

Requirements

Header: Declared in Dinput.h.


IDirectInputDevice8::WriteEffectToFile

Saves information about one or more force-feedback effects to a file that can be read by using IDirectInputDevice8::EnumEffectsInFile. This method is chiefly of interest to those wanting to write their own force-authoring applications.

HRESULT WriteEffectToFile(
  LPCSTR lpszFileName,
  DWORD dwEntries,
  LPCDIFILEEFFECT rgDiFileEft,
  DWORD dwFlags
);

Parameters

lpszFileName
Name of the RIFF file.
dwEntries
Number of structures in the rgDiFileEft array.
rgDiFileEft
Array of DIFILEEFFECT structures.
dwFlags
Flags which control how the effect should be written. This can be DIFEF_DEFAULT (= 0) or the following value:
DIFEF_INCLUDENONSTANDARD
Includes effects that are not defined by DirectInput. If this flag is not specified, only effects with GUIDs defined in Dinput.h, such as GUID_ConstantForce, are written.

Return Values

If the method succeeds, it returns DI_OK. If it fails, the return value can be DIERR_INVALIDPARAM.

Requirements

Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::EnumEffectsInFile


IDirectInputEffect Interface

Applications use the methods of the IDirectInputEffect interface to manage effects of force-feedback devices.

IDirectInputEffect Members

Method | Description
IDirectInputEffect::Download | Places the effect on the device.
IDirectInputEffect::Escape | Sends a hardware-specific command to the driver.
IDirectInputEffect::GetEffectGuid | Retrieves the globally unique identifier (GUID) for the effect represented by the IDirectInputEffect Interface object.
IDirectInputEffect::GetEffectStatus | Retrieves the status of an effect.
IDirectInputEffect::GetParameters | Retrieves information about an effect.
IDirectInputEffect::Initialize | Initializes a DirectInputEffect object.
IDirectInputEffect::SetParameters | Sets the characteristics of an effect.
IDirectInputEffect::Start | Begins playing an effect.
IDirectInputEffect::Stop | Stops playing an effect.
IDirectInputEffect::Unload | Removes the effect from the device.

Remarks

The interface is obtained by using the IDirectInputDevice8::CreateEffect method.

The LPDIRECTINPUTEFFECT type is defined as a pointer to the IDirectInputEffect interface:

typedef struct IDirectInputEffect    *LPDIRECTINPUTEFFECT;


IDirectInputEffect::Download

Places the effect on the device. If the effect is already on the device, the existing effect is updated to match the values set by the IDirectInputEffect::SetParameters method.

HRESULT Download();

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK or S_FALSE. If the method fails, the return value can be one of the following error values: DIERR_DEVICEFULL, DIERR_EFFECTPLAYING, DIERR_INCOMPLETEEFFECT, DIERR_INPUTLOST, DIERR_INVALIDPARAM, DIERR_NOTEXCLUSIVEACQUIRED, DIERR_NOTINITIALIZED.

Remarks

If the method returns S_FALSE, the effect has already been downloaded to the device.

It is valid to update an effect while it is playing. The semantics of such an operation are explained in the reference for IDirectInputEffect::SetParameters.

Requirements

Header: Declared in Dinput.h.


IDirectInputEffect::Escape

Sends a hardware-specific command to the driver.

HRESULT Escape(
  LPDIEFFESCAPE pesc
);

Parameters

pesc
DIEFFESCAPE structure that describes the command to be sent. On success, the cbOutBuffer member contains the number of bytes of the output buffer used.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_NOTINITIALIZED, DIERR_DEVICEFULL.

Remarks

Other device-specific error codes are also possible. Ask the hardware manufacturer for details.

Because each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the DIDEVICEINSTANCE structure against the value the application is expecting.

Requirements

Header: Declared in Dinput.h.


IDirectInputEffect::GetEffectGuid

Retrieves the globally unique identifier (GUID) for the effect represented by the IDirectInputEffect Interface object.

HRESULT GetEffectGuid(
  LPGUID pguid
);

Parameters

pguid
GUID structure that is filled by the method.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM DIERR_NOTINITIALIZED

Remarks

Additional information about the effect can be obtained by passing the GUID to IDirectInputDevice8::GetEffectInfo.

Requirements

Header: Declared in Dinput.h.


IDirectInputEffect::GetEffectStatus

Retrieves the status of an effect.

HRESULT GetEffectStatus(
  LPDWORD pdwFlags
);

Parameters

pdwFlags
Status flags for the effect. The value can be 0 or one or more of the following constants:
DIEGES_PLAYING
The effect is playing.
DIEGES_EMULATED
The effect is emulated.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM DIERR_NOTINITIALIZED

Requirements

Header: Declared in Dinput.h.


IDirectInputEffect::GetParameters

Retrieves information about an effect.

HRESULT GetParameters(
  LPDIEFFECT peff,
  DWORD dwFlags
);

Parameters

peff
Address of a DIEFFECT structure that receives effect information. The dwSize member must be filled in by the application before calling this method.
dwFlags
Flags that specify which parts of the effect information are to be retrieved. The value can be 0 or one or more of the following constants:
DIEP_ALLPARAMS
The union of all other DIEP_* flags, indicating that all members of the DIEFFECT structure are being requested.
DIEP_ALLPARAMS_DX5
The union of all other DIEP_* flags except the DIEP_STARTDELAY flag.
DIEP_AXES
The cAxes and rgdwAxes members should receive data. The cAxes member on entry contains the size (in DWORD) of the buffer pointed to by the rgdwAxes member. If the buffer is too small, the method returns DIERR_MOREDATA and sets cAxes to the necessary size of the buffer.
DIEP_DIRECTION
The cAxes and rglDirection members should receive data. The cAxes member on entry contains the size (in DWORD) of the buffer pointed to by the rglDirection member. If the buffer is too small, the IDirectInputEffect::GetParameters method returns DIERR_MOREDATA and sets cAxes to the necessary size of the buffer. The dwFlags member must include at least one of the coordinate system flags (DIEFF_CARTESIAN, DIEFF_POLAR, or DIEFF_SPHERICAL). DirectInput returns the direction of the effect in one of the coordinate systems you specified, converting between coordinate systems as necessary. On exit, exactly one of the coordinate system flags is set in the dwFlags member, indicating which coordinate system DirectInput used. In particular, passing all three coordinate system flags retrieves the coordinates in exactly the same format in which they were set.
DIEP_DURATION
The dwDuration member should receive data.
DIEP_ENVELOPE
The lpEnvelope member points to a DIENVELOPE structure that should receive data. If the effect does not have an envelope associated with it, the lpEnvelope member is set to NULL.
DIEP_GAIN
The dwGain member should receive data.
DIEP_SAMPLEPERIOD
The dwSamplePeriod member should receive data.
DIEP_STARTDELAY
The dwStartDelay member should receive data.
DIEP_TRIGGERBUTTON
The dwTriggerButton member should receive data.
DIEP_TRIGGERREPEATINTERVAL
The dwTriggerRepeatInterval member should receive data.
DIEP_TYPESPECIFICPARAMS
The lpvTypeSpecificParams member points to a buffer whose size is specified by the cbTypeSpecificParams member. On return, the buffer is filled in with the type-specific data associated with the effect, and the cbTypeSpecificParams member contains the number of bytes copied. If the buffer supplied by the application is too small to contain all the type-specific data, the method returns DIERR_MOREDATA, and the cbTypeSpecificParams member contains the required size of the buffer in bytes.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INVALIDPARAM, DIERR_MOREDATA, DIERR_NOTINITIALIZED.

Remarks

Common errors resulting in a DIERR_INVALIDPARAM error include not setting the dwSize member of the DIEFFECT structure, passing invalid flags, or not setting up the members in the DIEFFECT structure properly in preparation for receiving the effect information. For example, if information is to be retrieved in the dwTriggerButton member, the dwFlags member must be set to either DIEFF_OBJECTIDS or DIEFF_OBJECTOFFSETS so that DirectInput knows how to describe the button.

Requirements

Header: Declared in Dinput.h.


IDirectInputEffect::Initialize

Initializes a DirectInputEffect object.

HRESULT Initialize(
  HINSTANCE hinst,
  DWORD dwVersion,
  REFGUID rguid
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInputEffect object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility. It is an error for a DLL to pass the handle to the parent application.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.
rguid
Address of the globally unique identifier (GUID) identifying the effect with which the interface is associated. The IDirectInputDevice8::EnumEffects method can be used to determine which effect GUIDs are supported by the device.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be DIERR_DEVICENOTREG.

Remarks

If this method fails, the underlying object should be considered to be an indeterminate state and needs to be reinitialized before it can be subsequently used.

If this method succeeds, all effect parameters will be invalid. You must call IDirectInputEffect::SetParameters before an effect can be downloaded or started.

The IDirectInputDevice8::CreateEffect method automatically initializes the effect after creating it. Applications normally do not need to call the IDirectInputEffect::Initialize method.

Requirements

Header: Declared in Dinput.h.


IDirectInputEffect::SetParameters

Sets the characteristics of an effect.

HRESULT SetParameters(
  LPCDIEFFECT peff,
  DWORD dwFlags
);

Parameters

peff
DIEFFECT structure that contains effect information. The dwSize member must be filled in by the application before calling this method, as well as any members specified by corresponding bits in the dwFlags parameter.
dwFlags
Flags that specify which portions of the effect information are to be set and how the downloading of the parameters should be handled. The value can be 0 or one or more of the following constants:
DIEP_AXES
The cAxes and rgdwAxes members contain data.
DIEP_DIRECTION
The cAxes and rglDirection members contain data. The dwFlags member specifies (with DIEFF_CARTESIAN or DIEFF_POLAR) the coordinate system in which the values should be interpreted.
DIEP_DURATION
The dwDuration member contains data.
DIEP_ENVELOPE
The lpEnvelope member points to a DIENVELOPE structure that contains data. To detach any existing envelope from the effect, pass this flag and set the lpEnvelope member to NULL.
DIEP_GAIN
The dwGain member contains data.
DIEP_NODOWNLOAD
Suppress the automatic IDirectInputEffect::Download that is normally performed after the parameters are updated. See Remarks.
DIEP_NORESTART
Suppress the stopping and restarting of the effect to change parameters. See Remarks.
DIEP_SAMPLEPERIOD
The dwSamplePeriod member contains data.
DIEP_START
The effect is to be started (or restarted if it is currently playing) after the parameters are updated. By default, the play state of the effect is not altered.
DIEP_STARTDELAY
The dwStartDelay member contains data.
DIEP_TRIGGERBUTTON
The dwTriggerButton member contains data.
DIEP_TRIGGERREPEATINTERVAL
The dwTriggerRepeatInterval member contains data.
DIEP_TYPESPECIFICPARAMS
The lpvTypeSpecificParams and cbTypeSpecificParams members of the DIEFFECT structure contain the address and size of type-specific data for the effect.

Return Values

If the method succeeds, the return value can be DI_DOWNLOADSKIPPED, DI_EFFECTRESTARTED, DI_OK, DI_TRUNCATED, or DI_TRUNCATEDANDRESTARTED. If the method fails, the return value can be DIERR_NOTINITIALIZED, DIERR_INCOMPLETEEFFECT, DIERR_INPUTLOST, DIERR_INVALIDPARAM, or DIERR_EFFECTPLAYING, DI_DOWNLOADSKIPPED, DI_EFFECTRESTARTED.

Remarks

The dwDynamicParams member of the DIEffectInfo structure for the effect specifies which parameters can be dynamically updated while the effect is playing.

The IDirectInputEffect::SetParameters method automatically downloads the effect, but this behavior can be suppressed by setting the DIEP_NODOWNLOAD flag. If automatic download has been suppressed, you can manually download the effect by invoking the IDirectInputEffect::Download method.

If the effect is playing while the parameters are changed, the new parameters take effect as if they were the parameters when the effect started.

For example, suppose a periodic effect with a duration of three seconds is started. After two seconds, the direction of the effect is changed. The effect then continues for one additional second in the new direction. The envelope, phase, amplitude, and other parameters of the effect continue smoothly, as if the direction had not changed.

In the same situation, if after two seconds the duration of the effect were changed to 1.5 seconds, the effect would stop.

Normally, if the driver cannot update the parameters of a playing effect, the driver is permitted to stop the effect, update the parameters, and then restart the effect. Passing the DIEP_NORESTART flag suppresses this behavior. If the driver cannot update the parameters of an effect while it is playing, the error code DIERR_EFFECTPLAYING is returned, and the parameters are not updated.

No more than one of the DIEP_NODOWNLOAD, DIEP_START, and DIEP_NORESTART flags should be set. (It is also valid to pass none of them.)

These three flags control download and playback behavior as follows:

If DIEP_NODOWNLOAD is set, the effect parameters are updated but not downloaded to the device.

If the DIEP_START flag is set, the effect parameters are updated and downloaded to the device, and the effect is started just as if the IDirectInputEffect::Start method had been called with the dwIterations parameter set to 1 and with no flags. (Combining the update with DIEP_START is slightly faster than calling IDirectInputEffect::Start separately, because it requires less information to be transmitted to the device.)

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is not playing, the parameters are updated and downloaded to the device.

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is playing, the parameters are updated if the device supports on-the-fly updating. Otherwise the behavior depends on the state of the DIEP_NORESTART flag. If it is set, the error code DIERR_EFFECTPLAYING is returned. If it is clear, the effect is stopped, the parameters are updated, and the effect is restarted.

Requirements

Header: Declared in Dinput.h.


IDirectInputEffect::Start

Begins playing an effect. If the effect is already playing, it is restarted from the beginning. If the effect has not been downloaded or has been modified since its last download, it is downloaded before being started. This default behavior can be suppressed by passing the DIES_NODOWNLOAD flag.

HRESULT Start(
  DWORD dwIterations,
  DWORD dwFlags
);

Parameters

dwIterations
Number of times to play the effect in sequence. The envelope is re-articulated with each iteration. To play the effect exactly once, pass 1. To play the effect repeatedly until explicitly stopped, pass INFINITE. To play the effect until explicitly stopped without re-articulating the envelope, modify the effect parameters with the IDirectInputEffect::SetParameters method, and change the dwDuration member to INFINITE.
dwFlags
Flags that describe how the effect should be played by the device. The value can be 0 or one or more of the following values:
DIES_SOLO
All other effects on the device should be stopped before the specified effect is played. If this flag is omitted, the effect is mixed with existing effects already started on the device.
DIES_NODOWNLOAD
Do not automatically download the effect.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INCOMPLETEEFFECT, DIERR_INVALIDPARAM, DIERR_NOTEXCLUSIVEACQUIRED, DIERR_NOTINITIALIZED, DIERR_UNSUPPORTED.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Not all devices support multiple iterations.

Requirements

Header: Declared in Dinput.h.


IDirectInputEffect::Stop

Stops playing an effect.

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_NOTEXCLUSIVEACQUIRED, DIERR_NOTINITIALIZED.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Requirements

Header: Declared in Dinput.h.


IDirectInputEffect::Unload

Removes the effect from the device. If the effect is playing, it is automatically stopped before it is unloaded.

HRESULT Unload();

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK. If the method fails, the return value can be one of the following error values: DIERR_INPUTLOST, DIERR_INVALIDPARAM, DIERR_NOTEXCLUSIVEACQUIRED, DIERR_NOTINITIALIZED.

Requirements

Header: Declared in Dinput.h.


Callback Functions

This section describes the seven functions that are prototype callback functions for use with various enumeration methods. Applications can declare one of these callback functions under any name and define it in any way, but the parameter and return types must be the same as in the prototype.

  • DIConfigureDevicesCallback
  • DIEnumCreatedEffectObjectsCallback
  • DIEnumDeviceObjectsCallback
  • DIEnumDevicesBySemanticsCallback
  • DIEnumDevicesCallback
  • DIEnumEffectsCallback
  • DIEnumEffectsInFileCallback


DIConfigureDevicesCallback

Application-defined callback function that is called each time the property sheet image is refreshed. This function needs to be supplied only when the application is displaying the property sheet within its own window.

BOOL DIConfigureDevicesCallback(
  IUnknown * lpDDSTarget,
  LPVOID pvRef
);

Parameters

lpDDSTarget
Pointer to the IUnknown interface of the surface in the lpUnkDDSTarget member of the DICONFIGUREDEVICESPARAMS structure that was passed to IDirectInput8::ConfigureDevices.
pvRef
Application-defined value passed to IDirectInput8::ConfigureDevices as the pvRef parameter.

Return Values

Can return TRUE or FALSE. DirectInput does not use the return value.

Requirements

Header: Declared in Dinput.h.


DIEnumCreatedEffectObjectsCallback

Application-defined callback function that receives DirectInputDevice effects as a result of a call to the IDirectInputDevice8::EnumCreatedEffectObjects method.

BOOL DIEnumCreatedEffectObjectsCallback(
  LPDIRECTINPUTEFFECT peff,
  LPVOID pvRef
);

Parameters

peff
The address of an effect object that has been created.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumCreatedEffectObjects as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Requirements

Header: Declared in Dinput.h.


DIEnumDeviceObjectsCallback

Application-defined callback function that receives DirectInputDevice objects as a result of a call to the IDirectInputDevice8::EnumObjects method.

BOOL DIEnumDeviceObjectsCallback(
  LPCDIDEVICEOBJECTINSTANCE lpddoi,
  LPVOID pvRef
);

Parameters

lpddoi
DIDEVICEOBJECTINSTANCE structure that describes the object being enumerated.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumObjects as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Requirements

Header: Declared in Dinput.h.


DIEnumDevicesBySemanticsCallback

Application-defined callback function that receives DirectInput devices as a result of a call to the IDirectInput8::EnumDevicesBySemantics method.

BOOL DIEnumDevicesBySemanticsCallback(
  LPCDIDEVICEINSTANCE lpddi,
  LPDIRECTINPUTDEVICE8 lpdid,
  DWORD dwFlags,
  DWORD dwRemaining,
  LPVOID pvRef
);

Parameters

lpddi
Address of a DIDEVICEINSTANCE structure that describes the device instance.
lpdid
Pointer to the IDirectInputDevice8 Interface interface for the device.
dwFlags

Flags that provide information about why the device is being enumerated. This can be a combination of action-mapping flags and one usage flag. At least one action-mapping flag is always present.

The DIEDBS_MAPPEDPRI1 and DIEDBS_MAPPEDPRI2 action-mapping flags and the DIEDBS_RECENTDEVICE and DIEDBS_NEWDEVICE usage flags are defined below.

DIEDBS_MAPPEDPRI1
The device is being enumerated because priority 1 actions can be mapped to the device.
DIEDBS_MAPPEDPRI2
The device is being enumerated because priority 2 actions can be mapped to the device.
DIEDBS_RECENTDEVICE
The device is being enumerated because the commands described by the action-mapping flags were recently used.
DIEDBS_NEWDEVICE
The device is being enumerated because the device was installed recently. Devices described by this flag have not been used with this game before.
dwRemaining
Number of devices, after this one, remaining to be enumerated.
pvRef
The application-defined value passed to IDirectInput8::EnumDevicesBySemantics as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Remarks

If a single hardware device can function as more than one DirectInput device type, it is enumerated as each device type that it supports. For example, a keyboard with a built-in mouse is enumerated twice: once as a keyboard and once as a mouse. The product globally unique identifier (GUID) is the same for each device, however.

Requirements

Header: Declared in Dinput.h.

See Also

DIEnumDevicesCallback


DIEnumDevicesCallback

Application-defined callback function that receives DirectInput devices as a result of a call to the IDirectInput8::EnumDevices method.

BOOL DIEnumDevicesCallback(
  LPCDIDEVICEINSTANCE lpddi,
  LPVOID pvRef
);

Parameters

lpddi
Address of a DIDEVICEINSTANCE structure that describes the device instance.
pvRef
The application-defined value passed to IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Remarks

If a single hardware device can function as more than one DirectInput device type, it is enumerated as each device type that it supports. For example, a keyboard with a built-in mouse is enumerated twice: once as a keyboard and once as a mouse. The product globally unique identifier (GUID) is the same for each device, however.

Requirements

Header: Declared in Dinput.h.

See Also

DIEnumDevicesBySemanticsCallback


DIEnumEffectsCallback

Application-defined callback function used with the IDirectInputDevice8::EnumEffects method.

BOOL DIEnumEffectsCallback(
  LPCDIEffectInfo pdei,
  LPVOID pvRef
);

Parameters

pdei
DIEffectInfo structure that describes the enumerated effect.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumEffects as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration, or DIENUM_STOP to stop it.

Requirements

Header: Declared in Dinput.h.


DIEnumEffectsInFileCallback

Application-defined callback function used with the IDirectInputDevice8::EnumEffectsInFile method.

BOOL DIEnumEffectsInFileCallback(
  LPCDIFILEEFFECT lpDiFileEf,
  LPVOID pvRef
);

Parameters

lpDiFileEf
DIFILEEFFECT structure that describes the enumerated effect.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumEffectsInFile as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration, or DIENUM_STOP to stop it.

Requirements

Header: Declared in Dinput.h.


DirectInput Functions

This section is a reference for DirectInput functions other than COM interface methods and callback functions.

  • DirectInput8Create
  • ShowJoyCPL


DirectInput8Create

Creates a DirectInput object and returns an IDirectInput8 Interface or later interface.

HRESULT DirectInput8Create(
  HINSTANCE hinst,
  DWORD dwVersion,
  REFIID riidltf,
  LPVOID * ppvOut,
  LPUNKNOWN punkOuter
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility. It is an error for a DLL to pass the handle to the parent application. For example, an Microsoft ActiveX control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. If the application defines DIRECTINPUT_VERSION before including Dinput.h, the value must be greater than 0x0800. For earlier versions, use DirectInputCreateEx, which is in Dinput.lib.
riidltf
Unique identifier of the desired interface. This value is IID_IDirectInput8A or IID_IDirectInput8W. Passing the IID_IDirectInput8 define selects the ANSI or Unicode version of the interface, depending on whether UNICODE is defined during compilation.
ppvOut
Address of a pointer to a variable to receive the interface pointer if the call succeeds.
punkOuter
Pointer to the address of the controlling object's IUnknown interface for COM aggregation, or NULL if the interface is not aggregated. Most calling applications pass NULL. If aggregation is requested, the object returned in ppvOut is a pointer to IUnknown, as required by COM aggregation.

Return Values

If the function succeeds, the return value is DI_OK. If the function fails, the return value can be one of the following error values: DIERR_BETADIRECTINPUTVERSION, DIERR_INVALIDPARAM, DIERR_OLDDIRECTINPUTVERSION, DIERR_OUTOFMEMORY.

Remarks

The DirectInput object created by this function is implemented in Dinput8.dll. Versions of interfaces earlier than DirectX 8.0 cannot be obtained in this implementation.

To create a DirectX 8.x interface with the latest DirectX SDK without using CoCreateInstance:

  1. Set "#define DIRECTINPUT_VERSION 0x0800" before the include statement for Dinput8.h.
  2. Call DirectInput8Create instead of DirectInputCreateEx.
  3. Link to the Dinput8.lib library instead of Dinput.lib.

To create a DirectX 8.x interface with the DirectX 8.x SDK without using CoCreateInstance:

  1. Call DirectInput8Create instead of DirectInputCreateEx.
  2. Link to the Dinput8.lib library instead of Dinput.lib.

To create a DirectX 7.0 interface from the DirectX 8.x or latest DirectX SDK without using CoCreateInstance:

  1. Set "#define DIRECTINPUT_VERSION 0x0700" before the include statement for dinput.h.
  2. Call DirectInputCreateEx instead of DirectInput8Create.
  3. Link to the Dinput.lib library instead of Dinput8.lib.

To create a DirectX 7.0 interface from the DirectX 8.x or latest DirectX SDK using CoCreateInstance:

  1. Call CoInitializeEx.
  2. Call CoCreateInstance using CLISID_DirectInput.
  3. Use IDirectInput7::Initialize to initialize the DirectInput object.

To create a DirectX 8.x or DirectX 9.0 interface from the DirectX 8.x or latest DirectX SDK using CoCreateInstance:

  1. Call CoInitializeEx.
  2. Call CoCreateInstance using CLISID_DirectInput8.
  3. Use IDirectInput8::Initialize to initialize the DirectInput object.

Calling the function with pUnkOuter = NULL is equivalent to creating the object through CoCreateInstance( &CLSID_DirectInput8, punkOuter, CLSCTX_INPROC_SERVER, &IID_IDirectInput8W, lplpDirectInput), then initializing it with IDirectInput8::Initialize.

Calling the function with pUnkOuter != NULL is equivalent to creating the object through CoCreateInstance( &CLSID_DirectInput8, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInput). The aggregated object must be initialized manually.

Requirements

Header: Declared in Dinput.h.


ShowJoyCPL

Invokes the joystick control panel directly, using the passed window handle as the parent of the dialog box.

VOID ShowJoyCPL(
  HWND hWnd
);

Parameters

hWnd
Window handle of the parent dialog box.

Return Values

None.

Remarks

It is recommended that applications use IDirectInputDevice8::RunControlPanel instead of ShowJoyCPL.

The following typedef is provided to allow declaration and casting of an appropriately typed variable.

typedef void (WINAPI* LPFNSHOWJOYCPL)( HWND hWnd );
Example

ShowJoyCPL can be called using the function pointer returned by GetProcAddress, where hCPL is an HMODULE returned by LoadLibrary.

HMODULE hCPL;
LPFNSHOWJOYCPL pShowJoyCPL;
.
.
.
hCPL = LoadLibrary(TEXT("joy.cpl"));
pShowJoyCPL  = (LPFNSHOWJOYCPL)GetProcAddress(hCPL, TEXT("ShowJoyCPL"));

pShowJoyCPL(NULL);  //Invoke Joystick Control Panel

Requirements

Header: Declared in Dinput.h.


Macros

This section describes the macros used in Microsoft DirectInput.

Macros

  • DIDFT_GETINSTANCE
  • DIDFT_GetType
  • DIDFT_MAKEINSTANCE
  • DIDFT_GETTYPE
  • DIMAKEUSAGEDWORD
  • DISEQUENCE_COMPARE
  • GET_DIDEVICE_SUBTYPE
  • GET_DIDEVICE_TYPE

Dinput.h also defines macros for C calls to all the methods of the IDirectInput8 Interface and IDirectInputDevice8 Interface interfaces. These macros eliminate the need for pointers to method tables. For example, the following is a C call to the IDirectInputDevice8::Release method.

lpdid->lpVtbl->Release(lpdid));

The equivalent macro call looks like this.

idirectinputdevice9_Release(lpdid);

All these macros take the same parameters as the method calls themselves.


DIDFT_GETINSTANCE

The DIDFT_GETINSTANCE macro extracts the object instance number code from a data format type.

#define DIDFT_GETINSTANCE(n) LOWORD((n) >> 8)

Parameters

n
Type is DWORD. DirectInput data format type. The possible values for this parameter are identical to those found in the dwType member of the DIOBJECTDATAFORMAT structure.

See Also

DIDFT_MAKEINSTANCE, DIDFT_GetType


DIDFT_GetType

The DIDFT_GetType macro extracts the object type code from a data format type.

#define DIDFT_GetType(n) LOBYTE(n)

Parameters

n
Type is DWORD. DirectInput data format type. The possible values for this parameter are identical to those found in the dwType member of the DIOBJECTDATAFORMAT structure.

See Also

DIDFT_GETINSTANCE


DIDFT_MAKEINSTANCE

The DIDFT_MAKEINSTANCE macro creates an instance identifier of a device object for packing in the dwType member of the DIOBJECTDATAFORMAT structure.

#define DIDFT_MAKEINSTANCE(n) ((WORD)(n) << 8)

Parameters

n
Type is WORD. Instance of the object; for example, 1 for button 1 of a mouse.

See Also

DIDFT_GETINSTANCE


DIDFT_GETTYPE

The DIDFT_GETTYPE macro extracts the effect type code from an effect format type.

#define DIDFT_GETTYPE(n) LOBYTE(n)

Parameters

n
Type is DWORD. DirectInput effect format type. The possible values for this parameter are identical to those found in the dwEffType member of the DIEffectInfo structure.
DOCERROR: You must supply a description of the return value.


DIMAKEUSAGEDWORD

The DIMAKEUSAGEDWORD macro combines the usage page and usage codes for a device object representing a Human Interface Device (HID), for passing to the IDirectInputDevice8::GetObjectInfo method.

#define DIMAKEUSAGEDWORD(UsagePage,Usage) \ ((DWORD)MAKELONG(Usage, UsagePage))

Parameters

UsagePage
Type is WORD. Usage page of the device object.
Usage
Type is WORD. Usage of the device object.


DISEQUENCE_COMPARE

The DISEQUENCE_COMPARE macro compares two DirectInput sequence numbers, compensating for wraparound.

#define DISEQUENCE_COMPARE(dwSequence1,cmp,dwSequence2) \((int)((dwSequence1) - (dwSequence2)) cmp 0)

Parameters

dwSequence1
Type is DWORD. First sequence number to compare.
cmp
Type is CHAR. One of the following comparison operators: ==, !=, <, >, <=, or >=.
dwSequence2
Type is DWORD. Second sequence number to compare.

Return Values

Returns a nonzero value if the result of the comparison specified by the cmp parameter is true, or zero otherwise.

Remarks

The following example checks whether the dwSequence1 parameter value precedes the dwSequence2 parameter value chronologically.

BOOL Sooner = (DISEQUENCE_COMPARE(dwSequence1, <, dwSequence2));


GET_DIDEVICE_SUBTYPE

The GET_DIDEVICE_SUBTYPE macro extracts the device subtype code from a device type description code.

#define GET_DIDEVICE_SUBTYPE(dwDevType) HIBYTE(dwDevType)

Parameters

dwDevType
Type is DWORD. DirectInput device type description code. The possible values for this parameter are identical to those found in the dwDevType member of the DIDEVICEINSTANCE structure.

Remarks

The interpretation of the subtype code depends on the primary type.

See Also

GET_DIDEVICE_TYPE, DIDEVICEINSTANCE


GET_DIDEVICE_TYPE

The GET_DIDEVICE_TYPE macro extracts the device primary type code from a device type description code.

#define GET_DIDEVICE_TYPE(dwDevType) LOBYTE(dwDevType)

Parameters

dwDevType
Type is DWORD. DirectInput device type description code. Possible values for this parameter are identical to those found in the dwDevType member of the DIDEVICEINSTANCE structure.

See Also

GET_DIDEVICE_SUBTYPE, DIDEVICEINSTANCE


DirectInput Structures

This section contains information about the structures used with DirectInput.

  • CPOINT
  • DIACTION
  • DIACTIONFORMAT
  • DICOLORSET
  • DICONDITION
  • DICONFIGUREDEVICESPARAMS
  • DICONSTANTFORCE
  • DICUSTOMFORCE
  • DIDATAFORMAT
  • DIDEVCAPS
  • DIDEVICEIMAGEINFO
  • DIDEVICEIMAGEINFOHEADER
  • DIDEVICEINSTANCE
  • DIDEVICEOBJECTDATA
  • DIDEVICEOBJECTINSTANCE
  • DIEFFECT
  • DIEffectInfo
  • DIEFFESCAPE
  • DIENVELOPE
  • DIFILEEFFECT
  • DIJOYSTATE
  • DIJOYSTATE2
  • DIMOUSESTATE
  • DIMOUSESTATE2
  • DIOBJECTDATAFORMAT
  • DIPERIODIC
  • DIPROPCPOINTS
  • DIPROPDWORD
  • DIPROPGUIDANDPATH
  • DIPROPHEADER
  • DIPROPPOINTER
  • DIPROPRANGE
  • DIPROPSTRING
  • DIRAMPFORCE

Note The memory for all Microsoft DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member should set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DIDEVCAPS:

DIDEVCAPS didevcaps; // Can't use this yet

ZeroMemory(&didevcaps, sizeof(didevcaps));
didevcaps.dwSize = sizeof(didevcaps);

// Now the structure Can be used.


CPOINT

Deprecated, do not use. Describes a calibration point. An array of CPOINT structures is contained by a DIPROPCPOINTS structure.

typedef struct CPOINT {
    LONG lP;
    DWORD dwLog;
} CPOINT, *LPCPOINT;

Members

lP
Raw data
dwLog
Scaling value to be associated with the lP number. The percentage of the maximum value multiplied by 10000.

See Also

Using CPOINTs


DIACTION

Describes a mapping of one game action to one device semantic. An array of DIACTION structures is contained by a DIACTIONFORMAT structure.

Syntax

typedef struct _DIACTION {
    UINT_PTR    uAppData;
    DWORD       dwSemantic;
    DWORD       dwFlags;
    union {
        LPCTSTR lptszActionName;
        UINT    uResIdString;
    };
    GUID        guidInstance;
    DWORD       dwObjID;
    DWORD       dwHow;
} DIACTION, *LPDIACTION;

typedef const DIACTION *LPCDIACTION;

Members

uAppData
Address of an application-defined UINT value to be returned to the application by IDirectInputDevice8::GetDeviceData when the state of the control associated with the action changes. This value is returned in the uAppData member of the DIDEVICEOBJECTDATA structure. It is typically an identifier for the application-specific action associated with the device object, but can also be a function pointer.
dwSemantic
For a joystick, a predefined action mapping constant for this application genre representing a virtual control or a constant for a control not defined in the genre. For a keyboard or mouse, a constant that represents a particular device object. See Action Mapping Constants.
dwFlags

Flags used to request specific attributes or processing. Can be zero or one or more of the following values.

DIA_APPFIXED
The action cannot be remapped by DirectInput.
DIA_APPMAPPED
The dwObjID member is valid, and IDirectInputDevice8::BuildActionMap will not override the application-defined mapping.
DIA_APPNOMAP
This action is not to be mapped.
DIA_FORCEFEEDBACK
The action must be mapped to an actuator or trigger.
DIA_NORANGE
The default range is not to be set for this action. This flag can be set only for absolute axis actions.
lptszActionName
Application-defined name of the action. This string is displayed by the device property sheet when IDirectInput8::ConfigureDevices is called.
uResIdString
Resource identifier for the string for this action. The module instance for this resource is specified in the hInstString member of the DIACTIONFORMAT structure that contains this structure.
guidInstance
Device instance globally unique identifier (GUID) if a specific device is requested. Otherwise GUID_NULL.
dwObjID
Control identifier. Use the DIDFT_GETINSTANCE and DIDFT_GetType macros to retrieve the instance and type from this value.
dwHow

When the structure is returned by IDirectInputDevice8::BuildActionMap, this member receives a value to indicate the mapping mechanism used by DirectInput to configure the action. This memeber is ignored when the action map is passed to IDirectInputDevice8::SetActionMap. The following values are defined.

DIAH_APPREQUESTED
The mapping was configured by the application, which specified the device (guidInstance) and device object (dwObjID) when calling IDirectInputDevice8::BuildActionMap.
DIAH_DEFAULT
The mapping was determined by DirectInput in the absence of other mapping information.
DIAH_ERROR
An error occurred. The action cannot be matched to a control on the device. The action will be ignored when the action map is set.
DIAH_HWAPP
The mapping was specified by the hardware manufacturer for this game.
DIAH_HWDEFAULT
The mapping was specified by the hardware manufacturer for this genre.
DIAH_UNMAPPED
No suitable device object was found.
DIAH_USERCONFIG
The mapping was configured by the user.

See Also

IDirectInput8::EnumDevicesBySemantics, IDirectInputDevice8::SetActionMap, IDirectInput8::ConfigureDevices, IDirectInputDevice8::BuildActionMap


DIACTIONFORMAT

Contains information about the calling application and acts as a container for an array of DIACTION structures that define action-to-control mappings for a genre.

typedef struct DIACTIONFORMAT {
    DWORD dwSize;
    DWORD dwActionSize;
    DWORD dwDataSize;
    DWORD dwNumActions;
    LPDIACTION rgoAction;
    GUID guidActionMap;
    DWORD dwGenre;
    DWORD dwBufferSize;
    LONG lAxisMin;
    LONG lAxisMax;
    HINSTANCE hInstString;
    FILETIME ftTimeStamp;
    DWORD dwCRC;
    TCHAR tszActionMap[MAX_PATH];
} DIACTIONFORMAT, *LPDIACTIONFORMAT;

Members

dwSize
DWORD value that specifies the size of the DIACTIONFORMAT structure, in bytes.
dwActionSize
DWORD value that specifies the size of the DIACTION structure, in bytes.
dwDataSize
DWORD value that specifies the size of the device data to be returned by the device for immediate device data, in bytes. This member should be dwNumActions multiplied by four.
dwNumActions
DWORD value that specifies the number of elements in the rgoAction array.
rgoAction
Address of an array of DIACTION structures, each of which describes how an action maps to a virtual control or device object, and how the mapping information should be displayed to the user.
guidActionMap
Globally unique identifier (GUID) that identifies the action map. Device manufacturers can use this value to tune mappings for a specific title.
dwGenre
DWORD value that specifies the genre of the application. For possible values, see Action Mapping Constants.
dwBufferSize
DWORD value that specifies the number of input data packets in the buffer for each device to which this action map is to be applied. The buffer size must be set to a value greater than zero in order to retrieve data by using IDirectInputDevice8::GetDeviceData. Applications that set this member to the desired buffer size before calling IDirectInputDevice8::SetActionMap do not need to set the DIPROP_BUFFERSIZE property by using IDirectInputDevice8::SetProperty.
lAxisMin

Minimum value for the range of scaled data to be returned for all axes. This value is ignored for a specific action axis if the DIA_NORANGE flag is set in DIACTION.dwFlags.

This value is valid only for axis actions and should be set to zero for all other actions. It is used as the DIPROPRANGE.lmin value to set the range property on an absolute axis when the action map is applied using IDirectInputDevice8::SetActionMap.

lAxisMax

Maximum value for the range of scaled data to be returned for all axes. This value is ignored for a specific action axis if the DIA_NORANGE flag is set in DIACTION.dwFlags.

This value is valid only for axis actions and should be set to zero for all other actions. It is used as the DIPROPRANGE.lmax value to set the range property on an absolute axis when the action map is applied using IDirectInputDevice8::SetActionMap.

hInstString
Handle of the module containing string resources for action names, as specified in the uResIdString member of the DIACTION structure for each action. Can be zero if action names are specified in the lptszActionName member of the DIACTION structure for each action.
ftTimeStamp
FILETIME structure that receives the time at which this action map was last written to disk. See Remarks.
dwCRC
Cyclic redundancy check for this map. Used internally by DirectInput to determine when a set of mappings should be saved to disk.
tszActionMap
Null-terminated string, of maximum length MAX_PATH, that specifies the friendly name for this action map. This string appears in the drop-down list box in the default property sheet.

Remarks

The ftTimeStamp member can contain special values that apply to new and unused devices. New devices have never been enumerated for this application and have never had an action map applied to them. Unused devices have been enumerated for the application before but have never had an action map applied. New devices always have DIAFTS_NEWDEVICELOW and DIAFTS_NEWDEVICEHIGH in the low and high DWORDs respectively of the FILETIME structure. Unused devices have DIAFTS_UNUSEDDEVICELOW and DIAFTS_UNUSEDDEVICEHIGH in these positions.

Applications should not use ftTimeStamp to check for new devices. Instead, they should look for the DIEDBS_RECENTDEVICE and DIEDBS_NEWDEVICE flags in the enumeration callback. For more information, see DIEnumDevicesBySemanticsCallback.

See Also

IDirectInput8::EnumDevicesBySemantics, IDirectInputDevice8::SetActionMap, IDirectInput8::ConfigureDevices, IDirectInputDevice8::BuildActionMap


DICOLORSET

Describes a set of colors used to draw the device configuration user interface. It is part of the DICONFIGUREDEVICESPARAMS structure.

typedef struct DICOLORSET {
    DWORD dwSize;
    D3DCOLOR cTextFore;
    D3DCOLOR cTextHighlight;
    D3DCOLOR cCalloutLine;
    D3DCOLOR cCalloutHighlight;
    D3DCOLOR cBorder;
    D3DCOLOR cControlFill;
    D3DCOLOR cHighlightFill;
    D3DCOLOR cAreaFill;
} DICOLORSET, *LPDICOLORSET;

Members

dwSize
Size of this structure, in bytes.
cTextFore
Foreground text color.
cTextHighlight
Foreground color for highlighted text.
cCalloutLine
Color used to display callout lines.
cCalloutHighlight
Color used to display callout lines.
cBorder
Border color, used to display lines around controls such as tabs and buttons.
cControlFill
Fill color for controls such as tabs and buttons.
cHighlightFill
Fill color for highlighted controls.
cAreaFill
Fill color for areas outside controls such as tabs and buttons.

Remarks

Text background color is always transparent.

See Also

D3DCOLOR


DICONDITION

Contains type-specific information for effects that are marked as DIEFT_CONDITION.

A pointer to an array of DICONDITION structures for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure. The number of elements in the array must be either one, or equal to the number of axes associated with the effect.

typedef struct DICONDITION {
    LONG lOffset;
    LONG lPositiveCoefficient;
    LONG lNegativeCoefficient;
    DWORD dwPositiveSaturation;
    DWORD dwNegativeSaturation;
    LONG lDeadBand;
} DICONDITION, *LPDICONDITION;

Members

lOffset
Offset for the condition, in the range from - 10,000 through 10,000.
lPositiveCoefficient
Coefficient constant on the positive side of the offset, in the range from - 10,000 through 10,000.
lNegativeCoefficient
Coefficient constant on the negative side of the offset, in the range from - 10,000 through 10,000. If the device does not support separate positive and negative coefficients, the value of lNegativeCoefficient is ignored, and the value of lPositiveCoefficient is used as both the positive and negative coefficients.
dwPositiveSaturation
Maximum force output on the positive side of the offset, in the range from 0 through 10,000.

If the device does not support force saturation, the value of this member is ignored.

dwNegativeSaturation
Maximum force output on the negative side of the offset, in the range from 0 through 10,000.

If the device does not support force saturation, the value of this member is ignored.

If the device does not support separate positive and negative saturation, the value of dwNegativeSaturation is ignored, and the value of dwPositiveSaturation is used as both the positive and negative saturation.

lDeadBand
Region around lOffset in which the condition is not active, in the range from 0 through 10,000. In other words, the condition is not active between lOffset minus lDeadBand and lOffset plus lDeadBand.

Remarks

Different types of conditions interpret the parameters differently, but the basic idea is that force resulting from a condition is equal to A(q - q0) where A is a scaling coefficient, q is some metric, and q0 is the neutral value for that metric.

The preceding simplified formula must be adjusted if a nonzero deadband is provided. If the metric is less than lOffset - lDeadBand, the resulting force is given by the following formula:

force = lNegativeCoefficient * ( q - ( lOffset - lDeadBand))

Similarly, if the metric is greater than lOffset + lDeadBand, the resulting force is given by the following formula:

force = lPositiveCoefficient * ( q - ( lOffset + lDeadBand))

A spring condition uses axis position as the metric.

A damper condition uses axis velocity as the metric.

An inertia condition uses axis acceleration as the metric.

If the number of DICONDITION structures in the array is equal to the number of axes for the effect, the first structure applies to the first axis, the second applies to the second axis, and so on. For example, a two-axis spring condition with lOffset set to 0 in both DICONDITION structures would have the same effect as the joystick self-centering spring. When a condition is defined for each axis in this way, the effect must not be rotated.

If there is a single DICONDITION structure for an effect with more than one axis, the direction along which the parameters of the DICONDITION structure are in effect is determined by the direction parameters passed in the rglDirection field of the DIEFFECT structure. For example, a friction condition rotated 45 degrees (in polar coordinates) would resist joystick motion in the northeast-southwest direction but would have no effect on joystick motion in the northwest-southeast direction.


DICONFIGUREDEVICESPARAMS

Contains information for the device configuration property sheet. It is used by the IDirectInput8::ConfigureDevices method.

typedef struct DICONFIGUREDEVICESPARAMS {
    DWORD dwSize;
    DWORD dwcUsers;
    LPTSTR lptszUserNames;
    DWORD dwcFormats;
    LPDIACTIONFORMAT lprgFormats;
    HWND hwnd;
    DICOLORSET dics;
    IUnknown * lpUnkDDSTarget;
} DICONFIGUREDEVICESPARAMS, *LPDICONFIGUREDEVICESPARAMS;

Members

dwSize
Size of this structure, in bytes.
dwcUsers
Count of user names in the buffer at lptszUserNames. If lptszUserNames is NULL (to indicate that default user names should be used), the value in this member is ignored. If the dwcUsers value exceeds the number of entries actually in the buffer, the method fails, returning DIERR_INVALIDPARAM.
lptszUserNames
Pointer to a buffer containing a series of null-terminated name strings, the final element being designated by a double-null terminator. The lptszUserNames parameter can be set to NULL to instruct the use of default names. If the application passes more names than the dwcUsers count indicates, only the names within the count are used. If an application specifies names that are different from the names currently assigned to devices, ownership is revoked for all devices, a default name is created for the mismatched name, and the interface shows (No User) for all devices.
dwcFormats
Count of structures in the array at lprgFormats.
lprgFormats
Pointer to an array of DIACTIONFORMAT structures that contains action-mapping information for each genre used by the game. On input, this array contains action-to-control mappings and strings to display as callouts for each mapping. The configuration interface displays the genres in its drop-down list in the same order as in the array.
hwnd
Handle to the top-level window of the calling application. The member is needed only for applications that run in windowed mode and is otherwise ignored.
dics
DICOLORSET structure that describes the color scheme to apply to the configuration user interface. Passing a zero-initialized DICOLORSET structure causes the default color scheme to be used.
lpUnkDDSTarget

Pointer to the IUnknown interface for a Microsoft DirectDraw or Direct3D target surface object that will be filled to contain an image of the configuration user interface. The image represents the current state of the user interface at the time that the DIEnumDevicesBySemanticsCallback function is invoked. The target surface will retain any alpha information passed as part of the DICOLORSET structure above, and also any alpha information encoded into the device image by the hardware manufacturer. The target surface object referred to by the IUnknown interface must support either IDirect3DSurface8, IDirectDrawSurface7 or IDirectDrawSurface4. The IDirect3DSurface9 interface is not supported. For more information, see IDirectInput8::ConfigureDevices. Full-screen applications using DirectDraw must have target surfaces created using the DDSCAPS_SYSTEMEMORY flag.

Applications that are not using DirectDraw and applications that are using DirectDraw but are windowed rather than using the full screen may pass NULL in this parameter. This will cause DirectInput to use the Windows Graphics Device Interface (GDI) functions to draw the configuration user interface image. Passing NULL when using IDirect3DSurface9 surfaces will fail. For more information, see Remarks in IDirectInput8::ConfigureDevices.


DICONSTANTFORCE

Contains type-specific information for effects that are marked as DIEFT_CONSTANTFORCE.

The structure describes a constant force effect.

A pointer to a single DICONSTANTFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DICONSTANTFORCE {
    LONG lMagnitude;
} DICONSTANTFORCE, *LPDICONSTANTFORCE;

Members

lMagnitude
The magnitude of the effect, in the range from - 10,000 through 10,000. If an envelope is applied to this effect, the value represents the magnitude of the sustain. If no envelope is applied, the value represents the amplitude of the entire effect.


DICUSTOMFORCE

Contains type-specific information for effects that are marked as DIEFT_CUSTOMFORCE.

The structure describes a custom or user-defined force.

A pointer to a DICUSTOMFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DICUSTOMFORCE {
    DWORD cChannels;
    DWORD dwSamplePeriod;
    DWORD cSamples;
    LPLONG rglForceData;
} DICUSTOMFORCE, *LPDICUSTOMFORCE;

Members

cChannels
Number of channels (axes) affected by this force.

The first channel is applied to the first axis associated with the effect, the second to the second, and so on. If there are fewer channels than axes, nothing is associated with the extra axes.

If there is only a single channel, the effect is rotated in the direction specified by the rglDirection member of the DIEFFECT structure. If there is more than one channel, rotation is not allowed.

Not all devices support rotation of custom effects.

dwSamplePeriod
Sample period, in microseconds.
cSamples
Total number of samples in the rglForceData. It must be an integral multiple of the cChannels.
rglForceData
Pointer to an array of force values representing the custom force. If multiple channels are provided, the values are interleaved. For example, if cChannels is 3, the first element of the array belongs to the first channel, the second to the second, and the third to the third.


DIDATAFORMAT

Describes a device's data format. This structure is used with the IDirectInputDevice8::SetDataFormat method.

typedef struct DIDATAFORMAT {
    DWORD dwSize;
    DWORD dwObjSize;
    DWORD dwFlags;
    DWORD dwDataSize;
    DWORD dwNumObjs;
    LPDIOBJECTDATAFORMAT rgodf;
} DIDATAFORMAT, *LPDIDATAFORMAT;

Members

dwSize
Size of this structure, in bytes.
dwObjSize
Size of the DIOBJECTDATAFORMAT structure, in bytes.
dwFlags
Flags describing other attributes of the data format. This value can be one of the following:
DIDF_ABSAXIS
The axes are in absolute mode. Setting this flag in the data format is equivalent to manually setting the axis mode property, using the IDirectInputDevice8::SetProperty method. This cannot be combined with DIDF_RELAXIS flag.
DIDF_RELAXIS
The axes are in relative mode. Setting this flag in the data format is equivalent to manually setting the axis mode property using the IDirectInputDevice8::SetProperty method. This cannot be combined with the DIDF_ABSAXIS flag.
dwDataSize
Size of a data packet returned by the device, in bytes. This value must be a multiple of 4 and must exceed the largest offset value for an object's data within the data packet.
dwNumObjs
Number of objects in the rgodf array.
rgodf
Address to an array of DIOBJECTDATAFORMAT structures. Each structure describes how one object's data should be reported in the device data. Typical errors include placing two pieces of information in the same location and placing one piece of information in more than one location.

Remarks

Applications do not typically need to create a DIDATAFORMAT structure. An application can use one of the predefined global data format variables, c_dfDIMouse, c_dfDIMouse2, c_dfDIKeyboard, c_dfDIJoystick, or c_dfDIJoystick2.

Applications that need to create a DIDATAFORMAT structure must first call IDirectInputDevice8::EnumObjects to determine the available objects for the current device. This is because the IDirectInputDevice8::SetDataFormat method will return DIERR_INVALIDPARAM if an an object is described in the DIDATAFORMAT structure but does not exist on the current device.

The following code example sets a data format for a device that has an X-axis and a Y-axis:

// Suppose an application uses the following
// structure to read device data.

typedef struct MYDATA {
    LONG  lX;                   // X-axis goes here.
    LONG  lY;                   // Y-axis goes here.
    BYTE  bButtonA;             // One button goes here.
    BYTE  bButtonB;             // Another button goes here.
    BYTE  bPadding[2];          // Must be DWORD multiple in size.
} MYDATA;

// Then, it can use the following data format.

DIOBJECTDATAFORMAT rgodf[ ] = {
  { &GUID_XAxis, FIELD_OFFSET(MYDATA, lX),
    DIDFT_AXIS | DIDFT_ANYINSTANCE, 0, },
  { &GUID_YAxis, FIELD_OFFSET(MYDATA, lY),
    DIDFT_AXIS | DIDFT_ANYINSTANCE, 0, },
  { &GUID_Button, FIELD_OFFSET(MYDATA, bButtonA),
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0, },
  { &GUID_Button, FIELD_OFFSET(MYDATA, bButtonB),
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0, },
};
#define numObjects (sizeof(rgodf) / sizeof(rgodf[0]))

DIDATAFORMAT df = {
    sizeof(DIDATAFORMAT),       // Size of this structure
    sizeof(DIOBJECTDATAFORMAT), // Size of object data format
    DIDF_ABSAXIS,               // Absolute axis coordinates
    sizeof(MYDATA),             // Size of device data
    numObjects,                 // Number of objects
    rgodf,                      // And here they are
};

See Also

DIACTIONFORMAT


DIDEVCAPS

Describes a DirectInput device's capabilities. This structure is used with the IDirectInputDevice8::GetCapabilities method.

typedef struct DIDEVCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwDevType;
    DWORD dwAxes;
    DWORD dwButtons;
    DWORD dwPOVs;
    DWORD dwFFSamplePeriod;
    DWORD dwFFMinTimeResolution;
    DWORD dwFirmwareRevision;
    DWORD dwHardwareRevision;
    DWORD dwFFDriverVersion;
} DIDEVCAPS, *LPDIDEVCAPS;

Members

dwSize
Size of this structure, in bytes. This member must be initialized by the application before a call to the IDirectInputDevice8::GetCapabilities method.
dwFlags
Flags associated with the device. This value can be a combination of the following:
DIDC_ALIAS
The device is a duplicate of another DirectInput device. Alias devices are by default not enumerated by IDirectInput8::EnumDevices.
DIDC_ATTACHED
The device is physically attached to the user's computer.
DIDC_DEADBAND
The device supports deadband for at least one force-feedback condition.
DIDC_EMULATED
If this flag is set, the data is coming from a user mode device interface, such as a Human Interface Device (human interface device), or by some other ring 3 means. If it is not set, the data is coming directly from a kernel mode driver.
DIDC_FORCEFEEDBACK
The device supports force feedback.
DIDC_FFFADE
The force-feedback system supports the fade parameter for at least one effect. If the device does not support fade, the fade level and fade time members of the DIENVELOPE structure are ignored by the device.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual effect sets the DIEFT_FFFADE flag if fade is supported for that effect.

DIDC_FFATTACK
The force-feedback system supports the attack parameter for at least one effect. If the device does not support attack, the attack level and attack time members of the DIENVELOPE structure are ignored by the device.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual effect sets the DIEFT_FFATTACK flag if attack is supported for that effect.

DIDC_HIDDEN
Fictitious device created by a device driver so that it can generate keyboard and mouse events. Such devices are not normally enumerated by IDirectInput8::EnumDevices or configured by IDirectInput8::ConfigureDevices.
DIDC_PHANTOM
Placeholder. Phantom devices are by default not enumerated by IDirectInput8::EnumDevices.
DIDC_POLLEDDATAFORMAT
At least one object in the current data format is polled, rather than interrupt-driven. For these objects, the application must explicitly call the IDirectInputDevice8 Interface method to obtain data.
DIDC_POLLEDDEVICE
At least one object on the device is polled, rather than interrupt-driven. For these objects, the application must explicitly call the IDirectInputDevice8 Interface method to obtain data. HID devices can contain a mixture of polled and nonpolled objects.
DIDC_POSNEGCOEFFICIENTS
The force-feedback system supports two coefficient values for conditions (one for the positive displacement of the axis and one for the negative displacement of the axis) for at least one condition. If the device does not support both coefficients, the negative coefficient in the DICONDITION structure is ignored.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_POSNEGCOEFFICIENTS flag if separate positive and negative coefficients are supported for that condition.

DIDC_POSNEGSATURATION
The force-feedback system supports a maximum saturation for both positive and negative force output for at least one condition. If the device does not support both saturation values, the negative saturation in the DICONDITION structure is ignored.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_POSNEGSATURATION flag if separate positive and negative saturation are supported for that condition.

DIDC_SATURATION
The force-feedback system supports the saturation of condition effects for at least one condition. If the device does not support saturation, the force generated by a condition is limited only by the maximum force that the device can generate.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_SATURATION flag if saturation is supported for that condition.

DIDC_STARTDELAY
The force-feedback system supports the start delay parameter for at least one effect. If the device does not support start delays, the dwStartDelay member of the DIEFFECT structure is ignored.
dwDevType
Device type specifier. This member can contain values identical to those in the dwDevType member of the DIDEVICEINSTANCE structure.
dwAxes
Number of axes available on the device.
dwButtons
Number of buttons available on the device.
dwPOVs
Number of point-of-view controllers available on the device.
dwFFSamplePeriod
Minimum time between playback of consecutive raw force commands, in microseconds.
dwFFMinTimeResolution
Minimum time, in microseconds, that the device can resolve. The device rounds any times to the nearest supported increment. For example, if the value of dwFFMinTimeResolution is 1000, the device would round any times to the nearest millisecond.
dwFirmwareRevision
Firmware revision of the device.
dwHardwareRevision
Hardware revision of the device.
dwFFDriverVersion
Version number of the device driver.

Remarks

The semantics of version numbers are left to the manufacturer of the device. The only guarantee is that newer versions have larger numbers.

See Also

DIDEVICEINSTANCE


DIDEVICEIMAGEINFO

Carries information required to display a device image or an overlay image with a callout. This structure is passed to the IDirectInputDevice8::GetImageInfo method as an array within a DIDEVICEIMAGEINFOHEADER structure.

typedef struct DIDEVICEIMAGEINFO {
    TCHAR tszImagePath[MAX_PATH];
    DWORD dwFlags;
    DWORD dwViewID;
    RECT rcOverlay;
    DWORD dwObjID;
    DWORD dwcValidPts;
    POINT rgptCalloutLine[5];
    RECT rcCalloutRect;
    DWORD dwTextAlign;
} DIDEVICEIMAGEINFO, *LPDIDEVICEIMAGEINFO;

Members

tszImagePath
Fully qualified path to the file that contains an image of the device. The file format is given in dwFlags. If no image is available for the device, this member will be set to NULL. If so, the application is responsible for enumerating controls on the device and displaying a default listing of actions to device controls (similar to the method used by most applications before DirectX 8.0).
dwFlags
Flag that describes the intended use of the image.
DIDIFT_CONFIGURATION
The file is used to display the current configuration of actions on the device. Overlay image coordinates are relative to the upper-left corner of the configuration image.
DIDIFT_OVERLAY
The file (if provided) is an overlay for a configuration image. The dwViewID, rcOverlay, dwObjID, rgptCalloutLine, rcCalloutRect, and dwTextAlign members are valid and contain data used to display the overlay and callout information for a single control on the device. If no file is provided (null path string), all other pertinent members are relevant except rcOverlay.
dwViewID
For device view images (DIDIFT_CONFIGURATION), this is the ID of the device view. For device control overlays (DIDIFT_OVERLAY), this value refers to the device view (by ID) over which an image and callout information should be displayed.
rcOverlay
Rectangle, using coordinates relative to the top-left pixel of the device configuration image, in which the overlay image should be painted. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwObjID
Control identifier, as a combination of DIDFT_* flags and an instance value, to which an overlay image corresponds for this device. Applications use the DIDFT_GETINSTANCE and DIDFT_GetType macros to decode this value to its constituent parts. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwcValidPts
Number of points in the array at rgptCalloutLine.
rgptCalloutLine
Array of POINT structures that specify coordinates of the points describing a callout line. A callout line connects a device control to a caption for the game action. Each line can have from one to four segments. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
rcCalloutRect
RECT structure that describes the rectangle in which the game action string is displayed. If the string cannot fit within the rectangle, the application is responsible for handling clipping. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwTextAlign
DWORD value that specifies the alignment of the text in the rectangle described by the rcCalloutRect member. Must be one horizontal alignment flag combined with one vertical alignment flag. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.

The following horizontal alignment flags are defined.

DIDAL_LEFTALIGNED
Text is aligned on the left border.
DIDAL_CENTERED
Text is horizontally centered.
DIDAL_RIGHTALIGNED
Text is aligned on the right border.

The following vertical alignment flags are defined.

DIDAL_MIDDLE
The text is vertically centered.
DIDAL_TOPALIGNED
The text is aligned on the top border.
DIDAL_BOTTOMALIGNED
The text is aligned on the bottom border.


DIDEVICEIMAGEINFOHEADER

Contains information about device images. Used in the IDirectInputDevice8::GetImageInfo method.

typedef struct DIDEVICEIMAGEINFOHEADER {
    DWORD dwSize;
    DWORD dwSizeImageInfo;
    DWORD dwcViews;
    DWORD dwcButtons;
    DWORD dwcAxes;
    DWORD dwcPOVs;
    DWORD dwBufferSize;
    DWORD dwBufferUsed;
    DIDEVICEIMAGEINFO * lprgImageInfoArray;
} DIDEVICEIMAGEINFOHEADER, *LPDIDEVICEIMAGEINFOHEADER;

Members

dwSize
DWORD value that specifies the size of this structure, in bytes. Must be initialized before the structure can be used.
dwSizeImageInfo
DWORD value that specifies the size of the DIDEVICEIMAGEINFO structure, in bytes. Must be initialized before this structure can be used.
dwcViews
DWORD variable that receives the number of views of this device.
dwcButtons
DWORD variable that receives the number of buttons on the device.
dwcAxes
DWORD variable that receives the number of axes on the device.
dwcPOVs
DWORD variable that receives the number of point-of-view controllers on the device.
dwBufferSize
DWORD value that specifies the size, in bytes, of the buffer at lprgImageInfoArray. When set to zero, the IDirectInputDevice8::GetImageInfo method ignores all other members and returns the minimum buffer size required to hold information for all images.
dwBufferUsed
DWORD value that receives the size, in bytes, of the memory used in the buffer at lprgImageInfoArray. When dwBufferSize is set to zero, the IDirectInputDevice8::GetImageInfo method sets this member to the minimum size needed to hold information for all images.
lprgImageInfoArray
Pointer to a buffer that receives an array of DIDEVICEIMAGEINFO structures describing all the device images and views, overlay images, and callout-string coordinates.

Remarks

The buffer at lprgImageInfoArray must be large enough to hold all required image information structures. Applications can query for the required size by calling the IDirectInputDevice8::GetImageInfo method with the dwBufferSize member set to zero. After the call, dwBufferUsed contains the amount of memory, in bytes, that was modified.


DIDEVICEINSTANCE

Describes an instance of a DirectInput device. This structure is used with the IDirectInput8::EnumDevices, IDirectInput8::EnumDevicesBySemantics, and IDirectInputDevice8::GetDeviceInfo methods.

typedef struct DIDEVICEINSTANCE {
    DWORD dwSize;
    GUID guidInstance;
    GUID guidProduct;
    DWORD dwDevType;
    TCHAR tszInstanceName[MAX_PATH];
    TCHAR tszProductName[MAX_PATH];
    GUID guidFFDriver;
    WORD wUsagePage;
    WORD wUsage;
} DIDEVICEINSTANCE, *LPDIDEVICEINSTANCE;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
guidInstance
Unique identifier for the instance of the device. An application can save the instance globally unique identifier (GUID) into a configuration file and use it at a later time. Instance GUIDs are specific to a particular computer. An instance GUID obtained from one computer is unrelated to instance GUIDs on another.
guidProduct
Unique identifier for the product. This identifier is established by the manufacturer of the device.
dwDevType
Device type specifier. The least-significant byte of the device type description code specifies the device type. The next-significant byte specifies the device subtype. This value can also be combined with DIDEVTYPE_HID, which specifies a Human Interface Device (human interface device).
tszInstanceName
Friendly name for the instance. For example, "Joystick 1."
tszProductName
Friendly name for the product.
guidFFDriver
Unique identifier for the driver being used for force feedback. The driver's manufacturer establishes this identifier.
wUsagePage
If the device is a Human Interface Device (HID), this member contains the HID usage page code.
wUsage
If the device is a Human Interface Device (HID), this member contains the HID usage code.

Remarks

The following device types and subtypes are defined for use in the dwDevType member.

  • DI8DEVTYPE_1STPERSON

    First-person action game device. The following subtypes are defined.

    • DI8DEVTYPE1STPERSON_LIMITED

      Device that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPE1STPERSON_SHOOTER

      Device designed for first-person shooter games.

    • DI8DEVTYPE1STPERSON_SIXDOF

      Device with six degrees of freedom; that is, three lateral axes and three rotational axes.

    • DI8DEVTYPE1STPERSON_UNKNOWN

      Unknown subtype.

  • DI8DEVTYPE_DEVICE

    Device that does not fall into another category.

  • DI8DEVTYPE_DEVICECTRL

    Input device used to control another type of device from within the context of the application. The following subtypes are defined.

    • DI8DEVTYPEDEVICECTRL_COMMSSELECTION

      Control used to make communications selections.

    • DI8DEVTYPEDEVICECTRL_COMMSSELECTION_HARDWIRED

      Device that must use its default configuration and cannot be remapped.

    • DI8DEVTYPEDEVICECTRL_UNKNOWN

      Unknown subtype.

  • DI8DEVTYPE_DRIVING

    Device for steering. The following subtypes are defined.

    • DI8DEVTYPEDRIVING_COMBINEDPEDALS

      Steering device that reports acceleration and brake pedal values from a single axis.

    • DI8DEVTYPEDRIVING_DUALPEDALS

      Steering device that reports acceleration and brake pedal values from separate axes.

    • DI8DEVTYPEDRIVING_HANDHELD

      Hand-held steering device.

    • DI8DEVTYPEDRIVING_LIMITED

      Steering device that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEDRIVING_THREEPEDALS

      Steering device that reports acceleration, brake, and clutch pedal values from separate axes.

  • DI8DEVTYPE_FLIGHT

    Controller for flight simulation. The following subtypes are defined.

    • DI8DEVTYPEFLIGHT_LIMITED

      Flight controller that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEFLIGHT_RC

      Flight device based on a remote control for model aircraft.

    • DI8DEVTYPEFLIGHT_STICK

      Joystick.

    • DI8DEVTYPEFLIGHT_YOKE

      Yoke.

  • DI8DEVTYPE_GAMEPAD

    Gamepad. The following subtypes are defined.

    • DI8DEVTYPEGAMEPAD_LIMITED

      Gamepad that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEGAMEPAD_STANDARD

      Standard gamepad that provides the minimum number of device objects for action mapping.

    • DI8DEVTYPEGAMEPAD_TILT

      Gamepad that can report x-axis and y-axis data based on the attitude of the controller.

  • DI8DEVTYPE_JOYSTICK

    Joystick. The following subtypes are defined.

    • DI8DEVTYPEJOYSTICK_LIMITED

      Joystick that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEJOYSTICK_STANDARD

      Standard joystick that provides the minimum number of device objects for action mapping.

  • DI8DEVTYPE_KEYBOARD

    Keyboard or keyboard-like device. The following subtypes are defined.

    • DI8DEVTYPEKEYBOARD_UNKNOWN

      Subtype could not be determined.

    • DI8DEVTYPEKEYBOARD_PCXT

      IBM PC/XT 83-key keyboard.

    • DI8DEVTYPEKEYBOARD_OLIVETTI

      Olivetti 102-key keyboard.

    • DI8DEVTYPEKEYBOARD_PCAT

      IBM PC/AT 84-key keyboard.

    • DI8DEVTYPEKEYBOARD_PCENH

      IBM PC Enhanced 101/102-key or Microsoft Natural keyboard.

    • DI8DEVTYPEKEYBOARD_NOKIA1050

      Nokia 1050 keyboard.

    • DI8DEVTYPEKEYBOARD_NOKIA9140

      Nokia 9140 keyboard.

    • DI8DEVTYPEKEYBOARD_NEC98

      Japanese NEC PC98 keyboard.

    • DI8DEVTYPEKEYBOARD_NEC98LAPTOP

      Japanese NEC PC98 laptop keyboard.

    • DI8DEVTYPEKEYBOARD_NEC98106

      Japanese NEC PC98 106-key keyboard.

    • DI8DEVTYPEKEYBOARD_JAPAN106

      Japanese 106-key keyboard.

    • DI8DEVTYPEKEYBOARD_JAPANAX

      Japanese AX keyboard.

    • DI8DEVTYPEKEYBOARD_J3100

      Japanese J3100 keyboard.

  • DI8DEVTYPE_MOUSE

    A mouse or mouse-like device (such as a trackball). The following subtypes are defined.

    • DI8DEVTYPEMOUSE_ABSOLUTE

      Mouse that returns absolute axis data.

    • DI8DEVTYPEMOUSE_FINGERSTICK

      Fingerstick.

    • DI8DEVTYPEMOUSE_TOUCHPAD

      Touchpad.

    • DI8DEVTYPEMOUSE_TRACKBALL

      Trackball.

    • DI8DEVTYPEMOUSE_TRADITIONAL

      Traditional mouse.

    • DI8DEVTYPEMOUSE_UNKNOWN

      Subtype could not be determined.

  • DI8DEVTYPE_REMOTE

    Remote-control device. The following subtype is defined.

    • DI8DEVTYPEREMOTE_UNKNOWN

      Subtype could not be determined.

  • DI8DEVTYPE_SCREENPOINTER

    Screen pointer. The following subtypes are defined.

    • DI8DEVTYPESCREENPTR_UNKNOWN

      Unknown subtype.

    • DI8DEVTYPESCREENPTR_LIGHTGUN

      Light gun.

    • DI8DEVTYPESCREENPTR_LIGHTPEN

      Light pen.

    • DI8DEVTYPESCREENPTR_TOUCH

      Touch screen.

  • DI8DEVTYPE_SUPPLEMENTAL

    Specialized device with functionality unsuitable for the main control of an application, such as pedals used with a wheel. The following subtypes are defined.

    • DI8DEVTYPESUPPLEMENTAL_2NDHANDCONTROLLER

      Secondary handheld controller.

    • DI8DEVTYPESUPPLEMENTAL_COMBINEDPEDALS

      Device whose primary function is to report acceleration and brake pedal values from a single axis.

    • DI8DEVTYPESUPPLEMENTAL_DUALPEDALS

      Device whose primary function is to report acceleration and brake pedal values from separate axes.

    • DI8DEVTYPESUPPLEMENTAL_HANDTRACKER

      Device that tracks hand movement.

    • DI8DEVTYPESUPPLEMENTAL_HEADTRACKER

      Device that tracks head movement.

    • DI8DEVTYPESUPPLEMENTAL_RUDDERPEDALS

      Device with rudder pedals.

    • DI8DEVTYPESUPPLEMENTAL_SHIFTER

      Device that reports gear selection from an axis.

    • DI8DEVTYPESUPPLEMENTAL_SHIFTSTICKGATE

      Device that reports gear selection from button states.

    • DI8DEVTYPESUPPLEMENTAL_SPLITTHROTTLE

      Device whose primary function is to report at least two throttle values. It may have other controls.

    • DI8DEVTYPESUPPLEMENTAL_THREEPEDALS

      Device whose primary function is to report acceleration, brake, and clutch pedal values from separate axes.

    • DI8DEVTYPESUPPLEMENTAL_THROTTLE

      Device whose primary function is to report a single throttle value. It may have other controls.

    • DI8DEVTYPESUPPLEMENTAL_UNKNOWN

      Unknown subtype.

Versions of DirectInput earlier than DirectX 8.0 have a somewhat different scheme of device types and subtypes. See the DIDEVTYPExxx defines in Dinput.h.


DIDEVICEOBJECTDATA

Contains buffered device information. This structure is used with the IDirectInputDevice8::GetDeviceData and the IDirectInputDevice8::SendDeviceData methods.

typedef struct DIDEVICEOBJECTDATA {
    DWORD dwOfs;
    DWORD dwData;
    DWORD dwTimeStamp;
    DWORD dwSequence;
    UINT_PTR uAppData;
} DIDEVICEOBJECTDATA, *LPDIDEVICEOBJECTDATA;

Members

dwOfs
For IDirectInputDevice8::GetDeviceData, the offset into the current data format of the object whose data is being reported; that is, the location in which the dwData would have been stored if the data had been obtained by a call to the IDirectInputDevice8::GetDeviceState method. If the device is accessed as a mouse, keyboard, or joystick, the dwOfs member is one of the mouse device constants, keyboard device constants, or joystick device constants. If a custom data format has been set, it is an offset relative to the custom data format.

For IDirectInputDevice8::SendDeviceData, the instance ID of the object to which the data is being sent, as obtained from the dwType member of a DIDEVICEOBJECTINSTANCE structure.

dwData
Data obtained from or sent to the device.

For axis input, if the device is in relative axis mode, the relative axis motion is reported. If the device is in absolute axis mode, the absolute axis coordinate is reported.

For button input, only the low byte of dwData is significant. The high bit of the low byte is set if the button was pressed; it is clear if the button was released.

dwTimeStamp
System time at which the input event was generated, in milliseconds. This value wraps around approximately every 50 days. See Remarks.

When the structure is used with the IDirectInputDevice8::SendDeviceData method, this member must be 0.

dwSequence
DirectInput sequence number for this event. All input events are assigned an increasing sequence number. This enables events from different devices to be sorted chronologically. Because this value can wrap around, care must be taken when comparing two sequence numbers. The DISEQUENCE_COMPARE macro can be used to perform this comparison safely.

When the structure is used with the IDirectInputDevice8::SendDeviceData method, this member must be 0.

uAppData
Application-defined action value assigned to this object in the last call to IDirectInputDevice8::SetActionMap. This is the value in the uAppData member of the DIACTION structure associated with the object. Ignore this value if you are not using action mapping.

When the structure is used with the IDirectInputDevice8::SendDeviceData method, this member must be zero.

Remarks

The system time returned in dwTimeStamp comes from the same clock used by the Microsoft Win32 GetTickCount or timeGetTime functions, but it produces potentially more precise values. For example, on Microsoft Windows 95, the GetTickCount timer is updated only every 55 milliseconds, but the dwTimeStamp value is accurate to within 1 millisecond. Therefore, if you call GetTickCount and it returns n, and you then receive an event with a timestamp of n + n1, you cannot assume that the event took place exactly n1 milliseconds after the call to GetTickCount.


DIDEVICEOBJECTINSTANCE

Describes a device object instance. This structure is used with the IDirectInputDevice8::EnumObjects method to provide the DIEnumDeviceObjectsCallback callback function with information about a particular object associated with a device, such as an axis or button. It is also used with the IDirectInputDevice8::GetObjectInfo method to retrieve information about a device object.

typedef struct DIDEVICEOBJECTINSTANCE {
    DWORD dwSize;
    GUID guidType;
    DWORD dwOfs;
    DWORD dwType;
    DWORD dwFlags;
    TCHAR tszName[MAX_PATH];
    DWORD dwFFMaxForce;
    DWORD dwFFForceResolution;
    WORD wCollectionNumber;
    WORD wDesignatorIndex;
    WORD wUsagePage;
    WORD wUsage;
    DWORD dwDimension;
    WORD wExponent;
    WORD wReportId;
} DIDEVICEOBJECTINSTANCE, *LPDIDEVICEOBJECTINSTANCE;

Members

dwSize
Size of the structure, in bytes. During enumeration, the application can inspect this value to determine how many members of the structure are valid. When the structure is passed to the IDirectInputDevice8::GetObjectInfo method, this member must be initialized to sizeof(DIDEVICEOBJECTINSTANCE).
guidType
Unique identifier that indicates the object type. This member is optional. If present, it can be one of the following values:
GUID_XAxis
The horizontal axis. For example, it can represent the left-right motion of a mouse.
GUID_YAxis
The vertical axis. For example, it can represent the forward-backward motion of a mouse.
GUID_ZAxis
The z-axis. For example, it can represent the rotation of a mouse wheel or the movement of a joystick throttle control.
GUID_RxAxis
Rotation around the x-axis.
GUID_RyAxis
Rotation around the y-axis.
GUID_RzAxis
Rotation around the z-axis (often a rudder control).
GUID_Slider
A slider axis.
GUID_Button
A mouse button.
GUID_Key
A keyboard key.
GUID_POV
A point-of-view indicator.
GUID_Unknown
Unknown.
dwOfs
Offset in the native data format of the device. The native data format corresponds to the raw device data. The dwOfs member does not correspond to the device constant, such as DIJOFS_BUTTON0, for this object.
dwType
Device type that describes the object. It is a combination of DIDFT_* flags that describe the object type (axis, button, and so on) and contains the object instance number in the middle 16 bits. Use the DIDFT_GETINSTANCE macro to extract the object instance number. For the DIDFT_* flags, see IDirectInputDevice8::EnumObjects.
dwFlags
Flags describing other attributes of the data format. This value can be one of the following:
DIDOI_ASPECTACCEL
The object reports acceleration information.
DIDOI_ASPECTFORCE
The object reports force information.
DIDOI_ASPECTMASK
The bits that are used to report aspect information. An object can represent at most one aspect.
DIDOI_ASPECTPOSITION
The object reports position information.
DIDOI_ASPECTVELOCITY
The object reports velocity information.
DIDOI_FFACTUATOR
The object can have force-feedback effects applied to it.
DIDOI_FFEFFECTTRIGGER
The object can trigger playback of force-feedback effects.
DIDOI_GUIDISUSAGE
The pguid member of the DIOBJECTDATAFORMAT structure contains the desired usage page and usage in a packed DWORD. See DIMAKEUSAGEDWORD.
DIDOI_POLLED
The object does not return data until the IDirectInputDevice8 Interface method is called.
tszName
Name of the object; for example, "X-Axis" or "Right Shift."
dwFFMaxForce
The magnitude of the maximum force that can be created by the actuator associated with this object. Force is expressed in newtons and measured in relation to where the hand would be during normal operation of the device.
dwFFForceResolution
The force resolution of the actuator associated with this object. The returned value represents the number of gradations, or subdivisions, of the maximum force that can be expressed by the force-feedback system from 0 (no force) to maximum force.
wCollectionNumber
The Human Interface Device (human interface device) link collection to which the object belongs.
wDesignatorIndex
An index that refers to a designator in the HID physical descriptor. This number can be passed to functions in the HID parsing library (Hidpi.h) to obtain additional information about the device object.
wUsagePage
The Human Interface Device (HID) usage page associated with the object, if known. HIDs always report a usage page. Non-HID devices can optionally report a usage page; if they do not, the value of this member is 0.
wUsage
The HID usage associated with the object, if known. HIDs always report a usage. Non-HIDs can optionally report a usage; if they do not, the value of this member is 0.
dwDimension
A Human Interface Device (HID) code for the dimensional units in which the object's value is reported, if known, or 0 if not known.
wExponent
The exponent to associate with the dimension, if known. Dimensional units are always integral, so an exponent might be needed to convert them to nonintegral types.
wReportId
Reserved.

Remarks

Note The value in dwOfs is the offset within the raw data returned by the device, regardless of whether the data format has been set for the device.

Applications can use the wUsagePage and wUsage members to obtain additional information about how the object was designed to be used. For example, if wUsagePage has the value 0x02 (vehicle controls) and wUsage has the value 0xB9 (elevator trim), the object was designed to be the elevator trim control on a flight stick. A flight simulator application can use this information to provide more reasonable defaults for objects on the device. HID usage codes are determined by the USB standards committee.


DIEFFECT

Used by the IDirectInputDevice8::CreateEffect method to initialize a new IDirectInputEffect Interface object. It is also used by the IDirectInputEffect::SetParameters and IDirectInputEffect::GetParameters methods.

typedef struct DIEFFECT {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwDuration;
    DWORD dwSamplePeriod;
    DWORD dwGain;
    DWORD dwTriggerButton;
    DWORD dwTriggerRepeatInterval;
    DWORD cAxes;
    LPDWORD rgdwAxes;
    LPLONG rglDirection;
    LPDIENVELOPE lpEnvelope;
    DWORD cbTypeSpecificParams;
    LPVOID lpvTypeSpecificParams;
    DWORD dwStartDelay;
} DIEFFECT, *LPDIEFFECT;

Members

dwSize
Specifies the size, in bytes, of the structure. This member must be initialized before the structure is used.
dwFlags
Flags associated with the effect. This value can be a combination of one or more of the following values:
DIEFF_CARTESIAN
The values of rglDirection are to be interpreted as Cartesian coordinates.
DIEFF_OBJECTIDS
The values of dwTriggerButton and rgdwAxes are object identifiers as obtained by IDirectInputDevice8::EnumObjects.
DIEFF_OBJECTOFFSETS
The values of dwTriggerButton and rgdwAxes are data format offsets.
DIEFF_POLAR
The values of rglDirection are to be interpreted as polar coordinates.
DIEFF_SPHERICAL
The values of rglDirection are to be interpreted as spherical coordinates.
dwDuration
The total duration of the effect, in microseconds. If this value is INFINITE, the effect has infinite duration. If an envelope has been applied to the effect, the attack is applied, followed by an infinite sustain.
dwSamplePeriod
The period at which the device should play back the effect, in microseconds. A value of 0 indicates that the default playback sample rate should be used.

If the device is not capable of playing back the effect at the specified rate, it chooses the supported rate that is closest to the requested value.

Setting a custom dwSamplePeriod can be used for special effects. For example, playing a sine wave at an artificially large sample period results in a rougher texture.

dwGain
The gain to be applied to the effect, in the range from 0 through 10,000. The gain is a scaling factor applied to all magnitudes of the effect and its envelope.
dwTriggerButton
The identifier or offset of the button to be used to trigger playback of the effect. The flags DIEFF_OBJECTIDS and DIEFF_OBJECTOFFSETS determine the semantics of the value. If this member is set to DIEB_NOTRIGGER, no trigger button is associated with the effect.
dwTriggerRepeatInterval
The interval, in microseconds, between the end of one playback and the start of the next when the effect is triggered by a button press and the button is held down. Setting this value to INFINITE suppresses repetition.

Support for trigger repeat for an effect is indicated by the presence of the DIEP_TRIGGERREPEATINTERVAL flag in the dwStaticParams member of the DIEffectInfo structure.

cAxes
Number of axes involved in the effect. This member must be filled in by the calling application if changing or setting the axis list or the direction list.

The number of axes for an effect cannot be changed once it has been set.

rgdwAxes
Pointer to a DWORD array (of cAxes elements) containing identifiers or offsets identifying the axes to which the effect is to be applied. The flags DIEFF_OBJECTIDS and DIEFF_OBJECTOFFSETS determine the semantics of the values in the array.

The list of axes associated with an effect cannot be changed once it has been set.

No more than 32 axes can be associated with a single effect.

rglDirection
Pointer to a LONG array (of cAxes elements) containing either Cartesian coordinates, polar coordinates, or spherical coordinates. The flags DIEFF_CARTESIAN, DIEFF_POLAR, and DIEFF_SPHERICAL determine the semantics of the values in the array.

If Cartesian, each value in rglDirection is associated with the corresponding axis in rgdwAxes.

If polar, the angle is measured in hundredths of degrees from the (0, - 1) direction, rotated in the direction of (1, 0). This usually means that north is away from the user, and east is to the user's right. The last element is not used.

If spherical, the first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1). The second angle (if the number of axes is three or more) is measured in hundredths of a degree toward (0, 0, 1). The third angle (if the number of axes is four or more) is measured in hundredths of a degree toward (0, 0, 0, 1), and so on. The last element is not used.

lpEnvelope
Optional pointer to a DIENVELOPE structure that describes the envelope to be used by this effect. Not all effect types use envelope. If no envelope is to be applied, the member should be set to NULL.
cbTypeSpecificParams
Number of bytes of additional type-specific parameters for the corresponding effect type.
lpvTypeSpecificParams
Pointer to type-specific parameters, or NULL if there are no type-specific parameters.

If the effect is of type DIEFT_CONDITION, this member contains a pointer to an array of DICONDITION structures that define the parameters for the condition. A single structure may be used, in which case the condition is applied in the direction specified in the rglDirection array. Otherwise, there must be one structure for each axis, in the same order as the axes in rgdwAxes array. If a structure is supplied for each axis, the effect should not be rotated; you should use the following values in the rglDirection array:

  • DIEFF_SPHERICAL: 0, 0, ...
  • DIEFF_POLAR: 9000, 0, ...
  • DIEFF_CARTESIAN: 1, 0, ...

If the effect is of type DIEFT_CUSTOMFORCE, this member contains a pointer to a DICUSTOMFORCE structure that defines the parameters for the custom force.

If the effect is of type DIEFT_PERIODIC, this member contains a pointer to a DIPERIODIC structure that defines the parameters for the effect.

If the effect is of type DIEFT_CONSTANTFORCE, this member contains a pointer to a DICONSTANTFORCE structure that defines the parameters for the constant force.

If the effect is of type DIEFT_RAMPFORCE, this member contains a pointer to a DIRAMPFORCE structure that defines the parameters for the ramp force.

dwStartDelay
Time (in microseconds) that the device should wait after an IDirectInputEffect::Start call before playing the effect. If this value is 0, effect playback begins immediately. This member is not present in versions prior to DirectX 7.0.

Remarks

Note The rglDirection array must contain cAxes entries, even if polar or spherical coordinates are given. In these cases, the last element in the rglDirection array is reserved and must be 0.


DIEffectInfo

Used by the IDirectInputDevice8::EnumEffects and IDirectInputDevice8::GetEffectInfo methods to return information about a particular effect supported by a device.

typedef struct DIEffectInfo {
    DWORD dwSize;
    GUID guid;
    DWORD dwEffType;
    DWORD dwStaticParams;
    DWORD dwDynamicParams;
    TCHAR tszName[MAX_PATH];
} DIEffectInfo, *LPDIEffectInfo;

Members

dwSize
Size of the structure in bytes. During enumeration, the application can inspect this value to determine how many members of the structure are valid. This member must be initialized before the structure is passed to the IDirectInputDevice8::GetEffectInfo method.
guid
Identifier of the effect.
dwEffType
Zero or more of the following values:
DIEFT_ALL
Valid only for IDirectInputDevice8::EnumEffects. Enumerate all effects, regardless of type. This flag cannot be combined with any of the other flags.
DIEFT_CONDITION
The effect represents a condition. When creating or modifying a condition, the lpvTypeSpecificParams member of the DIEFFECT structure must point to an array of DICONDITION structures (one per axis), and the cbTypeSpecificParams member must be set to cAxis * sizeof(DICONDITION).

Not all devices support all the parameters of conditions. Check the effect capability flags to determine which capabilities are available.

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to conditions.

DIEFT_CONSTANTFORCE
The effect represents a constant-force effect. When creating or modifying a constant-force effect, the lpvTypeSpecificParams member of the DIEFFECT must point to a DICONSTANTFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DICONSTANTFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to constant-force effects.

DIEFT_CUSTOMFORCE
The effect represents a custom-force effect. When creating or modifying a custom-force effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DICUSTOMFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DICUSTOMFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to custom-force effects.

DIEFT_DEADBAND
The effect generator for this condition effect supports the lDeadBand parameter.
DIEFT_FFATTACK
The effect generator for this effect supports the attack envelope parameter. If the effect generator does not support attack, the attack level and attack time parameters of the DIENVELOPE structure are ignored by the effect.

If neither DIEFT_FFATTACK nor DIEFT_FFFADE is set, the effect does not support an envelope, and any provided envelope is ignored.

DIEFT_FFFADE
The effect generator for this effect supports the fade parameter. If the effect generator does not support fade, the fade level and fade time parameters of the DIENVELOPE structure are ignored by the effect.

If neither DIEFT_FFATTACK nor DIEFT_FFFADE is set, the effect does not support an envelope, and any provided envelope is ignored.

DIEFT_HARDWARE
The effect represents a hardware-specific effect. For additional information about using a hardware-specific effect, consult the hardware documentation.

The flag can be passed to the IDirectInputDevice8::EnumEffects method to restrict the enumeration to hardware-specific effects.

DIEFT_PERIODIC
The effect represents a periodic effect. When creating or modifying a periodic effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DIPERIODICstructure, and the cbTypeSpecificParams member must be set to sizeof(DIPERIODIC).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to periodic effects.

DIEFT_POSNEGCOEFFICIENTS
The effect generator for this effect supports two coefficient values for conditions, one for the positive displacement of the axis and one for the negative displacement of the axis. If the device does not support both coefficients, the negative coefficient in the DICONDITION structure is ignored, and the positive coefficient is used in both directions.
DIEFT_POSNEGSATURATION
The effect generator for this effect supports a maximum saturation for both positive and negative force output. If the device does not support both saturation values, the negative saturation in the DICONDITION structure is ignored, and the positive saturation is used in both directions.
DIEFT_RAMPFORCE
The effect represents a ramp-force effect. When creating or modifying a ramp-force effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DIRAMPFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DIRAMPFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to ramp-force effects.

DIEFT_SATURATION
The effect generator for this effect supports the saturation of condition effects. If the effect generator does not support saturation, the force generated by a condition is limited only by the maximum force that the device can generate.
DIEFT_STARTDELAY
The effect has a delay before it plays rather than beginning immediately. This can be used to offset effects so that they play in sequence.
dwStaticParams
Zero or more DIEP_* values describing the parameters supported by the effect. For example, if DIEP_ENVELOPE is set, the effect supports an envelope. For a list of possible values, see IDirectInputEffect::GetParameters.

It is not an error for an application to attempt to use effect parameters that are not supported by the device. The unsupported parameters are ignored.

This information is provided to enable the application to tailor its use of force feedback to the capabilities of the specific device.

dwDynamicParams
Zero or more DIEP_* values denoting parameters of the effect that can be modified while the effect is playing. For a list of possible values, see IDirectInputEffect::GetParameters.

If an application attempts to change a parameter while the effect is playing and the driver does not support modifying that effect dynamically, the driver is permitted to stop the effect, update the parameters, then restart it. For more information, see IDirectInputEffect::SetParameters.

tszName
Name of the effect; for example, "Sawtooth up" or "Constant force".

Remarks

Use the DIDFT_GETTYPE macro to extract the effect type from the dwEffType flags.


DIEFFESCAPE

Used by the IDirectInputDevice8::Escape and IDirectInputEffect::Escape methods to pass hardware-specific data directly to the device driver.

typedef struct DIEFFESCAPE {
    DWORD dwSize;
    DWORD dwCommand;
    LPVOID lpvInBuffer;
    DWORD cbInBuffer;
    LPVOID lpvOutBuffer;
    DWORD cbOutBuffer;
} DIEFFESCAPE, *LPDIEFFESCAPE;

Members

dwSize
Size of the structure in bytes. This member must be initialized before the structure is used.
dwCommand
Driver-specific command number. Consult the driver documentation for a list of valid commands.
lpvInBuffer
Buffer containing the data required to perform the operation.
cbInBuffer
Size, in bytes, of the lpvInBuffer buffer.
lpvOutBuffer
Buffer in which the operation's output data is returned.
cbOutBuffer
On entry, the size in bytes of the lpvOutBuffer buffer. On exit, the number of bytes actually produced by the command.

Remarks

Because each driver implements different escapes, it is the application's responsibility to ensure that it is talking to the correct driver by comparing the guidFFDriver member in the DIDEVICEINSTANCE structure against the value the application is expecting.


DIENVELOPE

Used by the DIEFFECT structure to specify the optional envelope parameters for an effect. The sustain level for the envelope is represented by the dwMagnitude member of the DIPERIODIC structure and the lMagnitude member of the DICONSTANTFORCE structure. The sustain time is represented by dwDuration member of the DIEFFECT structure.

typedef struct DIENVELOPE {
    DWORD dwSize;
    DWORD dwAttackLevel;
    DWORD dwAttackTime;
    DWORD dwFadeLevel;
    DWORD dwFadeTime;
} DIENVELOPE, *LPDIENVELOPE;

Members

dwSize
Size, in bytes, of the structure. This member must be initialized before the structure is used.
dwAttackLevel
Amplitude for the start of the envelope, relative to the baseline, in the range from 0 through 10,000. If the effect's type-specific data does not specify a baseline, the amplitude is relative to 0.
dwAttackTime
The time, in microseconds, to reach the sustain level.
dwFadeLevel
Amplitude for the end of the envelope, relative to the baseline, in the range from 0 through 10,000. If the effect's type-specific data does not specify a baseline, the amplitude is relative to 0.
dwFadeTime
The time, in microseconds, to reach the fade level.


DIFILEEFFECT

Describes data for a force-feedback effect stored in a file. It is used in conjunction with the IDirectInputDevice8::EnumEffectsInFile and IDirectInputDevice8::WriteEffectToFile methods.

typedef struct DIFILEEFFECT {
    DWORD dwSize;
    GUID GuidEffect;
    LPCDIEFFECT lpDiEffect;
    CHAR szFriendlyName[MAX_PATH];
} DIFILEEFFECT, *LPDIFILEEFFECT;

Members

dwSize
Size, in bytes, of the structure. This member must be initialized before the structure is used.
GuidEffect
Unique identifier of the effect type. This can be one of the standard GUIDs defined in Dinput.h, such as GUID_ConstantForce, or one created by the designer.
lpDiEffect
Pointer to a DIEFFECT structure containing information about the effect.
szFriendlyName
Name of the effect.


DIJOYSTATE

Describes the state of a joystick device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

typedef struct DIJOYSTATE {
    LONG lX;
    LONG lY;
    LONG lZ;
    LONG lRx;
    LONG lRy;
    LONG lRz;
    LONG rglSlider[2];
    DWORD rgdwPOV[4];
    BYTE rgbButtons[32];
} DIJOYSTATE, *LPDIJOYSTATE;

Members

lX
X-axis, usually the left-right movement of a stick.
lY
Y-axis, usually the forward-backward movement of a stick.
lZ
Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0.
lRx
X-axis rotation. If the joystick does not have this axis, the value is 0.
lRy
Y-axis rotation. If the joystick does not have this axis, the value is 0.
lRz
Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
rglSlider
Two additional axes, formerly called the u-axis and v-axis, whose semantics depend on the joystick. Use the IDirectInputDevice8::GetObjectInfo method to obtain semantic information about these values.
rgdwPOV
Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as - 1; but see Remarks. For indicators that have only five positions, the value for a controller is - 1, 0, 9,000, 18,000, or 27,000.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down, and clear if the button is up or does not exist.

Remarks

You must prepare the device for joystick-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIJoystick global data format variable.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

Note Under DirectX 7.0, sliders on some joysticks could be assigned to the Z axis, with subsequent code retrieving data from that member. Using DirectX 8.0 and later, those same sliders will be assigned to the rglSlider array. This should be taken into account when porting applications to later versions of DirectX. Make any necessary alterations to ensure that slider data is retrieved from the rglSlider array.

See Also

DIJOYSTATE2


DIJOYSTATE2

Describes the state of a joystick device with extended capabilities. This structure is used with the IDirectInputDevice8::GetDeviceState method.

typedef struct DIJOYSTATE2 {
    LONG lX;
    LONG lY;
    LONG lZ;
    LONG lRx;
    LONG lRy;
    LONG lRz;
    LONG rglSlider[2];
    DWORD rgdwPOV[4];
    BYTE rgbButtons[128];
    LONG lVX;
    LONG lVY;
    LONG lVZ;
    LONG lVRx;
    LONG lVRy;
    LONG lVRz;
    LONG rglVSlider[2];
    LONG lAX;
    LONG lAY;
    LONG lAZ;
    LONG lARx;
    LONG lARy;
    LONG lARz;
    LONG rglASlider[2];
    LONG lFX;
    LONG lFY;
    LONG lFZ;
    LONG lFRx;
    LONG lFRy;
    LONG lFRz;
    LONG rglFSlider[2];
} DIJOYSTATE2, *LPDIJOYSTATE2;

Members

lX
X-axis, usually the left-right movement of a stick.
lY
Y-axis, usually the forward-backward movement of a stick.
lZ
Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0.
lRx
X-axis rotation. If the joystick does not have this axis, the value is 0.
lRy
Y-axis rotation. If the joystick does not have this axis, the value is 0.
lRz
Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
rglSlider
Two additional axis values (formerly called the u-axis and v-axis) whose semantics depend on the joystick. Use the IDirectInputDevice8::GetObjectInfo method to obtain semantic information about these values.
rgdwPOV
Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as - 1; but see Remarks. For indicators that have only five positions, the value for a controller is - 1, 0, 9,000, 18,000, or 27,000.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down, and clear if the button is up or does not exist.
lVX
X-axis velocity.
lVY
Y-axis velocity.
lVZ
Z-axis velocity.
lVRx
X-axis angular velocity.
lVRy
Y-axis angular velocity.
lVRz
Z-axis angular velocity.
rglVSlider
Extra axis velocities.
lAX
X-axis acceleration.
lAY
Y-axis acceleration.
lAZ
Z-axis acceleration.
lARx
X-axis angular acceleration.
lARy
Y-axis angular acceleration.
lARz
Z-axis angular acceleration.
rglASlider
Extra axis accelerations.
lFX
X-axis force.
lFY
Y-axis force.
lFZ
Z-axis force.
lFRx
X-axis torque.
lFRy
Y-axis torque.
lFRz
Z-axis torque.
rglFSlider
Extra axis forces.

Remarks

You must prepare the device for access to a joystick with extended capabilities by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIJoystick2 global data format variable.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

Note Under DirectX 7.0, sliders on some joysticks could be assigned to the Z axis, with subsequent code retrieving data from that member. Using DirectX 8.0 and later, those same sliders will be assigned to the rglSlider array. This should be taken into account when porting applications to later versions of DirectX. Make any necessary alterations to ensure that slider data is retrieved from the rglSlider array.

See Also

DIJOYSTATE


DIMOUSESTATE

Describes the state of a mouse device that has up to four buttons, or another device that is being accessed as if it were a mouse device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

typedef struct DIMOUSESTATE {
    LONG lX;
    LONG lY;
    LONG lZ;
    BYTE rgbButtons[4];
} DIMOUSESTATE, *LPDIMOUSESTATE;

Members

lX
X-axis.
lY
Y-axis.
lZ
Z-axis, typically a wheel. If the mouse does not have a z-axis, the value is 0.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down.

Remarks

You must prepare the device for mouse-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIMouse global data format variable.

The mouse is a relative-axis device, so the absolute axis positions for mouse axes are accumulated relative motion. Therefore, the value of the absolute axis position is not meaningful except in comparison with other absolute axis positions.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

See Also

DIMOUSESTATE2


DIMOUSESTATE2

Describes the state of a mouse device that has up to eight buttons, or another device that is being accessed as if it were a mouse device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

typedef struct DIMOUSESTATE2 {
    LONG lX;
    LONG lY;
    LONG lZ;
    BYTE rgbButtons[8];
} DIMOUSESTATE2, *LPDIMOUSESTATE2;

Members

lX
X-axis.
lY
Y-axis.
lZ
Z-axis, typically a wheel. If the mouse does not have a z-axis, the value is 0.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down.

Remarks

You must prepare the device for mouse-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIMouse2 global data format variable.

The mouse is a relative-axis device, so the absolute axis positions for mouse axes are accumulated relative motion. Therefore, the value of the absolute axis position is not meaningful except in comparison with other absolute axis positions.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

See Also

DIMOUSESTATE


DIOBJECTDATAFORMAT

Describes a device object's data format for use with the IDirectInputDevice8::SetDataFormat method.

typedef struct DIOBJECTDATAFORMAT {
    CONST GUID * pguid;
    DWORD dwOfs;
    DWORD dwType;
    DWORD dwFlags;
} DIOBJECTDATAFORMAT, *LPDIOBJECTDATAFORMAT;

Members

pguid
Unique identifier for the axis, button, or other input source. When requesting a data format, making this member NULL indicates that any type of object is permissible.
dwOfs
Offset within the data packet where the data for the input source is stored. This value must be a multiple of 4 for DWORD size data, such as axes. It can be byte-aligned for buttons.
dwType
Device type that describes the object. It is a combination of the following flags describing the object type (axis, button, and so forth) and containing the object-instance number in the middle 16 bits. When requesting a data format, the instance portion must be set to DIDFT_ANYINSTANCE to indicate that any instance is permissible, or to DIDFT_MAKEINSTANCE(n) to restrict the request to instance n. See the examples under Remarks.
DIDFT_ABSAXIS
The object selected by the IDirectInputDevice8::SetDataFormat method must be an absolute axis.
DIDFT_AXIS
The object selected by the IDirectInputDevice8::SetDataFormat method must be an absolute or relative axis.
DIDFT_BUTTON
The object selected by the IDirectInputDevice8::SetDataFormat method must be a push button or a toggle button.
DIDFT_FFACTUATOR
The object selected by the IDirectInputDevice8::SetDataFormat method must contain a force-feedback actuator; in other words, it must be possible to apply forces to the object.
DIDFT_FFEFFECTTRIGGER
The object selected by the IDirectInputDevice8::SetDataFormat method must be a valid force-feedback effect trigger.
DIDFT_POV
The object selected by the IDirectInputDevice8::SetDataFormat method must be a point-of-view controller.
DIDFT_PSHBUTTON
The object selected by the IDirectInputDevice8::SetDataFormat method must be a push button.
DIDFT_RELAXIS
The object selected by IDirectInputDevice8::SetDataFormat must be a relative axis.
DIDFT_TGLBUTTON
The object selected by IDirectInputDevice8::SetDataFormat must be a toggle button.
DIDFT_VENDORDEFINED
The object selected by IDirectInputDevice8::SetDataFormat must be of a type defined by the manufacturer.
dwFlags
Zero or more of the following values:
DIDOI_ASPECTACCEL
The object selected by IDirectInputDevice8::SetDataFormat must report acceleration information.
DIDOI_ASPECTFORCE
The object selected by IDirectInputDevice8::SetDataFormat must report force information.
DIDOI_ASPECTPOSITION
The object selected by IDirectInputDevice8::SetDataFormat must report position information.
DIDOI_ASPECTVELOCITY
The object selected by IDirectInputDevice8::SetDataFormat must report velocity information.

Remarks

A data format is made up of several DIOBJECTDATAFORMAT structures, one for each object (axis, button, and so on). An array of these structures is contained in the DIDATAFORMAT structure that is passed to IDirectInputDevice8::SetDataFormat. An application typically does not need to create an array of DIOBJECTDATAFORMAT structures; rather, it can use one of the predefined data formats, c_dfDIMouse, c_dfDIMouse2, c_dfDIKeyboard, c_dfDIJoystick, or c_dfDIJoystick2, which have predefined settings for DIOBJECTDATAFORMAT.

The following object data format specifies that DirectInput should choose the first available axis and report its value in the DWORD at offset 4 in the device data.

DIOBJECTDATAFORMAT dfAnyAxis = {
    0,                              // Wildcard
    4,                              // Offset
    DIDFT_AXIS | DIDFT_ANYINSTANCE, // Any axis is okay.
    0,                              // Ignore aspect
};

The following object data format specifies that the x-axis of the device should be stored in the DWORD at offset 12 in the device data. If the device has more than one x-axis, the first available one should be selected.

DIOBJECTDATAFORMAT dfAnyXAxis = {
    &GUID_XAxis,                    // Must be an x-axis
    12,                             // Offset
    DIDFT_AXIS | DIDFT_ANYINSTANCE, // Any x-axis is okay.
    0,                              // Ignore aspect
};

The following object data format specifies that DirectInput should choose the first available button and report its value in the high bit of the byte at offset 16 in the device data.

DIOBJECTDATAFORMAT dfAnyButton = {
    0,                                // Wildcard
    16,                               // Offset
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, // Any button is okay.
    0,                                // Ignore aspect
};

The following object data format specifies that button 0 of the device should be reported as the high bit of the byte stored at offset 18 in the device data.

If the device does not have a button 0, the attempt to set this data format fails.

DIOBJECTDATAFORMAT dfButton0 = {
    0,                                    // Wildcard
    18,                                   // Offset
    DIDFT_BUTTON | DIDFT_MAKEINSTANCE(0), // Button zero
    0,                                    // Ignore aspect
};


DIPERIODIC

Contains type-specific information for effects that are marked as DIEFT_PERIODIC.

The structure describes a periodic effect.

A pointer to a single DIPERIODIC structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DIPERIODIC {
    DWORD dwMagnitude;
    LONG lOffset;
    DWORD dwPhase;
    DWORD dwPeriod;
} DIPERIODIC, *LPDIPERIODIC;

Members

dwMagnitude
Magnitude of the effect, in the range from 0 through 10,000. If an envelope is applied to this effect, the value represents the magnitude of the sustain. If no envelope is applied, the value represents the amplitude of the entire effect.
lOffset
Offset of the effect. The range of forces generated by the effect is lOffset minus dwMagnitude to lOffset plus dwMagnitude. The value of the lOffset member is also the baseline for any envelope that is applied to the effect.
dwPhase
Position in the cycle of the periodic effect at which playback begins, in the range from 0 through 35,999. See Remarks.
dwPeriod
Period of the effect, in microseconds.

Remarks

A device driver cannot provide support for all values in the dwPhase member. In this case, the value is rounded off to the nearest supported value.


DIPROPCPOINTS

Deprecated, do not use. Sets calibration points for the current instance.

typedef struct DIPROPCPOINTS {
    DIPROPHEADER diph;
    DWORD dwCPointsNum;
    CPOINT cp[MAXCPOINTSNUM];
} DIPROPCPOINTS, *LPDIPROPCPOINTS;

Members

diph
DIPROPHEADER structure.
dwCPointsNum
Number of stored calibration points. No more than 8 calibration points may be used.
cp
Array of calibration points.

Remarks

The diph member must be initialized as follows:

Member | Value
dwSize | sizeof(DIPROPCPOINTS)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (human interface device). The device object will be identified by the HID usage page and usage values in packed form.

This property can be applied only to individual device objects, so DIPH_DEVICE cannot be used.
dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.


DIPROPDWORD

Used to access DWORD properties.

typedef struct DIPROPDWORD {
    DIPROPHEADER diph;
    DWORD dwData;
} DIPROPDWORD, *LPDIPROPDWORD;

Members

diph
DIPROPHEADER structure.
dwData
Property-specific value being set or retrieved.

Remarks

The diph member must be initialized as follows:

Member | Value
dwSize | sizeof(DIPROPDWORD)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj

If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (human interface device). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

See Also

IDirectInputDevice8::GetProperty, IDirectInputDevice8::SetProperty


DIPROPGUIDANDPATH

Used to access properties whose values represent a globally unique identifier (GUID) and a path.

typedef struct DIPROPGUIDANDPATH {
    DIPROPHEADER diph;
    GUID guidClass;
    WCHAR wszPath[MAX_PATH];
} DIPROPGUIDANDPATH, *LPDIPROPGUIDANDPATH;

Members

diph
DIPROPHEADER structure.
guidClass
Class GUID for the object.
wszPath
Returned path for the object. This is a Unicode string.

Remarks

The diph member must be initialized as follows:

Member | Value
dwSize | sizeof(DIPROPGUIDANDPATH).
dwHeaderSize | sizeof(DIPROPHEADER).
dwObj | For this structure, this member must be set to 0.
dwHow | Specifies how the dwObj member should be interpreted. For this structure, dwHow should be DIPH_DEVICE.

The DIPROP_GUIDANDPATH property associated with the DIPROPGUIDANDPATH structure enables advanced applications to perform operations on a Human Interface Device (human interface device) that are not supported by DirectInput.

The application calls the IDirectInputDevice8::GetProperty method with DIPROP_GUIDANDPATH as the rguidProp parameter. The class GUID of the device is returned in the guidClass member of the DIPROPGUIDANDPATH structure, and the device interface path is returned in the wszPath member. The application can then call the CreateFile function on this path to access the device directly.


DIPROPHEADER

Serves as a header for all property structures.

typedef struct DIPROPHEADER {
    DWORD dwSize;
    DWORD dwHeaderSize;
    DWORD dwObj;
    DWORD dwHow;
} DIPROPHEADER, *LPDIPROPHEADER;

Members

dwSize
Size of the enclosing structure. This member must be initialized before the structure is used.
dwHeaderSize
Size of the DIPROPHEADER structure.
dwObj
Object for which the property is to be accessed. The value set for this member depends on the value specified in the dwHow member.
dwHow
Value that specifies how the dwObj member should be interpreted. This value can be one of the following:
DIPH_DEVICE
The dwObj member must be 0.
DIPH_BYOFFSET
The dwObj member is the offset into the current data format of the object whose property is being accessed.
DIPH_BYUSAGE
The dwObj member is the human interface device usage page and usage values in packed form.
DIPH_BYID
The dwObj member is the object type/instance identifier. This identifier is returned in the dwType member of the DIDEVICEOBJECTINSTANCE structure returned from a previous call to the IDirectInputDevice8::EnumObjects member.


DIPROPPOINTER

Used in setting and retrieving data values of type UINT_PTR. This is typically a value associated with an application-specific action associated with a device object in an action map, but can also be a function pointer.

typedef struct DIPROPPOINTER {
    DIPROPHEADER diph;
    UINT_PTR uData;
} DIPROPPOINTER, *LPDIPROPPOINTER;

Members

diph
DIPROPHEADER structure.
uData
Application-defined value of type UINT_PTR, which represents the uAppData value (from an action map) that is associated with a device control.

Remarks

The diph member must be initialized as follows:

Member | Value
dwSize | sizeof(DIPROPPOINTER)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj

If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (human interface device). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.


DIPROPRANGE

Contains information about the range of an object within a device. This structure is used with the DIPROP_RANGE flag set in the IDirectInputDevice8::GetProperty and IDirectInputDevice8::SetProperty methods.

typedef struct DIPROPRANGE {
    DIPROPHEADER diph;
    LONG lMin;
    LONG lMax;
} DIPROPRANGE, *LPDIPROPRANGE;

Members

diph
DIPROPHEADER structure.
lMin
Lower limit of the range. If the range of the device is unrestricted, this value is DIPROPRANGE_NOMIN when the IDirectInputDevice8::GetProperty method returns.
lMax
Upper limit of the range. If the range of the device is unrestricted, this value is DIPROPRANGE_NOMAX when the IDirectInputDevice8::GetProperty method returns.

Remarks

The diph member must be initialized as follows:

Member | Value
dwSize | sizeof(DIPROPRANGE)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj

If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.Identifier of the object whose property is being retrieved or set.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (human interface device). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

The range values for devices whose ranges are unrestricted wraparound.

See Also

IDirectInputDevice8::GetProperty, IDirectInputDevice8::SetProperty


DIPROPSTRING

Gets and retrieves properties as strings.

typedef struct DIPROPSTRING {
    DIPROPHEADER diph;
    WCHAR wsz[MAX_PATH];
} DIPROPSTRING, *LPDIPROPSTRING;

Members

diph
DIPROPHEADER structure.
wsz
Unicode string that specifies or retrieves the property.

Remarks

The diph member must be initialized as follows:

Member | Value
dwSize | sizeof(DIPROPSTRING)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj

If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (human interface device). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

The DIPROP_INSTANCENAME and DIPROP_PRODUCTNAME properties associated with the DIPROPSTRING structure enable advanced applications to perform operations on a Human Interface Device (HID) that are not supported by DirectInput.


DIRAMPFORCE

Contains type-specific information for effects that are marked as DIEFT_RAMPFORCE. The structure describes a ramp force effect.

A pointer to a single DIRAMPFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DIRAMPFORCE {
    LONG lStart;
    LONG lEnd;
} DIRAMPFORCE, *LPDIRAMPFORCE;

Members

lStart
Magnitude at the start of the effect, in the range from - 10,000 through 10,000.
lEnd
Magnitude at the end of the effect, in the range from - 10,000 through 10,000.

Remarks

The dwDuration for a ramp force effect cannot be INFINITE.


Device Constants

This section is a reference for constants used to interpret data for keys, buttons, and axes.

Constants

  • DirectInput and Japanese Keyboards
  • Joystick Device Constants
  • Keyboard Device
  • Mouse Device


DirectInput and Japanese Keyboards

This topic lists keys that are available on Japanese keyboards but not on standard U.S. keyboards, as well as keys that are available on U.S. keyboards but not on the various Japanese keyboards.

On Microsoft Windows 2000 and with some keyboards (such as the NEC PC-98) using other operating systems, the DIK_CAPSLOCK, DIK_KANJI, and DIK_KANA keys are toggle buttons and not push buttons. These generate a down event when first pressed, then generate an up event when pressed a second time.

Japanese Keyboard | Additional keys | Missing keys
DOS/V 106, NEC PC-98 106 | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_CONVERT, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_APOSTROPHE, DIK_EQUALS, DIK_GRAVE
NEC PC-98 | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_F13, DIK_F14, DIK_F15, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_NUMPADCOMMA, DIK_NUMPADEQUALS, DIK_STOP, DIK_UNDERLINE, DIK_YEN | DIK_APOSTROPHE, DIK_BACKSLASH, DIK_EQUALS, DIK_GRAVE, DIK_NUMLOCK, DIK_NUMPADENTER, DIK_RCONTROL, DIK_RMENU, DIK_RSHIFT, DIK_SCROLL
AX | DIK_AX, DIK_CONVERT, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_RCONTROL, DIK_RMENU
J-3100 | DIK_KANA, DIK_KANJI, DIK_NOLABEL, DIK_YEN | DIK_RCONTROL, DIK_RMENU


Joystick Device Constants

Joystick device constants represent offsets within a joystick device's data packet, the DIJOYSTATE structure. The data at a given offset is associated with a device object; that is, a button or axis. Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures.

The following macros return a constant indicating the offset of the data for a particular button or axis relative to the beginning of the DIJOYSTATE structure.

Constant | Device object
DIJOFS_BUTTON0 to DIJOFS_BUTTON31 or DIJOFS_BUTTON(n) | Button
DIJOFS_POV(n) | Point-of-view indicator
DIJOFS_RX | X-axis rotation
DIJOFS_RY | Y-axis rotation
DIJOFS_RZ | Z-axis rotation (rudder)
DIJOFS_X | X-axis
DIJOFS_Y | Y-axis
DIJOFS_Z | Z-axis
DIJOFS_SLIDER(n) | Slider axis


Keyboard Device

Keyboard device constants, defined in Dinput.h, represent offsets within a keyboard device's data packet, a 256-byte array.

typedef enum Keyboard_Device
{
    DIK_0,
    DIK_1,
    DIK_2,
    DIK_3,
    DIK_4,
    DIK_5,
    DIK_6,
    DIK_7,
    DIK_8,
    DIK_9,
    DIK_A,
    DIK_ABNT_C1,
    DIK_ABNT_C2,
    DIK_ADD,
    DIK_APOSTROPHE,
    DIK_APPS,
    DIK_AT,
    DIK_AX,
    DIK_B,
    DIK_BACK,
    DIK_BACKSLASH,
    DIK_C,
    DIK_CALCULATOR,
    DIK_CAPITAL,
    DIK_COLON,
    DIK_COMMA,
    DIK_CONVERT,
    DIK_D,
    DIK_DECIMAL,
    DIK_DELETE,
    DIK_DIVIDE,
    DIK_DOWN,
    DIK_E,
    DIK_END,
    DIK_EQUALS,
    DIK_ESCAPE,
    DIK_F,
    DIK_F1,
    DIK_F2,
    DIK_F3,
    DIK_F4,
    DIK_F5,
    DIK_F6,
    DIK_F7,
    DIK_F8,
    DIK_F9,
    DIK_F10,
    DIK_F11,
    DIK_F12,
    DIK_F13,
    DIK_F14,
    DIK_F15,
    DIK_G,
    DIK_GRAVE,
    DIK_H,
    DIK_HOME,
    DIK_I,
    DIK_INSERT,
    DIK_J,
    DIK_K,
    DIK_KANA,
    DIK_KANJI,
    DIK_L,
    DIK_LBRACKET,
    DIK_LCONTROL,
    DIK_LEFT,
    DIK_LMENU,
    DIK_LSHIFT,
    DIK_LWIN,
    DIK_M,
    DIK_MAIL,
    DIK_MEDIASELECT,
    DIK_MEDIASTOP,
    DIK_MINUS,
    DIK_MULTIPLY,
    DIK_MUTE,
    DIK_MYCOMPUTER,
    DIK_N,
    DIK_NEXT,
    DIK_NEXTTRACK,
    DIK_NOCONVERT,
    DIK_NUMLOCK,
    DIK_NUMPAD0,
    DIK_NUMPAD1,
    DIK_NUMPAD2,
    DIK_NUMPAD3,
    DIK_NUMPAD4,
    DIK_NUMPAD5,
    DIK_NUMPAD6,
    DIK_NUMPAD7,
    DIK_NUMPAD8,
    DIK_NUMPAD9,
    DIK_NUMPADCOMMA,
    DIK_NUMPADENTER,
    DIK_NUMPADEQUALS,
    DIK_O,
    DIK_OEM_102,
    DIK_P,
    DIK_PAUSE,
    DIK_PERIOD,
    DIK_PLAYPAUSE,
    DIK_POWER,
    DIK_PREVTRACK,
    DIK_PRIOR,
    DIK_Q,
    DIK_R,
    DIK_RBRACKET,
    DIK_RCONTROL,
    DIK_RETURN,
    DIK_RIGHT,
    DIK_RMENU,
    DIK_RSHIFT,
    DIK_RWIN,
    DIK_S,
    DIK_SCROLL,
    DIK_SEMICOLON,
    DIK_SLASH,
    DIK_SLEEP,
    DIK_SPACE,
    DIK_STOP,
    DIK_SUBTRACT,
    DIK_SYSRQ,
    DIK_T,
    DIK_TAB,
    DIK_U,
    DIK_UNDERLINE,
    DIK_UNLABELED,
    DIK_UP,
    DIK_V,
    DIK_VOLUMEDOWN,
    DIK_VOLUMEUP,
    DIK_W,
    DIK_WAKE,
    DIK_WEBBACK,
    DIK_WEBFAVORITES,
    DIK_WEBFORWARD,
    DIK_WEBHOME,
    DIK_WEBREFRESH,
    DIK_WEBSEARCH,
    DIK_WEBSTOP,
    DIK_X,
    DIK_Y,
    DIK_YEN,
    DIK_Z,
} Keyboard Device, *LPKeyboard Device;

Constants

DIK_0
On main keyboard
DIK_1
On main keyboard
DIK_2
On main keyboard
DIK_3
On main keyboard
DIK_4
On main keyboard
DIK_5
On main keyboard
DIK_6
On main keyboard
DIK_7
On main keyboard
DIK_8
On main keyboard
DIK_9
On main keyboard
DIK_A
DIK_ABNT_C1
On numeric pad of Brazilian keyboards
DIK_ABNT_C2
On numeric pad of Brazilian keyboards
DIK_ADD
PLUS SIGN (+) on numeric keypad
DIK_APOSTROPHE
DIK_APPS
Application key
DIK_AT
On Japanese keyboard
DIK_AX
On Japanese keyboard
DIK_B
DIK_BACK
BACKSPACE
DIK_BACKSLASH
DIK_C
DIK_CALCULATOR
DIK_CAPITAL
CAPS LOCK
DIK_COLON
On Japanese keyboard
DIK_COMMA
DIK_CONVERT
On Japanese keyboard
DIK_D
DIK_DECIMAL
PERIOD (decimal point) on numeric keypad
DIK_DELETE
DIK_DIVIDE
Forward slash (/) on numeric keypad
DIK_DOWN
DOWN ARROW
DIK_E
DIK_END
DIK_EQUALS
On main keyboard
DIK_ESCAPE
DIK_F
DIK_F1
DIK_F2
DIK_F3
DIK_F4
DIK_F5
DIK_F6
DIK_F7
DIK_F8
DIK_F9
DIK_F10
DIK_F11
DIK_F12
DIK_F13
On NEC PC-98 Japanese keyboard
DIK_F14
On NEC PC-98 Japanese keyboard
DIK_F15
On NEC PC-98 Japanese keyboard
DIK_G
DIK_GRAVE
Grave accent (`)
DIK_H
DIK_HOME
DIK_I
DIK_INSERT
DIK_J
DIK_K
DIK_KANA
On Japanese keyboard
DIK_KANJI
On Japanese keyboard
DIK_L
DIK_LBRACKET
Left square bracket [
DIK_LCONTROL
Left CTRL
DIK_LEFT
LEFT ARROW
DIK_LMENU
Left ALT
DIK_LSHIFT
Left SHIFT
DIK_LWIN
Left Windows logo key
DIK_M
DIK_MAIL
DIK_MEDIASELECT
Media Select key, which displays a selection of supported media players on the system
DIK_MEDIASTOP
DIK_MINUS
On main keyboard
DIK_MULTIPLY
Asterisk (*) on numeric keypad
DIK_MUTE
DIK_MYCOMPUTER
DIK_N
DIK_NEXT
PAGE DOWN
DIK_NEXTTRACK
Next track
DIK_NOCONVERT
On Japanese keyboard
DIK_NUMLOCK
DIK_NUMPAD0
DIK_NUMPAD1
DIK_NUMPAD2
DIK_NUMPAD3
DIK_NUMPAD4
DIK_NUMPAD5
DIK_NUMPAD6
DIK_NUMPAD7
DIK_NUMPAD8
DIK_NUMPAD9
DIK_NUMPADCOMMA
On numeric keypad of NEC PC-98 Japanese keyboard
DIK_NUMPADENTER
DIK_NUMPADEQUALS
On numeric keypad of NEC PC-98 Japanese keyboard
DIK_O
DIK_OEM_102
On British and German keyboards
DIK_P
DIK_PAUSE
DIK_PERIOD
On main keyboard
DIK_PLAYPAUSE
DIK_POWER
DIK_PREVTRACK
Previous track; circumflex on Japanese keyboard
DIK_PRIOR
PAGE UP
DIK_Q
DIK_R
DIK_RBRACKET
Right square bracket ]
DIK_RCONTROL
Right CTRL
DIK_RETURN
ENTER on main keyboard
DIK_RIGHT
RIGHT ARROW
DIK_RMENU
Right ALT
DIK_RSHIFT
Right SHIFT
DIK_RWIN
Right Windows logo key
DIK_S
DIK_SCROLL
SCROLL LOCK
DIK_SEMICOLON
DIK_SLASH
Forward slash (/) on main keyboard
DIK_SLEEP
DIK_SPACE
SPACEBAR
DIK_STOP
On NEC PC-98 Japanese keyboard
DIK_SUBTRACT
MINUS SIGN (-) on numeric keypad
DIK_SYSRQ
DIK_T
DIK_TAB
DIK_U
DIK_UNDERLINE
On NEC PC-98 Japanese keyboard
DIK_UNLABELED
On Japanese keyboard
DIK_UP
UP ARROW
DIK_V
DIK_VOLUMEDOWN
DIK_VOLUMEUP
DIK_W
DIK_WAKE
DIK_WEBBACK
DIK_WEBFAVORITES
Displays the Microsoft Internet Explorer Favorites list, the Windows Favorites folder, or the Netscape Bookmarks list.
DIK_WEBFORWARD
DIK_WEBHOME
DIK_WEBREFRESH
DIK_WEBSEARCH
DIK_WEBSTOP
DIK_X
DIK_Y
DIK_YEN
On Japanese keyboard
DIK_Z

Remarks

The following alternate names are available:

Alternate name | Regular name | Note
DIK_BACKSPACE | DIK_BACK | BACKSPACE
DIK_CAPSLOCK | DIK_CAPITAL | CAPS LOCK
DIK_CIRCUMFLEX | DIK_PREVTRACK | On Japanese keyboard
DIK_DOWNARROW | DIK_DOWN | On arrow keypad
DIK_LALT | DIK_LMENU | Left ALT
DIK_LEFTARROW | DIK_LEFT | On arrow keypad
DIK_NUMPADMINUS | DIK__SUBTRACT | MINUS SIGN (-) on numeric keypad
DIK_NUMPADPERIOD | DIK_DECIMAL | PERIOD (decimal point) on numeric keypad
DIK_NUMPADPLUS | DIK_ADD | PLUS SIGN (+) on numeric keypad
DIK_NUMPADSLASH | DIK__DIVIDE | Forward slash (/) on numeric keypad
DIK_NUMPADSTAR | DIK_MULTIPLY | Asterisk (*) on numeric keypad
DIK_PGDN | DIK_NEXT | On arrow keypad
DIK_PGUP | DIK_PRIOR | On arrow keypad
DIK_RALT | DIK_RMENU | Right ALT
DIK_RIGHTARROW | DIK_RIGHT | On arrow keypad
DIK_UPARROW | DIK_UP | On arrow keypad

For information about Japanese keyboards, see DirectInput and Japanese Keyboards.

The data at a given offset is associated with a keyboard key. Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures, or as indices when accessing data within the array using array notation.


Mouse Device

Mouse device constants, defined in Dinput.h, represent offsets within a mouse device's data packet, the DIMOUSESTATE or DIMOUSESTATE2 structure.

typedef enum Mouse_Device
{
    DIMOFS_BUTTON0,
    DIMOFS_BUTTON1,
    DIMOFS_BUTTON2,
    DIMOFS_BUTTON3,
    DIMOFS_BUTTON4,
    DIMOFS_BUTTON5,
    DIMOFS_BUTTON6,
    DIMOFS_BUTTON7,
    DIMOFS_X,
    DIMOFS_Y,
    DIMOFS_Z,
} Mouse Device, *LPMouse Device;

Constants

DIMOFS_BUTTON0
DIMOFS_BUTTON1
DIMOFS_BUTTON2
DIMOFS_BUTTON3
DIMOFS_BUTTON4
DIMOUSESTATE2 only
DIMOFS_BUTTON5
DIMOUSESTATE2 only
DIMOFS_BUTTON6
DIMOUSESTATE2 only
DIMOFS_BUTTON7
DIMOUSESTATE2 only
DIMOFS_X
DIMOFS_Y
DIMOFS_Z

Remarks

The data at a given offset is associated with a device object (button or axis). Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures.


Action Mapping Constants

This section is a reference to the constants defined in Dinput.h for application genres and controls mapped to actions within each genre.

The control constants, such as DIAXIS_FIGHTINGH_MOVE, are used in the dwSemantic member of the DIACTION structure to associate the control with an action in the application.

The constants for the genres, such as DIVIRTUAL_FIGHTING_HAND2HAND, are used in the dwGenre member of the DIACTIONFORMAT structure.

Action mapping constants are provided for application genres in the following categories.

  • Action Genres
  • Arcade Genres
  • CAD Genres
  • Control Genres
  • Driving Genres
  • Flight Genres
  • Sports Genres
  • Strategy Genres

The dwSemantic member of the DIACTION structure member can map the action to a particular device object rather than a virtual control. Device object constants are provided in the following categories.

  • Any-Control
  • Keyboard Mapping
  • Mouse Mapping


Action Genres

The following genres contain controls for fighting and action games.

  • Hand-to-Hand
  • Shooting
  • Third-Person Action


Hand-to-Hand

The DIVIRTUAL_FIGHTING_HAND2HAND genre contains controls for a first-person fighting game without guns.

Priority 1 Controls
DIAXIS_FIGHTINGH_LATERAL
DIAXIS_FIGHTINGH_MOVE
DIBUTTON_FIGHTINGH_BLOCK
DIBUTTON_FIGHTINGH_CROUCH
DIBUTTON_FIGHTINGH_JUMP
DIBUTTON_FIGHTINGH_KICK
DIBUTTON_FIGHTINGH_MENU
DIBUTTON_FIGHTINGH_PUNCH
DIBUTTON_FIGHTINGH_SPECIAL1
DIBUTTON_FIGHTINGH_SPECIAL2
Priority 2 Controls
DIAXIS_FIGHTINGH_ROTATE
DIBUTTON_FIGHTINGH_BACKWARD_LINK
DIBUTTON_FIGHTINGH_DEVICE
DIBUTTON_FIGHTINGH_DISPLAY
DIBUTTON_FIGHTINGH_DODGE
DIBUTTON_FIGHTINGH_FORWARD_LINK
DIBUTTON_FIGHTINGH_LEFT_LINK
DIBUTTON_FIGHTINGH_RIGHT_LINK
DIBUTTON_FIGHTINGH_PAUSE
DIBUTTON_FIGHTINGH_SELECT
DIHATSWITCH_FIGHTINGH_SLIDE


Shooting

The DIVIRTUAL_FIGHTING_FPS genre contains controls for a first-person fighting game with guns.

Priority 1 Controls
DIAXIS_FPS_LOOKUPDOWN
DIAXIS_FPS_MOVE
DIAXIS_FPS_ROTATE
DIBUTTON_FPS_APPLY
DIBUTTON_FPS_CROUCH
DIBUTTON_FPS_FIRE
DIBUTTON_FPS_JUMP
DIBUTTON_FPS_MENU
DIBUTTON_FPS_SELECT
DIBUTTON_FPS_STRAFE
DIBUTTON_FPS_WEAPONS
Priority 2 Controls
DIAXIS_FPS_SIDESTEP
DIBUTTON_FPS_BACKWARD_LINK
DIBUTTON_FPS_DEVICE
DIBUTTON_FPS_DISPLAY
DIBUTTON_FPS_DODGE
DIBUTTON_FPS_FIRESECONDARY
DIBUTTON_FPS_FORWARD_LINK
DIBUTTON_FPS_GLANCE_DOWN_LINK
DIBUTTON_FPS_GLANCE_UP_LINK
DIBUTTON_FPS_GLANCEL
DIBUTTON_FPS_GLANCER
DIBUTTON_FPS_PAUSE
DIBUTTON_FPS_ROTATE_LEFT_LINK
DIBUTTON_FPS_ROTATE_RIGHT_LINK
DIHATSWITCH_FPS_GLANCE


Third-Person Action

The DIVIRTUAL_FIGHTING_THIRDPERSON genre contains controls for a third-person action game.

Priority 1 Controls
DIAXIS_TPS_MOVE
DIAXIS_TPS_TURN
DIBUTTON_TPS_ACTION
DIBUTTON_TPS_JUMP
DIBUTTON_TPS_MENU
DIBUTTON_TPS_RUN
DIBUTTON_TPS_SELECT
DIBUTTON_TPS_USE
Priority 2 Controls
DIAXIS_TPS_STEP
DIBUTTON_TPS_BACKWARD_LINK
DIBUTTON_TPS_DEVICE
DIBUTTON_TPS_DODGE
DIBUTTON_TPS_FORWARD_LINK
DIBUTTON_TPS_GLANCE_DOWN_LINK
DIBUTTON_TPS_GLANCE_LEFT_LINK
DIBUTTON_TPS_GLANCE_RIGHT_LINK
DIBUTTON_TPS_GLANCE_UP_LINK
DIBUTTON_TPS_INVENTORY
DIBUTTON_TPS_PAUSE
DIBUTTON_TPS_STEPLEFT
DIBUTTON_TPS_STEPRIGHT
DIBUTTON_TPS_TURN_LEFT_LINK
DIBUTTON_TPS_TURN_RIGHT_LINK
DIBUTTON_TPS_VIEW
DIHATSWITCH_TPS_GLANCE


Arcade Genres

The following genres contain controls for arcade-type games in which the object is to move a figure through a dangerous environment.

  • Platform
  • Side-to-Side


Platform

The DIVIRTUAL_ARCADE_PLATFORM genre contains controls for an arcade-style game.

Priority 1 Controls
DIAXIS_ARCADEP_LATERAL
DIAXIS_ARCADEP_MOVE
DIBUTTON_ARCADEP_CROUCH
DIBUTTON_ARCADEP_FIRE
DIBUTTON_ARCADEP_JUMP
DIBUTTON_ARCADEP_MENU
DIBUTTON_ARCADEP_SELECT
DIBUTTON_ARCADEP_SPECIAL
Priority 2 Controls
DIBUTTON_ARCADEP_BACK_LINK
DIBUTTON_ARCADEP_DEVICE
DIBUTTON_ARCADEP_FIRESECONDARY
DIBUTTON_ARCADEP_FORWARD_LINK
DIBUTTON_ARCADEP_LEFT_LINK
DIBUTTON_ARCADEP_PAUSE
DIBUTTON_ARCADEP_RIGHT_LINK
DIBUTTON_ARCADEP_VIEW_DOWN_LINK
DIBUTTON_ARCADEP_VIEW_LEFT_LINK
DIBUTTON_ARCADEP_VIEW_RIGHT_LINK
DIBUTTON_ARCADEP_VIEW_UP_LINK
DIHATSWITCH_ARCADEP_VIEW


Side-to-Side

The DIVIRTUAL_ARCADE_SIDE2SIDE genre contains controls for a two-dimensional arcade-style game.

Priority 1 Controls
DIAXIS_ARCADES_LATERAL
DIAXIS_ARCADES_MOVE
DIBUTTON_ARCADES_ATTACK
DIBUTTON_ARCADES_CARRY
DIBUTTON_ARCADES_MENU
DIBUTTON_ARCADES_SELECT
DIBUTTON_ARCADES_SPECIAL
DIBUTTON_ARCADES_THROW
Priority 2 Controls
DIBUTTON_ARCADES_BACK_LINK
DIBUTTON_ARCADES_DEVICE
DIBUTTON_ARCADES_FORWARD_LINK
DIBUTTON_ARCADES_LEFT_LINK
DIBUTTON_ARCADES_PAUSE
DIBUTTON_ARCADES_RIGHT_LINK
DIBUTTON_ARCADES_VIEW_DOWN_LINK
DIBUTTON_ARCADES_VIEW_LEFT_LINK
DIBUTTON_ARCADES_VIEW_RIGHT_LINK
DIBUTTON_ARCADES_VIEW_UP_LINK
DIHATSWITCH_ARCADES_VIEW


CAD Genres

The following genres contain controls for computer-assisted drafting applications.

Constants

  • Objects in 2D
  • Models in 3D
  • Navigation in 3D
  • Objects in 3D


Objects in 2D

The DIVIRTUAL_CAD_2DCONTROL genre contains controls to select and move objects in a two-dimensional drafting environment.

Priority 1 Controls
DIAXIS_2DCONTROL_LATERAL
DIAXIS_2DCONTROL_MOVE
DIAXIS_2DCONTROL_INOUT
DIBUTTON_2DCONTROL_MENU
DIBUTTON_2DCONTROL_SELECT
DIBUTTON_2DCONTROL_SPECIAL
DIBUTTON_2DCONTROL_SPECIAL1
DIBUTTON_2DCONTROL_SPECIAL2
Priority 2 Controls
DIAXIS_2DCONTROL_ROTATEZ
DIBUTTON_2DCONTROL_DEVICE
DIBUTTON_2DCONTROL_DISPLAY
DIBUTTON_2DCONTROL_PAUSE
DIHATSWITCH_2DCONTROL_HATSWITCH


Models in 3D

The DIVIRTUAL_CAD_MODEL genre contains controls for modeling three-dimensional objects.

Priority 1 Controls
DIAXIS_CADM_LATERAL
DIAXIS_CADM_MOVE
DIAXIS_CADM_INOUT
DIBUTTON_CADM_MENU
DIBUTTON_CADM_SELECT
DIBUTTON_CADM_SPECIAL
DIBUTTON_CADM_SPECIAL1
DIBUTTON_CADM_SPECIAL2
Priority 2 Controls
DIAXIS_CADM_ROTATEX
DIAXIS_CADM_ROTATEY
DIAXIS_CADM_ROTATEZ
DIBUTTON_CADM_DEVICE
DIBUTTON_CADM_DISPLAY
DIBUTTON_CADM_PAUSE
DIHATSWITCH_CADM_HATSWITCH


Navigation in 3D

The DIVIRTUAL_CAD_FLYBY genre contains control for fly-through navigation of three-dimensional environments.

Priority 1 Controls
DIAXIS_CADF_LATERAL
DIAXIS_CADF_MOVE
DIAXIS_CADF_INOUT
DIBUTTON_CADF_MENU
DIBUTTON_CADF_SELECT
DIBUTTON_CADF_SPECIAL
DIBUTTON_CADF_SPECIAL1
DIBUTTON_CADF_SPECIAL2
Priority 2 Controls
DIAXIS_CADF_ROTATEX
DIAXIS_CADF_ROTATEY
DIAXIS_CADF_ROTATEZ
DIBUTTON_CADF_DEVICE
DIBUTTON_CADF_DISPLAY
DIBUTTON_CADF_PAUSE
DIHATSWITCH_CADF_HATSWITCH


Objects in 3D

The DIVIRTUAL_CAD_3DCONTROL genre contains controls to select and move objects in a three-dimensional drafting environment.

Priority 1 Controls
DIAXIS_3DCONTROL_LATERAL
DIAXIS_3DCONTROL_MOVE
DIAXIS_3DCONTROL_INOUT
DIBUTTON_3DCONTROL_MENU
DIBUTTON_3DCONTROL_SELECT
DIBUTTON_3DCONTROL_SPECIAL
DIBUTTON_3DCONTROL_SPECIAL1
DIBUTTON_3DCONTROL_SPECIAL2
Priority 2 Controls
DIAXIS_3DCONTROL_ROTATEX
DIAXIS_3DCONTROL_ROTATEY
DIAXIS_3DCONTROL_ROTATEZ
DIBUTTON_3DCONTROL_DEVICE
DIBUTTON_3DCONTROL_DISPLAY
DIBUTTON_3DCONTROL_PAUSE
DIHATSWITCH_3DCONTROL_HATSWITCH


Control Genres

The following genres contain controls for use with browsers and remote-control devices.

  • Browser
  • Remote Control


Browser

The DIVIRTUAL_BROWSER_CONTROL genre contains controls for a browser.

Priority 1 Controls
DIAXIS_BROWSER_LATERAL
DIAXIS_BROWSER_MOVE
DIAXIS_BROWSER_VIEW
DIBUTTON_BROWSER_MENU
DIBUTTON_BROWSER_REFRESH
DIBUTTON_BROWSER_SELECT
Priority 2 Controls
DIBUTTON_BROWSER_DEVICE
DIBUTTON_BROWSER_FAVORITES
DIBUTTON_BROWSER_HISTORY
DIBUTTON_BROWSER_HOME
DIBUTTON_BROWSER_NEXT
DIBUTTON_BROWSER_PAUSE
DIBUTTON_BROWSER_PREVIOUS
DIBUTTON_BROWSER_PRINT
DIBUTTON_BROWSER_SEARCH
DIBUTTON_BROWSER_STOP


Remote Control

The DIVIRTUAL_REMOTE_CONTROL genre contains controls for remote-control devices used with equipment such as media players.

Priority 1 Controls
DIAXIS_REMOTE_SLIDER
DIBUTTON_REMOTE_CHANGE
DIBUTTON_REMOTE_CUE
DIBUTTON_REMOTE_MENU
DIBUTTON_REMOTE_MUTE
DIBUTTON_REMOTE_PLAY
DIBUTTON_REMOTE_RECORD
DIBUTTON_REMOTE_REVIEW
DIBUTTON_REMOTE_SELECT
Priority 2 Controls
DIAXIS_REMOTE_SLIDER2
DIBUTTON_REMOTE_ADJUST
DIBUTTON_REMOTE_CABLE
DIBUTTON_REMOTE_CD
DIBUTTON_REMOTE_DEVICE
DIBUTTON_REMOTE_DIGIT0
DIBUTTON_REMOTE_DIGIT1
DIBUTTON_REMOTE_DIGIT2
DIBUTTON_REMOTE_DIGIT3
DIBUTTON_REMOTE_DIGIT4
DIBUTTON_REMOTE_DIGIT5
DIBUTTON_REMOTE_DIGIT6
DIBUTTON_REMOTE_DIGIT7
DIBUTTON_REMOTE_DIGIT8
DIBUTTON_REMOTE_DIGIT9
DIBUTTON_REMOTE_DVD
DIBUTTON_REMOTE_PAUSE
DIBUTTON_REMOTE_TUNER
DIBUTTON_REMOTE_TV
DIBUTTON_REMOTE_VCR


Driving Genres

The following genres are used in games where the players control vehicles in racing or combat.

  • Combat Racing
  • Mechanical Fighting
  • Racing
  • Tank


Combat Racing

The DIVIRTUAL_DRIVING_COMBAT genre contains controls for a vehicle race game with combat.

Priority 1 Controls
DIAXIS_DRIVINGC_ACCELERATE
DIAXIS_DRIVINGC_BRAKE
DIAXIS_DRIVINGC_STEER
DIBUTTON_DRIVINGC_FIRE
DIBUTTON_DRIVINGC_MENU
DIBUTTON_DRIVINGC_TARGET
DIBUTTON_DRIVINGC_WEAPONS
Priority 2 Controls
DIAXIS_DRIVINGC_ACCEL_AND_BRAKE
DIBUTTON_DRIVINGC_ACCELERATE_LINK
DIBUTTON_DRIVINGC_AIDS
DIBUTTON_DRIVINGC_BRAKE
DIBUTTON_DRIVINGC_DASHBOARD
DIBUTTON_DRIVINGC_DEVICE
DIBUTTON_DRIVINGC_FIRESECONDARY
DIBUTTON_DRIVINGC_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGC_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGC_PAUSE
DIBUTTON_DRIVINGC_SHIFTDOWN
DIBUTTON_DRIVINGC_SHIFTUP
DIBUTTON_DRIVINGC_STEER_LEFT_LINK
DIBUTTON_DRIVINGC_STEER_RIGHT_LINK
DIHATSWITCH_DRIVINGC_GLANCE


Mechanical Fighting

The DIVIRTUAL_DRIVING_MECHA genre contains controls for a walking vehicle in a mechanized-warfare game.

Priority 1 Controls
DIAXIS_MECHA_ROTATE
DIAXIS_MECHA_STEER
DIAXIS_MECHA_THROTTLE
DIAXIS_MECHA_TORSO
DIBUTTON_MECHA_FIRE
DIBUTTON_MECHA_JUMP
DIBUTTON_MECHA_MENU
DIBUTTON_MECHA_REVERSE
DIBUTTON_MECHA_TARGET
DIBUTTON_MECHA_WEAPONS
DIBUTTON_MECHA_ZOOM
Priority 2 Controls
DIBUTTON_MECHA_BACK_LINK
DIBUTTON_MECHA_CENTER
DIBUTTON_MECHA_DEVICE
DIBUTTON_MECHA_FASTER_LINK
DIBUTTON_MECHA_FIRESECONDARY
DIBUTTON_MECHA_FORWARD_LINK
DIBUTTON_MECHA_LEFT_LINK
DIBUTTON_MECHA_PAUSE
DIBUTTON_MECHA_RIGHT_LINK
DIBUTTON_MECHA_ROTATE_LEFT_LINK
DIBUTTON_MECHA_ROTATE_RIGHT_LINK
DIBUTTON_MECHA_SLOWER_LINK
DIBUTTON_MECHA_VIEW
DIHATSWITCH_MECHA_GLANCE


Racing

The DIVIRTUAL_DRIVING_RACE genre contains controls for an auto-racing game without combat.

Priority 1 Controls
DIAXIS_DRIVINGR_ACCELERATE
DIAXIS_DRIVINGR_BRAKE
DIAXIS_DRIVINGR_STEER
DIBUTTON_DRIVINGR_MENU
DIBUTTON_DRIVINGR_SHIFTDOWN
DIBUTTON_DRIVINGR_SHIFTUP
DIBUTTON_DRIVINGR_VIEW
Priority 2 Controls
DIAXIS_DRIVINGR_ACCEL_AND_BRAKE
DIBUTTON_DRIVINGR_ACCELERATE_LINK
DIBUTTON_DRIVINGR_AIDS
DIBUTTON_DRIVINGR_BOOST
DIBUTTON_DRIVINGR_BRAKE
DIBUTTON_DRIVINGR_DASHBOARD
DIBUTTON_DRIVINGR_DEVICE
DIBUTTON_DRIVINGR_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGR_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGR_MAP
DIBUTTON_DRIVINGR_PIT
DIBUTTON_DRIVINGR_PAUSE
DIBUTTON_DRIVINGR_STEER_LEFT_LINK
DIBUTTON_DRIVINGR_STEER_RIGHT_LINK
DIHATSWITCH_DRIVINGR_GLANCE


Tank

The DIVIRTUAL_DRIVING_TANK genre contains controls for a military tank simulation.

Priority 1 Controls
DIAXIS_DRIVINGT_ACCELERATE
DIAXIS_DRIVINGT_BARREL
DIAXIS_DRIVINGT_ROTATE
DIAXIS_DRIVINGT_STEER
DIBUTTON_DRIVINGT_FIRE
DIBUTTON_DRIVINGT_MENU
DIBUTTON_DRIVINGT_TARGET
DIBUTTON_DRIVINGT_WEAPONS
Priority 2 Controls
DIAXIS_DRIVINGT_ACCEL_AND_BRAKE
DIAXIS_DRIVINGT_BRAKE
DIBUTTON_DRIVINGT_ACCELERATE_LINK
DIBUTTON_DRIVINGT_BARREL_UP_LINK
DIBUTTON_DRIVINGT_BARREL_DOWN_LINK
DIBUTTON_DRIVINGT_BRAKE
DIBUTTON_DRIVINGT_DASHBOARD
DIBUTTON_DRIVINGT_DEVICE
DIBUTTON_DRIVINGT_FIRESECONDARY
DIBUTTON_DRIVINGT_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGT_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGT_PAUSE
DIBUTTON_DRIVINGT_ROTATE_LEFT_LINK
DIBUTTON_DRIVINGT_ROTATE_RIGHT_LINK
DIBUTTON_DRIVINGT_STEER_LEFT_LINK
DIBUTTON_DRIVINGT_STEER_RIGHT_LINK
DIBUTTON_DRIVINGT_VIEW
DIHATSWITCH_DRIVINGT_GLANCE


Flight Genres

The following genres are used in games and simulations where the players control aircraft or spaceships.

  • Air Combat
  • Civilian Flight
  • Helicopter Combat
  • Space Combat


Air Combat

The DIVIRTUAL_FLYING_MILITARY genre contains controls for a fixed-wing aerial combat simulation.

Priority 1 Controls
DIAXIS_FLYINGM_BANK
DIAXIS_FLYINGM_PITCH
DIAXIS_FLYINGM_THROTTLE
DIBUTTON_FLYINGM_FIRE
DIBUTTON_FLYINGM_MENU
DIBUTTON_FLYINGM_TARGET
DIBUTTON_FLYINGM_WEAPONS
Priority 2 Controls
DIAXIS_FLYINGM_BRAKE
DIAXIS_FLYINGM_FLAPS
DIAXIS_FLYINGM_RUDDER
DIBUTTON_FLYINGM_BRAKE_LINK
DIBUTTON_FLYINGM_COUNTER
DIBUTTON_FLYINGM_DEVICE
DIBUTTON_FLYINGM_DISPLAY
DIBUTTON_FLYINGM_FASTER_LINK
DIBUTTON_FLYINGM_FIRESECONDARY
DIBUTTON_FLYINGM_FLAPSDOWN
DIBUTTON_FLYINGM_FLAPSUP
DIBUTTON_FLYINGM_GEAR
DIBUTTON_FLYINGM_GLANCE_DOWN_LINK
DIBUTTON_FLYINGM_GLANCE_LEFT_LINK
DIBUTTON_FLYINGM_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGM_GLANCE_UP_LINK
DIBUTTON_FLYINGM_PAUSE
DIBUTTON_FLYINGM_SLOWER_LINK
DIBUTTON_FLYINGM_VIEW
DIHATSWITCH_FLYINGM_GLANCE


Civilian Flight

The DIVIRTUAL_FLYING_CIVILIAN genre contains controls for noncombat flight simulations.

Priority 1 Controls
DIAXIS_FLYINGC_BANK
DIAXIS_FLYINGC_PITCH
DIAXIS_FLYINGC_THROTTLE
DIBUTTON_FLYINGC_DISPLAY
DIBUTTON_FLYINGC_GEAR
DIBUTTON_FLYINGC_MENU
DIBUTTON_FLYINGC_VIEW
Priority 2 Controls
DIAXIS_FLYINGC_BRAKE
DIAXIS_FLYINGC_FLAPS
DIAXIS_FLYINGC_RUDDER
DIBUTTON_FLYINGC_BRAKE_LINK
DIBUTTON_FLYINGC_DEVICE
DIBUTTON_FLYINGC_FASTER_LINK
DIBUTTON_FLYINGC_FLAPSDOWN
DIBUTTON_FLYINGC_FLAPSUP
DIBUTTON_FLYINGC_GLANCE_DOWN_LINK
DIBUTTON_FLYINGC_GLANCE_LEFT_LINK
DIBUTTON_FLYINGC_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGC_GLANCE_UP_LINK
DIBUTTON_FLYINGC_PAUSE
DIBUTTON_FLYINGC_SLOWER_LINK
DIHATSWITCH_FLYINGC_GLANCE


Helicopter Combat

The DIVIRTUAL_FLYING_HELICOPTER genre contains controls for a combat helicopter simulation.

Priority 1 Controls
DIAXIS_FLYINGH_BANK
DIAXIS_FLYINGH_COLLECTIVE
DIAXIS_FLYINGH_PITCH
DIBUTTON_FLYINGH_FIRE
DIBUTTON_FLYINGH_MENU
DIBUTTON_FLYINGH_TARGET
DIBUTTON_FLYINGH_WEAPONS
Priority 2 Controls
DIAXIS_FLYINGH_THROTTLE
DIAXIS_FLYINGH_TORQUE
DIBUTTON_FLYINGH_COUNTER
DIBUTTON_FLYINGH_DEVICE
DIBUTTON_FLYINGH_FASTER_LINK
DIBUTTON_FLYINGH_FIRESECONDARY
DIBUTTON_FLYINGH_GEAR
DIBUTTON_FLYINGH_GLANCE_DOWN_LINK
DIBUTTON_FLYINGH_GLANCE_LEFT_LINK
DIBUTTON_FLYINGH_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGH_GLANCE_UP_LINK
DIBUTTON_FLYINGH_PAUSE
DIBUTTON_FLYINGH_SLOWER_LINK
DIBUTTON_FLYINGH_VIEW
DIHATSWITCH_FLYINGH_GLANCE


Space Combat

The DIVIRTUAL_SPACESIM genre contains controls for a spaceship combat simulation.

Priority 1 Controls
DIAXIS_SPACESIM_LATERAL
DIAXIS_SPACESIM_MOVE
DIAXIS_SPACESIM_THROTTLE
DIBUTTON_SPACESIM_FIRE
DIBUTTON_SPACESIM_MENU
DIBUTTON_SPACESIM_TARGET
DIBUTTON_SPACESIM_WEAPONS
Priority 2 Controls
DIAXIS_SPACESIM_CLIMB
DIAXIS_SPACESIM_ROTATE
DIBUTTON_SPACESIM_BACKWARD_LINK
DIBUTTON_SPACESIM_DEVICE
DIBUTTON_SPACESIM_DISPLAY
DIBUTTON_SPACESIM_FASTER_LINK
DIBUTTON_SPACESIM_FIRESECONDARY
DIBUTTON_SPACESIM_FORWARD_LINK
DIBUTTON_SPACESIM_GEAR
DIBUTTON_SPACESIM_GLANCE_DOWN_LINK
DIBUTTON_SPACESIM_GLANCE_LEFT_LINK
DIBUTTON_SPACESIM_GLANCE_RIGHT_LINK
DIBUTTON_SPACESIM_GLANCE_UP_LINK
DIBUTTON_SPACESIM_LEFT_LINK
DIBUTTON_SPACESIM_LOWER
DIBUTTON_SPACESIM_PAUSE
DIBUTTON_SPACESIM_RAISE
DIBUTTON_SPACESIM_RIGHT_LINK
DIBUTTON_SPACESIM_SLOWER_LINK
DIBUTTON_SPACESIM_TURN_LEFT_LINK
DIBUTTON_SPACESIM_TURN_RIGHT_LINK
DIBUTTON_SPACESIM_VIEW
DIHATSWITCH_SPACESIM_GLANCE


Sports Genres

The following genres contain controls for sports games and simulations.

Constants

  • Baseball Batting
  • Baseball Fielding
  • Baseball Pitching
  • Basketball Defense
  • Basketball Offense
  • Fishing
  • Football Defense
  • Football Offense
  • Football Play
  • Football Quarterback
  • Golf
  • Hockey Defense
  • Hockey Goalie
  • Hockey Offense
  • Hunting
  • Mountain Biking
  • Racquet
  • Skiing
  • Soccer Defense
  • Soccer Offense


Baseball Batting

The DIVIRTUAL_SPORTS_BASEBALL_BAT genre contains controls for a batter in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLB_LATERAL
DIAXIS_BASEBALLB_MOVE
DIBUTTON_BASEBALLB_BUNT
DIBUTTON_BASEBALLB_BURST
DIBUTTON_BASEBALLB_CONTACT
DIBUTTON_BASEBALLB_MENU
DIBUTTON_BASEBALLB_NORMAL
DIBUTTON_BASEBALLB_POWER
DIBUTTON_BASEBALLB_SELECT
DIBUTTON_BASEBALLB_SLIDE
DIBUTTON_BASEBALLB_STEAL
Priority 2 Controls
DIBUTTON_BASEBALLB_BOX
DIBUTTON_BASEBALLB_BACK_LINK
DIBUTTON_BASEBALLB_DEVICE
DIBUTTON_BASEBALLB_FORWARD_LINK
DIBUTTON_BASEBALLB_LEFT_LINK
DIBUTTON_BASEBALLB_NOSTEAL
DIBUTTON_BASEBALLB_PAUSE
DIBUTTON_BASEBALLB_RIGHT_LINK


Baseball Fielding

The DIVIRTUAL_SPORTS_BASEBALL_FIELD genre contains controls for fielders in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLF_LATERAL
DIAXIS_BASEBALLF_MOVE
DIBUTTON_BASEBALLF_BURST
DIBUTTON_BASEBALLF_DIVE
DIBUTTON_BASEBALLF_JUMP
DIBUTTON_BASEBALLF_MENU
DIBUTTON_BASEBALLF_NEAREST
DIBUTTON_BASEBALLF_THROW1
DIBUTTON_BASEBALLF_THROW2
Priority 2 Controls
DIBUTTON_BASEBALLF_AIM_LEFT_LINK
DIBUTTON_BASEBALLF_AIM_RIGHT_LINK
DIBUTTON_BASEBALLF_BACK_LINK
DIBUTTON_BASEBALLF_DEVICE
DIBUTTON_BASEBALLF_FORWARD_LINK
DIBUTTON_BASEBALLF_PAUSE
DIBUTTON_BASEBALLF_SHIFTIN
DIBUTTON_BASEBALLF_SHIFTOUT


Baseball Pitching

The DIVIRTUAL_SPORTS_BASEBALL_PITCH genre contains controls for a pitcher in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLP_LATERAL
DIAXIS_BASEBALLP_MOVE
DIBUTTON_BASEBALLP_BASE
DIBUTTON_BASEBALLP_FAKE
DIBUTTON_BASEBALLP_MENU
DIBUTTON_BASEBALLP_PITCH
DIBUTTON_BASEBALLP_SELECT
DIBUTTON_BASEBALLP_THROW
Priority 2 Controls
DIBUTTON_BASEBALLP_BACK_LINK
DIBUTTON_BASEBALLP_DEVICE
DIBUTTON_BASEBALLP_FORWARD_LINK
DIBUTTON_BASEBALLP_LEFT_LINK
DIBUTTON_BASEBALLP_LOOK
DIBUTTON_BASEBALLP_PAUSE
DIBUTTON_BASEBALLP_RIGHT_LINK
DIBUTTON_BASEBALLP_WALK


Basketball Defense

The DIVIRTUAL_SPORTS_BASKETBALL_DEFENSE genre contains controls for defensive moves in a basketball game.

Priority 1 Controls
DIAXIS_BBALLD_LATERAL
DIAXIS_BBALLD_MOVE
DIBUTTON_BBALLD_BURST
DIBUTTON_BBALLD_FAKE
DIBUTTON_BBALLD_JUMP
DIBUTTON_BBALLD_MENU
DIBUTTON_BBALLD_PLAY
DIBUTTON_BBALLD_PLAYER
DIBUTTON_BBALLD_SPECIAL
DIBUTTON_BBALLD_STEAL
Priority 2 Controls
DIBUTTON_BBALLD_BACK_LINK
DIBUTTON_BBALLD_DEVICE
DIBUTTON_BBALLD_FORWARD_LINK
DIBUTTON_BBALLD_LEFT_LINK
DIBUTTON_BBALLD_PAUSE
DIBUTTON_BBALLD_RIGHT_LINK
DIBUTTON_BBALLD_SUBSTITUTE
DIBUTTON_BBALLD_TIMEOUT
DIHATSWITCH_BBALLD_GLANCE


Basketball Offense

The DIVIRTUAL_SPORTS_BASKETBALL_OFFENSE genre contains controls for the player who has the ball in a basketball game.

Priority 1 Controls
DIAXIS_BBALLO_LATERAL
DIAXIS_BBALLO_MOVE
DIBUTTON_BBALLO_BURST
DIBUTTON_BBALLO_CALL
DIBUTTON_BBALLO_DUNK
DIBUTTON_BBALLO_FAKE
DIBUTTON_BBALLO_MENU
DIBUTTON_BBALLO_PASS
DIBUTTON_BBALLO_PLAYER
DIBUTTON_BBALLO_SHOOT
DIBUTTON_BBALLO_SPECIAL
Priority 2 Controls
DIBUTTON_BBALLO_BACK_LINK
DIBUTTON_BBALLO_DEVICE
DIBUTTON_BBALLO_FORWARD_LINK
DIBUTTON_BBALLO_JAB
DIBUTTON_BBALLO_LEFT_LINK
DIBUTTON_BBALLO_PAUSE
DIBUTTON_BBALLO_PLAY
DIBUTTON_BBALLO_POST
DIBUTTON_BBALLO_RIGHT_LINK
DIBUTTON_BBALLO_SCREEN
DIBUTTON_BBALLO_SUBSTITUTE
DIBUTTON_BBALLO_TIMEOUT
DIHATSWITCH_BBALLO_GLANCE


Fishing

The DIVIRTUAL_SPORTS_FISHING genre contains controls for a sport-fishing simulation.

Priority 1 Controls
DIAXIS_FISHING_LATERAL
DIAXIS_FISHING_MOVE
DIBUTTON_FISHING_BAIT
DIBUTTON_FISHING_BINOCULAR
DIBUTTON_FISHING_CAST
DIBUTTON_FISHING_MAP
DIBUTTON_FISHING_MENU
DIBUTTON_FISHING_TYPE
Priority 2 Controls
DIAXIS_FISHING_ROTATE
DIBUTTON_FISHING_BACK_LINK
DIBUTTON_FISHING_CROUCH
DIBUTTON_FISHING_DEVICE
DIBUTTON_FISHING_DISPLAY
DIBUTTON_FISHING_FORWARD_LINK
DIBUTTON_FISHING_JUMP
DIBUTTON_FISHING_LEFT_LINK
DIBUTTON_FISHING_PAUSE
DIBUTTON_FISHING_RIGHT_LINK
DIBUTTON_FISHING_ROTATE_LEFT_LINK
DIBUTTON_FISHING_ROTATE_RIGHT_LINK
DIHATSWITCH_FISHING_GLANCE


Football Defense

The DIVIRTUAL_SPORTS_FOOTBALL_DEFENSE genre contains controls for the defensive side in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLD_LATERAL
DIAXIS_FOOTBALLD_MOVE
DIBUTTON_FOOTBALLD_FAKE
DIBUTTON_FOOTBALLD_JUMP
DIBUTTON_FOOTBALLD_MENU
DIBUTTON_FOOTBALLD_PLAY
DIBUTTON_FOOTBALLD_SELECT
DIBUTTON_FOOTBALLD_SUPERTACKLE
DIBUTTON_FOOTBALLD_TACKLE
Priority 2 Controls
DIBUTTON_FOOTBALLD_AUDIBLE
DIBUTTON_FOOTBALLD_BACK_LINK
DIBUTTON_FOOTBALLD_BULLRUSH
DIBUTTON_FOOTBALLD_DEVICE
DIBUTTON_FOOTBALLD_FORWARD_LINK
DIBUTTON_FOOTBALLD_LEFT_LINK
DIBUTTON_FOOTBALLD_PAUSE
DIBUTTON_FOOTBALLD_RIGHT_LINK
DIBUTTON_FOOTBALLD_RIP
DIBUTTON_FOOTBALLD_SPIN
DIBUTTON_FOOTBALLD_SUBSTITUTE
DIBUTTON_FOOTBALLD_SWIM
DIBUTTON_FOOTBALLD_ZOOM


Football Offense

The DIVIRTUAL_SPORTS_FOOTBALL_OFFENSE genre contains controls for the ball carrier in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLO_LATERAL
DIAXIS_FOOTBALLO_MOVE
DIBUTTON_FOOTBALLO_JUMP
DIBUTTON_FOOTBALLO_LEFTARM
DIBUTTON_FOOTBALLO_MENU
DIBUTTON_FOOTBALLO_RIGHTARM
DIBUTTON_FOOTBALLO_SPIN
DIBUTTON_FOOTBALLO_THROW
Priority 2 Controls
DIBUTTON_FOOTBALLO_BACK_LINK
DIBUTTON_FOOTBALLO_DEVICE
DIBUTTON_FOOTBALLO_DIVE
DIBUTTON_FOOTBALLO_FORWARD_LINK
DIBUTTON_FOOTBALLO_JUKE
DIBUTTON_FOOTBALLO_LEFT_LINK
DIBUTTON_FOOTBALLO_PAUSE
DIBUTTON_FOOTBALLO_RIGHT_LINK
DIBUTTON_FOOTBALLO_SHOULDER
DIBUTTON_FOOTBALLO_SUBSTITUTE
DIBUTTON_FOOTBALLO_TURBO
DIBUTTON_FOOTBALLO_ZOOM


Football Play

The DIVIRTUAL_SPORTS_FOOTBALL_FIELD genre contains general controls for a North American football game.

Priority 1 Controls
DIBUTTON_FOOTBALLP_HELP
DIBUTTON_FOOTBALLP_MENU
DIBUTTON_FOOTBALLP_PLAY
DIBUTTON_FOOTBALLP_SELECT
Priority 2 Controls
DIBUTTON_FOOTBALLP_DEVICE
DIBUTTON_FOOTBALLP_PAUSE


Football Quarterback

The DIVIRTUAL_SPORTS_FOOTBALL_QBCK genre contains controls for the quarterback in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLQ_LATERAL
DIAXIS_FOOTBALLQ_MOVE
DIBUTTON_FOOTBALLQ_FAKE
DIBUTTON_FOOTBALLQ_JUMP
DIBUTTON_FOOTBALLQ_MENU
DIBUTTON_FOOTBALLQ_PASS
DIBUTTON_FOOTBALLQ_SELECT
DIBUTTON_FOOTBALLQ_SLIDE
DIBUTTON_FOOTBALLQ_SNAP
Priority 2 Controls
DIBUTTON_FOOTBALLQ_AUDIBLE
DIBUTTON_FOOTBALLQ_BACK_LINK
DIBUTTON_FOOTBALLQ_DEVICE
DIBUTTON_FOOTBALLQ_FAKESNAP
DIBUTTON_FOOTBALLQ_FORWARD_LINK
DIBUTTON_FOOTBALLQ_LEFT_LINK
DIBUTTON_FOOTBALLQ_MOTION
DIBUTTON_FOOTBALLQ_PAUSE
DIBUTTON_FOOTBALLQ_RIGHT_LINK


Golf

The DIVIRTUAL_SPORTS_GOLF genre contains controls for a golf game.

Priority 1 Controls
DIAXIS_GOLF_LATERAL
DIAXIS_GOLF_MOVE
DIBUTTON_GOLF_DOWN
DIBUTTON_GOLF_FLYBY
DIBUTTON_GOLF_MENU
DIBUTTON_GOLF_SELECT
DIBUTTON_GOLF_SWING
DIBUTTON_GOLF_TERRAIN
DIBUTTON_GOLF_UP
Priority 2 Controls
DIBUTTON_GOLF_BACK_LINK
DIBUTTON_GOLF_DEVICE
DIBUTTON_GOLF_FORWARD_LINK
DIBUTTON_GOLF_LEFT_LINK
DIBUTTON_GOLF_PAUSE
DIBUTTON_GOLF_RIGHT_LINK
DIBUTTON_GOLF_SUBSTITUTE
DIBUTTON_GOLF_TIMEOUT
DIBUTTON_GOLF_ZOOM
DIHATSWITCH_GOLF_SCROLL


Hockey Defense

The DIVIRTUAL_SPORTS_HOCKEY_DEFENSE genre contains controls for defensive moves in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYD_LATERAL
DIAXIS_HOCKEYD_MOVE
DIBUTTON_HOCKEYD_BLOCK
DIBUTTON_HOCKEYD_BURST
DIBUTTON_HOCKEYD_FAKE
DIBUTTON_HOCKEYD_MENU
DIBUTTON_HOCKEYD_PLAYER
DIBUTTON_HOCKEYD_STEAL
Priority 2 Controls
DIBUTTON_HOCKEYD_BACK_LINK
DIBUTTON_HOCKEYD_DEVICE
DIBUTTON_HOCKEYO_FORWARD_LINK
DIBUTTON_HOCKEYO_LEFT_LINK
DIBUTTON_HOCKEYD_PAUSE
DIBUTTON_HOCKEYO_RIGHT_LINK
DIBUTTON_HOCKEYD_STRATEGY
DIBUTTON_HOCKEYD_SUBSTITUTE
DIBUTTON_HOCKEYD_TIMEOUT
DIBUTTON_HOCKEYD_ZOOM
DIHATSWITCH_HOCKEYD_SCROLL


Hockey Goalie

The DIVIRTUAL_SPORTS_HOCKEY_GOALIE genre contains controls for a goalkeeper in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYG_LATERAL
DIAXIS_HOCKEYG_MOVE
DIBUTTON_HOCKEYG_BLOCK
DIBUTTON_HOCKEYG_MENU
DIBUTTON_HOCKEYG_PASS
DIBUTTON_HOCKEYG_POKE
DIBUTTON_HOCKEYG_STEAL
Priority 2 Controls
DIBUTTON_HOCKEYG_BACK_LINK
DIBUTTON_HOCKEYG_DEVICE
DIBUTTON_HOCKEYG_FORWARD_LINK
DIBUTTON_HOCKEYG_LEFT_LINK
DIBUTTON_HOCKEYG_PAUSE
DIBUTTON_HOCKEYG_RIGHT_LINK
DIBUTTON_HOCKEYG_STRATEGY
DIBUTTON_HOCKEYG_SUBSTITUTE
DIBUTTON_HOCKEYG_TIMEOUT
DIBUTTON_HOCKEYG_ZOOM
DIHATSWITCH_HOCKEYG_SCROLL


Hockey Offense

The DIVIRTUAL_SPORTS_HOCKEY_OFFENSE genre contains controls for offensive moves in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYO_LATERAL
DIAXIS_HOCKEYO_MOVE
DIBUTTON_HOCKEYO_BURST
DIBUTTON_HOCKEYO_FAKE
DIBUTTON_HOCKEYO_MENU
DIBUTTON_HOCKEYO_PASS
DIBUTTON_HOCKEYO_SHOOT
DIBUTTON_HOCKEYO_SPECIAL
Priority 2 Controls
DIBUTTON_HOCKEYO_BACK_LINK
DIBUTTON_HOCKEYO_DEVICE
DIBUTTON_HOCKEYO_FORWARD_LINK
DIBUTTON_HOCKEYO_LEFT_LINK
DIBUTTON_HOCKEYO_PAUSE
DIBUTTON_HOCKEYO_RIGHT_LINK
DIBUTTON_HOCKEYO_STRATEGY
DIBUTTON_HOCKEYO_SUBSTITUTE
DIBUTTON_HOCKEYO_TIMEOUT
DIBUTTON_HOCKEYO_ZOOM
DIHATSWITCH_HOCKEYO_SCROLL


Hunting

The DIVIRTUAL_SPORTS_HUNTING genre contains controls for a hunting simulation.

Priority 1 Controls
DIAXIS_HUNTING_LATERAL
DIAXIS_HUNTING_MOVE
DIBUTTON_HUNTING_AIM
DIBUTTON_HUNTING_BINOCULAR
DIBUTTON_HUNTING_CALL
DIBUTTON_HUNTING_FIRE
DIBUTTON_HUNTING_MAP
DIBUTTON_HUNTING_MENU
DIBUTTON_HUNTING_SPECIAL
DIBUTTON_HUNTING_WEAPON
Priority 2 Controls
DIAXIS_HUNTING_ROTATE
DIBUTTON_HUNTING_BACK_LINK
DIBUTTON_HUNTING_CROUCH
DIBUTTON_HUNTING_DEVICE
DIBUTTON_HUNTING_DISPLAY
DIBUTTON_HUNTING_FIRESECONDARY
DIBUTTON_HUNTING_FORWARD_LINK
DIBUTTON_HUNTING_JUMP
DIBUTTON_HUNTING_LEFT_LINK
DIBUTTON_HUNTING_PAUSE
DIBUTTON_HUNTING_RIGHT_LINK
DIBUTTON_HUNTING_ROTATE_LEFT_LINK
DIBUTTON_HUNTING_ROTATE_RIGHT_LINK
DIHATSWITCH_HUNTING_GLANCE


Mountain Biking

The DIVIRTUAL_SPORTS_BIKING_MOUNTAIN contains controls for a mountain-bike game.

Priority 1 Controls
DIAXIS_BIKINGM_PEDAL
DIAXIS_BIKINGM_TURN
DIBUTTON_BIKINGM_CAMERA
DIBUTTON_BIKINGM_JUMP
DIBUTTON_BIKINGM_MENU
DIBUTTON_BIKINGM_SELECT
DIBUTTON_BIKINGM_SPECIAL1
DIBUTTON_BIKINGM_SPECIAL2
Priority 2 Controls
DIAXIS_BIKINGM_BRAKE
DIBUTTON_BIKINGM_BRAKE_BUTTON_LINK
DIBUTTON_BIKINGM_DEVICE
DIBUTTON_BIKINGM_FASTER_LINK
DIBUTTON_BIKINGM_LEFT_LINK
DIBUTTON_BIKINGM_PAUSE
DIBUTTON_BIKINGM_RIGHT_LINK
DIBUTTON_BIKINGM_SLOWER_LINK
DIBUTTON_BIKINGM_ZOOM
DIHATSWITCH_BIKINGM_SCROLL


Racquet

The DIVIRTUAL_SPORTS_RACQUET genre includes racquet games such as tennis, table tennis, and squash.

Priority 1 Controls
DIAXIS_RACQUET_LATERAL
DIAXIS_RACQUET_MOVE
DIBUTTON_RACQUET_BACKSWING
DIBUTTON_RACQUET_MENU
DIBUTTON_RACQUET_SELECT
DIBUTTON_RACQUET_SMASH
DIBUTTON_RACQUET_SPECIAL
DIBUTTON_RACQUET_SWING
Priority 2 Controls
DIBUTTON_RACQUET_BACK_LINK
DIBUTTON_RACQUET_DEVICE
DIBUTTON_RACQUET_FORWARD_LINK
DIBUTTON_RACQUET_LEFT_LINK
DIBUTTON_RACQUET_PAUSE
DIBUTTON_RACQUET_RIGHT_LINK
DIBUTTON_RACQUET_SUBSTITUTE
DIBUTTON_RACQUET_TIMEOUT
DIHATSWITCH_RACQUET_GLANCE


Skiing

The DIVIRTUAL_SPORTS_SKIING contains controls for skiing games as well as for similar sports simulations such as snowboarding and skateboarding.

Priority 1 Controls
DIAXIS_SKIING_SPEED
DIAXIS_SKIING_TURN
DIBUTTON_SKIING_CAMERA
DIBUTTON_SKIING_CROUCH
DIBUTTON_SKIING_JUMP
DIBUTTON_SKIING_MENU
DIBUTTON_SKIING_SELECT
DIBUTTON_SKIING_SPECIAL1
DIBUTTON_SKIING_SPECIAL2
Priority 2 Controls
DIBUTTON_SKIING_DEVICE
DIBUTTON_SKIING_FASTER_LINK
DIBUTTON_SKIING_LEFT_LINK
DIBUTTON_SKIING_PAUSE
DIBUTTON_SKIING_RIGHT_LINK
DIBUTTON_SKIING_SLOWER_LINK
DIBUTTON_SKIING_ZOOM
DIHATSWITCH_SKIING_GLANCE


Soccer Defense

The DIVIRTUAL_SPORTS_SOCCER_DEFENSE contains controls for defensive moves in a soccer (international football) game.

Priority 1 Controls
DIAXIS_SOCCERD_LATERAL
DIAXIS_SOCCERD_MOVE
DIBUTTON_SOCCERD_BLOCK
DIBUTTON_SOCCERD_FAKE
DIBUTTON_SOCCERD_MENU
DIBUTTON_SOCCERD_PLAYER
DIBUTTON_SOCCERD_SELECT
DIBUTTON_SOCCERD_SLIDE
DIBUTTON_SOCCERD_SPECIAL
DIBUTTON_SOCCERD_STEAL
Priority 2 Controls
DIBUTTON_SOCCERD_BACK_LINK
DIBUTTON_SOCCERD_CLEAR
DIBUTTON_SOCCERD_DEVICE
DIBUTTON_SOCCERD_FORWARD_LINK
DIBUTTON_SOCCERD_FOUL
DIBUTTON_SOCCERD_GOALIECHARGE
DIBUTTON_SOCCERD_HEAD
DIBUTTON_SOCCERD_LEFT_LINK
DIBUTTON_SOCCERD_PAUSE
DIBUTTON_SOCCERD_RIGHT_LINK
DIBUTTON_SOCCERD_SUBSTITUTE
DIHATSWITCH_SOCCERD_GLANCE


Soccer Offense

The DIVIRTUAL_SPORTS_SOCCER_OFFENSE contains controls for offensive moves in a soccer (international football) game.

Priority 1 Controls
DIAXIS_SOCCERO_BEND
DIAXIS_SOCCERO_LATERAL
DIAXIS_SOCCERO_MOVE
DIBUTTON_SOCCERO_FAKE
DIBUTTON_SOCCERO_MENU
DIBUTTON_SOCCERO_PASS
DIBUTTON_SOCCERO_PLAYER
DIBUTTON_SOCCERO_SELECT
DIBUTTON_SOCCERO_SHOOT
DIBUTTON_SOCCERO_SPECIAL1
Priority 2 Controls
DIBUTTON_SOCCERO_BACK_LINK
DIBUTTON_SOCCERO_CONTROL
DIBUTTON_SOCCERO_DEVICE
DIBUTTON_SOCCERO_FORWARD_LINK
DIBUTTON_SOCCERO_HEAD
DIBUTTON_SOCCERO_LEFT_LINK
DIBUTTON_SOCCERO_PASSTHRU
DIBUTTON_SOCCERO_PAUSE
DIBUTTON_SOCCERO_RIGHT_LINK
DIBUTTON_SOCCERO_SHOOTHIGH
DIBUTTON_SOCCERO_SHOOTLOW
DIBUTTON_SOCCERO_SPRINT
DIBUTTON_SOCCERO_SUBSTITUTE
DIHATSWITCH_SOCCERO_GLANCE


Strategy Genres

The following genres contain controls for strategy, role-playing, and adventure games.

  • Role-Playing
  • Turn-Based


Role-Playing

The DIVIRTUAL_STRATEGY_ROLEPLAYING genre contains controls for a role-playing or adventure game in which navigation, problem-solving, and fighting with weapons and magic are common activities.

Priority 1 Controls
DIAXIS_STRATEGYR_LATERAL
DIAXIS_STRATEGYR_MOVE
DIBUTTON_STRATEGYR_APPLY
DIBUTTON_STRATEGYR_ATTACK
DIBUTTON_STRATEGYR_CAST
DIBUTTON_STRATEGYR_CROUCH
DIBUTTON_STRATEGYR_GET
DIBUTTON_STRATEGYR_JUMP
DIBUTTON_STRATEGYR_MENU
DIBUTTON_STRATEGYR_SELECT
Priority 2 Controls
DIAXIS_STRATEGYR_ROTATE
DIBUTTON_STRATEGYR_BACK_LINK
DIBUTTON_STRATEGYR_DEVICE
DIBUTTON_STRATEGYR_DISPLAY
DIBUTTON_STRATEGYR_FORWARD_LINK
DIBUTTON_STRATEGYR_LEFT_LINK
DIBUTTON_STRATEGYR_MAP
DIBUTTON_STRATEGYR_PAUSE
DIBUTTON_STRATEGYR_RIGHT_LINK
DIBUTTON_STRATEGYR_ROTATE_LEFT_LINK
DIBUTTON_STRATEGYR_ROTATE_RIGHT_LINK
DIHATSWITCH_STRATEGYR_GLANCE


Turn-Based

The DIVIRTUAL_STRATEGY_TURN genre contains controls for a turn-based strategy game.

Priority 1 Controls
DIAXIS_STRATEGYT_LATERAL
DIAXIS_STRATEGYT_MOVE
DIBUTTON_STRATEGYT_APPLY
DIBUTTON_STRATEGYT_INSTRUCT
DIBUTTON_STRATEGYT_MENU
DIBUTTON_STRATEGYT_SELECT
DIBUTTON_STRATEGYT_TEAM
DIBUTTON_STRATEGYT_TURN
Priority 2 Controls
DIBUTTON_STRATEGYT_BACK_LINK
DIBUTTON_STRATEGYT_DEVICE
DIBUTTON_STRATEGYT_DISPLAY
DIBUTTON_STRATEGYT_FORWARD_LINK
DIBUTTON_STRATEGYT_LEFT_LINK
DIBUTTON_STRATEGYT_MAP
DIBUTTON_STRATEGYT_PAUSE
DIBUTTON_STRATEGYT_RIGHT_LINK
DIBUTTON_STRATEGYT_ZOOM


Any-Control

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to any matching control on the device.

typedef enum Any_Control
{
    DIAXIS_ANY_1,
    DIAXIS_ANY_2,
    DIAXIS_ANY_3,
    DIAXIS_ANY_3,
    DIAXIS_ANY_A_1,
    DIAXIS_ANY_A_1,
    DIAXIS_ANY_B_1,
    DIAXIS_ANY_B_2,
    DIAXIS_ANY_C_1,
    DIAXIS_ANY_C_2,
    DIAXIS_ANY_R_1,
    DIAXIS_ANY_R_2,
    DIAXIS_ANY_S_1,
    DIAXIS_ANY_S_2,
    DIAXIS_ANY_U_1,
    DIAXIS_ANY_U_2,
    DIAXIS_ANY_V_1,
    DIAXIS_ANY_V_2,
    DIAXIS_ANY_X_1,
    DIAXIS_ANY_X_2,
    DIAXIS_ANY_Y_1,
    DIAXIS_ANY_Y_2,
    DIAXIS_ANY_Z_1,
    DIAXIS_ANY_Z_2,
    DIBUTTON_ANY,
    DIPOV_ANY_1,
    DIPOV_ANY_2,
    DIPOV_ANY_3,
    DIPOV_ANY_4,
} Any-Control, *LPAny-Control;

Constants

DIAXIS_ANY_1
Any axis
DIAXIS_ANY_2
Any axis
DIAXIS_ANY_3
Any axis
DIAXIS_ANY_3
Any axis
DIAXIS_ANY_A_1
Any accelerator
DIAXIS_ANY_A_1
Any accelerator
DIAXIS_ANY_B_1
Any brake
DIAXIS_ANY_B_2
Any brake
DIAXIS_ANY_C_1
Any clutch
DIAXIS_ANY_C_2
Any clutch
DIAXIS_ANY_R_1
Any r-axis
DIAXIS_ANY_R_2
Any r-axis
DIAXIS_ANY_S_1
Any s-axis
DIAXIS_ANY_S_2
Any s-axis
DIAXIS_ANY_U_1
Any u-axis
DIAXIS_ANY_U_2
Any u-axis
DIAXIS_ANY_V_1
Any v-axis
DIAXIS_ANY_V_2
Any v-axis
DIAXIS_ANY_X_1
Any x-axis
DIAXIS_ANY_X_2
Any x-axis
DIAXIS_ANY_Y_1
Any y-axis
DIAXIS_ANY_Y_2
Any y-axis
DIAXIS_ANY_Z_1
Any z-axis
DIAXIS_ANY_Z_2
Any z-axis
DIBUTTON_ANY
Any button. This is a constant macro that takes a button number as its argument. For example, DIBUTTON_ANY(3).
DIPOV_ANY_1
Any point-of-view controller
DIPOV_ANY_2
Any point-of-view controller
DIPOV_ANY_3
Any point-of-view controller
DIPOV_ANY_4
Any point-of-view controller

Remarks

These constants can be used to map an application action to a virtual control that is not defined in a genre. Such actions are mapped after genre-specific actions. If the mapper has already mapped all matching controls to genre-specific actions, the any-control action is left unmapped.

Any-control actions are treated with equal priority. If a device has one x-axis and the action array specifies DIAXIS_ANY_1 and DIAXIS_ANY_X_1, the action mapped to the x-axis is the one that appears first in the action array.

DIBUTTON_ANY(x) can accept any value from 0 through 255. Do not use an index more than once. For instance, the following set of DIACTION structures would be invalid.

{eB_MUTE,    DIBUTTON_ANY(0), 0, "Toggle Sound",},
{eB_VOLUP,   DIBUTTON_ANY(0), 0, "Volume Up",   },
{eB_VOLDOWN, DIBUTTON_ANY(0), 0, "Volume Down", },

The correct method uses different indexes, as shown below.

{eB_MUTE,    DIBUTTON_ANY(0), 0, "Toggle Sound",}
{eB_VOLUP,   DIBUTTON_ANY(1), 0, "Volume Up",   }
{eB_VOLDOWN, DIBUTTON_ANY(2), 0, "Volume Down", }


Keyboard Mapping

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a physical key.

typedef enum Keyboard_Mapping
{
    DIKEYBOARD_0,
    DIKEYBOARD_1,
    DIKEYBOARD_2,
    DIKEYBOARD_3,
    DIKEYBOARD_4,
    DIKEYBOARD_5,
    DIKEYBOARD_6,
    DIKEYBOARD_7,
    DIKEYBOARD_8,
    DIKEYBOARD_9,
    DIKEYBOARD_A,
    DIKEYBOARD_ABNT_C1,
    DIKEYBOARD_ABNT_C2,
    DIKEYBOARD_ADD,
    DIKEYBOARD_APOSTROPHE,
    DIKEYBOARD_APPS,
    DIKEYBOARD_AT,
    DIKEYBOARD_AX,
    DIKEYBOARD_B,
    DIKEYBOARD_BACK,
    DIKEYBOARD_BACKSLASH,
    DIKEYBOARD_C,
    DIKEYBOARD_CALCULATOR,
    DIKEYBOARD_CAPITAL,
    DIKEYBOARD_COLON,
    DIKEYBOARD_COMMA,
    DIKEYBOARD_CONVERT,
    DIKEYBOARD_D,
    DIKEYBOARD_DECIMAL,
    DIKEYBOARD_DELETE,
    DIKEYBOARD_DIVIDE,
    DIKEYBOARD_DOWN,
    DIKEYBOARD_E,
    DIKEYBOARD_END,
    DIKEYBOARD_EQUALS,
    DIKEYBOARD_ESCAPE,
    DIKEYBOARD_F,
    DIKEYBOARD_F1,
    DIKEYBOARD_F2,
    DIKEYBOARD_F3,
    DIKEYBOARD_F4,
    DIKEYBOARD_F5,
    DIKEYBOARD_F6,
    DIKEYBOARD_F7,
    DIKEYBOARD_F8,
    DIKEYBOARD_F9,
    DIKEYBOARD_F10,
    DIKEYBOARD_F11,
    DIKEYBOARD_F12,
    DIKEYBOARD_F13,
    DIKEYBOARD_F14,
    DIKEYBOARD_F15,
    DIKEYBOARD_G,
    DIKEYBOARD_GRAVE,
    DIKEYBOARD_H,
    DIKEYBOARD_HOME,
    DIKEYBOARD_I,
    DIKEYBOARD_INSERT,
    DIKEYBOARD_J,
    DIKEYBOARD_K,
    DIKEYBOARD_KANA,
    DIKEYBOARD_KANJI,
    DIKEYBOARD_L,
    DIKEYBOARD_LBRACKET,
    DIKEYBOARD_LCONTROL,
    DIKEYBOARD_LEFT,
    DIKEYBOARD_LMENU,
    DIKEYBOARD_LSHIFT,
    DIKEYBOARD_LWIN,
    DIKEYBOARD_M,
    DIKEYBOARD_MAIL,
    DIKEYBOARD_MEDIASELECT,
    DIKEYBOARD_MEDIASTOP,
    DIKEYBOARD_MINUS,
    DIKEYBOARD_MULTIPLY,
    DIKEYBOARD_MUTE,
    DIKEYBOARD_MYCOMPUTER,
    DIKEYBOARD_N,
    DIKEYBOARD_NEXT,
    DIKEYBOARD_NEXTTRACK,
    DIKEYBOARD_NOCONVERT,
    DIKEYBOARD_NUMLOCK,
    DIKEYBOARD_NUMPAD0,
    DIKEYBOARD_NUMPAD1,
    DIKEYBOARD_NUMPAD2,
    DIKEYBOARD_NUMPAD3,
    DIKEYBOARD_NUMPAD4,
    DIKEYBOARD_NUMPAD5,
    DIKEYBOARD_NUMPAD6,
    DIKEYBOARD_NUMPAD7,
    DIKEYBOARD_NUMPAD8,
    DIKEYBOARD_NUMPAD9,
    DIKEYBOARD_NUMPADCOMMA,
    DIKEYBOARD_NUMPADENTER,
    DIKEYBOARD_NUMPADEQUALS,
    DIKEYBOARD_O,
    DIKEYBOARD_OEM_102,
    DIKEYBOARD_P,
    DIKEYBOARD_PAUSE,
    DIKEYBOARD_PERIOD,
    DIKEYBOARD_PLAYPAUSE,
    DIKEYBOARD_POWER,
    DIKEYBOARD_PREVTRACK,
    DIKEYBOARD_PRIOR,
    DIKEYBOARD_Q,
    DIKEYBOARD_R,
    DIKEYBOARD_RBRACKET,
    DIKEYBOARD_RCONTROL,
    DIKEYBOARD_RETURN,
    DIKEYBOARD_RIGHT,
    DIKEYBOARD_RMENU,
    DIKEYBOARD_RSHIFT,
    DIKEYBOARD_RWIN,
    DIKEYBOARD_S,
    DIKEYBOARD_SCROLL,
    DIKEYBOARD_SEMICOLON,
    DIKEYBOARD_SLASH,
    DIKEYBOARD_SLEEP,
    DIKEYBOARD_SPACE,
    DIKEYBOARD_STOP,
    DIKEYBOARD_SUBTRACT,
    DIKEYBOARD_SYSRQ,
    DIKEYBOARD_T,
    DIKEYBOARD_TAB,
    DIKEYBOARD_U,
    DIKEYBOARD_UNDERLINE,
    DIKEYBOARD_UNLABELED,
    DIKEYBOARD_UP,
    DIKEYBOARD_V,
    DIKEYBOARD_VOLUMEDOWN,
    DIKEYBOARD_VOLUMEUP,
    DIKEYBOARD_W,
    DIKEYBOARD_WAKE,
    DIKEYBOARD_WEBBACK,
    DIKEYBOARD_WEBFAVORITES,
    DIKEYBOARD_WEBFORWARD,
    DIKEYBOARD_WEBHOME,
    DIKEYBOARD_WEBREFRESH,
    DIKEYBOARD_WEBSEARCH,
    DIKEYBOARD_WEBSTOP,
    DIKEYBOARD_X,
    DIKEYBOARD_Y,
    DIKEYBOARD_YEN,
    DIKEYBOARD_Z,
} Keyboard Mapping, *LPKeyboard Mapping;

Constants

DIKEYBOARD_0
On main keyboard
DIKEYBOARD_1
On main keyboard
DIKEYBOARD_2
On main keyboard
DIKEYBOARD_3
On main keyboard
DIKEYBOARD_4
On main keyboard
DIKEYBOARD_5
On main keyboard
DIKEYBOARD_6
On main keyboard
DIKEYBOARD_7
On main keyboard
DIKEYBOARD_8
On main keyboard
DIKEYBOARD_9
On main keyboard
DIKEYBOARD_A
DIKEYBOARD_ABNT_C1
On numeric pad of Brazilian keyboards
DIKEYBOARD_ABNT_C2
On numeric pad of Brazilian keyboards
DIKEYBOARD_ADD
PLUS SIGN (+) on numeric keypad
DIKEYBOARD_APOSTROPHE
DIKEYBOARD_APPS
Application key
DIKEYBOARD_AT
On Japanese keyboard
DIKEYBOARD_AX
On Japanese keyboard
DIKEYBOARD_B
DIKEYBOARD_BACK
BACKSPACE
DIKEYBOARD_BACKSLASH
DIKEYBOARD_C
DIKEYBOARD_CALCULATOR
DIKEYBOARD_CAPITAL
CAPS LOCK
DIKEYBOARD_COLON
On Japanese keyboard
DIKEYBOARD_COMMA
DIKEYBOARD_CONVERT
On Japanese keyboard
DIKEYBOARD_D
DIKEYBOARD_DECIMAL
PERIOD (decimal point) on numeric keypad
DIKEYBOARD_DELETE
DIKEYBOARD_DIVIDE
FORWARD SLASH (/) on numeric keypad
DIKEYBOARD_DOWN
DOWN ARROW
DIKEYBOARD_E
DIKEYBOARD_END
DIKEYBOARD_EQUALS
On main keyboard
DIKEYBOARD_ESCAPE
DIKEYBOARD_F
DIKEYBOARD_F1
DIKEYBOARD_F2
DIKEYBOARD_F3
DIKEYBOARD_F4
DIKEYBOARD_F5
DIKEYBOARD_F6
DIKEYBOARD_F7
DIKEYBOARD_F8
DIKEYBOARD_F9
DIKEYBOARD_F10
DIKEYBOARD_F11
DIKEYBOARD_F12
DIKEYBOARD_F13
On NEC PC-98 Japanese keyboard
DIKEYBOARD_F14
On NEC PC-98 Japanese keyboard
DIKEYBOARD_F15
On NEC PC-98 Japanese keyboard
DIKEYBOARD_G
DIKEYBOARD_GRAVE
GRAVE ACCENT (`)
DIKEYBOARD_H
DIKEYBOARD_HOME
DIKEYBOARD_I
DIKEYBOARD_INSERT
DIKEYBOARD_J
DIKEYBOARD_K
DIKEYBOARD_KANA
On Japanese keyboard
DIKEYBOARD_KANJI
On Japanese keyboard
DIKEYBOARD_L
DIKEYBOARD_LBRACKET
Left SQUARE BRACKET ([)
DIKEYBOARD_LCONTROL
Left CTRL
DIKEYBOARD_LEFT
LEFT ARROW
DIKEYBOARD_LMENU
Left ALT
DIKEYBOARD_LSHIFT
Left SHIFT
DIKEYBOARD_LWIN
Left Windows logo key
DIKEYBOARD_M
DIKEYBOARD_MAIL
DIKEYBOARD_MEDIASELECT
MEDIA SELECT key, which displays a selection of supported media players on the system
DIKEYBOARD_MEDIASTOP
DIKEYBOARD_MINUS
On main keyboard
DIKEYBOARD_MULTIPLY
ASTERISK (*) on numeric keypad
DIKEYBOARD_MUTE
DIKEYBOARD_MYCOMPUTER
DIKEYBOARD_N
DIKEYBOARD_NEXT
PAGE DOWN
DIKEYBOARD_NEXTTRACK
NEXT TRACK
DIKEYBOARD_NOCONVERT
On Japanese keyboard
DIKEYBOARD_NUMLOCK
DIKEYBOARD_NUMPAD0
DIKEYBOARD_NUMPAD1
DIKEYBOARD_NUMPAD2
DIKEYBOARD_NUMPAD3
DIKEYBOARD_NUMPAD4
DIKEYBOARD_NUMPAD5
DIKEYBOARD_NUMPAD6
DIKEYBOARD_NUMPAD7
DIKEYBOARD_NUMPAD8
DIKEYBOARD_NUMPAD9
DIKEYBOARD_NUMPADCOMMA
On numeric keypad of NEC PC-98 Japanese keyboard
DIKEYBOARD_NUMPADENTER
DIKEYBOARD_NUMPADEQUALS
On numeric keypad of NEC PC-98 Japanese keyboard
DIKEYBOARD_O
DIKEYBOARD_OEM_102
On British and German keyboards
DIKEYBOARD_P
DIKEYBOARD_PAUSE
DIKEYBOARD_PERIOD
On main keyboard
DIKEYBOARD_PLAYPAUSE
DIKEYBOARD_POWER
DIKEYBOARD_PREVTRACK
PREVIOUS TRACK; CIRCUMFLEX (^) on Japanese keyboard
DIKEYBOARD_PRIOR
PAGE UP
DIKEYBOARD_Q
DIKEYBOARD_R
DIKEYBOARD_RBRACKET
Right SQUARE BRACKET (])
DIKEYBOARD_RCONTROL
Right CTRL
DIKEYBOARD_RETURN
ENTER on main keyboard
DIKEYBOARD_RIGHT
RIGHT ARROW
DIKEYBOARD_RMENU
Right ALT
DIKEYBOARD_RSHIFT
Right SHIFT
DIKEYBOARD_RWIN
Right Windows logo key
DIKEYBOARD_S
DIKEYBOARD_SCROLL
SCROLL LOCK
DIKEYBOARD_SEMICOLON
DIKEYBOARD_SLASH
FORWARD SLASH (/) on main keyboard
DIKEYBOARD_SLEEP
DIKEYBOARD_SPACE
SPACEBAR
DIKEYBOARD_STOP
On NEC PC-98 Japanese keyboard
DIKEYBOARD_SUBTRACT
MINUS SIGN (-) on numeric keypad
DIKEYBOARD_SYSRQ
DIKEYBOARD_T
DIKEYBOARD_TAB
DIKEYBOARD_U
DIKEYBOARD_UNDERLINE
On NEC PC-98 Japanese keyboard
DIKEYBOARD_UNLABELED
On Japanese keyboard
DIKEYBOARD_UP
UP ARROW
DIKEYBOARD_V
DIKEYBOARD_VOLUMEDOWN
DIKEYBOARD_VOLUMEUP
DIKEYBOARD_W
DIKEYBOARD_WAKE
DIKEYBOARD_WEBBACK
DIKEYBOARD_WEBFAVORITES
Displays the Microsoft Internet Explorer Favorites list, the Windows Favorites folder, or the Netscape Bookmarks list
DIKEYBOARD_WEBFORWARD
DIKEYBOARD_WEBHOME
DIKEYBOARD_WEBREFRESH
DIKEYBOARD_WEBSEARCH
DIKEYBOARD_WEBSTOP
DIKEYBOARD_X
DIKEYBOARD_Y
DIKEYBOARD_YEN
On Japanese keyboard
DIKEYBOARD_Z


Mouse Mapping

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a physical axis or button on a mouse.

typedef enum Mouse_Mapping
{
    DIMOUSE_BUTTON0,
    DIMOUSE_BUTTON1,
    DIMOUSE_BUTTON2,
    DIMOUSE_BUTTON3,
    DIMOUSE_BUTTON4,
    DIMOUSE_BUTTON5,
    DIMOUSE_BUTTON6,
    DIMOUSE_BUTTON7,
    DIMOUSE_WHEEL,
    DIMOUSE_XAXIS,
    DIMOUSE_YAXIS,
    DIMOUSE_XAXISAB,
    DIMOUSE_YAXISAB,
} Mouse Mapping, *LPMouse Mapping;

Constants

DIMOUSE_BUTTON0
DIMOUSE_BUTTON1
DIMOUSE_BUTTON2
DIMOUSE_BUTTON3
DIMOUSE_BUTTON4
DIMOUSE_BUTTON5
DIMOUSE_BUTTON6
DIMOUSE_BUTTON7
DIMOUSE_WHEEL
DIMOUSE_XAXIS
DIMOUSE_YAXIS
DIMOUSE_XAXISAB
DIMOUSE_YAXISAB

Remarks

DIMOUSE_XAXISAB and DIMOUSE_YAXISAB represent the x-axis and y-axis on a mouse that returns absolute rather than relative axis data.


Return Values

The list below contains the HRESULT> values that can be returned by DirectInput methods and functions. Errors are represented by negative values and cannot be combined.

For a list of the error values each method or function can return, see the individual descriptions. Lists of error codes in the documentation are necessarily incomplete. For example, any DirectInput method can return DIERR_OUTOFMEMORY even though the error code is not explicitly listed as a possible return value in the documentation for that method.

typedef enum Return_Values
{
    DI_BUFFEROVERFLOW,
    DI_DOWNLOADSKIPPED,
    DI_EFFECTRESTARTED,
    DI_NOEFFECT,
    DI_NOTATTACHED,
    DI_OK,
    DI_POLLEDDEVICE,
    DI_PROPNOEFFECT,
    DI_SETTINGSNOTSAVED,
    DI_TRUNCATED,
    DI_TRUNCATEDANDRESTARTED,
    DI_WRITEPROTECT,
    DIERR_ACQUIRED,
    DIERR_ALREADYINITIALIZED,
    DIERR_BADDRIVERVER,
    DIERR_BETADIRECTINPUTVERSION,
    DIERR_DEVICEFULL,
    DIERR_DEVICENOTREG,
    DIERR_EFFECTPLAYING,
    DIERR_GENERIC,
    DIERR_HANDLEEXISTS,
    DIERR_HASEFFECTS,
    DIERR_INCOMPLETEEFFECT,
    DIERR_INPUTLOST,
    DIERR_INVALIDPARAM,
    DIERR_MAPFILEFAIL,
    DIERR_MOREDATA,
    DIERR_NOAGGREGATION,
    DIERR_NOINTERFACE,
    DIERR_NOTACQUIRED,
    DIERR_NOTBUFFERED,
    DIERR_NOTDOWNLOADED,
    DIERR_NOTEXCLUSIVEACQUIRED,
    DIERR_NOTFOUND,
    DIERR_NOTINITIALIZED,
    DIERR_OBJECTNOTFOUND,
    DIERR_OLDDIRECTINPUTVERSION,
    DIERR_OTHERAPPHASPRIO,
    DIERR_OUTOFMEMORY,
    DIERR_READONLY,
    DIERR_REPORTFULL,
    DIERR_UNPLUGGED,
    DIERR_UNSUPPORTED,
    E_HANDLE,
    E_PENDING,
    E_POINTER,
} Return Values, *LPReturn Values;

Constants

DI_BUFFEROVERFLOW
The device buffer overflowed and some input was lost. This value is equal to the S_FALSE standard COM return value.
DI_DOWNLOADSKIPPED
The parameters of the effect were successfully updated, but the effect could not be downloaded because the associated device was not acquired in exclusive mode.
DI_EFFECTRESTARTED
The effect was stopped, the parameters were updated, and the effect was restarted.
DI_NOEFFECT
The operation had no effect. This value is equal to the S_FALSE standard COM return value.
DI_NOTATTACHED
The device exists but is not currently attached to the user's computer. This value is equal to the S_FALSE standard COM return value.
DI_OK
The operation completed successfully. This value is equal to the S_OK standard COM return value.
DI_POLLEDDEVICE
The device is a polled device. As a result, device buffering does not collect any data and event notifications is not signaled until the IDirectInputDevice8 Interface method is called.
DI_PROPNOEFFECT
The change in device properties had no effect. This value is equal to the S_FALSE standard COM return value.
DI_SETTINGSNOTSAVED
The action map was applied to the device, but the settings could not be saved.
DI_TRUNCATED
The parameters of the effect were successfully updated, but some of them were beyond the capabilities of the device and were truncated to the nearest supported value.
DI_TRUNCATEDANDRESTARTED
Equal to DI_EFFECTRESTARTED | DI_TRUNCATED.
DI_WRITEPROTECT
A SUCCESS code indicating that settings cannot be modified.
DIERR_ACQUIRED
The operation cannot be performed while the device is acquired.
DIERR_ALREADYINITIALIZED
This object is already initialized
DIERR_BADDRIVERVER
The object could not be created due to an incompatible driver version or mismatched or incomplete driver components.
DIERR_BETADIRECTINPUTVERSION
The application was written for an unsupported prerelease version of DirectInput.
DIERR_DEVICEFULL
The device is full.
DIERR_DEVICENOTREG
The device or device instance is not registered with DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard COM return value.
DIERR_EFFECTPLAYING
The parameters were updated in memory but were not downloaded to the device because the device does not support updating an effect while it is still playing.
DIERR_GENERIC
An undetermined error occurred inside the DirectInput subsystem. This value is equal to the E_FAIL standard COM return value.
DIERR_HANDLEEXISTS
The device already has an event notification associated with it. This value is equal to the E_ACCESSDENIED standard COM return value.
DIERR_HASEFFECTS
The device cannot be reinitialized because effects are attached to it.
DIERR_INCOMPLETEEFFECT
The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.
DIERR_INPUTLOST
Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM
An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_MAPFILEFAIL
An error has occurred either reading the vendor-supplied action-mapping file for the device or reading or writing the user configuration mapping file for the device.
DIERR_MOREDATA
Not all the requested information fit into the buffer.
DIERR_NOAGGREGATION
This object does not support aggregation.
DIERR_NOINTERFACE
The object does not support the specified interface. This value is equal to the E_NOINTERFACE standard COM return value.
DIERR_NOTACQUIRED
The operation cannot be performed unless the device is acquired.
DIERR_NOTBUFFERED
The device is not buffered. Set the DIPROP_BUFFERSIZE property to enable buffering.
DIERR_NOTDOWNLOADED
The effect is not downloaded.
DIERR_NOTEXCLUSIVEACQUIRED
The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTFOUND
The requested object does not exist.
DIERR_NOTINITIALIZED
This object has not been initialized.
DIERR_OBJECTNOTFOUND
The requested object does not exist.
DIERR_OLDDIRECTINPUTVERSION
The application requires a newer version of DirectInput.
DIERR_OTHERAPPHASPRIO
Another application has a higher priority level, preventing this call from succeeding. This value is equal to the E_ACCESSDENIED standard DirectInput return value. This error can be returned when an application has only foreground access to a device but is attempting to acquire the device while in the background.
DIERR_OUTOFMEMORY
The DirectInput subsystem could not allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.
DIERR_READONLY
The specified property cannot be changed. This value is equal to the E_ACCESSDENIED standard COM return value.
DIERR_REPORTFULL
More information was requested to be sent than can be sent to the device.
DIERR_UNPLUGGED
The operation could not be completed because the device is not plugged in.
DIERR_UNSUPPORTED
The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.
E_HANDLE
The HWND parameter is not a valid top-level window that belongs to the process.
E_PENDING
Data is not yet available.
E_POINTER
An invalid pointer, usually NULL, was passed as a parameter.


The Windows Vista Game Explorer

Game Explorer provides an easy, customizable way to present your game to users of Windows Vista. Game Explorer provides access control, custom tasks, and localized game information and images.

The documentation is divided into the following sections:

Programming Guide
Conceptual information about how to interact with Game Explorer
Samples
Sample code and data to get you started working with Game Explorer
Tools
Information on the tool used to create game definition files
Reference
Information on the Game Explorer API

For an introduction, see Getting Started With Game Explorer.


Game Explorer Programming Guide

This section contains conceptual topics about how to interact with Windows Vista Game Explorer. Information is divided into the following sections:

Article | Description
Getting Started With Game Explorer | A broad overview of Game Explorer and how to get started with a typical installation scenario.
The Game-Definition-File (GDF) Schema | An explanation of the XML-based GDF schema and how to best use the fields to represent your game.
Game Explorer Tasks | An explanation of the Game Explorer task system, including how you can create your own custom tasks.
GDF Delivery and Localization | Description of how GDF resources are interpreted by Game Explorer and instructions on how to include the GDF resources in your game.
Rich Saved Games | Guide to understanding how to create and store rich saved games under Windows Vista.
Game Explorer and WMI | How to use Windows Management Instrumentation to access Game Explorer information on a computer running Windows Vista.
Legacy Game Support | An explanation of how legacy games (games that have not authored custom content for Game Explorer) are interpreted by Game Explorer.
Supporting an Upgrade from Windows XP to Windows Vista | Instructions to supporting users who have installed a game on Windows XP then upgraded to Windows Vista.


Getting Started With Game Explorer

Windows Vista Game Explorer provides game developers with a secure and attractive way to present their games to users in Windows Vista. This document details how to add a game to Game Explorer.

What is Game Explorer?

Windows Vista Game Explorer is a custom folder for the Windows Vista shell that provides a rich presence for games. It is accessed on the Start by clicking Games.

Game Explorer provides:

  • Display of game title, description, version, release date, publisher, and developer information
  • Display of general or region-specific game box art
  • Display of minimum and recommended system performance ratings
  • Display of game content ratings and descriptors
  • Restriction of game play based on parental control settings
  • Customizable context menus when a game is right-clicked
  • Unique settings for multiple installations on the same system

Using Game Explorer

To enable your game to use Game Explorer, you must create the data files that Game Explorer relies on, and add your game to Game Explorer.

Creating Game Explorer Data Files

The first part to adding a game to Game Explorer is to create and properly include a set of data that is consumed by Game Explorer. Doing this consists of the following steps.

Step 1. Create GDFs

Game Explorer displays a variety of data about each game. This data is stored in an XML-based document called a game definition file (GDF). For your information to be shown, you must author at least one GDF; if you want your game information to be localized for different world regions, you must author several GDFs, one for each region.

The GDF format is defined by a schema, which requires only a minimal set of information; many of the fields are optional. In creating your GDF, you can choose the level of detail that you want to supply to Game Explorer.

To see examples of minimal and full GDF files, and to understand the schema for GDF files, see The Game-Definition-File (GDF) Schema.

Step 2. Create Bitmaps

Game Explorer displays artwork for every game that provides it. The artwork provided is shown in a small format in the list of games, and in a large format when a game is selected by the user. Create an image file that will represent your game in Game Explorer.

The image should be in PNG format, as this allows for transparency features to give your artwork a clean look in the Game Explorer. Other formats are also available. For a list of formats, see GDF Delivery and Localization

Step 3. Embed GDFs and Bitmaps

The GDF files and bitmap files that are used by Game Explorer cannot be independent files that are simply installed in a game's directory along with the rest of the game files. They must be embedded as resources, either into an executable file or a DLL.

The Game Explorer header (GameUx.h) contains defined constants that you must use in the resource script to identify your GDF and bitmap file so that Game Explorer can find them. By separating the resource script into sections with #ifdef for multiple languages, you can instruct Game Explorer to search for localized versions of GDF files and bitmaps.

For more information, see GDF Delivery and Localization.

Adding a Game to Game Explorer

The second part to adding a game to Game Explorer is performed by the game's installater. The installer's code must identify for Game Explorer the location of the game data. Because Game Explorer is only available on Windows Vista, a different set of steps must be taken for an installation on a computer running Windows XP than on one running Windows Vista. Games that do not use an installer can perform these tasks at launch time, if necessary.

Adding a Game to Windows Vista

If a game is installed on Windows Vista, it can be added to Game Explorer, and this is the most straightforward scenario.

Step 1. Install Game Files

The first step in adding your game to the Game Explorer is to have your game files installed on the hard drive. It is important that all game files be installed by this step; once the game is added to Game Explorer in step 4, the parental controls of Windows Family Safety might prevent your installation process from accessing the game's base directory to add or change files.

Step 2. Create IGameExplorer COM Object

The next step is to create the IGameExplorer COM object that you will use to add your game information to the Game Explorer.

Step 3. Call IGameExplorer::VerifyAccess

To check whether the game has permission to run on the current user's account, call VerifyAccess. Note that doing so also adds the game to the "Parental Controls Acitivity Viewer" log. The VerifyAccess method takes as a parameter the path to your game's GDF. It checks parental control rating in the GDF against the current user's parental control settings and determines whether the current user has the necessary permission to run the game.

You might choose to inform the user of their lack of permission to run the game, since if VerifyAccess returns FALSE, the user will not be allowed to run the game.

Step 4. Call IGameExplorer::AddGame

To identify your game to Game Explorer, you must call AddGame with the path to your GDF resource, the path to your base installation, the installation scope, and optionally, an InstanceID (a GUID). You can either provide an InstanceID for the pguidInstanceID parameter using a GUID that you generate, or, by setting pguidInstanceID to GUID_NULL, one will be generated for you. The InstanceID uniquely identifies the instance of your game added to the Game Explorer, and you must persist it in the next step.

Note that after calling AddGame, restriction by parental control settings might prevent the game's installation directory from being accessed by the current user.

Step 5. Make the Game InstanceID Persistent

Store the InstanceID that you retrieved from or passed into AddGame, using either a file or the registry. Alternatively you can look up your InstanceID at runtime using WMI. See the various samples for more information on how to do this.

Step 6. Create Game Task Folders

Tasks are the actions that a user can perform on your game in Game Explorer. Actions such as playing the game, updating the game, or visiting the game's website are examples of tasks. You must create a directory structure that represents the tasks that you wish to support for your game, even if you only want to support the default task, which runs when the user double-clicks on the game in Game Explorer. See Game Explorer Tasks.

Adding the Game to Windows XP

You can install your game on a computer running Windows XP and store extra information so that your game will show up in Game Explorer if the user upgrades the system to Windows Vista.

Step 1. Install Game Files

As in the Windows Vista scenario, the first step will be to install all of your game files to the user's system.

Step 2. Generate Your Own InstanceID

Because the Game Explorer APIs are not available in Windows XP, the system cannot generate an InstanceID for your game. Therefore, you must create your own InstanceID, which you should persist in a file or the registry.

Step 3. Create Game Task Folders

As in the Windows Vista scenario, you can prepare tasks - commonly-used actions - for your user. Because the user is currently running Windows XP, the tasks will not be available for use immediately, but they will be automatically added to the game in the Game Explorer when the user upgrades to Windows Vista. See Game Explorer Tasks as well as Supporting an Upgrade from Windows XP to Windows Vista.

Step 4. Install Registry Values

So that Windows Vista will add your game automatically upon installation of the operating system, you must create some values in the registry; for more information, see Creating Custom Registry Values.


The Game-Definition-File (GDF) Schema

The first step in preparing your game title to be displayed in Windows Vista Game Explorer is to create a game definition file (GDF). A GDF is XML that must adhere to the GDF schema, which is described in this topic.

Base Types

The GDF schema refers to a set of base data types that are defined in a separate schema. These types are shown in the following table.

Name | Schema Component | Type | Description
fourPartVersion | simpleType | string (with facets) | A simple type that contains a regular expression for 4-part versions (0-65535.0-65535.0-65535.0-65535)
GUID | simpleType | string (with facets) | A simple type that contains a regular expression for GUIDs. GUIDs must be of the standard type, enclosed in braces, and following the pattern {AAAABBBB-CCCC-DDDD-EEEE-FFFFGGGGHHHH}.
boundedString | simpleType | string (with facets) | A string which preserves white space and is limited to 32768 characters.
filePathAttributeGroup | attributeGroup | n/a | Two frequently used attributes for file paths, combined.
filePathAttributeGroup: baseKnownFolderID | attribute | GUID | A GUID that represents a KnownFolder as the base path for folders. The path is relative to this known folder. If this folder isn't specified, then the path attribute, filePathAttributeGroup, is relative to the game's installation directory.
filePathAttributeGroup: path | attribute | boundedString | A bounded string for the file path represented by this group. This file path is relative to baseKnownFolderID.

Root Element: GameDefinitionFile

GameDefinitionFile is the root element of the GDF's XML, and it contains all of the imported namespaces.

<GameDefinitionFile xmlns="urn:schemas-microsoft-com:GameDescription.v1"
  xmlns:baseTypes="urn:schemas-microsoft-com:GamesExplorerBaseTypes.v1">

GameDefinition

GameDefinition is the actual root element of a game definition, and it contains two attributes, gameID and WMID.

<GameDefinition gameID="{5C08D2FF-A48E-43ca-846C-08924563E5A7}"
  WMID="{5C08D2FF-A48E-43ca-846C-08924563E5A7}">

GameDefinition Attributes

Name | Type | Description
gameID | GUID | The game ID. This uniquely identifies your game title to Game Explorer. This is generated by you, or in the case of certain titles, has already been provided. See Legacy Game Support.
WMID | GUID | The game ID for Windows Metadata Services. This should only be used for legacy games.

Name (boundedString)

Name boundedString type that provides the name of the game.

<Name>Super Game 2005</Name>

Description (boundedString, optional)

Description is a boundedString type that provides a description of the game.

<Description>The Penultimate Game</Description>

ReleaseDate (date, optional)

ReleaseDate is the date of the game's release, in standard XML date format, YYYY-MM-DD.

<ReleaseDate>2004-06-30</ReleaseDate>

Version (version)

The Version element is a choice type which contains one of the two ways of specifying the version number of your game. One method is an explicit version number embedded in the XML, VersionNumber. The other method is a path to an executable or DLL where the version number can be extracted, VersionFile.

VersionNumber (fourPartVersion)

VersionNumber is a version number.

<Version>
  <VersionNumber versionNumber="1.2.3.4"/>
</Version>
VersionFile (element with filePathAttributeGroup)

VersionFile provides the path to an executable or DLL file that contains version information. This element can contain a baseKnownFolderID attribute (a GUID) to indicate a location that the path is relative to. Not having a baseKnownFolderID attribute will make the path relative to the game's installation directory.

 <Version>  <VersionFile path="bin\MyGame.exe"/> </Version>

Developers (multiple elements with link type, optional)

Developers is a set of 1-5 developer elements that specify the names and respective URLs of the game developer(s).

<Developers>
  <Developer URI="http://www.microsoft.com">Microsoft</Developer>
</Developers>

Publishers (multiple elements with link type, optional)

Publishers is a set of 1-5 publisher elements that specify the names and respective URLs of the game publisher(s).

<Publishers>
  <Publisher URI="http://www.microsoft.com">Microsoft</Publisher>
</Publishers>

WindowsExperienceIndex (untyped element with several attributes, optional)

Windows Experience Index (WEI), a feature of Windows Vista, is an floating point number that specifies a level of performance that a particular computer has. The WindowsExperienceIndex element specifies the recommended and minimum WEI ratings that a computer should have for acceptable performance. This is for display purposes only and does not restrict access to the game.

<WindowsExperienceIndex minimum="4" recommended="5"/>
WindowsExperienceIndex Attributes
Name | Type | Description
minimum | float | The minimum WEI rating that a computer should have in order to play this game.
recommended | float | The recommended WEI rating that a computer should have in order to play this game.

Genres (multiple elements with boundedString type, optional)

Genres is a set of 1-5 publisher elements that specify the names and respective URLs of the game publisher(s).

<Genres>
  <Genre>Action</Genre>
  <Genre>Adventure</Genre>
</Genres>

SavedGames (element with filePathAttribute, optional)

SavedGames identifies the folder where saved games will be placed. As with the VersionFile element, this element can have an optional baseKnownFolderID element that starts the path with a known folder. If it is omitted, the path attribute will be relative to the game's installation directory.

<SavedGames baseKnownFolderID="{5C08D2FD-A48E-43ca-846C-08924563E5B7}"
  path="Game2005"/>

Ratings (elements with sub-elements that contain GUIDs, optional)

Ratings describes the parental controls ratings associated with the game. Multiple ratings are allowed, from multiple rating systems. Each rating can optionally have one or more content descriptors that are associated with that rating. Ratings, rating systems, and descriptors are GUIDs that are defined in ratings.dll.

<Ratings>
  <Rating>
  ratingID="{5C08D2FD-A48E-43ca-846C-08924563E5B7}"
  ratingSystemID="{5C08D2FE-A48E-43ca-846C-08924563E5A7}">
   <Descriptor
   descriptorID="{5C08D2FD-A48E-43ca-846C-08924563E5C7}" />
   <Descriptor
   descriptorID="{5C08D2FD-A48E-43ca-846C-08924563E5B7}" />
  </Rating>
</Ratings>
Rating (element with a ratingID and ratingSystemID attributes)

The Rating element specifies the rating ID and rating system ID that specifies a game rating, such as "T for Teen" in the ESRB system.

Rating Attributes

The following table shows the attributes for the Rating element.

Name | Type | Description
ratingID | GUID | The specific rating, such as "T for Teen".
ratingSystemID | GUID | The rating system that the rating corresponds to, such as the ESRB rating system.
Descriptor (element with a descriptorID attribute)

This is a content descriptor for a specific rating. You can have one or more descriptors for each rating.

Descriptor Attribute

The following table shows the attribute for the Descriptor element.

Name | Type | Description
descriptorID | GUID | A content descriptor for the rating.

GameExecutables {type: multiple elements of type GameExecutable, optional}

GameExecutables defines a list of executable files that are required for an application to run and is required for a game to be part of the Games for Windows program. It is very important that the application list all of the executable files that it installs or extracts (including copy protection, which is extracted at run time) in this section to ensure proper behavior with parental controls.

Parental controls includes a feature called General Application Restrictions, which allows a user to execute only those applications that have been specifically approved by the Administrator. This blocking is achieved at the CreateProcess layer using Software Restriction Policies in Windows Vista.

When General Application Restrictions is enabled, the executables listed in the application's signed GDF are automatically exempted or allowed based on the Games Parental Controls settings.

Including a GameExecutables section in the GDF allows the application to run with minimal interference when General Applications Restrictions is enabled.

GameExecutable {type: none, with a path attribute of type: boundedString}

GameExecutables has a required path element which is relative to the application's installation directory.

If the path begins with an environment variable (such as %TEMP%) then the path is treated as an absolute path and Game Explorer will replace the environment variable at run time. If a path starts with a percent sign and is not a real environment variable (for example, %FAKE%), the text will be taken literally. You should not have any percent signs in your game path whatsoever.

BaseKnownFolderID is not supported in this context because it is not supported by the Software Restrictions Policy system.

Important: Environment variable replacement is really only meant to support situations where your game, at run time, extracts a file into a temporary folder. It is supported only in the GameExecutable element and is not applicable elsewhere in the game definition file. If you wish to use this feature, you cannot have percent signs in your folder paths.

If you do not use environment variables and, instead, specify a path, such as "bin\\mygame.exe", the path will be relative to the subdirectory of your game installation directory as passed to IGameExplorer::AddGame when you register your game.

<GameExecutables>
  <GameExecutable path="bin\game.exe"/>
  <GameExecutable path="bin\gamecopyprotection.exe"/>
  <GameExecutable path="support\gamesettingswizard.exe"/>
  <GameExecutable path="%TEMP%\~e5.0001"/>
</GameExecutables>


Game Explorer Tasks

Users can interact with every game in Windows Vista Game Explorer by using tasks. An example of a task is launching the game when the user double-clicks on a game in the Game Explorer. This document details how and where to register tasks.

Tasks Introduction and Requirements

Tasks are the name for actions that can be taken with an entry in Windows Vista Game Explorer. Tasks determine how a user can interact with a game in Game Explorer. Using tasks, you can determine what will happen when the user double-clicks a game in Game Explorer, and what entries show up in the context menu when a user right-clicks on a game.

One task, the primary play task, is required for every game; the primary play task is the task that executes when a user double-clicks on a game in the Game Explorer.

How To Create Tasks

Tasks are associated with a game during installation of the game by creating subdirectories and adding shortcuts to these subdirectories associated with the game in Game Explorer. The subdirectories are identified using the InstanceID (a GUID), which was either created and passed into AddGame, or was generated and returned by AddGame.

To associate tasks with a game

  1. Install all game files.

  2. Call AddGame to add the game to Game Explorer, either by using a custom InstanceID that you designate, or by letting AddGame create one for you.

  3. Persist the GameInstanceID for use in uninstalling to either a file or the registry.

  4. Create a subdirectory with a name that matches the GameInstanceID, enclosed in braces, in one of the following locations:
    • The common task directory, if the game is installed for all users
    • The per-user task directory, if the game is installed for the current user only

  5. Create the task subdirectories in the {GameInstanceID} subdirectory created in the previous step. There are two possible subdirectories: PlayTasks and SupportTasks.

  6. Add the task shortcuts to the subdirectories created in the previous step.

Task Directory Structure and Rules

When installing your game, you must create subdirectories in specific places for Game Explorer to recognize the tasks inside them. These subdirectories identify whether the task is for all users or for a specific user, the instance of the game being installed, and which types of tasks you are creating (play tasks or support tasks).

To create the proper task directory structure

  1. Determine if the game instance is being installed for the current user or for all users, and then do the following:
    • If for the current user, call SHGetKnownFolderPath with FOLDERID_GameTasks to retrieve the current user's Game Explorer data directory. (Applications that require Windows XP compatibility should use SHGetFolderPath instead; see Table 1.)
    • If for all users, call SHGetKnownFolderPath with FOLDERID_CommonGameTasks to retrieve the common Game Explorer data directory. (Applications that require Windows XP compatibility should use SHGetFolderPath instead; see Table 1.)
  2. Append "Microsoft\Windows\GameExplorer\" to the directory path retrieved in the previous step.
  3. Retrieve the InstanceID from the earlier call to AddGame. Create a subdirectory in the previous step's directory, named with the InstanceID in registry format, enclosed in braces; for example, {00d8862b-6454-4957-a821-3d98d74c76be}. To make this easier, you can call the StringFromGUID2 function, which formats the GUID properly, including adding the brace characters.
  4. Create a subdirectory named PlayTasks under the InstanceID directory from the previous step.Optionally, create a subdirectory named SupportTasks if you will be presenting support tasks to the user.
  5. In the PlayTasks directory, create a directory named 0 (zero). Place the primary shortcut to the game in this subdirectory. This shorcut starts the default task for when the game is double-clicked in Game Explorer.
  6. For every other task that you want to create, create a subdirectory in one of the three directories from the previous step (PlayTasks or SupportTasks) that is sequentially numbered within that subdirectory. In this numbered subdirectory, place your task shortcut; the name of this shortcut will be the name displayed to users when they right-click the game in Game Explorer. The default task is always called Play.

Table 1. Parent Directories of Game Explorer Task Folders for Windows XP and Windows Vista

Name | FolderID Definition for use with SHGetKnownFolderPath (Windows Vista) | Legacy CSIDL Definition for use with SHGetFolderPath (Windows XP and Windows Vista)
Tasks for all users | FOLDERID_CommonGameTasks | CSIDL_COMMON_APPDATA\Microsoft\Windows\GameExplorer
Tasks for the current user only user | FOLDERID_GameTasks | CSIDL_LOCAL_APPDATA\Microsoft\Windows\GameExplorer

Example Task Directory Structure for a Game on both Windows XP and Windows Vista

//for all users
//use ShGetFolderPath with CSIDL_COMMON_APPDATA\Microsoft\Windows\GameExplorer\ as the parent directory

CSIDL_COMMON_APPDATA\Microsoft\Windows\GameExplorer\{00d8862b-6454-4957-a821-3d98d74c76be}\PlayTasks\0\Play.lnk
CSIDL_COMMON_APPDATA\Microsoft\Windows\GameExplorer\{00d8862b-6454-4957-a821-3d98d74c76be}\PlayTasks\1\Play Online.lnk
CSIDL_COMMON_APPDATA\Microsoft\Windows\GameExplorer\{00d8862b-6454-4957-a821-3d98d74c76be}\SupportTasks\0\My Game's Website.lnk

//for the current user only
//use ShGetFolderPath with CSIDL_LOCAL_APPDATA\Microsoft\Windows\GameExplorer\ as the parent directory
CSIDL_LOCAL_APPDATA\Microsoft\Windows\GameExplorer\{00d8862b-6454-4957-a821-3d98d74c76be}\PlayTasks\2\Play Saved Game.lnk

Example Task Directory Structure for a game on Windows Vista Only

//for all users
//use SHGetKnownFolderPath with FOLDERID_CommonGameTasks as the parent directory

FOLDERID_CommonGameTasks\{00d8862b-6454-4957-a821-3d98d74c76be}\PlayTasks\0\Play.lnk
FOLDERID_CommonGameTasks\{00d8862b-6454-4957-a821-3d98d74c76be}\PlayTasks\1\Play Online.lnk
FOLDERID_CommonGameTasks\{00d8862b-6454-4957-a821-3d98d74c76be}\SupportTasks\0\My Game's Website.lnk

Task Rules

Tasks must have the following characteristics:

  • A play task consists of one IShellLink or IUniformResourceLocator shortcut. A support task must be a IUniformResourceLocator shortcut.
  • A task is associated with an instance of a game installation. An instance is a copy of the game installed for a particular user or all users.
  • A task belongs to one of two categories of tasks: play or support. When the user right-clicks on a game in Game Explorer, play tasks and support tasks, are divided from one another by a separator.
  • A task shortcut must be placed in a sequentially-numbered subdirectory in the appropriate subdirectory for the task category (PlayTasks or SupportTasks). Each task in a given category must have its own numbered subdirectory. The tasks are displayed in ascending order by numbered subdirectory.
  • The task located in PlayTasks\0\ is the primary play task. This task is required. This task is run when the user double-clicks on the game in Game Explorer. The name displayed for this task is Play, regardless of the name of the shortcut.
  • Tasks located in the current user's directory override the same task in the common (all users) directory.

Removing Tasks

When removing your game from the system, use the persistent game InstanceID to find and delete the task directories for the instance of your game that is being removed.


GDF Delivery and Localization

The Windows Vista Game Explorer requires that game definition files (GDFs) and associated icons adhere to the following conventions to allow for proper, trusted behavior and localization.

Delivering a Game Definition File

Game titles can register themselves with Game Explorer in Windows Vista by providing a game definition file (GDF) and a graphic (a thumbnail) that represents the game's box art; both the GDF and the graphic must be embedded into a signed resource file.

Gameux.h contains two #define directives that identify the names of the resource file entries you must use to identify the GDF and the icon in your resource file; include Gameux.h in your resource file to use these values, shown in the following table.

Name | Type | Description
ID_GDF_XML | DATA | Name of the game's GDF file
ID_GDF_THUMBNAIL | DATA | Name of the game's icon bitmap file

Localizing a Game Definition File

To specify different GDF files and thumbnails for different localized versions of your game, set the language ID of the resource inside the resource file; assign ID_GDF_XML and ID_GDF_THUMBNAIL to the values for as many language sections as you have in the resource file. Game Explorer will automatically select the properly localized GDF and thumbnail resource depending on the system's current language setting.

Thumbnail Formats

The file format of the thumbnail graphic can be one of several values:

  • Bitmap (BMP)
  • Graphics Interchange Format (GIF)
  • Joint Photographic Experts Group (JPEG)
  • Exchangeable Image File (Exif)
  • Portable Network Graphics (PNG)
  • Tagged Image File Format (TIFF)

PNG is recommended; the built-in transparency in the PNG format allows the box art to attain the cleanest look in Game Explorer.

The recommended size for your box art graphic is 256×256 pixels. The image will be used for the main box art at that size, but will also automatically be scaled down to 48×48 to be used as a smaller icon, so you should test your graphic at the smaller size to ensure it scales well.

Example

The following code is an example of a resource script that includes localized GDFs and thumbnails for several languages.

/////////////////////////////////////////////////////////////////////////////
// Note! We do not show the other resource stuff that really should be here,
//like the VERSION INFORMATION.  Putting this into every executable is a superior idea!

#include "resource.h"
#include "gameux.h"

#define APSTUDIO_READONLY_SYMBOLS
#include "afxres.h"
#undef APSTUDIO_READONLY_SYMBOLS

/////////////////////////////////////////////////////////////////////////////
// Neutral resources

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU)
#ifdef _WIN32
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
#pragma code_page(1252)
#endif //_WIN32

ID_GDF_XML              DATA                    "D:\\GameInstall\\gdfmaker_neutral.gdf"
ID_GDF_THUMBNAIL		DATA				"D:\\GameInstall\\boxart_neutral.png"

#endif    // Neutral resources
/////////////////////////////////////////////////////////////////////////////
// French (France) resources

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_FRA)
#ifdef _WIN32
LANGUAGE LANG_FRENCH, SUBLANG_FRENCH
#pragma code_page(1252)
#endif //_WIN32

ID_GDF_XML              DATA                    "D:\\GameInstall\\gdfmaker_fr.gdf"
ID_GDF_THUMBNAIL		DATA				"D:\\GameInstall\\boxart_fr.png"

#endif    // French (France) resources
/////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32

ID_GDF_XML              DATA                    "D:\\GameInstall\\gdfmaker_us.gdf"
ID_GDF_THUMBNAIL		DATA				"D:\\GameInstall\\boxart_us.png"

#endif    // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////


Rich Saved Games

Description

Windows Vista enables a better experience for users when browsing saved games from Windows Explorer without creating lot of work for game developers. It does this by making it easy for saved games to expose metadata and thumbnails to Windows Vista's Game Explorer as well as Windows Vista Desktop Search. To do this, Windows Vista provides a shell handler that processes saved game files and extracts their metadata. Windows Vista is required to extract metadata from rich saved games; however, on Windows XP you can enable part of the functionality by creating a saved game file association.

How to Support Rich Saved Games

The steps to support rich saved games are as follows:

  1. Choose a unique file extension for your saved games, such as .MicrosoftHeartsSaved, to avoid collisions with other games. Avoid using extensions that are commonly used for saved game files, like .sav.
  2. Modify your setup program to create a file association with your saved game files so that the game launches and loads the saved game when a user double-clicks on a saved game file. Details about this are found later in this topic.
  3. Modify your setup program to register the saved game extension with Windows Vista's rich saved games property handler so that the saved game metadata can be extracted. This should be done during installation while the setup has administrative rights. Details about this are found later in this topic.
  4. Modify your game to write saved game files that begin with the header described later in this topic. This allows metadata to be extracted by the property handler.
  5. Modify your game to support loading a saved game from the command line if it doesn't already. This is needed for the file association to work properly.
  6. Include the path of the saved games folder in the game's GDF file so that Game Explorer can show the folder of your saved games. For more information about the path of saved games, see The Game-Definition-File (GDF) Schema and Game Definition File Editor.

Creating a File Association for Your Saved Game File Extension

After you've selected a unique file extension for your saved games, you must create an association for that file extension. The file association allows the user to double-click on a saved game file and have the game automatically launch and load the saved game. To do this, you need to add some values to the registry, which requires administrative privileges. Your setup program will typically have administrative privileges, so installation is a good time to modify the registry.

The following is a sample registry entry for a saved game created by ExampleGame.exe, with a file extension of .ExampleGameSaved and a ProgID of ExampleGameSavedFileType:

[HKEY_CLASSES_ROOT\.ExampleGameSaved]
(Default)="ExampleGameSavedFileType"

[HKEY_CLASSES_ROOT\ExampleGameSavedFileType\Shell\Open\Command]
(Default)=""%ProgramFiles%\ExampleGame.exe" "%1""

Windows Vista Metadata Extraction for Saved Games

To enable Windows Vista to extract and display metadata from your saved games, you simply have to create a few registry keys and follow the saved game header guidelines described later in this topic.

The following is a sample registry entry for a saved game created by ExampleGame.exe, with a file extension of .ExampleGameSaved and a ProgID of ExampleGameSavedFileType:

[HKEY_CLASSES_ROOT\ExampleGameSavedFileType]
PreviewTitle="prop:System.Game.RichSaveName;System.Game.RichApplicationName"
PreviewDetails="prop:System.Game.RichLevel;System.DateChanged;System.Game.RichComment;System.DisplayName;System.DisplayType"

[HKEY_CLASSES_ROOT\.ExampleGameSaved\ShellEx\{BB2E617C-0920-11D1-9A0B-00C04FC2D6C1}]
(Default)="{4E5BFBF8-F59A-4E87-9805-1F9B42CC254A}"

[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\PropertySystem\PropertyHandlers\.ExampleGameSaved]
(Default)="{ECDD6472-2B9B-4B4B-AE36-F316DF3C8D60}"

The DirectX SDK sample called GameuxInstallHelper contains example code that demonstrates how to create these registry keys. The sample is designed to work with InstallShield script, Wise script, MSI custom actions, or a custom installer.

Saved Game Header

In order for metadata to be extracted by the shell handler, the saved game must be written using the following header:

#define RM_MAXLENGTH    1024
#define RM_MAGICNUMBER  'HMGR'

#pragma pack(push)
#pragma pack(1)
typedef struct _RICH_GAME_MEDIA_HEADER
{
    DWORD       dwMagicNumber;
    DWORD       dwHeaderVersion;
    DWORD       dwHeaderSize;
    LARGE_INTEGER liThumbnailOffset;
    DWORD       dwThumbnailSize;
    GUID        guidGameId;
    WCHAR       szGameName[RM_MAXLENGTH];
    WCHAR       szSaveName[RM_MAXLENGTH];
    WCHAR       szLevelName[RM_MAXLENGTH];
    WCHAR       szComments[RM_MAXLENGTH];
} RICH_GAME_MEDIA_HEADER;
#pragma pack(pop)

The following table describes the fields in the header.

TYPE | DATA | DESCRIPTION
DWORD | dwMagicNumber | Must be 'HMGR'. This is used to recognize the header file format.
DWORD | dwHeaderVersion | Version of this header. This must be 1 to use this header.
DWORD | dwHeaderSize | Size of this header in bytes which is sizeof(RICH_GAME_MEDIA_HEADER).
LARGE_INTEGER | liThumbnailOffset | Offset to where the thumbnail starts relative from the end of the header. Thumbnails can be of any GDI+ type. Thumbnails should be in PNG or BMP format and no greater than 256×256 in size.
DWORD | dwThumbnailSize | Size of the thumbnail in bytes.
GUID | guidGameId | GUID of the game as used in the GDF file.
WCHAR[RM_MAXLENGTH] | szGameName | String name of the game. This text will be displayed and will be searchable.
WCHAR[RM_MAXLENGTH] | szSaveName | String description of the saved game. This text will be displayed and will be searchable.
WCHAR[RM_MAXLENGTH] | szLevelName | String description of the level. This can be an empty string. This text will be displayed and will be searchable
WCHAR[RM_MAXLENGTH] | szComments | String for comments about the saved game. This can be an empty string. This text will be displayed and will be searchable.
End of Header |  |
BYTE* | Game-specific data area until the end of file | This is the actual saved game data. There are no requirements for this format.

A sample supplied in the DirectX SDK called GameuxInstallHelper contains an example in source code of how to create a saved game with this header.


Game Explorer and WMI

You can use Windows Management Instrumentation (WMI) to query Game Explorer for the data that it has about installed games on a system. Following is the WMI provider configuration required to access this data.

Installed Game Provider

Namespace: ("\\\\.\\root\\CIMV2\\Applications\\Games")

InstalledGameProvider

Properties

Property | Value
Name | MS_InstalledGameProvider
ClsId | {F382DA49-9148-4a22-AF78-C378DFC32D02}
InitializeAsAdminFirst | False
PerUserInitialization | False
Pure | True
Name | Type | Description
InstanceID | String | GUID that represents this specific game instance.
GameID | String | GUID that represents the Game ID.
GDFBinaryPath | String | Path to the GDF binary.
InstanceID | String | Specific resource ID for the GDF.
Name | String | Name of the game as represented in the Windows registry.
InstallScope | Enumerated Type | Game installation scope (GIS_CURRENT_USER or GIS_ALL_USERS).
GameInstallPath | String | Game's installation directory.


Legacy Game Support

In addition to allowing developers to provide game definition files (see The Game-Definition-File (GDF) Schema) to identify their games, Windows Vista Game Explorer supports game titles that do not have GDFs.

If a game does not install a GDF and integrate with Game Explorer, Game Explorer's legacy game system will use Windows Metadata Services and automatically download game developer information, box-art, and ratings, which will be used in Game Explorer in lieu of developer-provided data. The information used by the legacy game system is supplied by All Media Guide.

Windows Vista supports many released games through the legacy game service. Each of these games is represented by a game ID that is provided in Windows Vista. If you wish to develop a GDF for your title to integrate custom data into Game Explorer, you must provide the corresponding game ID as the gameID attribute in the GameDefinition element in the GDF file; otherwise, the Game Explorer's legacy game system will overwrite your custom data. To arrange access to your game ID, contact the Microsoft Windows Gaming and Graphics Developer Relations Group.


Supporting an Upgrade from Windows XP to Windows Vista

Upgrading from Windows XP to Windows Vista is a scenario that your game should support. In this scenario, a user installs your game on a computer running Windows XP, and then upgrades the system to Windows Vista.

For your game to work after an upgrade to Windows Vista from Windows XP, you must create a GDF and embed it in an executable file or DLL, as you would normally need to do for a game made for Windows Vista. (For a description of creating and embedding GDFs, see Create Data Files That Game Explorer Will Consume). However, during the installation of your game, four separate tasks must be performed in to support an upgrade from Windows XP to Windows Vista. Those tasks are the following:

  • Install all of your game files.
  • Generate your own InstanceID.
  • Call SHGetFolderPath with the CLSIDs, instead of known folders IDs (because SHGetKnownFolderPath is not available in Windows XP).
  • Store values in the registry.

Generating Your Own InstanceID

In a Windows Vista installation scenario, you can simply call into the Game Explorer APIs to generate an InstanceID (a GUID) for your particular installation, but in a Windows XP installation scenario, the APIs are not available. Instead, you must generate your own InstanceID and store it in the registry or in a file. This InstanceID will be used in the next two tasks.

Installing Task Paths on Windows XP

For Windows XP, unlike the Windows Vista, you cannot use SHGetKnownFolderPath with FOLDERIDs to retrieve the task paths, as defined in Game Explorer Tasks. Instead, you must use SHGetFolderPath with CSIDLs to install your tasks.

Name | Windows XP CSIDL Definition
Play task install location for all users | CSIDL_COMMON_APPDATA\Microsoft\Windows\GameExplorer\{game instance ID}\PlayTasks
Play task install location for current user | CSIDL_LOCAL_APPDATA\Microsoft\Windows\GameExplorer\{game instance ID}\PlayTasks
Support task install location for all users | CSIDL_COMMON_APPDATA\Microsoft\Windows\GameExplorer\{game instance ID}\SupportTasks
Support task install location for current user | CSIDL_LOCAL_APPDATA\Microsoft\Windows\GameExplorer\{game instance ID}\SupportTasks

Creating Custom Registry Values

You need to create a set of registry values to identify your game to the Windows Vista installation process. Your game will be added automatically to Game Explorer when the user installs Windows Vista.

First, you must determine the location of the value — this differs depending on whether your installation was for the entire system or for a single user.

Installation Scope | Registry Location
Entire System | HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\GameUX\GamesToFindOnWindowsUpgrade
Current User Only | HKEY_CURRENT_USER\Software\Classes\Software\Microsoft\Windows\CurrentVersion\GameUX\GamesToFindOnWindowsUpgrade

In this location, you must install the subkey and values shown in the following table. Create the values in the new subkey, {game instance ID}.

Element | Name | Description
Subkey | {game instance ID} | A GUID enclosed in curly braces
String value | GDFBinaryPath | The fully qualified path of the binary file that contains the GDF
String value | GameInstallPath | The path to the game installation folder


Game Explorer Tools

This section contains information about the tool used to create game definition files for use by Windows Vista Game Explorer:

  • Game Definition File Editor


Game Definition File Editor

The Game Definition File Editor is a graphical utility designed for creating localized game definition files (GDFs), as well as the necessary resource compiler scripts to compile game-definition files. The GDF editor uses a project-based format to organize data.

Tutorial: Using the Game Definition File Editor

This tutorial leads you through the creation of a sample GDF project, consisting of the following steps:

  • Step 1: Start the Game Definition File Editor
  • Step 2: Create a New Project
  • Step 3: Edit Game Title and Metadata
  • Step 4: Select Game Ratings
  • Step 5: Select Allowed Executables
  • Step 6: Add Genres, Developers, and Publishers
  • Step 7: Add Thumbnail and Icon
  • Step 8: Edit Language-Specific Data
  • Step 9: Build the Project into a resource file
  • Step 10: Build a GDF binary from the resource file

Step 1: Start the Game Definition File Editor

On the Start menu, navigate to the DirectX SDK, point to DirectX Utilities, and then click Game Definition File Editor.

Alternatively, you can start the command line; the name of the executable file is GDFMaker.exe, and it is located in DirectX SDK root\Utilities\Bin\x86\.

The Game Definition File Editor starts with no data loaded.

Step 2: Create a New Project

In this step, you create a new GDF project by selecting a file name, a location for the project file and its language-specific subdirectories, and the languages that your title will be localized to.

To create a new project

  1. Click the New Project icon on the toolbar.

  2. Select a location and enter a name for your project file, and then click OK.

  3. In the New Game Definition Project window, select the languages that your title will be localized to, and then click OK. You can add additional languages to your project later.

The editor creates a project file, and a directory for each language that you selected will be created under the project directory. At the same time, the project appears as a node in the left-hand pane of the Game Definition File Editor window.

Double-click the project node to expand your project. In the expanded node, entries are displayed for each of the languages that you selected. There is also a language-neutral entry, the first entry.

Each of these entries is also represented by a tab and corresponding property page in the right-side pane of the Game Definition File Editor window. When the fields on a property page are filled, the editor can build the corresponding portion of the GDF, and the resources (.rc) file can reference it.

The language-neutral entry contains data that will be used across all languages, and some of this data will be used as defaults when a language-specific page is missing data. In this tutorial, we start by adding data to this entry's property page, and then move to the language-specific properties.

Step 3: Edit Game Title and Metadata

The first set of data to edit is related to general game information: title, description, and other metadata. The following figure shows a portion of a property page.

Enter data into each of the fields of the property page, using the field names and descriptions in the follow table as a guide.

Field | Description
Game ID | An automatically generated GUID that identifies your game to the IGameExplorer methods. There is normally no need to change this, but you can change or generate a new GUID by clicking the ellipses button (...) button to the right of the text box.
Game Name | The name of your game. This is displayed as the name of the game in Game Explorer.
Description | The description of your game. This text is not currently used in Game Explorer, but may be used in the future.
Release Date | The release date of your game. The date is displayed in the metadata section of Game Explorer when the user selects your game.
Saved Games Folder | A relative path to where your game will store saved games files. The drop-down box to the left of the text field allows you to set the location to which this path is relative. You should choose a path that specifies a location that a Standard User will have read and write access to. For more details, see Gaming with Least-Privileged User Accounts.
Version | Either a version number in four-part format (a.b.c.d), or a relative path from the game's installation directory to a DLL or executable file that will be queried for a version number. Use the drop-down box to choose either Version or File.
Windows Experience Index | A minimum and recommended number for this game in the Windows Experience Index (WEI). A WEI number is a measure of the overall performance of a computer system. As of Windows Vista Beta 2, the WEI ratings range from 1 to 5, with 5 being equal to the highest performing desktop computer currently available. Numbers higher than 5 may be used in the future as the hardware performance of computers increases. Game Explorer displays the WEI when the user selects your game.

Step 4: Select Game Ratings

Your game can also have content ratings associated with it. These content ratings can come from one or more organizations. You select one or more of these organizations, choose your ratings, and add content specifiers.

Note For the ratings to be interpreted and displayed by Game Explorer, you must digitally sign the DLL or executable file that contains the GDF data by using a trusted Certificate Authority. If your game is not signed, parental controls considers your game to be unrated, even if you have specified a rating in the GDF. For more information about signing code, see Authenticode Signing for Game Developers.

To add a game rating

  1. Click the drop-down box to the left of the Add Rating button to select a rating system. Then, click the Add Rating button.

    For the this tutorial, select Entertainment Software Ratings Board.

  2. If the ratings system uses ratings symbols, select one by clicking the currently displayed symbol. Since the rating system of the ESRB does use symbols, we are able to select a symbol in this tutorial.

    Choose a rating symbol from the list that is displayed when you click the currently displayed symbol. This list of ratings symbols is shown in the following figure.

  3. If the ratings system uses content specifiers, select those that apply to your game.

  4. Repeat this procedure to add as many rating systems and ratings as you wish. You might need to use the scroll bar to see all of the ratings that you have added.

Step 5: Select Allowed Executables

In Windows Vista, General Application Restrictions is a feature that, if enabled, prevents all but explicitly allowed executables from running. When General Application Restrictions is enabled, the executables listed in a GDF from a signed source are automatically allowed, based on the parental controls settings.

The path to an allowed executable file is relative to your game's installation directory, unless the path begins with an environment variable bounded by percent signs, such as %TEMP%; in such a case, the path is treated as an absolute path, beginning from the path indicated by the environment variable. See GDF Schema: GameExecutables for more information.

For every executable file that your game will run, add an entry to the list of allowed executable files.

To add an executable file as allowed

  1. Click the Add button under Executables.
  2. Edit the newly created entry to specify a path and executable file, and then press ENTER.

Step 6: Add Genres, Developers, and Publishers

You select genres to classify your game, as well as add names and URIs for the developers and publishers, at the bottom of the property page.

To specify genres for your game

  1. Click the Genres tab.
  2. Click the Add button.
  3. From the list that appears, select all of the genres that you wish to add, and click OK.
  4. Since genre information is not localized by the editor, you should replace the genre text in the generated GDF files yourself for each language.

To add developers or publishers for your game

  1. Click the Developers or Publishers tab.
  2. Click the Add button.
  3. In the dialog that appears, enter the name of the developer or publisher in the top field. In the bottom field, enter a full URI to the Web site for the developer or publisher (for example, http://www.msn.com). Click OK.

Step 7: Add Thumbnail and Icon

Your game is represented in Game Explorer by a thumbnail image, and in some cases, an icon file. You should provide box art or a similar type of logo for your thumbnail image.

When your game is viewed in Game Explorer:

  • The thumbnail is used when Game Explorer is viewed in Extra Large Icons and Large Icons modes.
  • The icon is used when Game Explorer is viewed in Details mode.

For information about acceptable formats and sizing recommendations for your thumbnail image, see Thumbnail Formats.

To choose a thumbnail and icon for your game

  1. Click the Add Thumbnail or Add Icon button.
  2. In the dialog that appears, browse to a graphics file you wish to use for your thumbnail or icon. For thumbnails, the drop-down list of file types in the dialog is the list of all of the file types that you can use for your thumbnail. For icons, only Windows icon files can be used.

  3. Click OK. The thumbnail or icon will be automatically copied to the appropriate directory in your GDF project and displayed in the Game Definition File Editor window, as shown in the following figure.

Step 8: Edit Language-Specific Data

At this point, all of fields in the language-neutral property page should be populated. Now, each language-specific property page must be populated with data specific to the language, such as a localized title, description, version, thumbnails, and so on.

Data is not automatically copied to language-specific pages from the language-neutral page — except for the Game ID, WSPR, and ratings. All other data must be entered for each language-specific page.

To enter data for language-specific property pages

  1. Double-click a language in the left pane or click the corresponding tab in the right pane of the Game Definition File Editor window.

  2. Enter data in the fields of the property page as described in the preceding steps in this tutorial.
  3. Repeat until you have entered data for each language-specific property page.

Step 9: Build the Project into a resource file

With the fields on all of the property pages filled, you can build your project into an resource file and header file that can be used to compile the GDF data into a DLL or executable file. The final results of building a project are following:

  • For each language and for language-neutral, the editor creates a directory under the GDF project directory named with a language abbreviation (such as ENU for English and FRA for French). Each of these directories contains the GDF and the thumbnail and icon graphics for that language.
  • The editor creates a .rc file and a .h file in the main GDF project directory that references the GDF resources in each of the language subdirectories.

To build your project

  1. On the Resources menu, click Build Script for Project.
  2. In the dialog that appears, choose a name for your resource file. Place the resource file in the same directory as your GDF project.

  3. Click OK.

Step 10: Build a GDF binary from the resource file

Next you must compile the GDF data into a DLL or executable file by using the .rc file, created when you built the GDF project. This DLL or executable file should be installed by the game's installer, and its path should be passed to the Game Explorer APIs during the installation process. The GDFExampleBinary sample, provided in the DirectX SDK, has the GDF data compiled into a DLL.


Game Explorer Samples

There are two sets of samples that illustrate using Windows Vista Game Explorer: a sample that is supplied with the Windows SDK and a set of samples and tools that are supplied with the DirectX SDK.

Windows SDK

One sample is included in the Windows SDK, starting with the December 2005 CTP Release.

The GameExplorerAPISample sample illustrates:

  • How to add, remove, and update games in Game Explorer by using the IGameExplorer COM Object
  • List the installed games on the local system via WMI
  • Create a game definition file (GDF), including the XML Schema for the GDF

To access these samples, install the latest Windows SDK, and browse to the following location:

Windows SDK folder\Samples\Multimedia\GameUX

DirectX SDK

The two samples supplied in the DirectX SDK are targeted specifically toward game development:

GDFExampleBinary
Compiles GDF data for multiple languages into a DLL file using a resource script. For more information about delivering and localizing a GDF, see GDF Delivery and Localization.
GameuxInstallHelper
A DLL can be used with installers to register a game with Game Explorer and help create Game Explorer tasks. It also supports upgrading GDF data for Windows XP to Windows Vista.

To access these samples in the latest DirectX SDK, click DirectX Sample Browser in the DirectX SDK folder on your Start menu.


Game Explorer Reference

This section contains reference information about the Game Explorer API. Information is divided into the following sections:

  • Interfaces
  • Enumerations
  • Constants


Game Explorer Interfaces

This section contains information about the interfaces used with Windows Vista Game Explorer.

Interface | Description
IGameExplorer | Use this interface to register, deregister, update, or verify access to games in the Game Explorer.

See Also

Game Explorer Reference


IGameExplorer

This section contains information about the methods used with the IGameExplorer interface.

Method | Description
AddGame | Registers an instance of a game with Game Explorer, and either uses a custom InstanceID or returns a generated InstanceID.
RemoveGame | Removes an instance of a game from Game Explorer. Also removes permissions for the game from parental controls, as well as for any related rich media settings.
UpdateGame | Notifies Game Explorer that the game definition file (GDF) for a title has been updated. This function call updates any permissions for the game in parental controls, as well as for any rich media information.
VerifyAccess | Checks whether the user has permission to play the game in the specified GDF.

Requirements

Header: Declared in GameUX.h.


IGameExplorer::AddGame

Registers an instance of a game with Game Explorer and either uses a custom InstanceID or returns a generated InstanceID.

HRESULT AddGame(
  const BSTR bstrGDFBinaryPath,
  const BSTR bstrGameInstallDirectory,
  GAME_INSTALL_SCOPE installScope,
  GUID* pguidInstanceID
);

Parameters

bstrGDFBinaryPath
[in] A string that contains the fully qualified path of the binary file that contains the game definition file (GDF).
bstrGameInstallDirectory
[in] A string that contains the path to the game's installation folder.
installScope
[in] GAME_INSTALL_SCOPE that defines whether the game is to be installed for all users or only the current user. If set to GIS_ALL_USERS, administrative access is required. If set to GIS_CURRENT_USER, administrative access is not required.
pguidInstanceID
[in, out] A pointer to a GUID to emit or receive the InstanceID associated with the game.

Return Values

This function returns an HRESULT. Use the SUCCEEDED and FAILED macros to test the return value of this function.

AddGame returns S_FALSE if the game was already installed on the system. This situation occurs if a game is added more than once with the same ApplicationID and GameInstallDirectory; that is, AddGame is called twice for the same game installed in the same folder.

Remarks

Note This function can cause lockdown by parental controls, rendering the game's directory unusable, so it must be one of the last steps in your installation phase. For a list of installation steps, see Getting Started With Game Explorer.

Callers should store the instanceID returned by this call, as it is necessary to call IGameExplorer::RemoveGame or IGameExplorer::UpdateGame, and to create tasks for the game in Game Explorer.

If a pointer to a GUID_NULL is passed, this method creates and returns an InstanceID for the caller.

If a pointer to an actual GUID value is passed in, this method uses that GUID as the InstanceID. If that InstanceID already exists on the system, the call fails with E_INVALIDARG.

It is not necessarily an error to call this function on a title that is already installed on the system, since titles can have multiple instances on the same system.

This method can also upgrade an older game that is no longer supported to a newer, supported version. To achieve that, please make sure that the GDF (described in The Game-Definition-File (GDF) Schema) has the same gameID attribute as was used for Game Explorer's legacy game services. For more information, see Legacy Game Support. To arrange access to your game ID, contact the Microsoft.

Requirements

Header: Declared in GameUX.h.

See Also

GAME_INSTALL_SCOPE


IGameExplorer::RemoveGame

Removes an instance of a game from Game Explorer. Also removes permissions for the game from parental controls, as well as for any related rich media settings.

HRESULT RemoveGame(
  GUID guidInstanceID
);

Parameters

guidInstanceID
[in] GUID of the InstanceID associated with the game to be removed.

Return Values

Returns an HRESULT. Use the SUCCEEDED and FAILED macros to test the return value of this function.

Remarks

This function does not remove the tasks associated with an instance of a supported game. For older titles, this function attempts to remove the tasks, and fails without an error if no tasks exist.

Requirements

Header: Declared in GameUX.h.

See Also

Game Explorer Task System


IGameExplorer::UpdateGame

Notifies Game Explorer that the game definition file (GDF) for a title has been updated. This function call updates any permissions for the game in parental controls, as well as for any rich media information.

HRESULT UpdateGame(
  GUID guidInstanceID
);

Parameters

guidInstanceID
[in] GUID of the InstanceID associated with the game to be updated.

Return Values

Returns an HRESULT. Use the SUCCEEDED and FAILED macros to test the return value of this function.

Requirements

Header: Declared in GameUX.h.


IGameExplorer::VerifyAccess

Checks whether the user has permission to play the game in the specified GDF.

HRESULT VerifyAccess(
  const BSTR bstrGDFBinaryPath,
  BOOL* pfHasAccess
);

Parameters

bstrGDFBinaryPath
[in] A string that contains the fully qualified path of the binary that contains the game definition file (GDF). The GDF must be present in the default resource location.
pfHasAccess
[out] Whether the current game will be allowed to run for the current user, given the current parental controls settings.

Return Values

Returns an HRESULT. Use the SUCCEEDED and FAILED macros to test the return value of this function.

Remarks

This method does not require IGameExplorer::AddGame to be called, previously or at any other time. This method can be used at any time to verify whether the current user can run a binary file associated with a GDF.

Games should call this method every time that they are run. By doing so, parental controls work even for a game that was installed on a FAT32 volume, which does not support ACLs, to lock the user out of the game.

Requirements

Header: Declared in GameUX.h.


Game Explorer Enumerations

This section contains information about the enumerations used with Windows Vista Game Explorer.

Enumeration | Description
GAME_INSTALL_SCOPE | Defines whether a game is to be installed for all users or only the current user.

See Also

Game Explorer Reference


GAME_INSTALL_SCOPE

Defines whether a game being installed is installed for all users or only the current user.

typedef enum
{
    GIS_NOT_INSTALLED,
    GIS_CURRENT_USER,
    GIS_ALL_USERS,
} GAME_INSTALL_SCOPE;

Constants

GIS_NOT_INSTALLED
Reserved for internal use only.
GIS_CURRENT_USER
Game is to be registered for only the current user.
GIS_ALL_USERS
Game is to be registered for all users.

Requirements

Header: Declared in GameUX.h.

See Also

IGameExplorer::AddGame


Game Explorer Defined Constants

The constants shown in the following table are defined in GameUX.h.

Constant | Description
ID_GDF_XML | The resource ID of an XML-based game definition file (GDF) that is used to represent a game in Game Explorer.
ID_GDF_THUMBNAIL | The resource ID of a thumbnail image that is used to represent a game in Game Explorer.

Requirements

Header: Declared in GameUX.h.

See Also

GDF Delivery and Localization | Game Explorer Reference

Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center


DirectX SDK Technical Articles

This section contains a series of technical articles about developing games for Microsoft Windows.

  • 64-bit programming for Game Developers
  • Making Video Games Accessible: Business Justifications and Design Considerations
  • Authenticode Signing for Game Developers
  • Best Security Practices in Game Development
  • Coding For Multiple Cores on Xbox 360 and Microsoft Windows
  • Crash Dump Analysis
  • DirectX Frequently Asked Questions
  • DirectX Installation for Game Developers
  • Disabling Shortcut Keys in Games
  • Game Timing and Multicore Processors
  • Windows Firewall for Game Developers
  • Games for Windows: Technical Requirements
  • Games for Windows Test Requirements
  • Graphics APIs in Windows Vista
  • Install-on-Demand for Games
  • Installation and Maintenance of Games
  • Installation Best Practices for Massively Multiplayer Online Games
  • Installing and Using Input Method Editors
  • Introduction to the 10-Foot Experience for Windows Game Developers
  • Lockless Programming Considerations for Xbox 360 and Microsoft Windows
  • Optimizing DVD performance for Windows Games
  • Patching Game Software in Windows XP and Windows Vista
  • Resource Management Best Practices
  • Simplifying Game Installation
  • Taking Advantage of High-Definition Mouse Movement
  • The Direct3D Transformation Pipeline
  • Top Issues for Windows Titles
  • Top Tools and Techniques for Making More Robust Windows Games
  • User Account Control for Game Developers
  • Using an Input Method Editor in a Game
  • Windows Game Explorer for Game Developers
  • Windows Installer for Game Developers


64-bit programming for Game Developers

XNA Developer Connection (XDC)

April 2006

Processor manufacturers are exclusively shipping 64-bit processors in their desktop computers, and even the chipsets of most laptop computers support x64 technology It is important for game developers to take advantage of the improvements that 64-bit processors offer with their new applications and to ensure that their earlier applications run correctly on the new processors and the 64-bit editions of Windows Vista. This article addresses compatibility and porting issues and helps developers ease their transition to 64-bit platforms.

The 64-bit platforms that Microsoft currently has are Windows Server 2003 Service Pack 1, Windows XP Professional x64 Edition (available to OEMs or to developers through MSDN), and Windows Vista.

This article covers the following topics:

  • Differences in Addressable Memory
  • Specifying Large-Address-Aware When Building
  • Compatibility of 32-Bit Applications on 64-Bit Platforms
  • Porting Applications to 64-Bit Platforms
  • Profiling and Optimization of Ported Applications
  • Summary

Differences in Addressable Memory

The first thing most developers notice is that 64-bit processors provide a huge leap in the amount of physical and virtual memory that can be addressed.

  • 32-bit applications on 32-bit platforms can address up to 2 GB
  • 32-bit applications built with the /LARGEADDRESSAWARE:YES linker flag on 32-bit Windows XP or Windows Server 2003 with the special /3gb boot option can address up to 3 GB. This constrains the kernel to only 1 GB which may cause some drivers and/or services to fail.

  • 32-bit applications built with the /LARGEADDRESSAWARE:YES linker flag on 32-bit versions of Windows Vista, and on 32-bit versions of Windows Server Code Name "Longhorn" operating systems, can address memory up to the number specified by the boot configuration data (BCD) element IncreaseUserVa. IncreaseUserVa can have a value ranging from 2048, the default, to 3072 (which matches the amount of memory configured by the /3gb boot option on Windows XP). The remainder of 4 GB is allocated to the kernel and can result in failing driver and service configurations.

    For more information about BCD, see Boot Configuration Data on MSDN.

  • 32-bit applications on 64-bit platforms can address up to 2 GB, or up to 4 GB with the /LARGEADDRESSAWARE:YES linker flag.
  • 64-bit applications use 43 bits for addressing, which provides 8 TB of virtual address for applications and 8 TB reserved for the kernel.

Beyond just memory, 64-bit applications that use memory-mapped file I/O benefit greatly from the increased virtual address space. The 64-bit architecture also has improved floating-point performance and faster passing of parameters. Sixty-four-bit processors have double the number of registers, of both general purpose and streaming SIMD extensions (SSE) types, as well as support for SSE and SSE2 instruction sets; many 64-bit processors even support SSE3 instruction sets.

Specifying Large-Address-Aware When Building

It is a good practice to specify large-address-aware when building, by using the linker flag /LARGEADDRESSAWARE, even if the application is not intended for a 64-bit platform, because of the advantages that are gained at no cost. As explained earlier, enabling this flag for a build allows a 32-bit program to access more memory with special boot options on a 32-bit OS or on a 64-bit OS. However, developers must be careful that pointer assumptions are not made, such as assuming that the high-bit is never set in a 32-bit pointer. In general, enabling the /LARGEADDRESSAWARE flag is a good practice.

Compatibility of 32-Bit Applications on 64-Bit Platforms

Sixty-four-bit Windows operating systems are binary compatible with the IA32 architecture, and the majority of APIs that 32-bit applications use are available through the Windows 32-bit on Windows 64-bit Emulator, WOW64. WOW64 helps ensure that these APIs will work as intended.

WOW64 has an execution layer that handles the marshalling of 32-bit data. WOW64 redirects DLL file requests, redirects some registry branches for 32-bit applications, and reflects some registry branches for 32- and 64-bit applications.

More information on WOW64 can be found at WOW64 Implementation Details.

Potential Compatibility Pitfalls

Most applications developed for a 32-bit platform will run without problems on a 64-bit platform. A few applications could have issues, which might include the following:

  • All drivers on a 64-bit OS must be 64-bit versions. Requiring new 64-bit drivers has implications for copy-protection schemes that rely on old drivers.
  • 64-bit processes cannot load 32-bit DLLs, and 32-bit processes cannot load 64-bit DLLs. Developers must ensure that 64-bit versions of third-party DLLs are available before proceeding with development. If you must use a 32-bit DLL in a 64-bit process, then Windows inter-process communication (IPC) can be used. COM components can also make use of out-of-process servers and marshalling to communicate between boundaries, but doing so may introduce a performance penalty.
  • Many x64 processors are also multi-core processors, and developers need to test to how this affects their legacy applications. More information on multi-core processors and the implications for gaming applications can be found in Game Timing and Multicore Processors.
  • Applications should also call SHGetFolderPath to discover file paths, as some folder names have changed in certain cases. For example, CSIDL_PROGRAM_FILES would return "C:\Program Files(x86)" for a 32-bit application running on a 64-bit platform instead of "C:\Program Files". Developers must be mindful of how the WOW64 emulator's redirection and reflection capabilities work.
  • Some older DirectX APIs have been dropped for 64-bit native applications: DirectMusic, DirectPlay 4 and earlier, DirectDraw 6 and earlier, Direct3D 8 and earlier, and DirectInput 7 and earlier. Visual Studio 2005 will issue deprecation warnings, and this is not an issue for developers using the latest APIs.

In addition, developers need to be wary of 16-bit programs that they might still be using. WOW64 cannot handle 16-bit applications; this includes old installers and all MS-DOS programs.

Note The most common compatibility issues are installers that execute 16-bit code and not having 64-bit drivers for copy protection schemes.

The next section discusses issues related to porting code to 64-bit native for developers that want to ensure their legacy programs work on 64-bit platforms. It is also for developers who are unfamiliar with 64-bit programming.

Porting Applications to 64-Bit Platforms

Having the right tools and libraries will help to ease the transition from 32-bit to 64-bit development. The DirectX 9 SDK has libraries to support both x86- and x64-based projects. Microsoft Visual Studio 2005 supports code generation for both x86 and x64, and it comes with libraries optimized for generating x64 code. However it will also be necessary for the developer to distribute the Visual C 2005 runtimes with their applications. Note that Visual Studio 2005 Express Editions do not include the x64 compiler, but that the Standard, Professional, and Team System versions all do.

Developers who are targeting 32-bit platforms can prepare for 64-bit development to make their transition easier later on. When compiling 32-bit projects, developers should use the /Wp64 flag, which will cause the generation of warnings about issues that affect portability. Switching to 64-bit tools and libraries will probably generate a lot of new build errors initially; so, it is advisable to switch bit-neutral tools and libraries and correct any warnings before switching to a 64-bit build.

Changing tools, changing libraries, and using certain compiler flags will not be enough, though. Assumptions in coding standards must be reevaluated to ensure that current coding standards don't allow portability issues. Portability issues can include pointer truncation, size and alignment of data types, reliance on 32-bit DLLs, use of legacy APIs, assembly code, and old binary files. Major porting issues include the following:

  • Pointer Truncation
  • Data Types and Binary Files
  • Older Win32 APIs and Data Alignment
  • Assembly Code

Pointer Truncation

Pointers are 64-bits on a 64-bit OS, so casting pointers to other data types can result in truncation, and pointer arithmetic can result in corruption. Using the /Wp64 flag will usually provide a warning about this kind of issue, but using polymorphic types (INT_PTR, DWORD_PTR, SIZE_T, UINT_PTR, and so on) when casting pointer types is a good practice to help avoid this issue altogether. Since pointers are 64-bit on new platforms, developers should check the ordering of pointers, and the data types in classes and structures, to reduce or eliminate padding.

Data Types and Binary Files

While pointers increase from 32 bits to 64 on a 64-bit platform, other data types don't. Fixed-precision data types (DWORD32, DWORD64, INT32, INT64, LONG32, LONG64, UINT32, UINT64) can be used in places where the size of the data type must be known; for example, in a binary file structure. The changes in pointer size and data alignment require special handling to ensure 32-bit-to-64-bit compatibility. More information can be found in Getting Ready for 64-bit Windows: The New Data Types

Older Win32 APIs and Data Alignment

Some Win32 APIs have been deprecated and replaced with more neutral API calls such as SetWindowLongPtr in place of SetWindowLong.

The performance penalty for non-aligned accesses is greater on x64 platform than on an x86 platform. The TYPE_ALIGNMENT(t) and the FIELD_OFFSET(t, member) macros can be used to determine alignment information that can used directly by code. Correct use of these aforementioned macros should eliminate potential non-aligned access penalties.

More information on the TYPE_ALIGNMENT macro, the FIELD_OFFSET macro, and general 64-bit programming information can be found at 64-bit Windows Programming: Migration Tips: Additional Considerations and Getting Ready for 64-bit Windows: Rules for Using Pointers.

Assembly Code

Inline assembly code is not supported on 64-bit platforms and needs to be replaced. Changes in the architecture may have changed application bottlenecks, and C/C++ or intrinsics can achieve similar results with code that is easier to read. The most advisable practice is to switch all assembly code to C or C++. Intrinsics can be used in place of assembly code, but should only be used after full profiling and analysis has been performed.

The x87, MMX, and 3DNow! instruction sets are deprecated in 64-bit modes. The instructions sets are still present for backward compatibility for 32-bit mode; however, to avoid compatibility issues in the future, their use in current and future projects is discouraged.

Profiling and Optimization of Ported Applications

All developers need to re-profile any applications that are being ported to new architectures. Many applications being ported to 64-bit platforms will have different performance profiles from their 32-bit versions. Developers need to run 64-bit performance tests before assessing what needs to be optimized. The good news about this is that many traditional optimizations work on 64-bit platforms. In addition, 64-bit compilers can also perform many optimizations with the correct use of compiler flags and coding hints.

Some structures may have their internal data types reordered to conserve memory space and improve caching. Array indices can be used instead of a full 64-bit pointer in some cases. The /fp:fast flag can improve floating-point optimizing and vectorization. Using __restrict, declspec(restrict), and declspec(noalias) can help the compiler resolve aliasing and improve use of the register file.

More information on /fp:fast can be found at /fp (Specify Floating-Point Behavior)

More information on __restrict can be found at Microsoft-Specific Modifiers

More information on declspec(restrict) can be found at Optimization Best Practices

More information on declspec(noalias) can be found at __declspec(noalias)

Summary

Sixty-four-bit architectures allow developers to push the limitations on how games look, sound, and play. Transitioning from 32-bit programming to 64-bit programming is not trivial, however. By understanding the differences between the two, and by using the newest tools, the transition to 64-bit platforms can be easier and faster.

More information on 64-bit programming can be found at Visual C++ Developer Center: 64-Bit Programming


Authenticode Signing for Game Developers

XNA Developer Connection (XDC)

December 2006

Introduction

Data authentication is increasingly important for game developers. Windows Vista has a number of features, such as parental controls, that require games to be properly signed to ensure that no one has tampered with the data. Microsoft Authenticode enables end users and the operating system to verify that program code comes from the rightful owner and that it hasn't been maliciously altered or accidentally corrupted. This article discusses how to get started with authenticating your game and how to integrate authentication into a daily build process.

Background

Digital certificates are used to establish the identity of the author. Digital certificates are issued by a trusted third party known as a Certificate Authority (CA) such as VeriSign or Thawte. The CA is responsible for verifying that owner is not claiming a false identify. After applying to a CA for a certificate, commercial developers can expect a response to their application in less than two weeks.

After the CA decides that you meet its policy criteria, it generates a Code-Signing Certificate (CER) that conforms to X.509, the industry-standard certificate format created by the International Telecommunications Union, with Version 3 extensions. This certificate identifies you and contains your public key. It is stored by the CA for reference, and a copy is given to you electronically. At the same time, you also create a private, key which you must keep safe and which you must not share with anyone, even the CA.

After you have a public and private key, you can then begin distributing signed software. Microsoft provides tools to do this in the Platform SDK. The tools utilize a one-way hash, produce a fixed-length digest, and generate an encrypted signature with a private key. They then combine that encrypted signature with your certificate and credentials into a structure known as a signature block and embed it into the file format of the executable. Any type of executable binary file can be signed, including DLLs, executable files, and cabinet files.

The signature can be verified in multiple ways. Programs can call the CertVerifyCertificateChainPolicy function, and SignTool (signtool.exe) can be used to verify a signature from the command-line prompt. Windows Explorer also has a Digital Signatures tab in File Properties that displays each certificate of a signed binary file. (The Digital Signatures tab will only appear in the File Properties of signed files.) Also, an application can be self-verifying by use of the CertVerifyCertificateChainPolicy API.

Authenticode signing is not only useful for data authentication by end users, but is also needed for Limited User Account Patching and by Windows Vista's parental controls. Future technologies in Windows may also require signed code, so it is strongly advised that all professional and amateur developers acquire a CER from a CA. More information on how this is done can be found later in this article in Using a Trusted Certificate Authority.

Getting Started

To get started, Microsoft provides tools with Visual Studio 2005 and in the Platform SDK to help perform and verify the code-signing process. After installing Visual Studio 2005 or the Platform SDK, these tools are in one of the following subdirectories, respectively:

  • %SystemDrive%\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin
  • %SystemDrive%\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\Bin

The following tools are the most useful for signing code:

Certificate Creation Tool (MakeCert.exe)
Generates a test X.509 certificate (CER) containing your public key and .pvk file containing your private key. This certificate is only for internal testing purposes and can't be used publicly.
pvk2pfx.exe
Creates a Personal Information Exchange (PFX) file from a CER and PVK file. The PFX contains both your public and private key.
SignTool (SignTool.exe)
Signs file using the PFX file. SignTool supports signing DLL, EXE, MSI, and CAB files.

Note While reading other documentation, you might find references to SignCode (SignCode.exe), but this tool is deprecated and is no longer supported — you should use SignTool instead.

Using a Trusted Certificate Authority

To obtain a trusted certificate, you must apply to a Certificate Authority (CA), such as VeriSign or Thawte. Microsoft doesn't recommend any CA over another, but if you want to integrate into the Windows Error Reporting (WER) service, you should consider using VeriSign to issue the certificate because accessing the WER database requires a WinQual account which requires a VeriSign ID. For a complete list of trusted third-party certificate authorities, see Microsoft Root Certificate Program Members on MSDN. For more information about registering with WER, see "Introducing Windows Error Reporting" in ISV Zone, also on MSDN.

After you receive your certificate from the CA, you can sign your program by using SignTool and release your program to the public. However, you must be careful to protect your private key, which is contained in your PFX and PVK files. Be sure to keep these files in a secure location.

Example Using a Test Certificate

The following steps demonstrate creation of a test Code-Signing certificate, followed by the signing of a Direct3D sample program (called BasicHLSL.exe) using this test certificate. This procedure creates a CER and PVK — your public and private keys, respectively — which cannot be used for public certification.

In this example, a time stamp is also added to the signature. A time stamp prevents the signature from becoming invalid when the certificate expires. Code that is signed but lacking a time stamp will not validate after the certificate expires. Therefore, all publicly released code should have a time stamp.

To create a certificate and sign a program

  1. Create a Test CER and PVK by using the Certificate Creation Tool (MakeCert.exe).

    The following command-line example specifies MyPrivateKey as the file name for the PVK, MyPublicKey as the file name for the CER, and MySoftwareCompany as the name of the certificate:

    makecert.exe -sv MyPrivateKey.pvk -n "CN=MySoftwareCompany" MyPublicKey.cer

  2. Create a PFX from your PVK and CER by using pvk2pfx.exe.

    The PFX file combines your public and private keys into a single file. The following command-line example uses the PVK and CER from the previous step to create the PFX in a file named MyPFX with the password your_password:

    pvk2pfx.exe -pvk MyPrivateKey.pvk -spc MyPublicKey.cer -pfx MyPFX.pfx -po your_password

  3. Sign your program with your PFX by using SignTool.

    You can specify several options on the command line. The following command-line example uses the PFX file from the previous step, gives your_password as the password, specifies BasicHLSL as the file to be signed, and retrieves a time stamp from a specified server:

    signtool.exe sign /f MyPFX.pfx /p your_password /v BasicHLSL.exe /t URL_to_time_stamp_service

    Note The URL to the time stamp service is provided by the CA.

  4. Verify that the program is signed by using SignTool.

    The following command-line example specifies that SignTool should attempt to verify the signature on BasickHLSL.exe by using all available methods while providing verbose output:

    signtool.exe verify /a /v BasicHLSL.exe

    In this example, SignTool should indicate that the certificate is attached, while also stating that it is not trusted, since it is not issued by a CA.

Integrating Code Signing into the Daily Build System

To integrate code signing into a project, you can create a batch file or script to run the command line tools. After the project is built, run SignTool with the proper settings (as shown in step 3 of our example).

Be especially cautious in your build process to insure that access to the PFX and PVK files is restricted to as few computers and users as possible. As a best practice, developers should only sign code with the test certificate until they are ready to ship. Again, the private key should be kept in a secured location, like a safe or locked room, and ideally on a cryptographic device, like a smart card.

Another layer of protection is provided by using Microsoft Authenticode to sign the Windows Installer (MSI) package itself. This helps protect the MSI package against tampering and accidental corruption. Refer to the documentation for your MSI creation tool for more information about how to sign packages with Authenticode.

Revocation

In the event that the security of the private key is compromised or some security-related event renders a Code-Signing certificate invalid, the developer must revoke the certificate. Not doing so would weaken the integrity of the developer and the effectiveness of signing code. A CA can also issue a revocation with specific time; code signed with a time stamp prior to the revocation time will still be considered valid, but code with a subsequent time stamp will be invalid. Certificate revocation affects code in any applications that is signed with the revocated certificate.

Code-Signing Drivers

Drivers can and should be Authenticode-signed. Kernel-mode drivers have additional requirements: 64-bit editions of Windows Vista will prevent installation of all unsigned kernel-mode drivers, and all versions of Windows will present a warning prompt when a user attempts to install an unsigned driver. In addition, administrators can set Group Policy to prevent unsigned drivers from being installed on Microsoft Windows Server 2003, Windows XP Professional x64 Edition, and 32-bit editions of Windows Vista.

Many types of drivers can be signed with a Microsoft-trusted signature — as part of the logo program of Windows Hardware Quality Labs (WHQL) or the Unclassified Signature Program (formerly named Driver Reliability Signature) — which allows the system to fully trust these drivers and install them even without administrative credentials.

At a minimum, drivers should be Authenticode-signed, because drivers that are unsigned or self-signed (that is, signed with a test certificate) will fail to install on many Windows-based platforms. For more information about signing drivers and code and related feature in Windows Vista, see Driver Signing Requirements for Windows on Windows Hardware Developer Central.

Summary

Using Microsoft Authenticode is a straightforward process. Once you have obtained a CER and created a private key, it is a simple matter of using the tools provided by Microsoft. You can then enable important Windows Vista features, such as parental controls, and let customers know that your product comes directly from its rightful owner.

More information

More information about tools and processes related to signing code, see the following links:

Cryptography Tools

Crypto API Tools Reference

Authenticode Overview and Turtorials

Digital Certificates

Frequently Asked Questions About Authenticode

Deploying Authenticode


Best Security Practices in Game Development

XNA Developer Connection (XDC)

February 2007

Introduction

An increasing number of people play online games and games with user-made content. This, combined with the increasing security of the Microsoft® Windows® Operating System, means that games are a growing and more tempting target for attackers to exploit. Game developers should place a strong emphasis on making sure that the games they release aren't creating new security holes for attackers to exploit. Game developers have a responsibility and a vested interest in helping to prevent their customers' computers from being hacked by malicious network data, user modifications, or tampering. If a vulnerability is exploited, it could result in losing customers and/or money. This article outlines and explains some common methods and tools to increase code security without over-inflating development time.

The three most common mistakes made by a development team when releasing a product are:

  1. Requiring administrative privileges. Games should not require administrative privileges. The best practice is to drop administrative privileges on program startup, if the user is running the game in an administrator account. For information on and an example of dropping administrator prvileges see Browsing the Web and Reading E-mail Safely as an Administrator by Michael Howard
  2. Not using automated protection. Developers are generally not using /GS, /SAFESEH, or /NX. Using these compile/link flags can spot or eliminate many basic security holes without significantly increasing workload. These flags are discussed later in this article.
  3. Using forbidden APIs. There are many APIs (strcpy, strncpy, etc.) that are prone to programmer error and easily generate security holes. Developers should replace these APIs with the safe versions. Visual Studio 2005 comes with a tool for analyzing binary files that can automatically check object files for references to unsafe APIs. For more information on what to do with information generated with this tool, see Repel Attacks on Your Code with the Visual Studio 2005 Safe C and C++ Libraries by Martyn Lovell.

Each of the listed mistakes is not only common but is easily correctable with no significant change in development workload, coding standards, or functionality.

Examples of Insecure Code

The following is a simple example of all it takes to allow an attacker to perform a buffer overrun attack:

void GetPlayerName(char *pDatafromNet)
{
    char playername[256];
    strncpy(playername, pDatafromNet, strlen(pDatafromNet));

    // ...
}

On the surface this code looks ok — it calls a safe function, after all. Data from the network is copied into a buffer that is 256 bytes. The strncpy function relies on finding a NULL terminator in the source string or is limited by the provided buffer count. The problem is that the buffer size is incorrect. If data from the network isn't validated or the buffer size is wrong (as in this example), an attacker could simply provide a large buffer to overwrite stack data, after the buffer ends, with any data in the network packet. This would allow the attacker to execute arbitrary code by overwriting the instruction pointer and changing the return address. The most basic lesson of this example is to never trust input until it has been verified.

Even if data doesn't come from the network initially, there still is potential risk. Modern game development requires many people designing, developing, and testing the same code base. There is no way to know how the function will be called in the future. Always ask yourself where the data came from and what could an attacker control? While network-based attacks are the most common, they are not the only methods of creating security holes. Could an attacker create a mod or edit a saved file in a way that opens a security hole? What about user-supplied image and sound files? Malicious versions of these files could be posted on the Internet and create dangerous security risks for your customers.

As a side note, use strsafe.h or Safe CRT instead of strncpy to correct the example. Safe CRT is a complete security overhaul of the C Runtime and comes with part of Visual Studio 2005. More information about Safe CRT can be found in Saying Goodbye to an Old Friend by Michael Howard.

Ways to improve security

There are several ways to improve security in the development cycle. Here are some of the best ways:

  1. Reading about security

    The book, Writing Secure Code, Second Edition by Michael Howard and David LeBlanc, provides an in-depth and clear explanation of strategies and methods of preventing attacks and mitigating exploits. Starting with methods of designing security into a release to techniques for securing network applications, the book covers all aspects that a game developer needs to help protect themselves, their products, and their customers from attackers. The book can be used to instill a culture of security in a development studio. Don't just think of code security as a developer's problem or a tester's problem. Think of security as something the whole team — from program manager to designer to developer to tester — should be thinking about when they work on a project. The more eyes that are part of the review process, the greater the chance of catching a security hole prior to release.

    Writing Secure Code, Second Edition can be found at Microsoft Learning and more general security information can be found in Fending Off Future Attacks by Reducing Attack Surface by Michael Howard.

    Michael Howard, David LeBlanc, and John Viega have written another book on the subject that covers all common operating systems and programming languages entitled, 19 Deadly Sins of Software Security.

    More good information can be found in the Meltdown 2005 presentations "Finding Security Bugs" and "Reviewing Code for Security Bugs" by Michael Howard.

  2. Threat Modeling Analysis

    A threat modeling analysis is a good way of assessing system security, not in a specific language or by using a tool, but in a broad, end-to-end method that can be accomplished in a few meetings. When implemented properly, a thread model can identify all of the strengths and weaknesses of a system, without adding significant workload or meeting time to the project. The method of threat modeling also emphasizes the idea of assessing system security prior to and during the development process to help ensure that a comprehensive assessment is being made while focusing on the most risky features. It can be thought of as a profiler for security. By not being based on a particular language or relying on a specific tool, threat modeling can be used in any development studio working on any project in any genre. Threat modeling is also an excellent method of reinforcing the idea that security is everyone's responsibility and not someone else's problem.

    When threat modeling, pay special attention to:

    • UDP data sources
    • Data sources that don't require authentication
    • Data sources that are frequently and normally probed as part of wide-scale information gathering
    • Any ability of a client to directly send data to other clients

    These are the areas that have good potential for security weaknesses.

    More on Threat Modeling can be found at Threat Modeling on the MSDN Security Development Center and in the book Threat Modeling by Frank Swiderski and Window Snyder.

  3. Data Execution Prevention (/NX)

    A recent tool in mitigating multiple exploits is data execution prevention (DEP). If you include the switch /NX in the build command, Visual Studio will mark memory pages with flags that denote whether the code has the right to execute or not. Any program attempting to execute in a memory page not flagged with EXECUTE permission will cause a forcible termination of the program. The prevention is enforced on the processor level and will impact developers who are using self-modifying code or native JIT language compilers. Currently, only AMD's Athlon64 and Opteron processors and Intel's Itanium and latest Pentium 4 processors support execution prevention, but it is expected that all 32-bit and 64-bit processors will support execution prevention in the future. (A copy-protection scheme used by a developer may be affected by execution prevention, but Microsoft has been working with copy-protection vendors to minimize the impact.) It is a good practice to use DEP.

  4. Buffer Security Check (/GS) and Image has Safe Exception Handlers (/SAFESEH)

    Buffer Security Check, specified by the compiler flag /GS, and Image has Safe Exception Handlers, specified by the linker flag /SAFESEH (first implemented in Visual Studio .NET 2003), can make the developer's job of securing code a little easier.

    Using the /GS flag causes the compiler to construct a check for some forms of stack-based buffer overruns that could be exploited to overwrite the return address of a function. Using /GS will not detect every potential buffer overrun and shouldn't be considered a catch-all, but a good defense-in-depth technology.

    Using the /SAFESEH flag will instruct the linker to only generate an executable or DLL if it can also generate a table of the safe exception handlers of the executable or DLL. Safe Structured Exception Handling (SafeSEH) eliminates exception handling as a target of buffer overrun attacks by ensuring that, before an exception is dispatched, the exception handler is registered in the function table located within the image file. These protection benefits are enabled with Windows XP SP2, Windows Server 2003, and Windows Vista. Also for /SAFESEH to work properly, it must be used in an all-or-nothing method. All libraries containing code bound to an executable or DLL must be compiled with /SAFESEH or the table will not be generated.

    More information about Buffer Security Check (/GS) and Image has Safe Exception Handlers (/SAFESEH) can be found in MSDN.

  5. PREfast

    PREfast is a free tool offered by Microsoft that analyzes execution paths in compiled C or C++ to help find run-time bugs. PREfast operates by working through all execution paths in all functions and assessing each path for problems. Originally used to develop drivers and other kernel code, this tool can help game developers save time by eliminating some bugs that are hard to find or are ignored by the compiler. Using PREfast is an excellent way of reducing workload and focusing the efforts of both the development team and test team. PREfast is available in Visual Studio Team Suite and Visual Studio Team Edition for Software Developers as Code Analysis, enabled by the compiler switch /analyze. (This option is also available in the free version of the compiler that ships with the Windows Software Development Kit.)

    Through the use of header annotation (particularly for buffer pointer arguments), PREfast can expose additional issues, such as memory overwrite bugs, a common source of crashes and potential security vulnerabilities. This is done by using the Standard Annotation Language (SAL), which is a form of mark-up for C/C++ function prototypes that provide additional information about expected pointer argument semantics and correlation with length parameters, declared buffer sizes, etc. All of the headers for Windows operating systems are annotated, and adding SAL mark-up in public API headers in your own libraries enables PREfast to perform more detailed and aggressive checks in your client code for such APIs. For an introduction to SAL and links to more information, see Michael Howard's blog entry, "A Brief Introduction to the Standard Annotation Language (SAL)."

  6. Windows Application Verifier

    The Windows Application Verifier, or AppVerifier, can help testers by providing multiple functions in one tool. The AppVerifier is a tool that was developed to make common programming errors more testable. AppVerifier can check parameters passed to API calls, inject erroneous input to check error handling ability, and log changes to the registry and file system. AppVerifier can also detect buffer overruns in the heap, check that an Access Control List (ACL) has been properly defined, and enforce the safe use of socket APIs. While not exhaustive, AppVerifier can be one tool in the tester's toolbox to help a development studio release a quality product.

    For more information on the Windows Application Verifier, see Analyzing Your Applications with Windows Application Verifier by Michael Howard.

  7. Fuzz Testing

    Fuzz testing is a semi-automated method of testing that can enhance current testing methodologies. The central idea behind fuzz testing is to make a full assessment of all inputs by inputing random data to see what breaks; this includes all network data, mods and saved games, etc. Fuzz testing is fairly easy to do. Simply alter well-formed files or network data by inserting random bytes, flipping adjacent bytes, or negating numerical values. 0xff, 0xffff, 0xffffffff, 0x00, 0x0000, 0x00000000, and 0x80000000 are values that are good at exposing security holes while fuzz testing. You can observe the resulting interaction combinations using AppVerifier. While fuzzing is not exhaustive, it is easy to implement and automate, and it can catch the more elusive and unpredictable bugs.

    For more information on fuzz testing, see "What is Fuzzing?" in the slideshow Finding Security Bugs, a presentation made at Microsoft Meltdown 2005 (all slideshows from Meltdown 2005).

  8. Authenticode Signing

    Authenticode is a method of ensuring that executable files, DLL files, and Windows installer packages (.msi files) that the user receives are unaltered from what a developer released. By using a combination of cryptographic principles, trusted entities, and industry standards, Authenticode verifies the integrity of executable content. Microsoft provides a cryptographic API, CryptoAPI, that can be used to auto-detect tampering of signed code. If a security leak occurs after a release, a certificate can be revoked and all code signed with that certificate will stop authenticating. Revoking a certificate will revoke the validation of all titles signed with that certificate. Windows has been designed to work with Authenticode signing and will alert a user of unsigned code, in specific situations, that could expose a user's PC to attack.

    Authenticode should not be considered a method of eliminating security flaws, but a method of detecting tampering after an executable has been released. An executable or DLL that contains an exploitable security flaw can be signed and verified using Authenticode, but it will still introduce the security flaw to the new system. Only after a product or update has been verified to be secure should the code be signed to assure users that they have a release that hasn't been tampered with.

    Even if a developer feels that there is no threat of their releases being modified, other technologies and services rely on Authenticode. Code signing is easy to integrate and automate; there is no reason for developers to not have their releases signed.

    For more information on Authenticode signing, see Authenticode Signing for Game Devlopers.

Summary

Developing a game for the current and future marketplace is costly and time consuming. Releasing a game with security flaws will ultimately cost more money and time to properly fix. So, it is in the interests of all game developers to integrate tools and techniques to mitigate security exploits prior to release.

The information in this article is just an introduction to what a development studio can do to help themselves and their customers. More information of general security practices and security information can be found at Microsoft Security Developer Center.


Coding For Multiple Cores on Xbox 360 and Microsoft Windows

By Bruce Dawson, Software Design Engineer

XNA Developer Connection (XDC)

August 2006

Introduction

For years the performance of processors has increased steadily, and games and other programs have reaped the benefits of this increasing power without having to do anything special.

The rules have changed. The performance of single processor cores is now increasing very slowly, if at all. However, the computing power available in a typical computer or console continues to grow. The difference is that most of this performance gain now comes from having multiple processor cores in a single machine, often in a single chip. The Xbox 360 CPU has three processor cores on one chip, and roughly 70 percent of PC processors sold in 2006 will be multi-core.

The increases in available processing power are just as dramatic as in the past, but now developers have to write multithreaded code in order to use this power. Multi-threaded programming brings with it new design and programming challenges. This paper gives some advice on how to get started with multithreaded programming.

The Importance of Good Design

Good multithreaded program design is critical, but it can be very difficult. If you haphazardly move your major game systems onto different threads, you will likely find that each thread spends most of its time waiting on the other threads. This type of design leads to increased complexity and significant debugging effort, with virtually no performance gain.

Every time that threads have to synchronize or share data there is the potential for data corruption, synchronization overhead, deadlocks, and complexity. Therefore, your multithreaded design needs to clearly document every synchronization and communication point, and it should minimize such points as much as possible. Where threads need to communicate, coding effort will increase, which can lower productivity if it affects too much source code.

The simplest design goal for multithreading is to break up the code into large independent pieces. If you then restrict these pieces to communicating just a few times per frame, you will see significant speedup from multithreading, without undue complexity.

Typical Threaded Tasks

A few types of tasks have proven amenable to being put onto separate threads. The following list is not intended to be exhaustive, but should give some ideas.

Rendering

Rendering — which may include walking the scene graph or, possibly, only calling D3D functions — often accounts for 50 percent or more of CPU time. Therefore, moving rendering to another thread can have significant benefits. The update thread can fill in some sort of render description buffer, which the rendering thread can then process.

The game update thread is always one frame ahead of the render thread, which means that it takes two frames before user actions show up on the screen. Although this increased latency can be a problem, the increased frame rate from splitting up the workload generally keeps the total latency acceptable.

In most cases all rendering is still done on a single thread, but it is a different th read from the game update.

Avoid using the D3DCREATE_MULTITHREADED flag, which is sometimes used to allow rendering on one thread and resource creation on other threads. Specifying this flag forces D3D to spend a significant amount of time on synchronization, thus slowing down the render thread.

File Decompression

Load times are always too long, and streaming data into memory without affecting the frame rate can be challenging. If all data is aggressively compressed on disc, then data transfer speed from the hard drive or optical disc is less likely to be a limiting factor. On a single-threaded processor, there is usually not enough processor time available for compression to help load times. On a multiprocessor system, however, file decompression uses CPU cycles that would otherwise be wasted; it improves load times and streaming; and it saves space on the disc.

Do not use file decompression as a replacement for processing that should be done during production. For instance, if you devote an extra thread to parsing XML data during level loading, you are not using multithreading to improve the player's experience.

When using a file decompression thread, you should still use asynchronous file I/O and large reads in order to maximize data-reading efficiency.

Graphics Fluff

There are many graphical niceties that improve the look of the game but aren't strictly necessary. These include things like procedurally generated cloud animations, cloth and hair simulations, procedural waves, procedural vegetation, more particles, or non-gameplay physics.

Because these effects don't affect gameplay, they don't cause tricky synchronization problems—they can synchronize with the other threads once per frame or less often. Additionally, on games for Windows these effects can add value for gamers with multicore CPUs, while silently being omitted on single-core machines, thus giving an easy way of scaling across a wide range of capabilities.

Physics

Physics often cannot be put onto a separate thread to run in parallel with the game update because the game update usually requires the results of the physics calculations immediately. The alternative for multithreading physics is to run it on multiple processors. Although this can be done, it is a complex task requiring frequent access to shared data structures. If you can keep your physics workload low enough to fit on the main thread, your job will be simpler.

Libraries that support running physics on multiple threads are available. However, this can lead to a problem: when your game is running physics, it uses many threads, but the rest of the time it uses few. Running physics on multiple threads will require addressing this so that the workload is distributed evenly over the frame. If you write a multithreaded physics engine, you must pay careful attention to all of your data structures, synchronization points, and load balancing.

Example Multithreaded Designs

Games for Windows need to run on machines with different numbers of CPU cores. Most game machines still have only one core, although the number of two-core machines is growing rapidly. A typical game for Windows might break its workload into one thread for update and rendering, with optional worker threads for adding extra functionality. In addition, some background threads for doing file I/O and networking would probably be used. Figure 1 shows the threads, together with the main data transfer points.

Figure 1. Threading design in a game for Windows

A typical Xbox 360 game can use additional CPU-intensive software threads, so it might break up its workload into an update thread, rendering thread, and three worker threads, as shown in Figure 2.

Figure 2. Threading design in a game for Xbox 360

With the exception of file I/O and networking, these tasks all have the potential to be CPU-intensive enough to benefit from being on their own hardware thread. These tasks also have the potential to be independent enough that they can run for an entire frame without communicating.

The game update thread manages controller input, AI, and physics, and prepares instructions for the other four threads. These instructions are placed into buffers owned by the game update thread, so no synchronization is required as the instructions are generated.

At the end of the frame, the game update thread hands off the instruction buffers to the four other threads, and then starts working on the next frame, filling in another set of instruction buffers.

Because the update and rendering threads work in lockstep with each other, their communication buffers are simply double buffered: at any given time, the update thread is filling one buffer while the render thread is reading from the other.

The other worker threads are not necessarily tied to the frame rate. Decompressing a piece of data may take much less than a frame, or it may take many frames. Even the cloth and hair simulation may not need to run exactly at the frame rate because less frequent updates may be quite acceptable. Therefore, these three threads need different data structures to communicate with the update thread and the render thread. They each need an input queue that can hold work requests, and the render thread needs a data queue that can hold the results produced by the threads. At the end of each frame the update thread will add a block of work requests to worker threads' queues. Adding to the list just once per frame ensures that the update thread minimizes the synchronization overhead. Each of the worker threads pulls assignments from the work queue as quickly as it can, using a loop that looks something like this:

for(;;)
{
    while( WorkQueueNotEmpty() )
    {
        RemoveWorkItemFromWorkQueue();
        ProcessWorkItem();
        PutResultInDataQueue();
    }
    WaitForSingleObject( hWorkSemaphore );
}

Because the data goes from the update threads to the worker threads and then to the render thread, there can be a delay of three or more frames before some actions make it to the screen. However, if you assign latency-tolerant tasks to the worker threads, then this should not be a problem.

An alternate design would be to have several worker threads all drawing from the same work queue. This would give automatic load balancing and would make it more likely that all of the worker threads would stay busy.

The game update thread must take care to not give too much work to the worker threads, or else the work queues may continuously grow. How the update thread manages this depends on what sort of tasks the worker threads are doing.

Simultaneous Multithreading and Number of Threads

All threads are not created equal. Two hardware threads might be on separate chips, on the same chip, or even on the same core. The most important configuration for game programmers to be aware of is two hardware threads on one core—Simultaneous Multi-Threading (SMT) or Hyper-Threading Technology (HT Technology).

SMT or HT Technology threads share the resources of the CPU core. Because they share the execution units, the maximum speedup from running two threads instead of one is typically 10 to 20 percent, instead of the 100 percent that is possible from two independent hardware threads.

More significantly, SMT or HT Technology threads share the L1 instruction and data caches. If their memory access patterns are incompatible, they can end up fighting over the cache and causing many cache misses. In the worst case, the total performance for the CPU core can actually decrease when a second thread is run. On Xbox 360, this is a fairly simple problem. The configuration of the Xbox 360 is known—three CPU cores each with two hardware threads—and developers assign their software threads to specific CPU threads and can measure to see whether their threading design gives them extra performance.

On Windows, the situation is more complicated. The number of threads and their configuration will vary from machine to machine, and determining the configuration is complicated. The function GetLogicalProcessorInformation gives information about the relationship between different hardware threads, but this function is available on Windows Vista, not Windows XP. Therefore, for now you have to use the CPUID instruction and the algorithms given by Intel and AMD in order to decide how many "real" threads you have available. See the references for more information.

The CoreDetection sample in the DirectX SDK contains sample code that uses the GetLogicalProcessorInformation function or the CPUID instruction to return the CPU core topology. The CPUID instruction is used if GetLogicalProcessorInformation is not supported on the current platform. CoreDetection can be found in the following locations:

Source:
DirectX SDK root\Samples\C++\Misc\CoreDetection
Executable:
DirectX SDK root\Samples\C++\Misc\Bin\CoreDetection.exe

The safest assumption is to have no more than one CPU-intensive thread per CPU core. Having more CPU-intensive threads than CPU cores gives little or no benefits, and brings the extra overhead and complexity of additional threads.

Creating Threads

Creating threads is a fairly simple operation, but there are many potential errors. The code below shows the proper way of creating a thread, waiting for it to terminate, and then cleaning up.

const int stackSize = 65536;
HANDLE hThread = (HANDLE)_beginthreadex( 0, stackSize,
            ThreadFunction, 0, 0, 0 );
// Do work on main thread here.
// Wait for child thread to complete
WaitForSingleObject( hThread, INFINITE );
CloseHandle( hThread );

...

unsigned __stdcall ThreadFunction( void* data )
{
#if _XBOX_VER >= 200
    // On Xbox 360 you must explicitly assign
    // software threads to hardware threads.
    XSetThreadProcessor( GetCurrentThread(), 2 );
#endif
    // Do child thread work here.
    return 0;
}

When you create a thread, you have the option to specify the stack size for the child thread, or specify zero, in which case the child thread will inherit the parent thread's stack size. On Xbox 360, where stacks are fully committed when the thread starts, specifying zero can waste significant memory, because many child threads will not need as much stack as the parent. On Xbox 360 it is also important that the stack size be a multiple of 64-KB.

If you use the CreateThread function to create threads, then the C/C++ runtime (CRT) will not get properly initialized on Windows. We recommend that you use the CRT _beginthreadex function instead.

The return value from CreateThread or _beginthreadex is a thread handle. This thread can be used to wait for the child thread to terminate, which is much simpler and much more efficient than spinning in a loop checking the thread status. To wait for the thread to terminate, simply call WaitForSingleObject with the thread handle.

The resources for the thread will not be freed until the thread has terminated and the thread handle has been closed. Therefore, it is important to close the thread handle with CloseHandle when you are finished with it. If you will be waiting for the thread to terminate with WaitForSingleObject, be sure to not close the handle until after the wait has completed.

On Xbox 360, you must explicitly assign software threads to a particular hardware thread by using XSetThreadProcessor. Otherwise, all child threads will stay on the same hardware thread as the parent. On Windows, you can use SetThreadAffinityMask to strongly suggest to the operating system which hardware threads your thread should run on. This technique should generally be avoided on Windows since you don't know what other processes might be running on the system. It is typically better to let the Windows scheduler assign your threads to idle hardware threads.

Creating threads is an expensive operation. Threads should be created and destroyed rarely. If you find yourself wanting to create and destroy threads frequently, use a pool of threads that wait around for work instead.

Synchronizing Threads

For multiple threads to work together, you must be able to synchronize threads, pass messages, and request exclusive access to resources. Windows and Xbox 360 come with a rich set of synchronization primitives. For full details on these synchronization primitives, see the platform documentation.

Exclusive Access

Gaining exclusive access to a resource, data structure, or code path is a common need. One option for gaining exclusive access is a mutex, whose typical usage is shown here.

// Initialize
HANDLE mutex = CreateMutex( 0, FALSE, 0 );

// Use
void ManipulateSharedData()
{
    WaitForSingleObject( mutex, INFINITE );
    // Manipulate stuff...
    ReleaseMutex( mutex );
}

// Destroy
CloseHandle( mutex );
The kernel guarantees that, for a particular mutex, only one thread at a time can
acquire it.
The main disadvantage to mutexes is that they are relatively expensive to acquire
and release. A faster alternative is a critical section.
// Initialize
CRITICAL_SECTION cs;
InitializeCriticalSection( &cs );

// Use
void ManipulateSharedData()
{
    EnterCriticalSection( &cs );
    // Manipulate stuff...
    LeaveCriticalSection( &cs );
}

// Destroy
DeleteCriticalSection( &cs );

Critical sections have similar semantics to mutexes, but they can be used to synchronize only within a process, not between processes. Their main advantage is that they execute roughly twenty times faster than mutexes.

Events

If two threads—perhaps an update thread and a render thread—are taking turns using a pair of render description buffers, they need a way to indicate when they are done with their particular buffer. This can be done by associating an event (allocated with CreateEvent) with each buffer. When a thread is done with a buffer, it can use SetEvent to signal this, and can then call WaitForSingleObject on the other buffer's event. This technique extrapolates easily to triple buffering of resources.

Semaphores

A semaphore is used to control how many threads can be running and is commonly used to implement work queues. One thread adds work to a queue and uses ReleaseSemaphore whenever it adds a new item to the queue. This allows one worker thread to be released from the pool of waiting threads. The worker threads just call WaitForSingleObject, and when it returns they know there is a work item in the queue for them. In addition, a critical section or other synchronization technique must be used in order to guarantee safe access to the shared work queue.

Avoid SuspendThread

Sometimes when you want a thread to stop what it is doing, it is tempting to use SuspendThread instead of the correct synchronization primitives. This is always a bad idea and can easily lead to deadlocks and other problems. SuspendThread also interacts badly with the Visual Studio debugger. Avoid SuspendThread. Use WaitForSingleObject instead.

WaitForSingleObject and WaitForMultipleObjects

The function WaitForSingleObject is the most commonly used synchronization function. However, sometimes you want a thread to wait until several conditions are simultaneously satisfied, or until one of a set of conditions are satisfied. In this case, you should use WaitForMultipleObjects.

Interlocked Functions and Lockless Programming

There is a family of functions for performing simple thread-safe operations without using locks. These are the Interlocked family of functions, such as InterlockedIncrement. These functions, plus other techniques using careful setting of flags, are together known as lockless programming. Lockless programming can be extremely tricky to do correctly, and is substantially more difficult on Xbox 360 than on Windows.

Minimizing Synchronization

Some synchronization methods are faster than others. However, rather than optimizing your code by choosing the fastest synchronization techniques possible, it is usually better to synchronize less often. This is faster than synchronizing too frequently, and it makes for simpler code that is easier to debug.

Some operations, such as memory allocation, may have to use synchronization primitives in order to work correctly. Therefore, doing frequent allocations from the default shared heap will result in frequent synchronization, which will waste some performance. Avoiding frequent allocations or using per-thread heaps (using HEAP_NO_SERIALIZE if you use HeapCreate) can avoid this hidden synchronization. Another cause of hidden synchronization is D3DCREATE_MULTITHREADED, which causes D3D to use synchronization on many operations.

Per-thread data, also known as thread local storage, can be an important way of avoiding synchronization. Visual C++ allows you to declare global variables as being per-thread with the __declspec(thread) syntax.

__declspec( thread ) int tls_i = 1;

This gives each thread in the process its own copy of tls_i, which can be referenced safely and efficiently without requiring synchronization.

The __declspec(thread) technique does not work with dynamically loaded DLLs. If you use dynamically loaded DLLs, you will need to use the TLSAlloc family of functions to implement thread local storage.

Destroying Threads

The only safe way to destroy a thread is to have the thread itself exit, either by returning from the main thread function or by having the thread call ExitThread or _endthreadex. If a thread is created with _beginthreadex, then it should use _endthreadex or return from the main thread function, since using ExitThread won't properly free CRT resources. Never call the TerminateThread function, because the thread will not be properly cleaned up. Threads should always commit suicide—they should never be murdered.

OpenMP

OpenMP is a language extension for adding multithreading to your program by using pragmas to guide the compiler in parallelizing loops. OpenMP is supported by Visual C++ 2005 on Windows and Xbox 360 and can be used in conjunction with manual thread management. OpenMP can be a convenient way to multithread parts of your code, but is unlikely to be the ideal solution, especially for games. OpenMP may be more applicable to longer-running production tasks such as processing art and other resources. For more information, see the Visual C++ documentation or go to the OpenMP website.

Profiling

Multithreaded profiling is important. It is easy to end up with long stalls where threads are waiting on each other. These stalls can be difficult to find and diagnose. To help identify them, consider adding instrumentation to your synchronization calls. A sampling profiler can also help identify these problems because it can record timing information without substantially altering it.

Timing

The rdtsc instruction is one way to get accurate timing information on Windows. Unfortunately, rdtsc has multiple problems that make it a poor choice for your shipping title. The rdtsc counters are not necessarily synchronized between CPUs, so when your thread moves between hardware threads you may get large positive or negative differences. Depending on power management settings, the frequency at which the rdtsc counter increments may also change as your game runs. To avoid these difficulties, you should prefer QueryPerformanceCounter and QueryPerformanceFrequency for high-precision timing in your shipping game. For more information about timing, see Game Timing and Multicore Processors.

Debugging

Visual Studio fully supports multithreaded debugging for Windows and Xbox 360. The Visual Studio threads window lets you switch between threads in order to see the different call stacks and local variables. The threads window also lets you freeze and thaw particular threads.

On Xbox 360, you can use the @hwthread meta-variable in the watch window to show the hardware thread on which the currently selected software thread is running.

The threads window is easier to use if you name your threads meaningfully. Visual Studio and other Microsoft debuggers allow you to name your threads. Implement the following SetThreadName function and call it from each thread as it starts up.

typedef struct tagTHREADNAME_INFO
{
    DWORD dwType;     // must be 0x1000
    LPCSTR szName;    // pointer to name (in user address space)
    DWORD dwThreadID; // thread ID (-1 = caller thread)
    DWORD dwFlags;    // reserved for future use, must be zero
} THREADNAME_INFO;

void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName )
{
    THREADNAME_INFO info;
    info.dwType = 0x1000;
    info.szName = szThreadName;
    info.dwThreadID = dwThreadID;
    info.dwFlags = 0;

    __try
    {
        RaiseException( 0x406D1388, 0,
                    sizeof(info) / sizeof(DWORD),
            (DWORD*)&info );
    }
    __except( EXCEPTION_CONTINUE_EXECUTION ) {
    }
}

// Example usage:
SetThreadName(-1, "Main thread");

The kernel debugger (KD) and WinDBG also support multithreaded debugging.

Testing

Multithreaded programming can be tricky, and some multithreaded bugs show up only rarely, making them difficult to find and fix. One of the best ways to flush them out is to test on a wide range of machines, particularly those with four or more processors. Multithreaded code that works perfectly on a single-threaded machine may fail instantly on a four-processor computer. The performance and timing characteristics of AMD and Intel CPUs can vary substantially, so be sure to test on multiprocessor machines from both vendors.

Summary

With careful design that minimizes the interactions between threads, you can get substantial performance gains from multithreaded programming without adding excessive complexity to your code. This will let your game code ride the next wave of processor improvements and deliver ever more compelling gaming experiences.

References

  • Jim Beveridge & Robert Weiner. Multithreading Applications in Win32. Addison-Wesley. 1997.
  • Chuck Walbourn. Game Timing and Multicore Processors. Microsoft Corporation. 2005.
  • Microsoft Corporation: Multiprocessor Considerations for Kernel-Mode Drivers. 2004.
  • Intel: Detecting Multi-Core Processor Topology in an IA-32 Platform. 2006.
  • AMD: CPUID Specification. 2006.
  • MSDN Library: GetLogicalProcessorInformation.
  • OpenMP.


Crash Dump Analysis

XNA Developer Connection (XDC)

December 2005

Not all bugs can be found prior to release, which means not all bugs that throw exceptions can be found before release. Fortunately, Microsoft has included in the Platform SDK a function to help developers collect information on exceptions discovered by users. The MiniDumpWriteDump function writes the necessary crash dump information to file without saving the whole process space. This crash dump information file is called a minidump.

This technical article covers the following topics:

  • Writing a Minidump
  • Thread safety
  • Writing a Minidump with Code
  • Using Dumpchk.exe
  • Analyzing a Minidump
  • Summary

Writing a Minidump

The basic options for writing a minidump are as follows:

  1. Do nothing. Windows automatically generates a minidump whenever a program throws an unhandled exception. Automatic generation of a minidump is only available on Windows XP and Windows Vista. If the user allows it, the minidump will be sent to Microsoft, and not to the developer, via Microsoft Windows Error Reporting (WER). Developers can contact the Microsoft Windows Gaming & Graphics developer relations group to arrange for access to the WER service.

    Use of WER requires:

    • Developers to sign their applications using Authenticode
    • Developers to obtain a VeriSign ID to access the WinQual service
    • Applications have valid VERSIONINFO resource in every executable and DLL

    If you implement a custom routine for unhandled exceptions, you are strongly urged to use the ReportFault function in the exception handler to also send an automated minidump to WER. The ReportFault function handles all of the issues of connecting to and sending the minidump to WER. Not sending minidumps to WER violates the Games for Windows requirements.

    For more information on how WER works, see How Windows Error Reporting Works. For an explanation of registration details, see Introducing Windows Error Reporting on MSDN's ISV Zone.

  2. Use a product from the Microsoft Visual Studio® Team System. On the Debug menu, click Save Dump As to save a copy of a dump. Use of a locally saved dump is only an option for in-house testing and debugging.
  3. Add code to your project. Add the MiniDumpWriteDump function and the appropriate exception handling code to save and send a minidump directly to the developer. This article demonstrates how to implement this option. However, note that MiniDumpWriteDump does not currently work with managed code and is only available on Windows XP and Windows Vista.

Thread safety

MiniDumpWriteDump is part of the DBGHELP library. This library is not thread-safe, so any program using MiniDumpWriteDump should synchronize all threads before attempting to call MiniDumpWriteDump.

Writing a Minidump with Code

The actual implementation is straightforward. The following is a simple example of how to use MiniDumpWriteDump.

#include <dbghelp.h>
#include <shellapi.h>
#include <shlobj.h>

int GenerateDump(EXCEPTION_POINTERS* pExceptionPointers)
{
    BOOL bMiniDumpSuccessful;
    WCHAR szPath[MAX_PATH];
    WCHAR szFileName[MAX_PATH];
    WCHAR* szAppName = L"AppName";
    WCHAR* szVersion = L"v1.0";
    DWORD dwBufferSize = MAX_PATH;
    HANDLE hDumpFile;
    SYSTEMTIME stLocalTime;
    MINIDUMP_EXCEPTION_INFORMATION ExpParam;

    GetLocalTime( &stLocalTime );
    GetTempPath( dwBufferSize, szPath );

    StringCchPrintf( szFileName, MAX_PATH, L"%s%s", szPath, szAppName );
    CreateDirectory( szFileName, NULL );

    StringCchPrintf( szFileName, MAX_PATH, L"%s%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
               szPath, szAppName, szVersion,
               stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
               stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
               GetCurrentProcessId(), GetCurrentThreadId());
    hDumpFile = CreateFile(szFileName, GENERIC_READ|GENERIC_WRITE,
                FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);

    ExpParam.ThreadId = GetCurrentThreadId();
    ExpParam.ExceptionPointers = pExceptionPointers;
    ExpParam.ClientPointers = TRUE;

    bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
                    hDumpFile, MiniDumpWithDataSegs, &ExpParam, NULL, NULL);

    return EXCEPTION_EXECUTE_HANDLER;
}

void SomeFunction()
{
    __try
    {
        int *pBadPtr = NULL;
        *pBadPtr = 0;
    }
    __except(GenerateDump(GetExceptionInformation()))
    {
    }
}

This example demonstrates the basic usage of MiniDumpWriteDump and the minimum information necessary to call it. The name of the dump file is up to the developer; however, it is advisable to generate the file name from the application's name and version number, the process and thread IDs, and the date and time to avoid file name collisions. This will also help to keep the minidumps grouped by application and version. It is up to the developer how much or little information is used to differentiate minidump file names.

It should be noted that the path name in the preceding example was generated by calling the GetTempPath function to retrieve the path of the directory designated for temporary files. Use of this directory works even with least-privileged user accounts, and it also prevents the minidump from taking up hard drive space after it is no longer needed.

If you archive the product during your daily build process, also be sure to include symbols for the build so that if you need to debug an old version of the product, you can. You also need to take steps to maintain full compiler optimizations while generating symbols. This can be done by opening your project's properties in the development environment and, for the release configuration, doing the following:

  1. On the left side of the project's property page, click C/C++. By default, this displays General settings. On the right side of the project's property page, set Debug Information Format to Program Database (/Zi).
  2. On the left side of the property page, expand Linker, and then click Debugging. On the right side of the property page, set Generate Debug Info to Yes (/DEBUG).
  3. Click Optimization, and set References to Eliminate Unreferenced Data (/OPT:REF).
  4. Set Enable COMDAT Folding to Remove Redundant COMDATs (/OPT:ICF).

MSDN has more detailed information on the MINIDUMP_EXCEPTION_INFORMATION structure and the MiniDumpWriteDump function.

Using Dumpchk.exe

Dumpchk.exe is a command-line utility that can be used to verify that a dump file was created correctly. If Dumpchk.exe generates an error, then the dump file is corrupt and cannot be analyzed. For information on using Dumpchk.exe, see How to Use Dumpchk.exe to Check a Memory Dump File.

Dumpchk.exe is included on the Windows XP product CD and can be installed to System Drive\Program Files\Support Tools\ by running Setup.exe in the Support\Tools\ folder on the Windows XP product CD.

Analyzing a Minidump

Opening a minidump for analysis is as easy as creating one.

To analyze a minidump

  1. Open Visual Studio.
  2. On the File menu, click Open Project.
  3. Set Files of type to Dump Files, navigate to the dump file, select it, and click Open.
  4. Run the debugger.

The debugger will create a simulated process. The simulated process will be halted at the instruction that caused the crash.

Using the Microsoft Public Symbol Server

To get the stack for driver- or system-level crashes, it might be necessary to configure Visual Studio to point to the Microsoft public symbol server.

To set a path to the Microsoft symbol server

  1. On the Debug menu, click Options.
  2. In the Options dialog box, open the Debugging node, and click Symbols.
  3. Make sure Search the above locations only when symbols are loaded manually is not selected, unless you want to load symbols manually when you debug.
  4. If you are using symbols on a remote symbol server, you can improve performance by specifying a local directory that symbols can be copied to. To do this, enter a path for Cache symbols from symbol server to this directory. To connect to the Microsoft public symbol server, you need to enable this setting. Note that if you are debugging a program on a remote computer, the cache directory refers to a directory on the remote computer.
  5. Click OK.
  6. Because you are using the Microsoft public symbol server, an End User License Agreement dialog box appears. Click Yes to accept the agreement and download symbols to your local cache.

Debugging a Minidump with WinDbg

You can also use WinDbg, a debugger that is part of the Windows Debugging Tools, to debug a minidump. WinDbg allows you to debug without having to use Visual Studio. To download Windows Debugging Tools, see Windows Debugging Tools on Windows Hardware Developer Central.

After installing Windows Debugging Tools, you must enter the symbol path in WinDbg.

To enter a symbol path in WinDbg

  1. On the File menu, click Symbol Path.

  2. In the Symbol Search Path window, enter the following:

    "srv*c:\cache*http://msdl.microsoft.com/download/symbols;"

Using Copy-Protection Tools with Minidumps

Developers also need to be aware of how their copy-protection scheme might affect the minidump. Most copy-protection schemes have their own descramble tools, and it is up to the developer to learn how to use those tools with MiniDumpWriteDump.

Summary

The MiniDumpWriteDump function can be an extremely useful tool in collecting and solving bugs after the product has been released. Writing a custom exception handler that uses MiniDumpWriteDump allows the developer to customize the information collection and improve the debugging process. The function is flexible enough to be used in any C++-based project and should be considered part of any project's stability process.


DirectX Frequently Asked Questions

Microsoft Corporation

April 2007

This is a collection of Frequently Asked Questions (FAQ) about Microsoft DirectX.

Contents:

  • General DirectX Development Issues
  • Direct3D Questions
  • DirectSound Questions
  • DirectX Extensions for Alias Maya
  • XInput Questions

General DirectX Development Issues

  • Should game developers really care about supporting x64 editions?
  • Should game developers still be publishing games for Windows 95, Windows 98 or Windows ME?
  • Should game developers still be publishing games for Windows 2000?
  • What are the differences between the various editions of Windows Vista? How do they impact my DirectX application?
  • Will DirectX 10 be available for Windows XP?
  • What Happened to DirectShow? I can't find it in the DirectX SDK.
  • What changes were made to the DirectX runtime for Windows Vista?
  • I think I have found a driver bug, what do I do?
  • Why do I get so many error messages when I try to compile the samples?
  • I get linker errors about multiple or missing symbols for globally unique identifiers (GUIDs), what do I do?
  • Can I cast a pointer to a DirectX interface to a lower version number?
  • Can I mix the use of DirectX 9 components and DirectX 8 or earlier components within the same application?
  • Can I mix the use of Direct3D 9 and Direct3D 10 within the same application?
  • What do the return values from the Release or AddRef methods mean?
  • Does it matter in which order I release DirectX interfaces?
  • What is a smart pointer and should I use it?
  • I have trouble debugging my DirectX application, any tips?
  • What's the correct way to check return codes?
  • How do I disable ALT+TAB and other task switching?
  • Is there a recommended book explaining COM?
  • What is managed code?
  • What books are there about general Windows programming?
  • How do I debug using the Windows symbol files?

Should game developers really care about supporting x64 editions?

Absolutely. x64 technology is widely available in the market. The majority of new CPUs sold in the past few years, and almost all processor lines in development from AMD and Intel, are x64-capable. Windows XP Professional x64 Edition introduced the OS enabling technology for x64 released in April of 2005. Because x64 editions require a new generation of 64-bit native drivers, this first release was limited to OEM distribution.

With Windows Vista, customers are free to choose either 32-bit or 64-bit editions when purchasing Windows-based computers, and licenses for Windows Vista are valid for both 32-bit or 64-bit editions of the OS. In addition, many 64-bit drivers are available in the box, and device manufactures are required to provide both 32-bit and 64-bit native drivers as part the Windows Logo Program.

All of these factors will greatly increase the deployments of 64-bit editions of Windows. As new computers start shipping with more than 2 GB of physical RAM, the incentive to use a 32-bit operating system greatly diminishes in favor of 64-bit editions. Sixty-four-bit technology fully supports 32-bit native code, although 64-bit native implementations are required to take full advantage of the new 64-bit memory space. Every 32-bit application should have 64-bit compatibility as a minimum shipping requirement, and meeting that requirement is a baseline requirement for Windows Vista compatibility. Incompatibilities typically arise from use of 16-bit code designed for the Windows 3.1 operating system or installing drivers that are not provided in both 32-bit and 64-bit native forms.

For more details on 64-bit technology, see 64-bit programming for Game Developers.

Should game developers still be publishing games for Windows 95, Windows 98 or Windows ME?

Not anymore for two reasons: performance and feature set.

If the minimum CPU speed required for your game is 1.2GHz or above (which is more common for high performance titles), then the vast majority of eligible computers will be running Windows XP. By the time computers with CPU speeds above 1.2GHz were being sold, Windows XP was installed as the default operating system by almost all manufacturers. This means that there are many features found in Windows XP that today's game developers should be taking advantage of including:

  • Improved multitasking - which results in a better, smoother experience for video, audio and gaming.
  • More stable video driver model - which allows easier debugging, smoother game play and better performance.
  • Easier configuration for networking - which allows easier access to multi-player games.
  • Support for DMA transfers by default from hard drives - which results in smoother, faster loading applications.
  • Windows error reporting - which results in a more stable OS, drivers and applications.
  • Unicode support - which greatly simplifies localization issues.
  • Better security and stability - which results in better consumer experiences.
  • Better support for modern hardware - most of which no longer uses Windows 98 drivers.
  • Improved memory management - which results in better stability and security.
  • Improved NTFS file system - which is more resistant to failure, and has better performance with security features.

Should game developers still be publishing games for Windows 2000?

Not anymore. In addition to the reasons listed in Should game developers still be publishing games for Windows 95, Windows 98 or Windows ME?, Windows 2000 does not have these features:

  • Windows XP supports advanced processor features such as Hyper-Threading, Multi-Core and x64.
  • Windows XP supports side-by-side components which significantly reduces application versioning conflicts.
  • Windows XP supports no-execute memory protection which helps prevent malicious programs and can aid debugging.
  • Windows XP has improved support for advanced AGP and PCI Express based video cards.
  • Windows XP supports fast user switching, remote desktop and remote assistance which can help lower product support costs.
  • Performance tools like Reference (in the DirectX Developer SDK) no longer support Windows 2000.

In short, Windows 2000 was never designed or marketed as a consumer operating system.

What are the differences between the various editions of Windows Vista? How do they impact my DirectX application?

The Windows Vista family includes five editions:

  • Windows Vista Home Basic
  • Windows Vista Home Premium
  • Windows Vista Business
  • Windows Vista Enterprise
  • Windows Vista Ultimate

Home Basic and Home Premium are consumer-focused versions, with features like Family Safety (formerly known as Parental Controls), and Home Premium includes Media Center. Business and Enterprise are corporate-focused editions, with features like Domain join and Remote Desktop/Terminal Services. The Ultimate edition combines all features of both the consumer and corporate editions into one version. All editions come in both 32-bit (x86) and 64-bit (x64) editions, and users are free to use the same product identifier for both platforms.

The technology underlying the various editions is identical, and they all have the same version of the DirectX runtime and other components. However, the editions do have some minor differences with respect to gaming:

  • Game Explorer exists on all editions, but the Games shortcut on the Start menu is only in Home Basic, Home Premium, and Ultimate. Game Explorer can still be found on all editions (by clicking Start, pointing to All Programs, and then clicking Games), and the IGameExplorer interface functions on all editions.

  • The games that are included with Windows are not available by default on Business and Enterprise, but they can be enabled by the administrator.

  • Family Safety and game ratings do not display or have any influence on the behavior of Business or Enterprise, and they are disabled on Ultimate when a domain is joined.

User Account Control settings have the same defaults on all editions, but they can be overridden by Group Policy settings for the domain on Business, Enterprise, and Ultimate. For example, the policy setting User Account Control: Behavior of the elevation prompt for standard users may well be set to Automatically deny elevation requests in many business settings to enhance security, and many users in those environments will always be running as standard users without the ability to even choose to run as Administrator. Any program (such as an installer) that requires administrative rights, either due to legacy setup detection or to having a manifest that specifies the requested execution level as "requireAdministrator", will always fail to start in such situations. Other policy settings, such as User Account Control: Only elevate executables that are signed and validated, can also prevent your installer from functioning if you do not sign your executable file using Authenticode.

These types of policy changes can be applied to any edition of Windows Vista, but are more likely on computers that are joined to a domain.

Will DirectX 10 be available for Windows XP?

No. Windows Vista, which has DirectX 10, includes an updated DirectX runtime based on the runtime in Windows XP SP2 (DirectX 9.0c) with changes to work with the new Windows Display Driver Model (WDDM) and the new audio driver stack, and with other updates in the operating system. In addition to Direct3D 9, Windows Vista supports two new interfaces when the correct video hardware and drivers are present: Direct3D9Ex and Direct3D10.

Since these new interfaces rely on the WDDM technology, they will never be available on earlier versions of Windows. All the other changes made to DirectX technologies for Windows Vista are also specific to the new version of Windows. The name DirectX 10 is misleading in that many technologies shipping in the DirectX SDK (XACT, XINPUT, D3DX) are not encompassed by this version number. So, referring to the version number of the DirectX runtime as a whole has lost much of its meaning, even for 9.0c. The DirectX Diagnostic Tool (DXdiag.exe) on Windows Vista does report DirectX 10, but this really only refers to Direct3D 10.

What Happened to DirectShow? I can't find it in the DirectX SDK.

DirectShow was removed from the DirectX SDK as of April 2005. You can obtain the headers, libraries, tools, and samples for DirectShow in the Windows® Software Development Kit (formerly known as the Platform SDK). DirectSetup in the DirectX SDK continues to support the redistribution of DirectShow's system components, and the latest components are already installed on the following operating systems: Microsoft Windows XP Service Pack 2, Windows XP Professional x64 Edition, Windows Server 2003 Service Pack 1, and Windows Vista.

What changes were made to the DirectX runtime for Windows Vista?

The primary changes were to support the new Windows Display Driver Model. For details on the new driver model, impacts on Direct3D 9, and on the two new graphics interfaces, Direct3D 9Ex and Direct3D 10, review Graphics APIs in Windows Vista.

DirectSound was updated to expose the capabilities of the new Windows Vista audio driver stack, which supports multi-channel software buffers. The legacy Direct3D Retained Mode API was completely removed from Windows Vista. DirectPlay Voice was also removed, as well as DirectPlay's NAT Helper.

I think I have found a driver bug, what do I do?

First, ensure you have checked the results with the Reference Rasterizer. Then check the results with the latest WHQL certified version of the IHVs driver. You can programmatically check the WHQL status using the GetAdapterIdentifier() method on the IDirect3D9 interface passing the D3DENUM_WHQL_LEVEL flag. With a WHQL certified driver issue, send a description of the bug, the output from dxdiag and a repro case to directx@microsoft.com with a note in the subject line "WHQL Driver Bug".

Why do I get so many error messages when I try to compile the samples?

You probably don't have your include path set correctly. Many compilers, including Microsoft Visual C++, include an earlier version of the SDK, so if your include path searches the standard compiler include directories first, you'll get incorrect versions of the header files. To remedy this issue, make sure the include path and library paths are set to search the Microsoft DirectX include and library paths first. See also the dxreadme.txt file in the SDK. If you install the DirectX SDK and you are using Visual C++, the installer can optionally set up the include paths for you.

I get linker errors about multiple or missing symbols for globally unique identifiers (GUIDs), what do I do?

The various GUIDs you use should be defined once and only once. The definition for the GUID will be inserted if you #define the INITGUID symbol before including the DirectX header files. Therefore, you should make sure that this only occurs for one compilation unit. An alternative to this method is to link with the dxguid.lib library, which contains definitions for all of the DirectX GUIDs. If you use this method (which is recommended), then you should never #define the INITGUID symbol.

Can I cast a pointer to a DirectX interface to a lower version number?

No. DirectX interfaces are COM interfaces. This means that there is no requirement for higher numbered interfaces to be derived from corresponding lower numbered ones. Therefore, the only safe way to obtain a different interface to a DirectX object is to use the QueryInterface method of the interface. This method is part of the standard IUnknown interface, from which all COM interfaces must derive.

Can I mix the use of DirectX 9 components and DirectX 8 or earlier components within the same application?

You can freely mix different components of differing version; for example, you could use DirectInput 8 with Direct3D 9 in the same application. However, you generally cannot mix different versions of the same component within the same application; for example, you cannot mix DirectDraw 7 with Direct3D 9 (since these are effectively the same component as DirectDraw has been subsumed into Direct3D as of DirectX 8). There are exceptions, however, such as the use of Direct3D 9 and Direct3D 10 together in the same application, which is allowed.

Can I mix the use of Direct3D 9 and Direct3D 10 within the same application?

Yes, you may use these versions of Direct3D together in the same application.

What do the return values from the Release or AddRef methods mean?

The return value will be the current reference count of the object. However, the COM specification states that you should not rely on this and the value is generally only available for debugging purposes. The values you observe may be unexpected since various other system objects may be holding references to the DirectX objects you create. For this reason, you should not write code that repeatedly calls Release until the reference count is zero, as the object may then be freed even though another component may still be referencing it.

Does it matter in which order I release DirectX interfaces?

It shouldn't matter because COM interfaces are reference counted. However, there are some known bugs with the release order of interfaces in some versions of DirectX. For safety, you are advised to release interfaces in reverse creation order when possible.

What is a smart pointer and should I use it?

A smart pointer is a C++ template class designed to encapsulate pointer functionality. In particular, there are standard smart pointer classes designed to encapsulate COM interface pointers. These pointers automatically perform QueryInterface instead of a cast and they handle AddRef and Release for you. Whether you should use them is largely a matter of taste. If your code contains lots of copying of interface pointers, with multiple AddRefs and Releases, then smart pointers can probably make your code neater and less error prone. Otherwise, you can do without them. Visual C++ includes a standard Microsoft COM smart pointer, defined in the "comdef.h" header file (look up com_ptr_t in the help).

I have trouble debugging my DirectX application, any tips?

The most common problem with debugging DirectX applications is attempting to debug while a DirectDraw surface is locked. This situation can cause a "Win16 Lock" on Microsoft Windows 9x systems, which prevents the debugger window from painting. Specifying the D3DLOCK_NOSYSLOCK flag when locking the surface can usually eliminate this. Windows 2000 does not suffer from this problem. When developing an application, it is useful to be running with the debugging version of the DirectX runtime (selected when you install the SDK), which performs some parameter validation and outputs useful messages to the debugger output.

What's the correct way to check return codes?

Use the SUCCEEDED and FAILED macros. DirectX methods can return multiple success and failure codes, so a simple:

== D3D_OK

or similar test will not always suffice.

How do I disable ALT+TAB and other task switching?

You don't! Games need to be able to handle task switching gracefully, as they many things cause it to happen: ALT+TAB, remote desktop connections, Fast User Switching, Parental Controls usage limits, and many other events.

At the same time, two common sources of accidental task switching on games with keyboard-centric control schemes are pressing the Windows logo key and activating the accessibility feature StickyKeys with the SHIFT key. To address these cases by disabling the functionality, see the techniques described in Disabling Shortcut Keys in Games.

Is there a recommended book explaining COM?

Inside COM by Dale Rogerson, published by Microsoft Press, is an excellent introduction to COM. For a more detailed look at COM, the book Essential COM by Don Box, published by Longman, is also highly recommended.

What is managed code?

Managed code is code that has its execution managed by the .NET Framework Common Language Runtime (CLR). It refers to a contract of cooperation between natively executing code and the runtime. This contract specifies that at any point of execution, the runtime may stop an executing CPU and retrieve information specific to the current CPU instruction address. Information that must be query-able generally pertains to runtime state, such as register or stack memory contents.

Before the code is run, the IL is compiled into native executable code. And, since this compilation happens by the managed execution environment (or, more correctly, by a runtime-aware compiler that knows how to target the managed execution environment), the managed execution environment can make guarantees about what the code is going to do. It can insert traps and appropriate garbage collection hooks, exception handling, type safety, array bounds and index checking, and so forth. For example, such a compiler makes sure to lay out stack frames and everything just right so that the garbage collector can run in the background on a separate thread, constantly walking the active call stack, finding all the roots, chasing down all the live objects. In addition because the IL has a notion of type safety the execution engine will maintain the guarantee of type safety eliminating a whole class of programming mistakes that often lead to security holes.

In contrast this to the unmanaged world: Unmanaged executable files are basically a binary image, x86 code, loaded into memory. The program counter gets put there and that's the last the OS knows. There are protections in place around memory management and port I/O and so forth, but the system doesn't actually know what the application is doing. Therefore, it can't make any guarantees about what happens when the application runs.

What books are there about general Windows programming?

Lots. However, the two that are highly recommended are:

  • Programming Windows by Charles Petzold (Microsoft Press)
  • Programming Applications for Windows by Jeffrey Richter (Microsoft Press)

How do I debug using the Windows symbol files?

Microsoft publish stripped symbols for all system DLLs (plus a few others). To access them add the following to your symbol path in the project settings inside Visual Studio:

srv*http://msdl.microsoft.com/download/symbols

for caching symbols locally use the following syntax:

srv*c:\cache*http://msdl.microsoft.com/download/symbols

Where c:\cache is a local directory for caching symbol files.

Direct3D Questions

  • General Direct3D Questions
  • Geometry (Vertex) Processing
  • Performance Tuning
  • D3DX Utility Library

General Direct3D Questions

  • Where can I find information about 3D graphics techniques?
  • Does Direct3D emulate functionality not provided by hardware?
  • Is there a software rasterizer included with Direct3D?
  • How can I perform color keying with DirectX graphics?
  • Does the Direct3D geometry code utilize 3DNow! and/or Pentium III SIMD instructions?
  • How do I prevent transparent pixels being written to the z-buffer?
  • What is a stencil buffer?
  • How do I use a stencil buffer to render shadow volumes?
  • What are the texel alignment rules? How do I get a one-to-one mapping?
  • What is the purpose of the D3DCREATE_PUREDEVICE flag?
  • How do I enumerate the display devices in a multi-monitor system?
  • What happened to Fixed Function Bumpmapping in D3D9?

Where can I find information about 3D graphics techniques?

The standard book on the subject is Computer Graphics: Principles and Practice by Foley, Van Dam et al. It is a valuable resource for anyone wanting to understand the mathematical foundations of geometry, rasterization and lighting techniques. The FAQ for the comp.graphics.algorithms Usenet group also contains useful material.

Does Direct3D emulate functionality not provided by hardware?

It depends. Direct3D has a fully featured software vertex-processing pipeline (including support for custom vertex shaders). However, no emulation is provided for pixel level operations; applications must check the appropriate caps bits and use the ValidateDevice API to determine support.

Is there a software rasterizer included with Direct3D?

Not for performance applications. A reference rasterizer is supplied for driver validation but the implementation is designed for accuracy and not performance. Direct3D does support plug-in software rasterizers.

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.

Does the Direct3D geometry code utilize 3DNow! and/or Pentium III SIMD instructions?

Yes. The Direct3D geometry pipeline has several different code paths, depending on the processor type, and it will utilize the special floating-point operations provided by the 3DNow! or Pentium III SIMD instructions where these are available. This includes processing of custom vertex shaders.

How do I prevent transparent pixels being written to the z-buffer?

You can filter out pixels with an alpha value above or below a given threshold. You control this behavior by using the renderstates ALPHATESTENABLE, ALPHAREF and ALPHAFUNC.

What is a stencil buffer?

A stencil buffer is an additional buffer of per-pixel information, much like a z-buffer. In fact, it resides in some of the bits of a z-buffer. Common stencil/z-buffer formats are 15-bit z and 1-bit stencil, or 24-bit z and 8-bit stencil. It is possible to perform simple arithmetic operations on the contents of the stencil buffer on a per-pixel basis as polygons are rendered. For example, the stencil buffer can be incremented or decremented, or the pixel can be rejected if the stencil value fails a simple comparison test. This is useful for effects that involve marking out a region of the frame buffer and then performing rendering only the marked (or unmarked) region. Good examples are volumetric effects like shadow volumes.

How do I use a stencil buffer to render shadow volumes?

The key to this and other volumetric stencil buffer effects, is the interaction between the stencil buffer and the z-buffer. A scene with a shadow volume is rendered in three stages. First, the scene without the shadow is rendered as usual, using the z-buffer. Next, the shadow is marked out in the stencil buffer as follows. The front faces of the shadow volume are drawn using invisible polygons, with z-testing enabled but z-writes disabled and the stencil buffer incremented at every pixel passing the z-test. The back faces of the shadow volume are rendered similarly, but decrementing the stencil value instead.

Now, consider a single pixel. Assuming the camera is not in the shadow volume there are four possibilities for the corresponding point in the scene. If the ray from the camera to the point does not intersect the shadow volume, then no shadow polygons will have been drawn there and the stencil buffer is still zero. Otherwise, if the point lies in front of the shadow volume the shadow polygons will be z-buffered out and the stencil again remains unchanged. If the points lies behind the shadow volume then the same number of front shadow faces as back faces will have been rendered and the stencil will be zero, having been incremented as many times as decremented.

The final possibility is that the point lies inside the shadow volume. In this case the back face of the shadow volume will be z-buffered out, but not the front face, so the stencil buffer will be a non-zero value. The result is portions of the frame buffer lying in shadow have non-zero stencil value. Finally, to actually render the shadow, the whole scene is washed over with an alpha-blended polygon set to only affect pixels with non-zero stencil value. An example of this technique can been seen in the "Shadow Volume" sample that comes with the DirectX SDK.

What are the texel alignment rules? How do I get a one-to-one mapping?

This is explained fully in the Direct3D 9 documentation. However, the executive summary is that you should bias your screen coordinates by -0.5 of a pixel in order to align properly with texels. Most cards now conform properly to the texel alignment rules, however there are some older cards or drivers that do not. To handle these cases, the best advice is to contact the hardware vendor in question and request updated drivers or their suggested workaround. Note that in Direct3D 10, this rule no longer holds.

What is the purpose of the D3DCREATE_PUREDEVICE flag?

Use the D3DCREATE_PUREDEVICE flag during device creation to create a pure device. A pure device does not save the current state (during state changes), which often improves performance; this device also requires hardware vertex processing. A pure device is typically used when development and debugging are completed, and you want to achieve the best performance.

One drawback of a pure device is that it does not support all Get* API calls; this means you can not use a pure device to query the pipeline state. This makes it more difficult to debug while running an application. Below is a list of all the methods that are disabled by a pure device.

  • ID3D10Device9::GetClipPlane
  • ID3D10Device9::GetClipStatus
  • ID3D10Device9::GetLight
  • ID3D10Device9::GetLightEnable
  • ID3D10Device9::GetMaterial
  • ID3D10Device9::GetPixelShaderConstantF
  • ID3D10Device9::GetPixelShaderConstantI
  • ID3D10Device9::GetPixelShaderConstantB
  • ID3D10Device9::GetRenderState
  • ID3D10Device9::GetSamplerState
  • ID3D10Device9::GetTextureStageState
  • ID3D10Device9::GetTransform
  • ID3D10Device9::GetVertexShaderConstantF
  • ID3D10Device9::GetVertexShaderConstantI
  • ID3D10Device9::GetVertexShaderConstantB

A second drawback of a pure device is that it does not filter any redundant state changes. When using a pure device, your application should reduce the number of state changes in the render loop to a minimum; this may include filtering state changes to make sure that states do not get set more than once. This trade-off is application dependent; if you use more than a 1000 Set calls per frame, you should consider taking advantage of the redundancy filtering that is done automatically by a non-pure device.

As with all performance issues, the only way to know whether or not your application will perform better with a pure device is to compare your application's performance with a pure vs. non-pure device. A pure device has the potential to speed up an application by reducing the CPU overhead of the API. But be careful! For some scenarios, a pure device will slow down your application (due to the additional CPU work caused by redundant state changes). If you are not sure which type of device will work best for your application, and you do not filter redundant changes in the application, use a non-pure device.

How do I enumerate the display devices in a multi-monitor system?

Enumeration can be performed through a simple iteration by the application using methods of the IDirect3D9 interface. Call GetAdapterCount to determine the number of display adapters in the system. Call GetAdapterMonitor to determine which physical monitor an adapter is connected to (this method returns an HMONITOR, which you can then use in the Win32 API GetMonitorInfo to determine information about the physical monitor). Determining the characteristics of a particular display adapter or creating a Direct3D device on that adapter is as simple as passing the appropriate adapter number in place of D3DADAPTER_DEFAULT when calling GetDeviceCaps, CreateDevice, or other methods.

What happened to Fixed Function Bumpmapping in D3D9?

As of Direct3D 9 we tightened the validation on cards that could only support > 2 simultaneous textures. Certain older cards only have 3 texture stages available when you use a specific alpha modulate operation. The most common usage that people use the 3 stages for is emboss bumpmapping, and you can still do this with D3D9,

The height field has to be stored in the alpha channel and is used to modulate the lights contribution i.e.:

// Stage 0 is the base texture, with the height map in the alpha channel
m_pd3dDevice->SetTexture(0, m_pEmbossTexture );
m_pd3dDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0 );
m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP,   D3DTOP_SELECTARG1 );
m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
if( m_bShowEmbossMethod )
{
 // Stage 1 passes through the RGB channels (SELECTARG2 = CURRENT), and
 // does a signed add with the inverted alpha channel.
 // The texture coords associated with Stage 1 are the shifted ones, so
 // the result is:
 //    (height - shifted_height) * tex.RGB * diffuse.RGB
   m_pd3dDevice->SetTexture( 1, m_pEmbossTexture );
   m_pd3dDevice->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, 1 );
   m_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_SELECTARG2 );
   m_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
   m_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG2, D3DTA_CURRENT );
   m_pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_ADDSIGNED );
   m_pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE|D3DTA_COMPLEMENT );
   m_pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAARG2, D3DTA_CURRENT );

   // Set up the alpha blender to multiply the alpha channel
   // (monochrome emboss) with the src color (lighted texture)
   m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
   m_pd3dDevice->SetRenderState( D3DRS_SRCBLEND,  D3DBLEND_SRCALPHA );
   m_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ZERO );
}

This sample, along with other older samples, are no longer shipped in the current SDK release, and will not be shipped in future SDK releases.

Geometry (Vertex) Processing

  • Vertex streams confuse me how do they work?
  • What is a vertex shader?
  • Does a vertex shader perform perspective division or clipping?
  • Can I generate geometry with a vertex shader?
  • Can I apply a custom vertex shader to the results of the fixed-function geometry pipeline (or vice-versa)?
  • Can I use a custom vertex shader if my hardware does not support it?
  • How do I determine if the hardware supports my custom vertex shader?
  • How many constant registers are available for vertex shaders?
  • Can I share position data between vertices with different texture coordinates?
  • When I submit an indexed list of primitives, does Direct3D process all of the vertices in the buffer, or just the ones I indexed?
  • What is an index buffer?
  • I notice that 32-bit indices are a supported type; can I use them on all devices?
  • Does S/W vertex processing support 64 bit?

Vertex streams confuse me how do they work?

Direct3D assembles each vertex that is fed into the processing portion of the pipeline from one or more vertex streams. Having only one vertex stream corresponds to the old pre-DirectX 8 model, in which vertices come from a single source. With DirectX 8, different vertex components can come from different sources; for example, one vertex buffer could hold positions and normals, while a second held color values and texture coordinates.

What is a vertex shader?

A vertex shader is a procedure for processing a single vertex. It is defined using a simple assembly-like language that is assembled by the D3DX utility library into a token stream that Direct3D accepts. The vertex shader takes as input a single vertex and a set of constant values; it outputs a vertex position (in clip-space) and optionally a set of colors and texture coordinates, which are used in rasterization. Notice that when you have a custom vertex shader, the vertex components no longer have any semantics applied to them by Direct3D and vertices are simply arbitrary data that is interpreted by the vertex shader you create.

Does a vertex shader perform perspective division or clipping?

No. The vertex shader outputs a homogenous coordinate in clip-space for the transformed vertex position. Perspective division and clipping is performed automatically post-shader.

Can I generate geometry with a vertex shader?

A vertex shader cannot create or destroy vertices; it operates on a single vertex at a time, taking one unprocessed vertex as input and outputting a single processed vertex. It can therefore be used to manipulate existing geometry (applying deformations, or performing skinning operations) but cannot actually generate new geometry per se.

Can I apply a custom vertex shader to the results of the fixed-function geometry pipeline (or vice-versa)?

No. You have to choose one or the other. If you are using a custom vertex shader, then you are responsible for performing the entire vertex transformation.

Can I use a custom vertex shader if my hardware does not support it?

Yes. The Direct3D software vertex-processing engine fully supports custom vertex shaders with a surprisingly high level of performance.

How do I determine if the hardware supports my custom vertex shader?

Devices capable of supporting vertex shaders in hardware are required to fill out the D3DCAPS9::VertexShaderVersion field to indicate the version level of vertex shader they support. Any device claiming to support a particular level of vertex shader must support all legal vertex shaders that meet the specification for that level or below.

How many constant registers are available for vertex shaders?

Devices supporting vs 1.0 vertex shaders are required to support a minimum of 96 constant registers. Devices may support more than this minimum number and can report this through the D3DCAPS9::MaxVertexShaderConst field.

Can I share position data between vertices with different texture coordinates?

The usual example of this situation is a cube in which you want to use a different texture for each face. Unfortunately the answer is no, it's not currently possible to index the vertex components independently. Even with multiple vertex streams, all streams are indexed together.

When I submit an indexed list of primitives, does Direct3D process all of the vertices in the buffer, or just the ones I indexed?

When using the software geometry pipeline, Direct3D first transforms all of the vertices in the range you submitted, rather than transforming them "on demand" as they are indexed. For densely packed data (that is, where most of the vertices are used) this is more efficient, particularly when SIMD instructions are available. If your data is sparsely packed (that is, many vertices are not used) then you may want to consider rearranging your data to avoid too many redundant transformations. When using the hardware geometry acceleration, vertices are typically transformed on demand as they are required.

What is an index buffer?

An index buffer is exactly analogous to a vertex buffer, but instead it contains indices for use in DrawIndexedPrimitive calls. It is highly recommended that you use index buffers rather than raw application-allocated memory when possible, for the same reasons as vertex buffers.

I notice that 32-bit indices are a supported type; can I use them on all devices?

No. You must check the D3DCAPS9::MaxVertexIndex field to determine the maximum index value that is supported by the device. This value must be greater than 2 to the 16th power -1 (0xffff) in order for index buffers of type D3DFMT_INDEX32 to be supported. In addition, note that some devices may support 32-bit indices but support a maximum index value less than 2 to the 32nd power -1 (0xffffffff); in this case the application must respect the limit reported by the device.

Does S/W vertex processing support 64 bit?

There is an optimized s/w vertex pipeline for x64, but it does not exist for IA64.

Performance Tuning

  • How can I improve the performance of my Direct3D application?
  • Which primitive types (strips, fans, lists and so on) should I use?
  • How do you determine the total texture memory a card has, excluding AGP memory?
  • What's a good usage pattern for vertex buffers if I'm generating dynamic data?
  • Why do I have to specify more information in the D3DVERTEXELEMENT9 structure?

How can I improve the performance of my Direct3D application?

The following are key areas to look at when optimizing performance:

Batch size

Direct3D is optimized for large batches of primitives. The more polygons that can be sent in a single call, the better. A good rule of thumb is to aim to average 1000 vertices per primitive call. Below that level you're probably not getting optimal performance, above that and you're into diminishing returns and potential conflicts with concurrency considerations (see below).

State changes

Changing render state can be an expensive operation, particularly when changing texture. For this reason, it is important to minimize as much as possible the number of state changes made per frame. Also, try to minimize changes of vertex or index buffer.

Note As of DirectX 8, the cost of changing vertex buffer is no longer as expensive as it was with previous versions, but it is still good practice to avoid vertex buffer changes where possible.

Concurrency

If you can arrange to perform rendering concurrently with other processing, then you will be taking full advantage of system performance. This goal can conflict with the goal of reducing renderstate changes. You need to strike a balance between batching to reduce state changes and pushing data out to the driver early to help achieve concurrency. Using multiple vertex buffers in round-robin fashion can help with concurrency.

Texture uploads

Uploading textures to the device consumes bandwidth and causes a bandwidth competition with vertex data. Therefore, it is important to not to over commit texture memory, which would force your caching scheme to upload excessive quantities of textures each frame.

Vertex and index buffers

You should always use vertex and index buffers, rather than plain blocks of application allocated memory. At a minimum, the locking semantics for vertex and index buffers can avoid a redundant copy operation. With some drivers, the vertex or index buffer may be placed in more optimal memory (perhaps in video or AGP memory) for access by the hardware.

State macro blocks

These were introduced in DirectX 7.0. They provide a mechanism for recording a series of state changes (including lighting, material and matrix changes) into a macro, which can then be replayed by a single call. This has two advantages:

  • You reduce the call overhead by making one call instead of many.
  • An aware driver can pre-parse and pre-compile the state changes, making it much faster to submit to the graphics hardware.

State changes can still be expensive, but using state macros can help reduce at least some of the cost. Use only a single Direct3D device. If you need to render to multiple targets, use SetRenderTarget. If you are creating a windowed application with multiple 3D windows, use the CreateAdditionalSwapChain API. The runtime is optimized for a single device and there is a considerable speed penalty for using multiple devices.

Which primitive types (strips, fans, lists and so on) should I use?

Many meshes encountered in real data feature vertices that are shared by multiple polygons. To maximize performance it is desirable to reduce the duplication in vertices transformed and sent across the bus to the rendering device. It is clear that using simple triangle lists achieves no vertex sharing, making it the least optimal method. The choice is then between using strips and fans, which imply a specific connectivity relationship between polygons and using indexed lists. Where the data naturally falls into strips and fans, these are the most appropriate choice, since they minimize the data sent to the driver. However, decomposing meshes into strips and fans often results in a large number of separate pieces, implying a large number of DrawPrimitive calls. For this reason, the most efficient method is usually to use a single DrawIndexedPrimitive call with a triangle list. An additional advantage of using an indexed list is that a benefit can be gained even when consecutive triangles only share a single vertex. In summary, if your data naturally falls into large strips or fans, use strips or fans; otherwise use indexed lists.

How do you determine the total texture memory a card has, excluding AGP memory?

IDirect3DDevice9::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 running under a Unified Memory Architecture (UMA) or 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.

What's a good usage pattern for vertex buffers if I'm generating dynamic data?

  1. Create a vertex buffer using the D3DUSAGE_DYNAMIC and D3DUSAGE_WRITEONLY usage flags and the D3DPOOL_DEFAULT pool flag. (Also specify D3DUSAGE_SOFTWAREPROCESSING if you are using software vertex processing.)
  2. I = 0.
  3. Set state (textures, renderstates and so on).
  4. Check if there is space in the buffer, that is, for example, I + M <= N? (Where M is the number of new vertices).
  5. If yes, then Lock the VB with D3DLOCK_NOOVERWRITE. This tells Direct3D and the driver that you will be adding vertices and won't be modifying the ones that you previously batched. Therefore, if a DMA operation was in progress, it isn't interrupted. If no, goto 11.
  6. Fill in the M vertices at I.
  7. Unlock.
  8. Call Draw[Indexed]Primitive. For non-indexed primitives use I as the StartVertex parameter. For indexed primitives, ensure the indices point to the correct portion of the vertex buffer (it may be easiest to use the BaseVertexIndex parameter of the SetIndices call to achieve this).
  9. I += M.
  10. Goto 3.
  11. Ok, so we are out of space, so let us start with a new VB. We don't want to use the same one because there might be a DMA operation in progress. We communicate to this to Direct3D and the driver by locking the same VB with the D3DLOCK_DISCARD flag. What this means is "you can give me a new pointer because I am done with the old one and don't really care about the old contents any more."
  12. I = 0.
  13. Goto 4 (or 6).

Why do I have to specify more information in the D3DVERTEXELEMENT9 structure?

As of Direct3D 9, the vertex stream declaration is no longer just a DWORD array, it is now an array of D3DVERTEXELEMENT9 structures. The runtime makes use of the additional semantic and usage information to bind the contents of vertex streams to vertex shaders input registers/variables. For Direct3D 9, vertex declarations are decoupled from vertex shaders, which makes it easier to use shaders with geometries of different formats as the runtime only binds the data that the shader needs.

The new vertex declarations can be used with either the fixed function pipeline or with shaders. For the fixed function pipeline, there is no need to call SetVertexShader. If however, you want to switch to the fixed function pipeline and have previously used a vertex shader, call SetVertexShader(NULL). When this is done, you will still need to call SetFVF to declare the FVF code.

When using vertex shaders, call SetVertexShader with the vertex shader object. Additionally, call SetFVF to set up a vertex declaration. This uses the information implicit in the FVF. SetVertexDeclaration can be called in place of SetFVF because it supports vertex declarations that cannot be expressed with an FVF.

D3DX Utility Library

  • What file formats are supported by the D3DX image file loader functions?
  • The text rendering functions in D3DX don't seem to work, what am I doing wrong?
  • How can I save the contents of a surface or texture to a file?
  • How can I make use of the High Level Shader Language (HLSL) in my game?
  • What is the purpose of the new shader compiler flag?
  • What is the correct way to get shaders from an Effect?
  • What is the HLSL noise() intrinsic for?
  • How do I detect whether to use pixel shader model 2.0 or 2.a?
  • How do I access the Parameters in my Precompiled Effects Shaders?
  • Is there a way to add user data to an effect or other resource?
  • Why does rendering of an ID3DXMesh object slow down significantly after I define subsets?
  • I've heard a lot about Pre-computed Radiance Transfer (PRT), where can I learn more?
  • How can I render to a texture and make use of Anti Aliasing?

What file formats are supported by the D3DX image file loader functions?

The D3DX image file loader functions support BMP, TGA, JPG, DIB, PPM and DDS files.

The text rendering functions in D3DX don't seem to work, what am I doing wrong?

A common mistake when using the ID3DXFont::DrawText functions is to specify a zero alpha component for the color parameter; resulting in completely transparent (that is, invisible) text. For fully opaque text, ensure that the alpha component of the color parameter is fully saturated (255).

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 Windows GDI: Storing an Image.

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.

How can I make use of the High Level Shader Language (HLSL) in my game?

There are three ways that the High Level Shading Language can be incorporated into your game engine:

  • Compile your shader source into vertex or pixel shading assembly (using the command line utility fxc.exe) and use D3DXAssembleShader() at run time. This way even a DirectX 8 game can even take advantage of the power of the HLSL.
  • Use D3DXCompileShader() to compile your shader source into token stream and constant table form. At run time load the token stream and constant table and call CreateVertexShader() or CreatePixelShader() on the device to create your shaders.
  • The easiest way to get up and running is to take advantage of the D3DX Effects system by calling D3DXCreateEffectFromFile() or D3DXCreateEffectFromResource() with your effect file.

What is the purpose of the new shader compiler flag?

Beginning with the December 2006 DirectX SDK, the new HLSL compiler that was developed for Direct3D 10 has been enabled for Direct3D 9 targets. The new compiler has no support for ps_1_x targets, and is now the default compiler for all Direct3D HLSL shaders. A flag for backwards compatibility can be used to force ps_1_x targets to compile as ps_2_0 targets.

Applications that do wish to use the legacy compiler can continue to do so by supplying a flag at runtime (see compiler flags) or by supplying a switch when using fxc

What is the correct way to get shaders from an Effect?

Use D3DXCreateEffect to create an ID3DXEffect and then use GetPassDesc to retrieve a D3DXPASS_DESC. This structure contains pointers to vertex and pixel shaders.

Do not use ID3DXEffectCompiler::GetPassDesc. Vertex and pixel shader handles returned from this method are NULL.

What is the HLSL noise() intrinsic for?

The noise intrinsic function generates perlin noise as defined by Ken Perlin. The HLSL function can currently only be used to fill textures in texture shaders as current h/w does not support the method natively. Texture shaders are used in conjuction with the D3DXFill*Texture() functions which are useful helper functions to generate procedurally defined textures during load time.

How do I detect whether to use pixel shader model 2.0 or 2.a?

You can use the D3DXGetPixelShaderProfile() and D3DXGetPixelShaderProfile() functions which return a string determining what HLSL profile is best suited to the device being ran.

How do I access the Parameters in my Precompiled Effects Shaders?

Through the ID3DXConstantTable interface which is used to access the constant table. This table contains the variables that are used by high-level language shaders and effects.

Is there a way to add user data to an effect or other resource?

Yes, to set private data you call SetPrivateData (pReal is the D3D texture object, pSpoof is the wrapped texture object).

hr = pReal->SetPrivateData(IID_Spoof, &pSpoof,
            sizeof(IDirect3DResource9*), 0)));

To look up the wrapped pointer:

    IDirect3DResource9* pSpoof;
    DWORD dwSize = sizeof(pSpoof);
    hr = pReal->GetPrivateData(IID_Spoof, (void*) &pSpoof, &dwSize);

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. 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 faces are encoded as 0xffffffff.

I've heard a lot about Pre-computed Radiance Transfer (PRT), where can I learn more?

PRT is a new feature of D3DX added in the Summer 2003 SDK Update. It enables rendering of complex lighting scenarios such as global -llumination, soft shadowing and sub-surface scatter in real time. The SDK contains documentation and samples of how to integrate the technology into your game. The PRT Demo Sample and LocalDeformablePRT Sample samples demonstrate how to use the simulator for per vertex and per pixel lighting scenarios respectively. Further information about this and other topics can also be found at Peter Pike Sloan's Web page.

How can I render to a texture and make use of Anti Aliasing?

Create a multisampled render target using Direct3DDevice9::CreateRenderTarget. After rendering the scene to that render target, StretchRect from it to a render target texture. If you make any changed to the offscreen textre (such as blurring or blooming it), copy it back to the back buffer before you present().

DirectSound Questions

  • Why do I get a burst of static when my application starts up? I notice this problem with other applications too.
  • Why I am experiencing a delay in between changing an effects parameters and hearing the results?
  • Is it possible to have a hardware midi synth play back in 3D?
  • How do I detect if DSound is installed?
  • How do I create multichannel audio with WAVEFORMATEXTENSIBLE?
  • How can I use the DirectSound Voice Manager with property sets like EAX?
  • I am having problems with unreliable behavior when using cursor position notifications. How can I get more accurate information?
  • I am suffering from performance degradation when using GetCurrentPosition(). What can I do to improve performance?
  • My DirectSound application is taking up too much CPU time or is performing slowly. Is there anything I can do to optimize my code?
  • When I stream a buffer it tends to glitch and perform poorly. What's the best way to stream a buffer?
  • I am playing the same sounds over and over very often and very quickly and sometimes they don't play properly, or the Play() call takes a long time. What should I do?
  • How do I encode WAV files into WMA?
  • How do I decode MP3 files with DirectSound?

Why do I get a burst of static when my application starts up? I notice this problem with other applications too.

You probably installed the debug DirectX runtime. The debug version of the runtime fills buffers with static in order to help developers catch bugs with uninitialized buffers. You cannot guarantee the contents of a DirectSound buffer after creation; in particular, you cannot assume that a buffer with be zeroed out.

Why I am experiencing a delay in between changing an effects parameters and hearing the results?

Changes in effect parameters do not always take place immediately on DirectX 8. For efficiency, DirectSound processes 100 milliseconds of sound data in a buffer, starting at the play cursor, before the buffer is played. This preprocessing happens after all of the following calls:

IDirectSoundBuffer8::SetCurrentPosition
IDirectSoundBuffer8::SetFX
IDirectSoundBuffer8::Stop
IDirectSoundBuffer8::Unlock

As of DirectX 9, a new FX processing algorithm that processes effects just-in-time addresses this problem and has reduced the latency. The algorithm has been added to the IDirectSoundBuffer8::Play() call, along with an additional thread that processes effects just ahead of the write cursor. So you can set parameters at any time and they'll work as expected. However, note that on a playing buffer there'll be a small delay (usually 100ms) before you hear the parameter change, because the audio between the play and write cursors (and a bit more padding) has already been processed at that time.

Is it possible to have a hardware midi synth play back in 3D?

Unfortunately not as there are no DirectMusic hardware synths that support 3D positioning. There are also no DirectMusic hardware synths that support AudioPaths (which is how you get 3D). If you use hardware synths you are limited to DirectX 7-era DMusic functionality.

How do I detect if DSound is installed?

If you do not need to use DirectSoundEnumerate() to list the available DSound devices, don't link your application with dsound.lib and instead use it via COMs CoCreateInstance(CLSID_DirectSound...) then initialize the DSound object using Initialize(NULL). If you need to use DirectSoundEnumerate(), you can dynamically load dsound.dll using LoadLibrary("dsound.dll"); and access its methods using GetProcAddress("DirectSoundEnumerateA/W") and GetProcAddress("DirectSoundCreateA/W") and so on.

How do I create multichannel audio with WAVEFORMATEXTENSIBLE?

If you can't find an answer to your question in the DirectSound help files, there is a good article with more information available at Multiple Channel Audio Data and WAVE Files.

How can I use the DirectSound Voice Manager with property sets like EAX?

In DirectSound 9.0 when you duplicate a buffer it is now possible to get the IDirectSoundBuffer8 interface on the duplicate buffer, which will give you access to the AcquireResources method. This will allow you to associate a buffer with the DSBCAPS_LOCDEFER flag with a hardware resource. You can then set your EAX parameters on this buffer before having to call Play().

I am having problems with unreliable behavior when using cursor position notifications. How can I get more accurate information?

There are some subtle bugs in various versions of DirectSound, the core Windows audio stack, and audio drivers which make cursor positions notifications unreliable. Unless you're targeting a known HW/SW configuration on which you know that notifications are well-behaved, avoid cursor position notifications. For position tracking GetCurrentPosition() is a safer technique.

I am suffering from performance degradation when using GetCurrentPosition(). What can I do to improve performance?

Each GetCurrentPosition() call on each buffer causes a system call, and system calls should be minimized as they are a large component of DSound's CPU footprint. On NT (Win2K and XP) the cursors in SW buffers (and HW buffers on some devices) move in 10ms increments, so calling GetCurrentPosition() every 10ms is ideal. Calling it more often than every 5ms will cause some performance degradation.

My DirectSound application is taking up too much CPU time or is performing slowly. Is there anything I can do to optimize my code?

There are several things you can do to improve the performance of your audio code:

  • Don't call GetCurrentPosition too often. Each GetCurrentPosition() call on each buffer causes a system call, and system calls should be minimized as they are a large component of DSound's CPU footprint. On NT (Win2K and XP) the cursors in SW buffers (and HW buffers on some devices) move in 10ms increments, so calling GetCurrentPosition() every 10ms is ideal. Calling it more often than every 5ms will cause some perf degradation.
  • Utilize a separate, lower frame-rate for audio. Nowadays many Windows games can exceed 100 Frames per Second and it is not necessary in most cases to update your 3D audio parameters at the same frame rate. Processing your audio every second or third graphics frame, or every 30ms or so, can reduce the number of audio calls significantly throughout your application without reducing audio quality.
  • Use DS3D_DEFERRED for 3D objects. Most sound cards respond immediately to parameter changes and in a single frame much can change, especially if you change the position or orientation of the listener. This causes the soundcard / CPU to perform many unnecessary calculations, so another quick and universal optimization is to defer some parameter changes and commit them at the end of the frame.

    or at least use SetAllParameters rather than individual Set3DParamX calls on buffers.

    Similarly, you should use at least use SetAllParamenters calls on 3D buffers rather the individual Set3DParamX calls. Just try to minimize system calls whenever possible.

  • Don't make redundant calls; store and sort a list of play calls. Often, in one audio update frame, there are 2 requests to play new sounds. If the requests are processed as they arrive, then the first new sound could be started and then immediately replaced the second requested sound. This results in redundant calculations, an unnecessary play call, and an unnecessary stop call. It is better to store a list of requests for new sounds to be played, so that the list can be sorted, and only those voices that should start playing, are actually ever played.

    Also, you should store local copies of the 3D and EAX parameters for each sound source. If a request is made to set a parameter to a particular value, you can check to see if the value is actually different from the last value set. If it isn't, the call does not need to be made.

    Although the sound card driver will probably detect this scenario and not perform the (same) calculation again, the audio call will have to reach the audio driver (via a ring transition) and this is already a slow operation.

When I stream a buffer it tends to glitch and perform poorly. What's the best way to stream a buffer?

When streaming audio into a buffer there are two basic algorithms: After-Write-Cursor (AWC) and Before-Play-Cursor (BPC). AWC minimizes latency at the cost of glitching, whereas BPC is the opposite. Because there are usually no interactive changes to the streamed sound this sort of latency is rarely a problem for games and similar applications, so BPC is the more appropriate algorithm. In AWC, each time your streaming thread runs you "top up" the data in your looping buffers up to N ms beyond their write cursors (typically N=40 or so, to allow for Windows scheduling jitter). In BPC, you always write as much data to the buffers as possible, filling them right up to their play cursors (or perhaps 32 bytes before to allow for drivers that incorrectly report their play cursor progress).

Use BPC to mimimize glitching, and use buffers 100ms or larger even if your games doesn't glitch on your test hardware, it will glitch on some machine out there.

I am playing the same sounds over and over very often and very quickly and sometimes they don't play properly, or the Play() call takes a long time. What should I do?

Startup latency (which is different from streaming latency mentioned above) can be an issue in the case of some hardware (the Play() call just takes a long time sometimes on certain sound cards). If you really want to reduce this latency, for twitch sounds (gun shots, footsteps, and so on.) a handy trick is to keep some buffers always looping and playing silence. When you need to play a twitch sound, pick a free buffer, see where its write cursor is, and put the sound into the buffer just beyond the write cursor. Some soundcards fail QuerySupport for deferred properties that I know they support. Is there a workaround? You could just QuerySupport for the non-deferred versions of the properties and use deferred settings anyway. The most recent soundcard drivers may also fix this issue.

How do I encode WAV files into WMA?

Refer to the documentation on the Windows Media Encoder at: Windows Media Encoder 9 Series.

How do I decode MP3 files with DirectSound?

DirectSound does not natively support MP3 decoding. You can decode the files in advance yourself (using an ACM codec of a DirectShow filter), or else just use DirectShow itself, which can do the decode for you; you can then copy the resulting PCM audio data into your DirectSound buffers.

DirectX Extensions for Alias Maya

  • Why aren't my NURBS showing up?
  • Why aren't my SUBDs showing up?
  • Why does my animation in the X file look different than the animation in the preview window?
  • I skinned my mesh with RigidSkin but the mesh (or portion) isn't moving. Why?
  • Where has all of my IK gone in the X-file?
  • Why do none of my materials colors show up except DirectXShaders?

Why aren't my NURBS showing up?

NURBS are not supported. You can convert them to polygon meshes.

Why aren't my SUBDs showing up?

SUBDs are not supported. You can convert them to polygon meshes.

Why does my animation in the X file look different than the animation in the preview window?

The preview window is not animating in the strictest sense of the matter. It is not playing animation but instead is synchronizing to the most current state of Maya's scene. When animation is exported the matrices at each transform are decomposed into scale, rotation (quaternion), and translation components (often referred to as SRTs). SRTs are more desirable than matrices because they interpolate well, provide a more compact form of the data, and can be compressed independently. Not all matrices can break down into SRTs. If they cannot decompose, the resulting SRTs will be unknown, so small errors in animation may be detected. The two features in Maya that most often cause problems during decomposition are shears and off-center rotations or scales. If you are encountering this problem, because you are using off-center rotations or scales, consider adding additional transforms increasing your level of hierarchy.

Where D3DX animation supports SRTs, it looks like this:

[S]x[R]x[T]

Maya's matrices are much more complicated and require a significant amount of additional process, which looks like this:

[SpInv]x[S]x[Sh]x[Sp]x[St]x[RpInv]x[Ro]x[R]x[Rp]x[Rt]x[T]

I skinned my mesh with RigidSkin but the mesh (or portion) isn't moving. Why?

Maya's Rigid Skin is not supported at this time. Please use Smooth Skin.

Where has all of my IK gone in the X-file?

X-files do not support IK. Instead, the IK solutions are baked into the frames stored in the X-file.

Why do none of my materials colors show up except DirectXShaders?

The DirectX Extensions for Maya currently only support DirectXShader materials for preview and export. In a future version other materials may be supported.

XInput Questions

  • Can I use DirectInput to read the triggers?
  • How many controllers does XInput support?
  • Does XInput support non-common controllers?
  • Are common controllers available through DirectInput?
  • How do I get force feedback on the common controllers?
  • Why does my default audio device change?
  • How do I control the lights on the controller?
  • How do I access the Xbox 360 button in my applications?
  • Where do I get drivers?
  • How is controller ID determined?
  • How do I get the audio devices for the controller?
  • What should I do when a controller is unplugged?

Can I use DirectInput to read the triggers?

Yes, but they act as the same axis. So you can not read the triggers independently with DirectInput. Using XInput, the triggers return seperate values.

For more information on why DirectInput interprets the triggers as one axis, see Using the Xbox 360 Controller with DirectInput.

How many controllers does XInput support?

XInput supports 4 controllers plugged in at a time.

Does XInput support non-common controllers?

No, it does not.

Are common controllers available through DirectInput?

Yes, you may access common controllers through DirectInput.

How do I get force feedback on the common controllers?

Use the XInputSetState function.

Why does my default audio device change?

When connecting the headset, the controller's headset acts as a standard USB audio device, so when it is connected, Windows automatically changes to use this USB audio device as the default. Since the user likely does not want all audio to go through the headset, they will need to manually adjust it back to the original setting.

How do I control the lights on the controller?

The lights on the controller are predetermined by the operating system and can't be changed.

How do I access the Xbox 360 button in my applications?

Sorry, this button is reserved for future use.

Where do I get drivers?

The drivers will be available via Windows Update, or through windowsgaming.com.

How is controller ID determined?

At XInput startup, the ID is determined non-deterministically by the XInput engine and the controllers that are plugged in. If controllers are plugged in while an XInput application is running, the system will assign the new controller the lowest available number. If a controller is disconnected, its number will be made available again.

How do I get the audio devices for the controller?

Use the XInputGetDSoundAudioDeviceGuids function. See the AudioController sample for details.

What should I do when a controller is unplugged?

If the controller was in use by a player, you should pause the game until the controller is reconnected and the player presses a button to signal that they are ready to unpause.


DirectX Installation for Game Developers

Jason Sandlin, Software Development Lead

Chuck Walbourn, Software Design Engineer

XNA Developer Connection (XDC)

December 2006

This article is intended to address some of the common questions about the DirectX runtime and using DirectSetup to install DirectX.

DirectX Runtime

The DirectX runtime consists of core components and optional components.

The core components, such as Direct3D, DirectSound, and DirectInput, are considered part of the operating system. The core components for DirectX 9.0c have not changed since the DirectX SDK Summer 2004 Update and match what was released with Microsoft Windows XP SP2, Windows XP Pro x64 Edition, and Windows Server 2003 SP1. The next update after DirectX 9.0c is DirectX 10 which is only included in Windows Vista. There were no changes any core DirectX component in DirectX 10 except to Direct3D, the new version of which adds support for Windows Vista driver models (WDDM) and features for new and upcoming graphics hardware.

The optional components are released in the bimonthly updates of DirectX SDK and include components such as D3DX, XACT, XINPUT, and Managed DirectX. Many of the optional DirectX components are regularly updated to integrate customer feedback and expose new features.

DirectX Version Number

The DirectX version number, such as 9.0c, refers only to the version of the core components, such as Direct3D, DirectInput, or DirectSound. This number does not cover the versions of the various optional components that are released in the DirectX SDK, such as D3DX, XACT, XINPUT, etc.

Generally speaking, the DirectX version number is not meaningful except as a quick reference to the core runtime bits. This number should not be used to check if the correct DirectX runtime is already installed, because it doesn’t take into account the optional DirectX components.

DirectX Libraries

In the past, the optional components of the DirectX SDK, including D3DX, were released as static libraries. However, these are now released as dynamic-like libraries (DLLs) because of the increased demand for better security practices. DLLs allow servicing of previously released code. If these components were deployed as static libraries, there would be no way for Microsoft to address security issues found after release.

As features are added or changed to the optional components, the names of the corresponding DLLs are also changed to ensure that no regressions are caused to existing games that are using released components. The DLLs for each component live side by side, and game developers can choose exactly which DLL version that the game uses by linking to the corresponding import library.

While ensuring that DLLs are installed on a system isn’t as easy as simply linking to static libraries, some changes have been made to the DirectX SDK to address the pain of the DLL model:

  • The DirectX redistributable can be configured to contain only those components that your application requires to minimize distribution and media sizes.

  • The redistributable folder, Program Files\DirectX SDK\Redist\, now contains a cabinet (.cab) file for every possible optional component, so you don't have to dig up an older SDK to find them.

  • Installing the SDK itself installs every possible optional component.

  • A DirectX redistributable that contains all the optional components is available as both a web-based installer and as a downloadable package; see the DirectX Developer Center (http://msdn.microsoft.com/directx/) for more information.

Installation of DirectX by the Game’s Installer

The following are the best practices for adding installation of DirectX to a game's installer:

Install the redistributable components every time.

A game’s installation process should install the DirectX redistributable components during every single installation without allowing users to opt-out of it. If you allow opting-out, then some users will guess that they don’t need it, and if they actually do, the game will not run.

Let the DirectX installer check for optional components.

Do not assume that the latest optional components are already installed on a system, b ecause Windows Update and Service Packs do not provide any of DirectX’s optional components. You must install the DirectX runtime either by running dxsetup.exe directly or calling DirectSetup.

Set up silently.

Launch setup in silent mode so that users do not accidentally skip updating the DirectX runtime. You can do this by launching dxsetup.exe with the following command:

path-to-redistributable\dxsetup.exe/silent

or by calling DirectSetup and not displaying any UI.

Combine EULA acceptances.

If you prompt the user to accept a EULA, then combine that with prompting for acceptance of the DirectX EULA when installing in silent mode so that prompting for acceptance of EULAs happens just once. Prompting should happen before you install anything so that if user doesn’t accept, you don't end up with a failed and partial installation.

Just run dxsetup or call DirectSetup.

Because the DirectX version number doesn’t refer to anything except the core DirectX components, do not check an installed version before running dxsetup.exe or calling DirectSetup. Also, do not check for a file’s existence to test if an optional component is already installed, since this usually will not correctly determine when a component exists but needs updating; however, the DirectX setup package will quickly determine this and perform the right action.

For more information about using DirectSetup, see Installing DirectX with DirectSetup.

Small Installation Packages

You can create smaller installation packages for DirectX by stripping the contents of the DirectX redistributable folder down to the minimal set of files required to make the installer work and retaining any additional components that your game uses.

Depending on your minimum specifications, you might not even need to include the core DirectX 9.0c cabinet files in the redistributable folder of your installation media. A large majority of Windows XP installations have Service Pack 2, which includes the core DirectX 9.0c components, so the DirectX setup operation will be very fast and will not require a reboot. The smallest package that can be created is about 3 MB, and it can be compressed to about half that size. A package like this contains one version of the D3DX DLL, and it requires that DirectX 9.0c be already present.

The minimal set of files that are required to build a redistributable package are the following files, located in the DirectX SDK Redist folder (Program Files\DirectX SDK\Redist\):

  • dxsetup.exe

  • dsetup32.dll

  • dsetup.dll

  • dxupdate.cab

  • dxdllreg_x86.cab

Add to these the cabinet files for the components that you want to install. If you require the users of your application to already have DirectX 9.0c, then you do not need to include DirectX.cab or dxnt.cab, which make up most of the space requirement. DirectX.cab is only needed for Windows 98 and Windows ME, and dxnt.cab is only needed for Windows 2000, Windows XP, and Windows XP SP1. Also, if you do not make use of DirectShow, or you assume that it is already installed, you can omit BDA.cab, BDANT.cab, and BDAXP.cab.

Note You can assume that users of your application already have DirectX 9.0c if it was installed by a previous version of your application, you force users to manually update via the Web Installer, or you assume that they have Windows XP SP2 or later.

Continuing with this example, if you are using only the 32-bit version of D3DX for April 2006, you can add Apr2006_d3dx9_30_x86.cab. If you are using the 32-bit August 2006 32-bit version of XINPUT, you add Aug2006_xinput_x86.cab.

If you have a native 64-bit application, you'll need to add the _x64 versions. However, if you have a 32-bit application running on a 64-bit OS, the 32-bit versions of the DLLs will work.

You can then distribute this package of files and launch DirectSetup in silent mode or run dxsetup.exe in the command shell in silent mode. Remember not to guard this package by any version checking of files, and make sure that your users cannot opt out of running the DirectX setup, because either of these events creates a fallible installation process.

DirectX Web Installer

The DirectX Web Installer is a downloaded executable file that checks the user’s computer for DirectX components, both optional and core. It downloads and installs components as needed after examining the currently installed components. It is available by clicking Download on the following web page: http://www.microsoft.com/directx/. Do not redistribute the DirectX Web Installer, simply point users to the Microsoft website.

The DirectX Web Installer is updated on a regular basis, and is intended mostly for use by those who play small downloadable games, for which even a few additional megabytes to download is considered too much.

Alternatively, you can point users to the latest DirectX End-User Runtime which includes all components, but it is a large package. This is mostly useful for scenarios in which having the SDK is not necessary, such as setting up an artist’s computer or download-only games for which users are accustomed to fetching additional components.

Internal Deployment of the Debug DirectX Runtime

The debug runtimes of the DirectX components are installed when the DirectX SDK is installed, but installing the SDK on every test computer can be painful, so design your setup process to copy the debug runtime DLLs from Program Files\Microsoft DirectX SDK\Developer Runtime\architecture\ to Windows\system32\ or to the game’s folder.

However, we strongly recommend that you do not simply copy the released runtime DLLs, because it is easy to forget to remove them for the final product. Instead, put the DirectX setup files in a shared folder and run the setup silently from the shared folder.

Driver for the Xbox 360 Controller for Windows

The user is expected to obtain the XInput driver for Xbox 360 controller from Windows Update or from the controller packaging. The XInput driver is included with Windows Vista.


Disabling Shortcut Keys in Games

By Jason Sandlin, Software Development Lead

XNA Developer Connection (XDC)

December 2004

This document describes how to temporarily disable keyboard shortcuts in Microsoft® Windows® to prevent disruption of game play for full screen games. The SHIFT key and the CTRL key are often used as fire or run buttons in games. Accidentally pressing the Windows key (located near these keys) can cause the user to suddenly jump out of the application, ruining the game experience. Simply using the SHIFT key as a game button can inadvertently execute the StickyKeys shortcut which may display a warning dialog. To avoid these issues, you should disable these keys when running in full-screen mode, and either enable the keys back to their default handlers when running in windowed mode or exit the application.

This article describes how to do the following:

  • Disable the Windows Key with a Keyboard Hook
  • Disable the Accessibility Shortcut Keys

Disable the Windows Key with a Keyboard Hook

Use a low-level keyboard hook to filter out the Windows key from being processed. The low-level keyboard hook shown in Example 1 remains in effect even if a user minimizes the window or switches to another application. This means that you must be careful to ensure that the Windows key is not disabled when the application is deactivated. The code in Example 1 does this by handling the WM_ACTIVATEAPP message.

Note This method works on Windows 2000 and later versions of Windows. This method also works with least-privileged user accounts (also known as limited-user accounts).

This method is used by DXUT and is illustrated in the following code example.

Example 1. Using a low-level keyboard hook to disable the Windows key

HHOOK g_hKeyboardHook;
BOOL g_bFullscreen;

INT WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
    // Initialization
    g_hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL,  LowLevelKeyboardProc, GetModuleHandle(NULL), 0 );

    //
    // main application code here
    //

    // Cleanup before shutdown
    UnhookWindowsHookEx( g_hKeyboardHook );
}

LRESULT CALLBACK LowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lParam )
{
    if (nCode < 0 || nCode != HC_ACTION )  // do not process message
        return CallNextHookEx( g_hKeyboardHook, nCode, wParam, lParam);

    bool bEatKeystroke = false;
    KBDLLHOOKSTRUCT* p = (KBDLLHOOKSTRUCT*)lParam;
    switch (wParam)
    {
        case WM_KEYDOWN:
        case WM_KEYUP:
        {
            bEatKeystroke = (g_bFullscreen && g_bWindowActive && ((p->vkCode == VK_LWIN) || (p->vkCode == VK_RWIN)));
            break;
        }
    }

    if( bEatKeystroke )
        return 1;
    else
        return CallNextHookEx( g_hKeyboardHook, nCode, wParam, lParam );
}

LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
    switch( uMsg )
    {
       case WM_ACTIVATEAPP:
            // g_bWindowActive is used to control if the Windows key is filtered by the keyboard hook or not.
            if( wParam == TRUE )
                g_bWindowActive  = true;
            else
                g_bWindowActive  = false;
            break;
    }
}

Disable the Accessibility Shortcut Keys

Windows includes accessibility features such as StickyKeys, FilterKeys, and ToggleKeys (see Windows Accessability). Each of these serves a different purpose; StickyKeys for example, is designed for people who have difficulty holding down two or more keys simultaneously. Each of these accessibility features also has a keyboard shortcut that allows the feature to be turned on or off. For example, the StickyKeys shortcut is triggered by pressing the SHIFT key five times. If the SHIFT key is also used in the game, the user could accidentally trigger this shortcut during game play. When the shortcut is triggered, Windows (by default) presents a warning in a dialog box, which would cause Windows to minimize a game running in full-screen mode. This, of course, can have a drastic effect on game play.

The accessibility features are required for some customers and do not themselves interfere with full-screen games; therefore, you should not change the accessibility settings. However, because the shortcuts for accessibility features can disrupt game play if triggered accidentally, you should turn off an accessibility shortcut only when that feature is not enabled by calling SystemParametersInfo.

An accessibility shortcut that is turned off by SystemParametersInfo remains turned off even after the application has exited. This means that you must restore the settings before exiting the application. Because it is possible for the application to fail to exit correctly, you should write these settings to persistent storage so that they can be restored when the application is run again. You could also use an exception handler to restore these settings if a crash occurs.

To turn off these shortcuts, you need to:

  1. Capture the current accessibility settings before disabling them.
  2. Disable the accessibility shortcut when the application goes into full-screen mode if the accessibility feature is off.
  3. Restore the accessibility settings when the application goes into windowed mode or exits.

This method is used in DXUT, and is illustrated in the following code example.

Note This method works when running on a limited user account.

Example 2. Disabling accessibility shortcut keys

STICKYKEYS g_StartupStickyKeys = {sizeof(STICKYKEYS), 0};
TOGGLEKEYS g_StartupToggleKeys = {sizeof(TOGGLEKEYS), 0};
FILTERKEYS g_StartupFilterKeys = {sizeof(FILTERKEYS), 0};

INT WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
    // Save the current sticky/toggle/filter key settings so they can be restored them later
    SystemParametersInfo(SPI_GETSTICKYKEYS, sizeof(STICKYKEYS), &g_StartupStickyKeys, 0);
    SystemParametersInfo(SPI_GETTOGGLEKEYS, sizeof(TOGGLEKEYS), &g_StartupToggleKeys, 0);
    SystemParametersInfo(SPI_GETFILTERKEYS, sizeof(FILTERKEYS), &g_StartupFilterKeys, 0);

    // Disable when full screen
    AllowAccessibilityShortcutKeys( true );

    // Restore back when going to windowed or shutting down
    AllowAccessibilityShortcutKeys( false );
}

void AllowAccessibilityShortcutKeys( bool bAllowKeys )
{
    if( bAllowKeys )
    {
        // Restore StickyKeys/etc to original state and enable Windows key
        STICKYKEYS sk = g_StartupStickyKeys;
        TOGGLEKEYS tk = g_StartupToggleKeys;
        FILTERKEYS fk = g_StartupFilterKeys;

        SystemParametersInfo(SPI_SETSTICKYKEYS, sizeof(STICKYKEYS), &g_StartupStickyKeys, 0);
        SystemParametersInfo(SPI_SETTOGGLEKEYS, sizeof(TOGGLEKEYS), &g_StartupToggleKeys, 0);
        SystemParametersInfo(SPI_SETFILTERKEYS, sizeof(FILTERKEYS), &g_StartupFilterKeys, 0);
    }
    else
    {
        // Disable StickyKeys/etc shortcuts but if the accessibility feature is on,
        // then leave the settings alone as its probably being usefully used

        STICKYKEYS skOff = g_StartupStickyKeys;
        if( (skOff.dwFlags & SKF_STICKYKEYSON) == 0 )
        {
            // Disable the hotkey and the confirmation
            skOff.dwFlags &= ~SKF_HOTKEYACTIVE;
            skOff.dwFlags &= ~SKF_CONFIRMHOTKEY;

            SystemParametersInfo(SPI_SETSTICKYKEYS, sizeof(STICKYKEYS), &skOff, 0);
        }

        TOGGLEKEYS tkOff = g_StartupToggleKeys;
        if( (tkOff.dwFlags & TKF_TOGGLEKEYSON) == 0 )
        {
            // Disable the hotkey and the confirmation
            tkOff.dwFlags &= ~TKF_HOTKEYACTIVE;
            tkOff.dwFlags &= ~TKF_CONFIRMHOTKEY;

            SystemParametersInfo(SPI_SETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tkOff, 0);
        }

        FILTERKEYS fkOff = g_StartupFilterKeys;
        if( (fkOff.dwFlags & FKF_FILTERKEYSON) == 0 )
        {
            // Disable the hotkey and the confirmation
            fkOff.dwFlags &= ~FKF_HOTKEYACTIVE;
            fkOff.dwFlags &= ~FKF_CONFIRMHOTKEY;

            SystemParametersInfo(SPI_SETFILTERKEYS, sizeof(FILTERKEYS), &fkOff, 0);
        }
    }
}


Game Timing and Multicore Processors

By Chuck Walbourn, Software Design Engineer

XNA Developer Connection (XDC)

December 2005

Introduction

With power management technologies becoming more commonplace in today's computers, a commonly-used method to obtain high-resolution CPU timings, the RDTSC instruction, may no longer work as expected. This article suggests a more accurate, reliable solution using the Windows APIs QueryPerformanceCounter and QueryPerformanceFrequency.

Background

Since the introduction of the x86 P5 instruction set, many game developers have made use of read time stamp counter, the RDTSC instruction, to perform high-resolution timing. The Windows multimedia timers are precise enough for sound and video processing, but with frame times of a dozen milliseconds or less, they don't have enough resolution to provide delta-time information. Many games still use a multimedia timer at start-up to establish the frequency of the CPU, and they use that frequency value to scale results from RDTSC to get accurate time. Due to the limitations of RDTSC, the Windows API exposes the more correct way to access this functionality through the routines of QueryPerformanceCounter and QueryPerformanceFrequency.

This use of RDTSC for timing suffers from three fundamental issues:

  1. Discontinuous values. Using RDTSC directly assumes that the thread is always running on the same processor. Multiprocessor and dual-core systems do not guarantee synchronization of their cycle counters between cores. This is exacerbated when combined with modern power management technologies that idle and restore various cores at different times, which results in the cores typically being out of synchronization. For an application, this generally results in glitches or in potential crashes as the thread jumps between the processors and gets timing values that result in large deltas, negative deltas, or halted timing.

  2. Availability of dedicated hardware. RDTSC locks the timing information that the application requests to the processor's cycle counter. For many years this was the best way to get high-precision timing information, but newer motherboards are now including dedicated timing devices which provide high-resolution timing information without the drawbacks of RDTSC.

  3. Variability of the CPU's frequency. The assumption is often made that the frequency of the CPU is fixed for the life of the program. However, with modern power management technologies, this is an incorrect assumption. While initially limited to laptop computers and other mobile devices, technology that changes the frequency of the CPU is in use in many high-end desktop PCs; disabling its function to maintain a consistent frequency is generally not acceptable to users.

Recommendations

Games need accurate timing information, but developers also need to implement timing code in a way that avoids the problems associated with using RDTSC. The following steps should be taken when implementing high-resolution timing:

  1. Use QueryPerformanceCounter and QueryPerformanceFrequency instead of RDTSC. These APIs may make use of RDTSC, but might instead make use of a timing devices on the motherboard or some other system services that provide high-quality high-resolution timing information. While RDTSC is much faster than QueryPerformanceCounter, since the latter is an API call, it is an API that can be called several hundred times per frame without any noticeable impact. (Nevertheless, developers should attempt to have their games call QueryPerformanceCounter as little as possible to avoid any performance penalty.)

  2. When computing deltas, the values should be clamped to ensure that any bugs in the timing values do not cause crashes or unstable time-related computations. The clamp range should be from 0 (to prevent negative delta values) to some reasonable value based on your lowest expected framerate. Clamping is likely to be useful in any debugging of your application, but be sure to keep it in mind if doing performance analysis or running the game in some unoptimized mode.

  3. Compute all timing on a single thread. Computation of timing on multiple threads — for example, with each thread associated with a specific processor — greatly reduces performance of multi-core systems.

  4. Set that single thread to remain on a single processor by using the Windows API SetThreadAffinityMask. Typically, this is the main game thread. While QueryPerformanceCounter and QueryPerformanceFrequency typically adjust for multiple processors, bugs in the BIOS or drivers may result in these routines returning different values as the thread moves from one processor to another. So, it's best to keep the thread on a single processor.

    All other threads should operate without gathering their own timer data. We do not recommend using a worker thread to compute timing, as this will become a synchronization bottleneck. Instead, worker threads should read timestamps from the main thread, and because the worker threads only read timestamps, there is no need to use critical sections.

  5. Call QueryPerformanceFrequency only once, because the frequency will not change while the system is running.

Application Compatibility

Many developers have made assumptions about the behavior of RDTSC over many years, so it is quite likely that some existing applications will exhibit problems when run on a system with multiple processors or cores due to the timing implementation. These problems will usually manifest as glitching or slow-motion movement. There is no easy remedy for applications that are not aware of power management, but there is an existing shim for forcing an application to always run on a single processor in a multiprocessor system.

To create this shim, download the Microsoft Application Compatibility Toolkit from "Windows XP/SP2 application compatibility resources" on Windows Application Compatibility:

http://www.microsoft.com/windows/appcompatibility/

Using the Compatibility Administrator, part of the toolkit, create a database of your application and associated fixes. Create a new compatibility mode for this database and select the compatibility fix SingleProcAffinity to force all of the threads of the application to run on a single processor/core. By using the command-line tool Fixpack.exe (also part of the toolkit), you can convert this database into an installable package for installation, testing, and distribution.

For instruction on using Compatibility Administrator, see the toolkit's documentation. For syntax for and examples of using Fixpack.exe, see its command-line help.


Games for Windows: Technical Requirements

Microsoft Corporation

Version 1.1.0006

October 2006

The information presented in these guidelines reflects Microsoft Corporation’s views as of the date of publication. These views can and probably will change in response to changing market conditions. Microsoft makes no warranties or guarantees, implicit or explicit, in or by virtue of this document. Unless otherwise permitted by law, no part of this document may be copied without Microsoft’s prior written permission.

This document has the following categories:

  • Games for Windows
  • Security and Compatibility
  • Installation
  • Reliability
  • Resources

Games for Windows

Summary of Games Requirements

Customer Benefits

Computer games are a key entertainment experience on Windows, but ease-of-use concerns have caused customer frustration over the years. Traditionally games are installed like applications, but are utilized more like entertainment media (movies, songs, etc.) as demonstrated by the gaming experience on consoles. These requirements help ensure the Windows platform provides a more accessible and unified gaming experience.

This section describes the following requirements:

  • 1.1 Games Explorer Integration
  • 1.2 Support Parental Controls
  • 1.3 Support Rich Saved Games
  • 1.4 Support the Xbox 360 Common Controller for Windows
  • 1.5 Support Multiple Aspect Ratios and Resolutions
  • 1.6 Support Launch from Windows Media Center
  • 1.7 Direct3D Support

1.1 Games Explorer Integration

Requirement

The game must be visible within the Games Explorer on Windows Vista.

The game must not create shortcuts on the desktop, in the Start menu, or in any other location to launch the game. Instead, this functionality should be exposed through the Games Explorer through the game’s icon and associated tasks list.

Tasks and shortcuts for uninstall must not be created. Users should be able to remove the game using the Programs control panel (known as Add/Remove Programs on Windows XP and previous versions).

Rationale

The Windows Vista Games Explorer (GE) is similar in concept to the Windows XP folders "My Documents" or "My Pictures." The idea behind all three of these is to centralize similar content in one place and allow for easier organization and context-sensitive activities. The GE extends the My Documents or My Pictures concept by allowing richer organization and control over games. The GE allows gamers to view, organize, modify and interact with all the games installed on their system. It also offers the opportunity to game publishers to communicate important game information more effectively. The system is completely data-driven, so it is very easy for a game publisher to update game information over time. In this way, the Games Explorer enables gamers to keep up to date with game communities, tips & tricks, etc.

Additional Information

This requirement is met by authoring a Game Definition File (GDF), an XML text file that is then embedded within a binary (EXE or DLL) as a resource along with a thumbnail bitmap image. The game must then be registered with the Games Explorer. The GDF also enables the exposure of supplied information such as the game title, publisher, developer, links to websites and optional tasks.

Details on integrating with the Windows Vista Games Explorer are provided in the DirectX SDK. An example GDF is provided in the DirectX SDK as the GDFExampleBinary sample. The GameUxInstallHelper sample provides helper routines for integrating the required functionality into existing installation systems.

Also see the article Windows Game Explorer Integration in the DirectX SDK Documentation for C++.

On Windows XP or previous versions, the game install is free to create shortcuts.

1.2 Support Parental Controls

Requirement

All games must execute within the context of a Standard User in order to allow Windows Vista Parental Controls-enabled accounts to play the game. Installation, patching, and removal may require elevated rights, subject to the requirements in section 3.

Games rated by supported ratings boards such as ESRB must include this rating information in their Game Definition File (GDF).

Games must also call the VerifyAccess() method of the Game Explorer interface during startup on Windows Vista and exit if the check result is false.

Rationale

Parents want the ability to monitor and control their children’s access to games. Moreover, numerous industry, government and advocacy groups desire better ways to allow parents to monitor and control the games to which their children are exposed. In conjunction with the new architecture of the Games Explorer in Windows Vista, Microsoft provides parents this ability through Windows Vista Parental Controls.

The Windows Vista Parental Controls system allows parents to select ratings they believe are appropriate for their children. Parental Controls support many of the various worldwide ratings systems. Parental Controls also allow parents to restrict based on Content Descriptors (if the applicable rating system supports them) and to allow / disallow access to individual games.

Even for games that do not participate in a ratings board program, requiring elevated rights creates a poor play experience for the majority of user accounts, particularly those with Parental Controls enabled, requiring the parent to enter the administrator password every time the game is launched.

Additional Information

For more information about making a game compatible with executing as a Standard User, see the DirectX SDK article User Account Control for Game Developers.

See requirement 1.1 for more details on the Game Definition File (GDF).

1.3 Support Rich Saved Games

Requirement

If the game creates save game files, then the title must support the Rich Saved Games feature of the Windows Vista Games Explorer.

Rationale

Better integration of save game functionality within the Windows gaming experience mimics common features on gaming consoles, simplifying resuming of play by jumping directly to a recent saved game.

Additional Information

This requires using a unique file extension, registering that extension using Windows APIs, supporting command-line launch of the game with the provided save game filename, and registering the save game folder in the Game Definition File (GDF).

Metadata may be added by embedding the Rich Saved Games header including a thumbnail image and several descriptive strings into your save game file format.

See the DirectX SDK documentation on the Windows Vista Games Explorer for details on supporting Rich Saved Games.

1.4 Support the Xbox 360 Common Controller for Windows

Requirement

Games that support gamepad controllers must support the Xbox 360 Controller for Windows using the XInput API. If DirectInput peripherals are also supported, then DirectInput can be used in addition. However, XInput must be the default API selected when an Xbox 360 compatible device is used.

Once a player has begun to use an Xbox 360 Controller for Windows with a title they must not be required to use the mouse/keyboard until after the game has exited to the Windows desktop. The exception to this is if the user removes the controller from the PC, in which case the game must pause or control with mouse/keyboard must become the default.

All menus in the game must be navigable with the controller.

Controller vibration must be turned off when the game is in a paused or suspended state.

The game must gracefully handle the controller being added or removed from the PC during gameplay. When the controller is added mid-game the user must be able to immediately begin playing with the controller.

Games must use the widely accepted standard controller buttons as follows in menus:

A
Accept
B
Cancel
Start
Accept or pause
Back
Cancel, back one screen or up a menu level
Rationale

Many gamers find the use of a gamepad a more natural and intuitive interface.

Additional Information

This requirement does not apply to games that only make use of the mouse and/or keyboard.

See the DirectX SDK Documentation on XInput for details.

The topic XInput and DirectInput discusses issues with using both APIs at the same time.

1.5 Support Multiple Aspect Ratios and Resolutions

Requirement

The game must support at least the following aspect ratios and associated minimum screen resolutions:

  • 4:3 "normal" (800 × 600)

  • 16:9 "widescreen" (1280 × 720)

  • 16:10 "widescreen" (1152 × 720)

The game must prompt the user to confirm new display settings whenever a change is made. If the user does not accept within 15 seconds the display must revert to the previous setting.

Rationale

With the Windows Vista 3D desktop, a particular aspect ratio or resolution can not be assumed due to the support for high DPI environments, increased market share of widescreen monitors, HDTV deployments for Windows Media Center, and accessibility requirements.

Additional Information

Ideally, the game should default to the native aspect ratio of the display. Obtaining this information reliably can be a challenge, so one assumption that can be made is that the desktop is running at the native aspect ratio. Using GetWindowRect() call on the handle returned from GetDesktopWindow() and computing the aspect ratio from the resulting rectangle is the easiest method for obtaining this data.

1.6 Support Launch from Windows Media Center

Requirement

Games must be visible in the Media Center distance viewing interface and be successfully launched from it. The game may optionally provide a ’10-foot’ interface once launched if appropriate.

Games may choose not to launch, after displaying an appropriate message to the user, if the viewing display is unsuitable (e.g., "This display does not support the minimum resolution to play this game.").

Rationale

Microsoft Windows XP Media Center Edition introduces consumers to an exciting new experience that allows the PC to be used from across the room – the Media Center user interface (UI). Because a PC with Windows XP Media Center Edition (MCE PC) can be accessed from the couch, and yet still harness the power of a Windows PC, it makes a very powerful platform for gaming and presents unique opportunities. Most SKUs of Windows Vista include Media Center, and many customers will upgrade to versions that support Media Center over the life of the operating system.

Additional Information

For details on how to support Media Center, see the DirectX SDK article Introduction to the 10-Foot Experience for Windows Game Developers.

1.7 Direct3D Support

Requirement

If the game uses Direct3D, then the minimum version supported must be Direct3D 9, and Direct3D must be the default for any display configuration option.

Rationale

The Windows Vista core graphics architecture is designed around Direct3D, and versions previous to 9 are supported through remapping of legacy interfaces.

Security and Compatibility

Summary of Security and Compatibility Requirements

Customer Benefits

The following requirements improve the overall security of games and help ensure that they work with Windows Vista on different architectures, under different configurations, and in different modes.

Windows Security and Compatibility Requirements

This section describes the following requirements:

  • 2.1 Follow User Account Control Guidelines
  • 2.2 Support x64 Versions
  • 2.3 Sign Files
  • 2.4 Sign Drivers
  • 2.5 Perform Proper Version Checking
  • 2.6 Support Concurrent User Sessions
  • 2.7 Support Long Names

2.1 Follow User Account Control Guidelines

Requirement

Every executable file (.EXE extension) must have an embedded manifest that defines its execution level:

<requestedExecutionLevel level="asInvoker |requireAdministrator" uiAccess="false"/>

If only a small number of features in an application will require administrative privileges (for example, an application that needs to configure a firewall), the main process of the application must still be run as a Standard User. The administrative features must be moved into a separate process that runs with administrative privileges, such as an installer or configuration utility.

Rationale

A user’s Windows experience is more secure when applications run only with the permissions needed.

Additional Information

For more information about User Account Control, see User Account Control for Game Developers.

Per requirement 1.2, the main game executable must have an execution level of "asInvoker" to support Standard User contexts.

See requirement 3.1 for details on the special cases of installation, patching, and uninstallation.

Dynamic Link Libraries (.DLL files) do not require such manifests.

2.2 Support x64 Versions

Requirement

To maintain compatibility with x64 versions of Windows:

  • Titles and title installers must not contain any 16-bit code or rely on any 16-bit component.

  • If the game is dependent on kernel-mode drivers for operation, x64 versions of these drivers must be available. The game setup must detect and install the proper drivers and components for the 64-bit Windows OS.

Rationale

Many Windows Vista users will be running x64 versions of the operating system, so it is crucial for applications to be compatible with this OS.

Additional Information

Windows on Windows 64 (WOW64) will allow 32-bit code to run on 64-bit versions of Windows, so it is not necessary that the application be native 64-bit code on x64 versions of Windows. 16-bit code will not run on 64-bit versions of Windows.

For details see the DirectX SDK article 64-bit Programming for Game Developers.

2.3 Sign Files

Requirement

All executable code files (e.g., .EXE and .DLL extensions) must be signed with an Authenticode certificate.

Rationale

Signing helps users decide if they want to trust an application, and assures users that files have not been tampered with. It also allows applications to run properly in locked-down environments.

Additional Information

For details see the DirectX SDK article Authenticode Signing for Game Developers.

2.4 Sign Drivers

Requirement

Any kernel-mode drivers that are installed by the game must have a Microsoft signature obtained through the Windows Hardware Quality Labs (WHQL) or Driver Reliability Signature (DRS) program.

Rationale

Poorly written or malware drivers can severely affect the stability and security of a system. On 64-bit versions of Windows Vista, unsigned drivers will not load.

Additional Information

More information about driver signing programs can be found at the Windows Hardware Developer portal.

2.5 Perform Proper Version Checking

Requirement

Titles must not fail to run if the OS version number increases, unless the End User License Agreement prohibits use on future operating systems. If the title is supposed to fail, it must do so gracefully by sending a message to the user.

Applications must use the version-checking APIs (GetVersionEx) to check the OS version. They must not read the registry keys for the OS version.

Explicit version checks for DirectX runtime should not be present in the game. Such version checks should not be present in the installation guarding the launch of Direct Setup.

Rationale

When Windows users upgrade their operating system, they shouldn’t be blocked from playing their current games simply because the OS version has increased.

Version check assumptions for the DirectX runtime have created failed installations. The DirectX version number only applies to the core OS inband components and has changed between Windows Vista and previous releases. Proper use of the DirectX runtime redistribution package (DirectX Setup) involves always launching it during installation (preferably in silent mode). This allows the Microsoft-provided code to perform any required version updates, and installation of any optional side-by-side DirectX SDK components present such as D3DX, XACT, MDX, XINPUT, etc.

2.6 Support Concurrent User Sessions

Requirement

  • Games must allow multiple sessions unless prevented by architecture issues. If a game does not support this scenario, the user must be alerted upon failure. Additionally, games that rely on 3D graphics are not required to work over a Remote Desktop Connection, but the user must be alerted upon failure.

  • If a title does not support running in multiple user logon sessions, it must alert the user of this fact before failing. This includes user sessions created using Remote Desktop Connection.

  • Games must correctly check for multiple sessions. If multiple sessions are unsupported, the game must check both user session and task information. This will avoid the blocking of use in concurrent user sessions.

  • Sound from a title in one user session must not be heard when another user is active in the current session.

  • Games must support Fast User Switching if they support multiple sessions.

Rationale

Windows users should be able to run concurrent sessions without conflict or disruption. This is a common scenario for a Windows PC shared by a family, roommates, etc.

Additional Information

Titles should not depend on globally named OS/kernel objects (such as a named mutex, shared pipe, etc.). Because globally named objects can be created by any application or service, a game dependent on creating or maintaining such an object could fail. Additionally, a Standard User context application cannot create a globally named object.

To test if the game is being launched in a remote session, call GetSystemMetrics( SM_REMOTESESSION ) and a non-zero value indicates the session is remote.

For more information, see Fast User Switching.

2.7 Support Long Names

Requirement

If a game supports saving files, it must be able to save files with long names and paths.

Games must work properly when a user has a long user name.

Rationale

Players are accustomed to using long names on deep paths which are supported by the underlying operating system.

Additional Information

Long names are defined as those with up to the maximum defined values in the Windows / Platform SDK.

Installation

Summary of Installation Requirements

Customer Benefits

Customers can be confident that applications will install on Windows without degrading the operating system or other applications.

Installation Requirements

This section describes the following requirements:

  • 3.1 Support Easy Install
  • 3.2 Support User Account Control for Installation
  • 3.3 Install to Correct Folders
  • 3.4 Install Windows Resources Properly
  • 3.5 Avoid Reboots During Installation
  • 3.6 Use File Versioning Correctly
  • 3.7 Support Autorun

3.1 Support Easy Install

Requirement

Games with a traditional installation must provide a simplified path in their setup user interface:

  • Display a maximum of one EULA

  • Provide default and custom installation options. The default option must bypass all selections for the install (such as installation folder, component selections, etc.), assume the default selections and then run the game or launcher upon successful install without addition prompts.

  • Install any required OS components (such as the DirectX and Visual C runtimes) silently without prompting or guarded by component version checks using the correct Microsoft redistribution package(s).

  • Provide removal only via the Programs control panel for both the game application as well as user-generated game files. This must ensure all installed files are removed and all settings (firewall, registry, etc.) are cleared. Redistributed OS components must not be removed.

Installation and uninstall can require administrator rights. Patching may or may not require prompting for administrator rights depending on frequency of update. Normal play of the game must not require administrator rights per requirement 2.1.

Rationale

Easy Install is a Windows-centric game development philosophy designed to simplify and streamline the sometimes tedious and confusing process of installing games on Windows. This is enabled by utilizing a set of technologies and best practices which greatly reduce the unnecessary complexity and perceived risk of installing games on Windows.

The key goals are to:

  1. Reduce the amount of time it takes to get into the game and begin play.

  2. Reduce the number of dialog boxes and choices to very few, or none, in order to simplify the game install experience.

Some traditional installations also have paths that allow invalid installations despite appearing to be successfully installed. For example, prompting for the game’s EULA, installing the game, and then prompting for the DirectX EULA which allows users to decline and thus skip the DirectX runtime install can often result in the game failing to run due to missing components.

Additional Information

See the DirectX SDK articles Simplifying Game Installation, Install-on-Demand for Games, and Patching Methods in Windows XP and Vista.

3.2 Support User Account Control for Installation

Requirement

The game installer must not assume it is running in the same context as the user. Per-user locations will be different from the installer and the player even for single-user systems due to administrator elevation. Games must therefore perform per-user tasks on first-run separately from the install.

The game installation program must provide an embedded manifest designating the desired execution level per requirement 2.1.

If the game is launched by the installer after installation is complete, the application must be launched in the context of the original user.

Rationale

One of the largest changes to the Windows operating system for the Vista release is the addition of User Account Control, which by default will run applications with reduced privileges. Installers need to manage their privilege levels accordingly.

3.3 Install to Correct Folders

Requirement

Games must be installed to the Program Files folder by default. User data must be written at first run and not during the install.

Rationale

Users should have the flexibility to install applications where they need them and should have a consistent and secure experience with the default location of files.

Additional Information

This requirement does not apply to fully per-user (side-by-side) installations.

Games may make use of the various known folder locations (CSIDL_LOCAL_APPDATA, CSIDL_COMMON_APPDATA) to store significant amounts of game data and supporting executables to implement advanced install-on-demand and patching scenarios.

Because the install potentially elevates to a different user account during the per-machine install, there is no correct user location to store data at install time. Also, if file encryption is enabled, such files can only be accessed by the user account that created them.

3.4 Install Windows Resources Properly

Requirement

Applications must not attempt to install files or registry keys that are protected by Windows Resource Protection (WRP). If the application requires newer versions of system components, it must update these components by using a Microsoft Service Pack or a Microsoft-approved installation package containing the system component. System components must never be repackaged.

Rationale

Windows Resource Protection (WRP) is designed to ensure that protected system resources are updated only by using Microsoft-approved installation or update mechanisms. WRP improves system reliability by ensuring that the results of an installation are predictable.

Additional Information

WRP is the follow-on to Windows File Protection, which protects the majority of the system components installed to the Windows folder. WRP also protects most COM OS registry keys and certain folders for use exclusively by the OS. Attempts to access protected resources typically result in an ‘access denied’ error.

3.5 Avoid Reboots During Installation

Requirement

The game installer should not assume Microsoft OS component redistribution packages require a reboot unless indicated by a return result and/or Microsoft documentation.

If the game installer always forces a reboot, this must be approved by Microsoft.

Files-in-use dialogs authored into Windows Installer packages must contain an option to "Automatically close applications and attempt to restart them after setup is complete."

Rationale

Rebooting the system after an install is an inconvenient disruption for users and is usually unnecessary.

Additional Information

For more information, visit this link.

3.6 Use File Versioning Correctly

Reqirement

The game installation program must properly check to ensure that the latest file versions are installed. Installing a game must never regress any files that you do not produce or that are shared by applications that you do not produce.

Rationale

Shared and system components are often updated for security fixes and expanded functionality. Installing an application that includes an older version of updated components should not result in the loss of already-applied updates and fixes.

3.7 Support Autorun

Requirement

For games distributed on CD, DVD, or other removable media that support Autorun, the first time the disc is inserted, the application must use Autorun to run or prompt the user to install unless the user has disabled the Autorun feature. In the case of games distributed on multiple discs, subsequent discs must either use the Autorun feature or continue installation without prompting the user to press a key or take other action when the CD has been inserted.

After the application has been successfully installed, re-inserting the disc in the drive must not cause installation to automatically begin again. It is acceptable to ask users if they want to update or change their installation choices.

Rationale

Autorun simplifies the experience of using media-distributed applications such as games that typically require the disc to be present in the drive in order to play.

Additional Information

It is not acceptable to require the user to use Start/Run to launch the installation from the CD or DVD.

The Autorun executable must follow the guidelines of requirement 2.1.

Reliability

Summary of Reliability Requirements

Customer Benefits

These requirements make an application more reliable by minimizing the number of crashes, hangs, and reboots experienced by users. The reliability requirements can help ensure that software is more predictable, maintainable, resilient, and recoverable.

This section describes the following requirements:

  • 4.1 Eliminate Unnecessary Reboots
  • 4.2 Eliminate Application Verifier Failures
  • 4.3 Support Windows Error Reporting

4.1 Eliminate Unnecessary Reboots

Requirement

  • All application installers must take advantage of the Restart Manager APIs to avoid system reboots(see requirement 3.5.

  • All applications must be "restart manager aware" by listening and responding to the following shutdown messages:

    1. WM_QUERYENDSESSION with LPARAM = ENDSESSION_CLOSEAPP(0x1): GUI applications must respond (TRUE) immediately in preparation for a restart.

    2. WM_ENDSESSION with LPARAM = ENDSESSION_CLOSEAPP(0x1): Applications must return a 0 value within 5 seconds and shutdown.

    3. CTRL C: Console applications that receive this message must shutdown immediately.

Rationale

System reboots are a major disruption and lead to a bad user experience. By registering for a restart and listening to shutdown messages, applications can avoid causing system reboots after installs and updates.

Additional Information

If a game installer uses the Windows Installer technology (MSI) without any custom actions, this functionality is provided. Microsoft redistribution packages also support the Restart Manager.

For more information, see this article on the Restart Manager.

4.2 Eliminate Application Verifier Failures

Requirement

All errors found in the following Application Verifier (version 3.1 or later) tests must be fixed:

  • Basics: Exceptions, Handles, Heaps, Locks, Memory, TLS

  • Miscellaneous: DangerousAPIs, DirtyStacks

Rationale

The Application Verifier tool tests for many known issues that cause crashes and hangs in Windows applications, as well as known security vulnerabilities.

Additional Information

The Application Verifier can be downloaded from here.

4.3 Support Windows Error Reporting

Requirement

  • Games must handle only exceptions that are known and expected, and Windows Error Reporting must not be disabled. If a fault (such as an Access Violation) is injected into a game, it must allow Windows Error Reporting to report the crash.

  • All executable (e.g., EXE or DLL) files must contain an accurate Product Name, Company Name, and File Version.

  • Normal exit of the game must not result in an unknown exception fault.

Rationale

The Windows Error Reporting provides vital feedback to Microsoft for detecting wide-spread crashes and hangs in applications. This allows Microsoft and partners to detect and resolve system and driver issues that lead to application failures quickly.

Additional Information

Games may include custom unhandled exception handlers to perform custom support and repotting functionality, but must pass the error on to the ReportFault API.

Proper file version information can be verified by viewing the file properties in the Windows desktop UI and checking the Version property page.

See DirectX SDK article Crash Dump Analysis.

Resources

Windows Vista SDK

http://windowssdk.msdn.microsoft.com/library/

User Account Control Guidelines

http://www.microsoft.com/downloads/details.aspx?FamilyID=ba73b169-a648-49af-bc5e-a2eebb74c16b

Windows Installer Information

http://go.microsoft.com/fwlink/?LinkId=3985

WinQual Developer Portal

https://winqual.microsoft.com/member/wer/user/default.aspx

DirectX Developer Portal

http://msdn.microsoft.com/directx/

Additional DirectX SDK Articles

  • Disabling Shortcut Keys in Games

  • Game Timing and Multicore Processors

  • Windows Installer for Game Developers


Games for Windows Test Requirements

Microsoft Corporation

Version 1.1.0006

October 10, 2006

The information presented in these guidelines reflects Microsoft Corporation's views as of the date of publication. These views can and probably will change in response to changing market conditions. Microsoft makes no warranties or guarantees, implicit or explicit, in or by virtue of this document. Unless otherwise permitted by law, no part of this document may be copied without Microsoft's prior written permission.

  • How To Use This Document
  • Test Requirements
  • Sample Test Script
  • Test Tool Notes
  • Resources

How To Use This Document

There are three main sections to this document: Test Requirements, Sample Test Script, and Test Tool Notes.

Test Requirements

Each test requirement in this document has four main sections: a title and a table with three notable cells.

Title

This is the name of the test case.

Cell, top left

Names of the operating systems to which the test case applies.

Cell, top right

A brief summary of the test case.

Cell, bottom right

Details of the actual test case

Sample Test Script

This section is a sample of the sequence that a typical test pass would follow if using the test requirements as a guide.

Test Tool Notes

This section contains detailed notes on each of the test tools used to verify pass or fail conditions in the test requirements.

Test Requirements

  • Game Requirements
  • Security and Compatibility
  • Installation
  • Reliability

Game Requirements

  • 1.1 Windows Vista Games Explorer
  • 1.2 Windows Vista Parental Controls
  • 1.3 Windows Vista Rich Saved Games
  • 1.4 Xbox 360 Common Controller for Windows
  • 1.5 Multiple Aspect Ratios and Resolutions
  • 1.6 Windows Media Center
  • 1.7 Direct 3D

1.1 Windows Vista Games Explorer

    Vista

    The game must be visible within the Games Explorer on Windows Vista.

    • After installing the game open the Game Explorer.

    • Ensure that there is an icon for the game within the Game Explore

    • Right click on Icon and test each app-defined play & support task

    • Click on icon and verify the meta-data (publisher, developer, genre, release date, version) at the bottom is correct

    • Verify the hyperlinks for the metadata work correctly (if hyperlinks don't show up then this is a possible sign that the exe isn't signed; See section 2.3)

    • Verify the parental controls rating shows up correctly on the right hand side (if it says unrated then verify that this is an unrated game, otherwise this is a sign that the exe isn't signed; See section 2.3)
    Vista / XP

    The game must not create shortcuts on the desktop, in the Start menu, or in any other location to launch the game. The game must not place an "uninstaller" shortcut in the Start Menu or on the desktop.

    • Windows Vista: Ensure that there were no icons created on the desktop when installing the game.

    • Click on Start -> All Programs

    • Windows Vista: Click on Start -> All Programs and ensure that there are no shortcuts to launch or uninstall the game from within the Start menu outside of Game Explorer

    • Windows XP: Verify that there is no "uninstaller" shortcut in the Start Menu entry.

    1.2 Windows Vista Parental Controls

      Vista

      Game must execute within the context of a "Standard User". Parental Controls must be able to block the game.

      Create a Standard User account in Windows Vista called Toby. Start -> Control Panel -> Add or Remove User Accounts -> Create New Account

      As Jane, from Administrator account set up Parental Controls for the game. Start -> Control Panel -> Set Up Parental Controls for Any User -> Toby

      • Set Parental Controls to "On"

      • In the Windows Settings section Click on "Games"

      • Click "OK"

      • Log off as Jane and log on as Toby

      • Verify that the game runs with these settings (Should be AO / all games)

      • Log off as Toby and back on as Jane

      • Go back to the previous screen and select "Set Game Ratings"

      • Select a rating lower than the game's ESRB Rating. NOTE: If the game is not rated then skip this step and move onto the next part of this test

      • Log off as Jane and back on as Toby

      • Verify that the game DOES NOT launch

      • Log off as Toby and back on as Jane

      • If changed previously restore the ESRB settings

      • If there are no ESRB settings then select "Block or Allow Specific Games" and select the game by name

      • Log off as Jane and on as Toby

      • Verify that the game DOES NOT launch
      Vista

      Verify that the GDF has EXE names.

      • As Jane, open User Controls -> Application Restrictions

      • Click "Toby can only use the programs I allow" and click ok (i.e., allow no exes)

      • Go to User Controls | Games Controls and allow the specific game using the ESRB rating

      • Log off as Jane and log on as Toby and try to play the game

      • Ensure that the game is NOT blocked and that Toby can play it

      1.3 Windows Vista Rich Saved Games

        Vista

        If the game creates saved game files, then the title must support the Rich Saved Games feature of the Windows Vista Games Explorer.

        Note This only applies to games that create saved games.

        • Play the game and create several saved games

        • Right click on the Saved Game folder of the game's Game Explorer icon and click "Saved Games" to jump to the app-defined saved game folder.

        • Ensure that the saved game folder only contains saved game files

        • Double click on a saved game file. Verify that the game automatically launches and loads the saved game immediately after any intro video

        1.4 Xbox 360 Common Controller for Windows

          Vista / XP

          Games that support gamepad controllers must support the Xbox 360 Controller for Windows using the XInput API.

          • Launch the game

          • Go into the controller options**

          • Verify that the Xbox 360 for Windows Controller is showing up as the controller

          • Play the game and verify the game and menu system is controllable with the Xbox 360 controller

          • Verify the controller behaves according to accepted standards (b for back, a for accept, etc)

          **Settings for the controller might be located outside of the game.

          1.5 Multiple Aspect Ratios and Resolutions

            Vista / XP

            The game must support at least the following aspect ratios and associated minimum screen resolutions:

            • 4:3 "normal" (800 × 600)

            • 16:9 "widescreen" (1280 × 720)

            • 16:10 "widescreen" (1152 × 720)

            Locate the Video Options for the game (this may be in our out of game)

            • In the video resolution section select 800×600

            • Verify that the game runs at this resolution

            • In the video resolution section select 1280×700

            • Verify that the game runs at this resolution

            • In the video resolution section select 1152×720

            • Verify that the game runs at this resolution

            • Try the game on a widescreen monitor and verify it doesn't stretch (has a wider field of view or uses black bars)

            1.6 Windows Media Center

              Vista / XP

              Games must be visible in, launch from, and return to the Media Center interface.

              • Click on Start -> All Programs -> Media Center

              • In the Media Center interface select Online Media -> Program Library

              • Verify that the game icon is visible

              • Verify that the game launches the game from this interface

              • Verify that the game returns to the Media Center interface when the user exits the game

              1.7 Direct 3D

                Vista / XP | If the game uses Direct3D, then the minimum version supported must be Direct3D 9, and Direct3D must be the default for any display configuration option.
 | Manual Launch the game. In the video options check to see if there are render options, D3D and/or OpenGL. If there are verify that the render options default to D3D. If you are unable to verify that D3D9 is the version of DirectX that is being used then proceed to Automated Test Automated Test Use tool: Depends.exe

                Security and Compatibility

                • 2.1 Follow User Account Control Guidelines
                • 2.2 Support x64 Versions of Windows Vista
                • 2.3 Sign Files
                • 2.4 Sign Drivers
                • 2.5 Perform Version Checking Properly
                • 2.6 Support Concurrent User Sessions
                • 2.7 Support Long Names

                2.1 Follow User Account Control Guidelines

                  Vista / XP?

                  Every executable file (.EXE extension) included with an application must have an embedded manifest that defines its execution level:

                  <requestedExecutionLevel level="asInvoker|highestAvailable|requireAdministrator" uiAccess="true|false"/>

                  Use tool: Mt.exe

                  2.2 Support x64 Versions of Windows Vista

                    Vista

                    To maintain compatibility with x64 versions of Windows:

                    • Titles and title installers must not contain any 16-bit code or rely on any 16-bit component
                    • If the game is dependent on kernel-mode drivers for operation, x64 versions of these drivers must be available. The game setup must detect and install the proper drivers and components for the 64-bit Windows OS.

                    Manual Test

                    • Ensure that no errors are displayed as a result if 16-bit executables. The error will mention the 16-bit application as being a 16-bit application in the error window.

                    • Run the game on 64-bit Windows. It should install and run fine. If it does, it passed.

                    • If the game has a native 64bit exe, then use that instead.

                    2.3 Sign Files

                      Vista / XP

                      All executable code files (e.g., .EXE and .DLL extensions) must be signed with an Authenticode certificate.

                      Manual Test

                      • Navigate to the game directory

                      • Locate all of the .exe and .dll files

                      • Right-click -> Properties on each file

                      • Ensure that there is a 'Digital Signatures' tab and that there is a name in the 'Name of signer:' column

                      2.4 Sign Drivers

                        Vista / XP

                        Any kernel-mode drivers that are installed by the game must have a Microsoft signature obtained through the Windows Hardware Quality Labs (WHQL) or Driver Reliability Signature (DRS) program.

                        Manual Test

                        • Install the game

                        • Verify during the installation process that the user is not prompted with unsigned driver dialog

                        2.5 Perform Version Checking Properly

                          Vista / XP

                          Titles must not fail to run if the OS version number increases, unless the End User License Agreement prohibits use on future operating systems.

                          Manual Test

                          Ensure that there are no error prompts during the installation process regarding the OS unsigned version

                          Automated Test

                          Use tool: AppVerifier

                          • Launch AppVerifier

                          • Enable Version-Lie

                          • Install the game

                          • Run the game

                          • View the log file (View -> Logs -> Select .exe -> View)

                          • Ensure that there are no failures

                          2.6 Support Concurrent User Sessions

                            Vista / XP

                            Games must allow multiple sessions of Windows Vista unless prevented by architecture issues.

                            Create a Standard User account in Windows Vista called Toby. Start -> Control Panel -> Add or Remove User Accounts -> Create New Account

                            • Launch the game

                            • ALT+Tab back to the desktop

                            • Click on Start -> [arrow to the right of Lock] -> Switch User

                            • Log on as the user Toby

                            • Verify that the game launches as Toby

                            • Switch back to the original user and game

                            • Verify that the game does not crash during this process. If the game does close, verify that the game alerts the user of its closing.

                            • Verify that you cannot hear audio from the game while tabbed away from it.

                            2.7 Support Long Names

                              Vista / XP

                              If a game supports saving files, it must be able to save files with long names and paths.

                              • Launch the game

                              • Start a new game

                              • Save the game. During the save process verify that the game saves using the name: My First Saved Game

                              • Exit back to the main menu

                              • Attempt to load the newly saved game

                              • Ensure that the game gracefully handles unsupported file system characters, such as \ / : * ? " <>, if the game allows you name the saved game

                              • If the user is allowed to name their profile and/or character ensure that the game does not fail when using long names here as well

                              Installation

                              • 3.1 Easy Install
                              • 3.2 Support User Account Control for Installation
                              • 3.3 Install to Correct Folders
                              • 3.4 Install Windows Resources Properly
                              • 3.5 Avoid Reboots During Installation
                              • 3.6 Use File Versioning Correctly
                              • 3.7 Support Autorun

                              3.1 Easy Install

                                Vista / XP

                                Games with a traditional installation must provide a simplified path in their setup user interface.

                                • Insert the game disc

                                • Verify that there is no more than one EULA

                                • If the setup does ask questions, verify that there are Default and Custom installation options

                                • Verify that the Default installation option bypasses all selections for the installation (install folder, components selection, etc.)

                                • Verify that no OS component setup (DirectX setup, Visual C Runtimes, etc.) prompts appear

                                • Verify that the only method of removal is via Control Panel

                                3.2 Support User Account Control for Installation

                                  Vista

                                  The game installer must not assume it is running in the same context as the user. Games must therefore perform per-user tasks on first-run separately from the install.

                                  • Verify that you can install the game as a standard user. This will require elevated rights during the setup/install process.

                                  • Elevate installation process via Admin password (the prompt to elevate will come up when the user attempts to install)

                                  • If supported: Opt to Autorun the game at the end of install if it does not already do so

                                  • Once in-game, create a new profile, play and save a game

                                  • Exit the game

                                  • Restart the game and verify that Standard User Jane can still access the profile and save games that were created

                                  3.3 Install to Correct Folders

                                    Vista / XP

                                    Games must be installed to the Program Files or (Vista only) ProgramData folder by default. User data must be written at first run and not during the install.

                                    • Install the game using the Default install type

                                    • Verify that the game is located in Program Files

                                    3.4 Install Windows Resources Properly

                                      Vista

                                      Applications must not attempt to install files or registry keys that are protected by Windows Resource Protection (WRP).

                                      • Verify that no Windows Resource Protection WRP dialogs appear during the install process

                                      3.5 Avoid Reboots During Installation

                                        Vista / XP

                                        The game installer should not assume Microsoft OS component redistribution packages require a reboot unless indicated by a return result and/or Microsoft documentation.

                                        • Install the game

                                        • Verify that the game does not require the system to be rebooted after installation

                                        • Microsoft must approve of system reboots and must be notified of such prior to running this test case

                                        3.6 Use File Versioning Correctly

                                          Vista

                                          The game installation program must properly check to ensure that the latest file versions are installed. Installing a game must never regress any files that you do not produce or that are shared by applications that you do not produce.

                                          • Prior to installing the game create a pre-install snapshot of System32

                                            • Make a directory called G4Wtest

                                            • Bring up a command Window (Start -> Run -> cmd)

                                            • Navigate to c:\windows\system32

                                            • Type dir /o:-g /o:-d >> c:\G4Wtest\pregame.txt

                                          • Create a post-install snapshot of System32

                                            • Bring up a command Window (Start -> Run -> cmd)

                                            • Navigate to c:\windows\system32

                                            • Type dir /o:-g /o:-d >> c:\G4Wtest\postgame.txt

                                            • Ensure that game did not regress any file versions of the files listed in the two documents by comparing pregame.txt to postgame.txt

                                          3.7 Support Autorun

                                            Vista / XP

                                            For games distributed on CD, DVD, or other removable media that support Autorun, the first time the disc is inserted, the application must use Autorun to run or prompt the user to install unless the user has disabled the Autorun feature.

                                            • Insert the game disc or media

                                            • Ensure that the install / run dialog comes up automatically

                                            • If the game uses multiple discs ensure that subsequent discs don't prompt the user for input regarding actions when the CD is inserted

                                            Reliability

                                            • 4.1 Eliminate Unnecessary Reboots
                                            • 4.2 Eliminate Application Verifier Failures
                                            • 4.3 Support Windows Error Reporting

                                            4.1 Eliminate Unnecessary Reboots

                                              Vista

                                              All application installers must take advantage of the Restart Manager APIs to avoid system reboots (see requirement 3.5)

                                              4.2 Eliminate Application Verifier Failures

                                                Vista

                                                All errors found in the following Application Verifier (version 3.2 or later) tests must be fixed:

                                                • Basics: Exceptions, Handles, Heaps, Locks, Memory, TLS

                                                • Miscellaneous: DangerousAPIs, DirtyStacks

                                                Use Tool: AppVerifier 3.2 (or later)

                                                • Install AppVerifier

                                                • Launch AppVerifier and select File -> Add Application

                                                • Locate the game executable, select it and click the "Open" button

                                                • In the "Applications" section select the game executable

                                                • In the "Tests" section select the tests listed above under the categories "Basics" and "Miscellaneous" (uncheck ThreadPool and TimeRollOver)

                                                • Launch the game

                                                Note Some tests may require a debugger to be fully run. If this is the case you should omit this test from the selection list unless you have an executable that runs on a debugger.

                                                4.3 Support Windows Error Reporting

                                                  Vista / XP

                                                  Games must handle only exceptions that are known and expected, and Windows Error Reporting must not be disabled. If a fault (such as an Access Violation) is injected into a game, it must allow Windows Error Reporting to report the crash.

                                                  • If the application crashes while testing ensure that Windows Error Reporting comes up and collects crash data
                                                  Vista / XP

                                                  All executable (e.g., EXE or DLL) files must contain an accurate Product Name, Company Name, and File Version.

                                                  • Right click on the game's executable file

                                                  • Select Properties

                                                  • Click on the Details tab

                                                  • Verify that the Product Name, Copyright, and File Version fields are properly populated
                                                  Vista / XP

                                                  Normal exit of the game must not result in an unknown exception fault.
                                                  • After playing the game for a normal gaming session ensure that the game doesn't generate an error on exit

                                                  Sample Test Script

                                                  This is an example of a typical test pass using the above test requirements as a guide.

                                                  • 5.1 Tools
                                                  • 5.2 Pre-Install
                                                  • 5.3 Install
                                                  • 5.4 Post-Install
                                                  • 5.5 Runtime
                                                  • 5.6 Post-Runtime
                                                  • 5.7 Parental Controls
                                                  • 5.8 Media Center
                                                  • 5.9 Automated Tests
                                                  • 5.10 Other Tests
                                                  • 5.11 Uninstall

                                                  5.1 Tools

                                                    • x86 Version of Windows Vista Ultimate on an AMD CPU

                                                    • x86 Version of Windows Vista Ultimate on an Intel CPU

                                                    • x64 Version of Windows Vista Ultimate on an AMD CPU

                                                    • x64 Version of Windows Vista Ultimate on an Intel CPU

                                                    • x86 Version of Windows MCE 2005 SP2 on an Intel CPU

                                                    • Wide Screen Monitor that supports 1680×1050

                                                    • Xbox 360 Controller for Windows

                                                    5.2 Pre-Install

                                                      • Create two standard users: Jane and Toby

                                                      • Create a pre-install snapshot of System32

                                                        • Make a directory called G4Wtest

                                                        • Bring up a command Window (Start -> Run -> cmd)

                                                        • Navigate to c:\windows\system32

                                                        • Type dir /o:-g /o:-d >> c:\G4Wtest\pregame.txt

                                                      • See section Install

                                                      5.3 Install

                                                        • Log in as user Jane

                                                        • Insert the game disc into the DVD drive, autorun should launch the install process [3.7]

                                                        • If prompted enter the Administrator password at the challenge/elevation prompt [3.2]

                                                        • Verify that Install only presents one EULA [3.1]

                                                        • Verify that Install presents an "Easy Install" option [3.1]

                                                        • Verify that the game does not report version issues when installing on the OS [2.5] [4.2]

                                                        • Verify that no "Unsigned Driver" messages are displayed during install [2.4]

                                                        • Verify that no administrator elevation prompts are required during install that want to install files or registry keys that are protected by Windows Resource Protection WRP [3.4]

                                                        • Verify that the game does not reboot the system after install [3.5] [4.1]

                                                        • Game may auto-launch after install, if so skip to RUNTIME

                                                        • See section POST-INSTALL

                                                        5.4 Post-Install

                                                          • Ensure that there are no icons on the desktop [1.1]

                                                          • Ensure that the game did not make entries in the Start Menu [1.1]

                                                          • Verify that the game is visible in Game Explorer [1.1]

                                                          • Verify that the GFD is enabled [1.1]

                                                          • Create a post-install snapshot of System32

                                                            • Bring up a command Window (Start -> Run -> cmd)

                                                            • Navigate to c:\windows\system32

                                                            • Type dir /o:-g /o:-d >> c:\G4Wtest\postgame.txt

                                                            • Ensure that game did not regress any file versions of the files listed in the two documents by comparing pregame.txt to postgame.txt [3.6]

                                                          • See section RUNTIME

                                                          5.5 Runtime

                                                            • Verify that the game launches from Game Explorer [1.1]

                                                              Note If game auto-ran after install you will have to re-check this

                                                            • If the game supports a game pad verify Common Controller support is properly implemented [1.4]

                                                              • If needed enable the controller via the options menu

                                                              • Verify menu navigation

                                                              • Verify the controller behaves according to accepted standards (b for back, a for accept, etc.

                                                            • Verify that you can set the video to [1.5]:

                                                              • 4:3 "normal" (800 × 600)

                                                              • 16:9 "widescreen" (1280 × 720)

                                                              • 16:10 "widescreen" (1152 × 720)

                                                            • If available in the video settings, ensure that D3D is the default renderer [1.7] otherwise see AUTOMATED TESTS section

                                                            • If prompted of if the option is there create a user profile

                                                            • Start a new game and verify that you can save a game properly [2.7]

                                                            • Attempt to ALT+Tab out of the game [2.6]

                                                              • If the game allows ALT+Tab Switch users with the game running by clicking Start -> Switch User

                                                              • Switch back to the original user where the game is running

                                                              • ALT+Tab back into the game

                                                            • Exit the game

                                                            • Launch the game and verify that the user profile data and save games are accessible [3.2]

                                                            • Exit the game: See section POST-RUNTIME

                                                            5.6 Post-Runtime

                                                              • Verify that the game does not generate errors on exit [4.3c]

                                                              • Verify that the game installed to \Program Files [3.3]

                                                              • Verify that the game supports Rich Save games [1.3]

                                                                • Right click on the Saved Game folder of the game's Game Explorer icon and click "Saved Games" to jump to the app-defined saved game folder

                                                                • Verify that the saved game folder only contains saved game files

                                                                • Left click on a saved game file. Verify that the saved game file has correct metadata (save name, game name, level name, comment) display at the bottom of the folder

                                                                • Double click on a saved game file. Verify that the game automatically launches and loads the saved game immediately after any intro video

                                                              • See section PARENTAL CONTROLS

                                                              5.7 Parental Controls

                                                                • In the Parental Control section, block the user Toby from seeing games one ESRB level up and higher from the game that you just installed. Example: If the game is rated E, set if so Toby can only play games that are rated C [1.2]

                                                                • Verify that user Jane can still see play the game normally [1.2]

                                                                • Log off and log on as user Toby [1.2]

                                                                • Verify that user Toby cannot launch the game and that user Toby receives a Parental Control message stating that they have been blocked [1.2]

                                                                • Log off as user Toby and back on as user Jane

                                                                • Go to Parental Controls in Control Panel and remove the ESRB restrictions

                                                                • Under "Windows Settings" select "Games"

                                                                • Select "Block any game on your computer by name"

                                                                • Locate the game, select "Always block" and click OK

                                                                • Verify that user Jane can still see play the game normally [1.2]

                                                                • Log off and log on as user Toby [1.2]

                                                                • Verify that user Toby cannot launch the game and that user Toby receives a Parental Control message stating that they have been blocked [1.2]

                                                                • Log off as user Toby and back on as user Jane

                                                                • Go to Parental Controls in Control Panel and remove the restrictions

                                                                • Verify that both users can now play the game [1.2]

                                                                • See section MEDIA CENTER

                                                                5.8 Media Center

                                                                  • Open Media Center

                                                                  • Navigate to Programs

                                                                  • Verify that the game icon is visible within the Media Center interface [1.6]

                                                                  • Verify that the game launches from the Media Center interface [1.6]

                                                                  • Verify that the game returns to the Media Center interface after game exit [1.6]

                                                                  • See section AUTOMATED TESTS

                                                                  5.9 Automated Tests

                                                                    • Verify that AppVerifier tests pass – see Branding Test Tool Documentation [4.2]

                                                                    • Verify that Manifest tests pass – see Branding Test Tool Documentation [2.1]

                                                                    • See section OTHER TESTS

                                                                    5.10 Other Tests

                                                                      • Verify that all of the .exe and .dll files included with the game are digitally signed [2.3]

                                                                      • Verify that the above tests pass on 64-bit versions of Windows Vista [2.2]

                                                                      • If the application crashes while testing ensure that Windows Error Reporting comes up and collects crash [4.3a]

                                                                      • Ensure proper file summaries [4.3b]

                                                                        • Click on Start -> Computer

                                                                        • Navigate to the game directory

                                                                        • In the search window type *.dll

                                                                        • For each file: Right click the file and select Properties

                                                                        • Click on the Details tab

                                                                        • Ensure that there are Properties (such as 'Product Name') and that each one contains something in the value field (such as 'Microsoft Windows Operating System')

                                                                        • Repeat this check for .exe files as well

                                                                      • See section UNINSTALL

                                                                      5.11 Uninstall

                                                                        • Verify that the game can be installed via 'Uninstall a program' or 'Add / Remove Programs' [1.1]

                                                                          • Verify in Windows Vista that this is the only way to remove the program

                                                                          • Verify that all links to the game have been removed from the system

                                                                        Test Tool Notes

                                                                        These are notes for each of the test tools listed in the above test requirements.

                                                                        • 6.1 Appverifier 3.2 (or higher)
                                                                        • Manifest Test - mt.exe

                                                                        6.1 Appverifier 3.2 (or higher)

                                                                        Test Case: 2.5, 4.2

                                                                        Note Some applications fail to run with AppVerifier running. This can be resolved by running with the debug version of the game executable.

                                                                          • Install AppVerifier 3.2 (or higher) on a Windows XP machine

                                                                          • Launch AppVerifier and select File -> Add Application

                                                                          • Locate the game executable, select it and click the "Open" button

                                                                          • In the "Applications" section select the game executable

                                                                          • If you have access to the debug version of the executable select the following tests in the "Basics" section. If not move on to the next part of this test:

                                                                            • Exceptions

                                                                            • Handles

                                                                            • Heaps

                                                                            • Locks

                                                                            • Memory

                                                                            • TLS

                                                                          • In the "Basics" section select the Following test:

                                                                            • Threadpool

                                                                          • Select all of the tests in the "Compatibility" section

                                                                          • Select "Low Resource Simulation"

                                                                          • Select "LuaPriv"

                                                                          • Select all of the tests in the "Miscellaneous" section

                                                                          • Launch the game

                                                                          • Play the game

                                                                          • Close the game

                                                                          • In AppVerifier select View -> Logs

                                                                          • In the "Applications" section select the app .exe file

                                                                          • In the "Logs" section select the log file, observer the error count. If there are no errorsthen end AppVerifier tests. If there are errors move on to the next part of this test

                                                                          • If there are errors select click the "View" button

                                                                          • Search the document (CTRL+f) for Severity="Error

                                                                          • Create bugs based on the LayerName= portion of the failure

                                                                          Manifest Test - mt.exe

                                                                          Test Case: 2.1

                                                                          This tool is run from a command prompt where MT.exe is located.

                                                                          Example:

                                                                          mt.exe -inputresource:"c:\yourdir\YourGame.exe";#1 -out:yourgame.manifest

                                                                          • Click on Start -> Run -> type cmd and click the OK button

                                                                          • Run the mt.exe tool to generate a .manifest file for each .exe file that installs with the game

                                                                          • Open the generated .manifest file

                                                                          • Ensure that each .exe file contains the following:

                                                                            <description>Example Game Name</description><trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"><security><requestedPrivileges><requestedExecutionLevel level="asInvoker"></requestedExecutionLevel></requestedPrivileges></security></trustInfo>

                                                                          Resources

                                                                          Games for Windows: Technical Requirements

                                                                          Games for Windows: Technical Requirements

                                                                          Windows Vista SDK

                                                                          http://windowssdk.msdn.microsoft.com/library/

                                                                          User Account Control Guidelines

                                                                          http://msdn.microsoft.com/windowsvista/default.aspx?pull=/library/en-us/dnlong/html/AccProtVista.asp

                                                                          Windows Installer Information

                                                                          http://go.microsoft.com/fwlink/?LinkId=3985

                                                                          WinQual Developer Portal

                                                                          https://winqual.microsoft.com/member/wer/user/default.aspx

                                                                          DirectX Developer Portal

                                                                          http://msdn.microsoft.com/directx

                                                                          Additional DirectX SDK Articles
                                                                          Disabling Shortcut Keys in Games
                                                                          Game Timing and Multicore Processors
                                                                          Windows Installer for Game Developers


Gaming with Least-Privileged User Accounts

By Jack Lin, Software Design Engineer

Microsoft Corporation

December 2004

Introduction

This article describes how games developers can author Microsoft Windows games that work well with least-privileged user accounts (also known as limited-user accounts).

Contents:

  • File Access for Least-Privileged User Accounts
  • Registry Access for Least-Privileged User Accounts
  • Patching with Least-Privileged User Accounts

Windows manages its users with accounts. Today, more than eighty percent of computer users at home share their computer with other family members. When multiple users share a Windows computer, multiple user accounts are created, and each user logs in with an individual account to access the computer. With the increasing awareness for security, more people operate their computers with least-privileged user accounts, also known as limited-user accounts, which do not have complete control over the system. Administrator accounts typically have unrestricted access to every part of the computer. This can affect how Windows-based games work.

There are additional benefits for games developers who write their games to work with least-privileged user accounts. In the upcoming Windows release code-named "Longhorn", least-privileged user accounts are enforced, which means that every account on the system, with the exception of the local administrator, is a least-privileged user account. This will affect how games that do not follow the guideline (legacy applications) run on "Longhorn". For instance, when an application attempts to write to a folder or a registry value to which it does not have permission, the file write is redirected to a virtual file store for the user. This virtual file store will reside in a folder to which the user has write access. This behavior may not seem as catastrophic as outright failing the write attempt; however, applications that create virtualized files may confuse users because files will not be written to the location users expect. For instance, games that write high score files to the same folder as the executable folder will write these files to a virtualized folder instead. Consequently, one user cannot see the high score achieved by another user because every user has a separate virtualized file store.

Games that follow the guidelines in this document will run with least-privileged user accounts, and consequently will maintain compatibility with "Longhorn".

File Access for Least-Privileged User Accounts

Windows supports two file systems: FAT32 and NTFS. FAT32 is a legacy file system supported only for backward compatibility; NTFS supports more powerful and robust file permissions. The use of NTFS is expanding as retailers are shipping new computers with Windows pre-installed on a NTFS-partitioned hard drive. On an NTFS-based Windows XP system, users with least-privileged user accounts have only limited access to several folders. However, they would have complete access on a FAT32-based Windows XP system.

The following table lists the default location of these folders and their permissions.

Path | Folder Contents | Read | Write | Create/Delete
<Drive>:\Windows | The Windows operating system | x |  |
<Drive>:\Program Files | Executable application files | x |  |
<Drive>:\Documents and Settings\Username* | Each user's files | x | x | x
<Drive>:\Documents and Settings\All Users | All user files | x | x | x

* Username is the user's login name.

In a least-privileged user account, you may read, write, create and delete files in either folder: Documents and Settings\Username or Documents and Settings\All Users.

What this means is that you should not place save games in \Program Files, instead they should go in a sub-folder in \My Documents. Also you should not place temporary application data in \Program Files or \My Documents, instead it should be placed in Application Data folder (CSIDL_LOCAL_APPDATA).

More specifically, there are two scenarios that each game should handle:

Scenario 1: Files that do not need to be viewed or altered by users

A typical example would be the game's configuration file, temporary files, and game cache files. These files are typically kept in the Application Data folder. To obtain this folder path, call SHGetFolderPath with CSIDL_APPDATA or CSIDL_LOCAL_APPDATA as shown in the following code example.

#include <shlobj.h>
#include <strsafe.h>

#define APPNAME L"MyApp"

WCHAR wszPath[MAX_PATH];

// Local Application Data
SHGetFolderPath( hWnd, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, wszPath );
StringCchCatW( wszPath, MAX_PATH, L"\\" );
StringCchCatW( wszPath, MAX_PATH, APPNAME );

// Create the folder wszPath
// Then create files in wszPath
// Roaming Application Data
SHGetFolderPath( hWnd, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, wszPath );
StringCchCatW( wszPath, MAX_PATH, L"\\" );
StringCchCatW( wszPath, MAX_PATH, APPNAME );

// Create the folder wszPath
// Then create files in wszPath

The difference between local and roaming Application Data folders is that on Windows 2000 and Windows XP, roaming content is copied to and from the server during the logon/logoff process, while local content is not. For most games, local Application Data is sufficient.

Scenario 2: Files that need to be viewed or altered by users

A typical example would be a user's saved game files. Store the files in the user's document folder so that they are easily visible to the user. An application gets the user's document folder path by calling SHGetFolderPath with CSIDL_PERSONAL, as the following code example shows:

#include <shlobj.h>
#include <strsafe.h>

#define APPNAME L"MyApp"

WCHAR wszPath[MAX_PATH];

SHGetFolderPath( hWnd, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, wszPath );
StringCchCatW( wszPath, MAX_PATH, L"\\" );
StringCchCatW( wszPath, MAX_PATH, APPNAME );

// Create the folder wszPath
// Then create files in wszPath

At times, a game may need to store files that all users are meant to see and use. One example is the high score record, where all users write to the same record file so that high scores are maintained system-wide instead of a separate high score for each user. Other examples are downloaded maps, missions, and game modifications. If these are shared, then only one user has to download them instead of every user. In this scenario, use the document folder under the shared profile folder, as demonstrated in the following code.

#include <shlobj.h>
#include <strsafe.h>

#define APPNAME L"MyApp"

WCHAR wszPath[MAX_PATH];

SHGetFolderPath( hWnd, CSIDL_COMMON_DOCUMENTS, NULL, SHGFP_TYPE_CURRENT, wszPath );
StringCchCatW( wszPath, MAX_PATH, L"\\" );
StringCchCatW( wszPath, MAX_PATH, APPNAME );

// Create the folder wszPath
// Then create files in wszPath

Registry Access for Least-Privileged User Accounts

It is common for applications to use the Windows registry to store information. Similar to file access, administrator and least-privileged user accounts do not have the same permission to the registry. For least-privileged user accounts, the entire HKEY_LOCAL_MACHINE node is read-only. For instance, a game can read the default configuration information, but may not write any new information to this node. Consequently, games running in least-privileged user mode that need to write to the registry will need to use the HKEY_CURRENT_USER node to store per-user information, as illustrated in the following code.

#define APP_REGISTRY_KEY_PATH L"Software\\MyCompany\\MyApp"

LONG lRetVal;
HKEY hKey;

lRetVal = RegCreateKeyExW( HKEY_CURRENT_USER,
                           APP_REGISTRY_KEY_PATH,
                           0,
                           NULL,
                           REG_OPTION_NON_VOLATILE,
                           KEY_WRITE|KEY_READ,
                           NULL,
                           &hKey,
                           NULL );

if( ERROR_SUCCESS == lRetVal )
{
    // Store information in hKey
}

It is worth noting that during installation, registry information should be written to HKEY_LOCAL_MACHINE, not HKEY_CURRENT_USER. This is because the person running the installation is usually an administrator, and may not be the only person to use the program. In this situation, writing to HKEY_CURRENT_USER makes the information unavailable to other users. This is not usually an issue because the information written to the registry during installation is the configuration and default settings that apply to every user of the program.

When uninstalling the game, extra effort is necessary to remove every value that the game has written to the registry. Because the uninstaller is run by one person, usually the administrator, simply deleting the relevant information in HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER will not remove values for other users. One way to remove the per-user information in the registry is to enumerate the HKEY_USERS registry hive root. Each subkey under HKEY_USERS corresponds to the HKEY_CURRENT_USER hive for a particular user on the system. By enumerating HKEY_USERS and removing the game-specific information under each subkey, the uninstaller can ensure that no information is left behind.

Patching with Least-Privileged User Accounts

Patching a game involves updating the game's files. Therefore, it usually requires write access to the game's program folder. Patching a game is a straightforward process when it is done by an administrator because they have unrestricted access to the game's program folder. Conversely, it has traditionally been difficult, if not impossible, for a least privileged user to patch games because of the access restriction. Now, Windows Installer has been enhanced to make least-privileged user account patching possible. To take advantage of this feature, games are encouraged to utilize Windows Installer for installation and patching.

Starting with Windows Installer 3.0, application patches can be applied by least privileged users when certain conditions are met. These conditions are:

  1. The application was installed using Windows Installer 3.0.
  2. The application was originally installed per-machine.
  3. The application is installed from removable media, such a CD-ROM or digital video disc (DVD).
  4. The patches are digitally signed by a certificate that is identified by the original installer package (.msi file).
  5. The patches can be validated against the digital signature.
  6. The original installer package has not disabled least-privileged user account patching.
  7. The system administrator has not disabled least-privileged user account patching via system policy.

Normally, a least privileged user cannot modify a game's program files. However, when the above conditions are met and LUA patching is enabled, Windows Installer can update the game's files so that the user gets the latest version.

Note

The information contained in this document relates to pre-release software product, which may be substantially modified before its first commercial release. Accordingly, the information may not accurately describe or reflect the software product when first commercially released. This document is provided for informational purposes only, and Microsoft makes no warranties, express or implied, with respect to this document or the information contained in it.


Graphics APIs in Windows Vista

By Chuck Walbourn, Software Design Engineer

XNA Developer Connection (XDC)

August 2006

Windows Vista includes support for an entirely new display driver model that represents a major revision in the design of video drivers since the introduction of the Windows Driver Model (WDM) for Windows 98. This redesigned model reflects the evolution of video hardware from the world of 2D raster operations and GDI applications, to that of 3D games with fixed-function graphics hardware, to that of the modern programmable graphical processing unit (GPU) that supports a wide-range of high-performance graphics applications.

Background

The primary API for programming graphics since the early days of Windows has been the Graphical Device Interface (GDI). This API was designed to handle a plethora of 2D output devices and formed the basis for the Windows user interface experience. DirectDraw and Direct3D were introduced as alternative APIs to support full-screen games and 3D rendering as extensions to the existing hardware of the time. Interactions with GDI were complicated, and the effective intermixing of traditional GDI elements with Direct3D elements has been limited by this design. The Windows XP version of WDM, known as XPDM, reflects the side-by-side nature of GDI and Direct3D (see Figure 1).

Figure 1. Graphics APIs in Windows XP

Over the years, the power of 3D video cards has grown dramatically to the point where the vast majority of hardware is dedicated to this function. A new driver model, Windows Vista Display Driver Model (WDDM), brings the GPU and Direct3D to the forefront, allowing the creation of an entirely new experience, the 3D desktop, that seamlessly blends the 2D world of GDI with the power of modern programmable GPUs. With WDDM, the video hardware is driven entirely by Direct3D, and all other graphics interfaces communicate with the video hardware via the new Direct3D–centric driver model (see Figure 2).

Figure 2. Graphics APIs in Windows Vista

Direct3D 9

Version 9 of DirectX was first released for Windows in 2002, with subsequent updates in 2003 and 2004. This API represents a decade of evolution of the DirectX technologies, the introduction of more powerful shader programming models for Direct3D, and a maturity backed by thousands of shipping titles. Direct3D 9 is the primary graphics interface on Windows Vista, and it remains the ideal API to use for writing 3D games and applications that need to run on the broad range of existing hardware and Windows releases. The details of the new driver model are hidden from applications using the Direct3D 9 interfaces, but behind the scenes the operating system is taking full advantage of the new capabilities to provide true multitasking of the GPU, more efficient resource management, and robust performance.

To ensure full compatibility with older versions of Windows, some quirks of the old driver model must be emulated even with the new Windows Vista display driver model. For example, when a full-screen application loses focus, it must assume it has lost all the resources in video memory (VRAM) and reload those it created as unmanaged resources even though the new driver model handles the resources transparently without evicting them from the device context. Even the concept of a managed vs. default resource type is specific to the old driver model. Another example is the expectation of failure when allocating unmanaged (default pool) resources in excess of the amount of VRAM available, even though the new driver model can provide a nearly unlimited amount of virtual video memory. Because of these requirements, Direct3D applications running on Windows Vista will still receive these error conditions, and thus are limited in their ability to fully utilize some features of the new driver model using the basic Direct3D 9 interfaces.

While new systems shipping with Windows Vista will include video cards with WDDM drivers, and new drivers for a number of popular video cards are included in the box, Windows Vista continues to support the ability to use older XPDM drivers for upgrades and corporate editions. On systems using the old driver model, Direct3D 9 and older interfaces must be used, and the operation of the graphics system is very similar to that of Windows XP (Figure 1). WDDM is required for applications to use Direct3D 9Ex, Direct3D 10, and later versions.

Direct3D 9Ex

The Direct3D 9Ex interface provides access to a slight extension of the standard Direct3D 9 API that exposes the virtualized resource allocation, new lost device semantics, and some other new features available while running on Windows Vista. By creating this extended object, the Direct3D 9 API uses the new semantics and therefore requires the application to use different logic (and therefore different code paths) for resource creation, management, and error handling for new kinds of conditions. This API is only available on Windows Vista, and it requires WDDM drivers. Because Direct3D 9Ex uses a separate API and driver code path than Direct3D 9, supporting this API requires additional test cases for your application.

The primary reason for creating the new Direct3D 9Ex API was to allow full access to the new capabilities of WDDM while maintaining compatibility for existing Direct3D applications. The new 3D desktop and many Windows Vista-specific applications make use of this version of Direct3D 9, but they are not functional when running on older XPDM drivers. Because the Direct3D 9Ex API will never appear on older versions of Windows due to a lack of support for the WDDM, the standard Direct3D 9 interfaces cover a much broader set of systems. For high-performance applications that can take advantage of the next generation of video hardware, the entirely new version 10 of Direct3D provides many new capabilities not exposed by Direct3D 9Ex. As a result, for games and most other applications, Direct3D 9 or Direct3D 10 is the recommended API.

Note The DirectX SDK does not provide samples, headers, or libraries for the Direct3D 9Ex interface. The MSDN Library and Windows SDK (formerly known as the Platform SDK) contain the available documentation, headers, and libraries.

For more information about Direct3D 9Ex, see DirectX for Windows Vista on MDSN.

Direct3D 10

To fully realize the potential of the new Windows Vista driver model and next-generation hardware, an entirely new version of the Direct3D API has been created. While WDDM eliminates some of the limitations on performance in the existing graphics system, Direct3D 10 goes further by removing design bottlenecks in the existing Direct3D API and greatly simplifies the task of programming the GPU.

The new API completely eliminates all but a few fixed-function aspects, replacing them with programmable constructs and greatly streamlining the internal implementation. The hundreds of capability bits in previous versions of Direct3D have been completely eliminated and replaced with a well-defined, inclusive set of functionality that has only a few optional usage scenarios for specific resource formats. CPU-intensive resource creation and validation now have explicit semantics in the new API, allowing for much more predictable performance behavior and greatly reduced per-draw overhead. Resources can be reconfigured into multiple forms to allow efficient use at various stages, and the feature set imposes far fewer restrictions on usage scenarios for formats. There area also new block-compressed normal-map texture formats.

In the new API, shader constants and device state are explicit resources, allowing for far more efficient caching on the hardware and greatly simplified driver validation. The programmable shader model has been unified across both vertex and pixel shaders, and made more expressive with a well-defined computational model and operator set. Also, a new geometry shader stage has been added to operate on primitives after the vertex shader stage. The results of the GPU’s work in the vertex and geometry shader stages of the pipeline can be streamed out to video RAM for reuse, allowing for the possibility of extremely complex multi-pass GPU operations with minimal CPU interaction.

All of these enhancements enable next-generation graphics technology and expand the ability of applications to off-load work to the GPU. Offloading allows more complex GPU-based character skinning, accelerated morphing techniques, shadow volume generation and extrusion, particle and physics systems that are entirely GPU-based, more complex materials combined into efficient large-draw batches, procedural detailing, real-time ray-traced displacement mapping, single-pass cube-map generation, and many more techniques — all while freeing up CPU resources for more complex applications.

To provide this level of innovation in Direct3D 10, older hardware cannot be expressed as a partial implementation of a new interface. A video card is either capable of supporting all of the new features, or it’s not a Direct3D 10–capable card. Therefore, while Direct3D 9 could drive DirectX7-era hardware with many missing capability bits and usage limitations, Direct3D 10 only works on a new generation of video cards. For an application to support older video hardware, it must also support the Direct3D 9 interfaces. Future versions of Direct3D will build on version 10, extending it to new versions of the API while ensuring a strict superset of Direct3D 10 functionality.

For more information about Direct3D 10, see the DirectX SDK documentation for DirectX 10.

OpenGL

Windows Vista provides the same support as Windows XP for OpenGL, which allows video card manufactures to provide an installable client driver (ICD) for OpenGL that provides hardware-accelerated support; note that newer versions of such ICDs are required to fully support Windows Vista. If no ICD is installed, the system will fall back to the OpenGL v1.1 software layer in most cases.

Application Compatibility, GDI, and older versions of Direct3D

The Windows Vista graphics system is designed to support a broad range of hardware and usage scenarios to enable new technology while continuing to support existing systems. Existing graphics interfaces, such as GDI, GDI+, and older versions of Direct3D, continue to work on Windows Vista, but are internally remapped where possible. This means that the majority of existing Windows applications will continue to work.

Windows Vista continues to support the same Direct3D and DirectDraw interfaces as Windows XP, back to version 3 of DirectX (with the exception of Direct3D's Retained Mode, which has been removed). Just as with Windows XP Professional x64 Edition, 64-bit native applications on Windows Vista are limited to Direct3D9, DirectDraw7, or newer interfaces. High-performance applications should make use of Direct3D 9 or later to ensure that they have the closest match to the hardware capabilities.

Recommendations

Consider the following recommendations when selecting an API for your graphical application:

  • Use Direct3D 9 if your application must support Windows XP or an earlier version of Windows.
  • Use Direct3D 9 if you want to support Windows Vista running with XPDM drivers and upgraded systems that lack Direct3D 10–capable hardware.
  • Use Direct3D 10 to take advantage of the next generation of video hardware on Windows Vista


Install-on-Demand for Games

By Jack Lin, Software Design Engineer

Microsoft Corporation

December 2004

Introduction

This technical article discusses two techniques, install-on-demand and background install, using Windows Installer. Games can utilize these installation techniques to provide a better and more pleasant gaming experience for players by reducing the installation time.

Contents:

  • Overview
  • Patching Support
  • The InstallOnDemand SDK Sample
  • The Sample's Features and Components
  • Installation
  • Limitation

Overview

Installation has been an element of computer-based applications for a long time. Most applications today require that they be installed on the user's local hard drive first before they can be used. Computer games are no exception; when a consumer buys a Microsoft Windows game and tries to run it, he must first go through an installation process that copies necessary files from the game disc to the hard drive. This installation process is usually lengthy and can take as much as an hour to complete. The installation time is a factor that makes console games more desirable than computer-based games for some players, as they are able to immediately play a console game after inserting the game disc. The technology discussed in this article will attempt to remedy this by drastically reducing the installation time.

Traditionally, games require that all or most of the files be installed prior to launching. In order to achieve install-on-demand, the game resources need to be modular; that is, the developer must divide the application's resources (graphics, audio, and so on) into components. Each component is a set of resources that can be installed or removed as a unit. Once this is done, the game developer defines one or more features, typically one or more per level or zone. Each feature of an application specifies a set of components necessary for running that particular feature. When an application is installed, its features can be marked as "install" (components copied to the local hard drive at installation time) or "advertised" (components copied to the local hard drive after the initial install when the application uses that feature). A game developer can reduce the installation time by designing the game to launch and run with a minimal set of features installed. The rest of its features can be marked as advertised and installed on demand when the application actually needs to use functionalities that those features provide.

Games can call Windows Installer to install a particular feature that may not have been installed. To make the installation appear in the background, a worker thread can be used to make the calls to the installer while the primary thread continues to handle game logic and to render the screen. This minimizes the disruption of gameplay caused by the installation. The game can initiate the installation at any time. However, because the installation consumes processor cycles, it is generally not a good idea to perform the installation when the primary thread is in critical need of processing power, such as when the user is in the middle of the action. For example, a good time to perform the installation may be during the time the user is in the game menu, when the game is paused or minimized, or when the user is watching the introduction movie or cutscenes.

Patching Support

Most games today need to be updated even after they ship as bugs get fixed and new features get added. Updating often requires patching, which is traditionally a straightforward procedure for games. Because all of the necessary files are installed onto the user's hard drive, patching a game involves copying revised files onto the hard drive, overwriting existing files. When install-on-demand is employed, not all files are installed and copied at the time of patching. Therefore, the patcher cannot simply write updated files onto the game folder.

Windows Installer has features for patching applications that use install-on-demand. When applying a patch, the installer caches the patch onto the system. This feature works well for patches with small deltas. The originally released files no longer need to be on the disk at the time of patching, so those files can be advertised. Later, when the application runs and needs to access the files, the installer installs the most recent version of those files by copying the originally released version from the media (for example, CDs) and applying the patch after reading the saved patch data.

The InstallOnDemand SDK Sample

The Install-on-Demand for Games sample demonstrates the install-on-demand techniques discussed in this article. Unlike other samples, Install-on-Demand for Games cannot be run directly from the sample browser. Because the sample uses the Windows Installer to manage its installation, it needs to be included in the installer's database of installed applications. To launch the sample:

  1. Use the Install Project link in the sample browser to copy the sample's files to a folder.
  2. Double click InstallOnDemand.msi to install the sample.
  3. Select Typical Install.
  4. Start the sample by launching the InstallOnDemand.exe in the installed folder (typically Program Files\InstallOnDemand) or by launching from Start Menu\Programs.

InstallOnDemand.msi is a database recognized by the installer. It defines the entire installation process: the directory structure, what will and will not be copied, what resources will be copied together, what registry values to write, what shortcuts to create, and so forth.

When launched, the sample plays an introduction sequence. The player can end it and enter the main menu by pressing the ESC key. Following the introduction, the player can start a new game by entering a character name and scrolling through the statistics. Before the sample begins to play the introduction sequence, the sample calls an installer function to check if the feature for level 1 is installed. If the level 1 feature has not been installed, the sample uses a background thread to ask the installer to install the game, while the primary thread is doing something else (such as playing the introduction sequence, rendering the menu, or interacting with the player on character creation). The experience is different from traditional game installation in that the user is occupied in the game (watching the introduction or creating a new character) while installation is in progress. After the player has finished creating a character, the sample loads the resources for level 1.

On the right side of the sample screen are five buttons marked "Play Level 1" through "Play Level 5." These buttons simulate the player's completion of the current level and advancement to the next. When one of these buttons is clicked, a statistics screen appears showing information about the level that he has just finished. The sample also takes this time to ask the installer to check and install the next level, if it is not already installed. The installation occurs while the player is reading the statistics screen, so that when the user clicks OK to enter the next level, the level's resources are all installed and ready to be loaded.

The Sample's Features and Components

Traditionally, games require that all or most of the files be installed prior to launching. In order to achieve install-on-demand, the game resources need to be modular; that is, the developer must divide the application's resources (graphics, audio, and so on) into components. Each component is a set of resources that can be installed or removed as a unit. Once this is done, the game developer defines one or more features, typically one or more per level or zone. Each feature of an application specifies a set of components necessary for running that particular feature. When an application is installed, its features can be marked as "install" (components copied to the local hard drive at installation time) or "advertised" (components copied to the local hard drive when the application later uses that feature). A game developer can reduce the installation time by designing the game to launch and start running with a minimal set of features installed. The rest of its features can be marked as advertised and installed on-demand when the application actually needs to use functionalities that those features provide.

The following table lists the six top-level features that the sample defines.

Feature Name | Functionality | Components | Files
Core | Includes resources required at all times, regardless of level. These resources are: sample executable, media required by introduction sequence and loading screen, and .fx file that handles all rendering in the sample. | Core | InstallOnDemand.exe, InstallOnDemand.fx, Loading.bmp, Level.x
Core | (same as above) | CoreUI | Media\UI\dxutcontrols.dds, Media\UI\DXUTShared.fx, Media\UI\arrow.x
Core | (same as above) | CoreMisc | Media\Misc\seafloor.x, Media\Misc\seafloor.bmp
Core | (same as above) | CoreSpeeder | Media\PRT Demo\LandShark.x, Media\PRT Demo\speeder_diff.jpg
Core | (same as above) | CoreReg | N/A (registry value)
Level1 | Provides resources used by level 1. | Level1 | Level1.jpg
Level1 | (same as previous) | L1Skybox | Media\Light Probes\galileo_cross.dds
Level2 | Provides resources used by level 2. | Level2 | Level2.jpg
Level2 | (same as previous) | L2Skybox | Media\Light Probes\grace_cross.dds
Level3 | Provides resources used by level 3. | Level3 | Level3.jpg
Level3 | (same as previous) | L3Skybox | Media\Light Probes\rnl_cross.dds
Level4 | Provides resources used by level 4. | Level4 | Level4.jpg
Level4 | (same as previous) | L4Skybox | Media\Light Probes\stpeters_cross.dds
Level5 | Provides resources used by level 5. | Level5 | Level5.jpg
Level5 | (same as previous) | L5Skybox | Media\Light Probes\uffizi_cross.dds

The Level1 through Level5 features have additional sub-features that contain files not directly used by the sample. These sub-features files have been added to make the installation take longer. This is done to illustrate the ongoing installation operation that is running in the background while the sample is running.

The following table lists the sub-features.

Feature | Sub-features | Files
Level1 | L1PH1, L1PH2, L1PH3, L1PH4, L1PH5 | Level1 Placeholder Data\L1PH1.dat Level1 Placeholder Data\L1PH2.dat Level1 Placeholder Data\L1PH3.dat Level1 Placeholder Data\L1PH4.dat Level1 Placeholder Data\L1PH5.dat
Level2 | L2PH1, L2PH2, L2PH3, L2PH4, L2PH5 | Level2 Placeholder Data\L2PH1.dat Level2 Placeholder Data\L2PH2.dat Level2 Placeholder Data\L2PH3.dat Level2 Placeholder Data\L2PH4.dat Level2 Placeholder Data\L2PH5.dat
Level3 | L3PH1, L3PH2, L3PH3, L3PH4, L3PH5 | Level3 Placeholder Data\L3PH1.dat Level3 Placeholder Data\L3PH2.dat Level3 Placeholder Data\L3PH3.dat Level3 Placeholder Data\L3PH4.dat Level3 Placeholder Data\L3PH5.dat
Level4 | L4PH1, L4PH2, L4PH3, L4PH4, L4PH5 | Level4 Placeholder Data\L4PH1.dat Level4 Placeholder Data\L4PH2.dat Level4 Placeholder Data\L4PH3.dat Level4 Placeholder Data\L4PH4.dat Level4 Placeholder Data\L4PH5.dat
Level5 | L5PH1, L5PH2, L5PH3, L5PH4, L5PH5 | Level5 Placeholder Data\L5PH1.dat Level5 Placeholder Data\L5PH2.dat Level5 Placeholder Data\L5PH3.dat Level5 Placeholder Data\L5PH4.dat Level5 Placeholder Data\L5PH5.dat

During installation, the core feature should be marked "install" and all other features should be marked "advertised." By only installing one feature instead of six, the time that the player must wait until the game launches is significantly reduced.

Installation

The Windows Installer provides a mechanism for an application to request that an advertised feature be installed. However, the mechanism is a synchronous application programming interface (API) call, which means that the application has to wait inside the call until the installation is complete. To achieve background installation, a worker thread is required so that the main application thread is free to perform other important tasks, such as rendering on the screen to continue giving the player visual feedback.

In the sample, there are three states of installation that happen during the sample execution: active installation, passive installation, and no installation.

  • Active installation is a request initiated by the sample when it needs to access or load resources provided by one or more features. The sample does this when it can not continue until the resource is installed.
  • Passive installation is initiated when the sample is not performing a critical task such as when the player is at a menu or watching a cut scene. When this is the case, the worker thread checks if any feature of the sample is still advertised. If it can find one, it calls the installer to install that feature. This process repeats until every feature of the sample is installed. Essentially, passive installation utilizes extra processor cycles to perform installation in the background when it is least intrusive to the main sample.
  • No installation happens when the player is actively engaged in the game; this prevents a framerate drop which would disrupt the user experience.

In the sample, a class CMsiUtil is defined to handle all installation-related tasks. Essentially, CMsiUtil uses a worker thread that invokes the installer to install the sample's features in a loop. The class has two queues that store installation requests: one high priority queue for active installation and one low priority queue for passive installation. During initialization, the class enumerates all features of the product and adds them to the passive installation queue. Because the entire product is queued this way, the entire product will eventually be installed if the sample has enough free processor cycles.

When the sample needs to request an active installation, the sample can call CMsiUtil::UseFeatureSet() and pass the name of the top-level feature. UseFeatureSet() will queue the requested feature and all of its sub-features in the active installation queue so that the worker thread can install them.

While executing an install request, the worker thread will check the active installation queue as well as the passive installation queue to see if either queue has any additional requests. Each time the thread finds a request, it will call the installer API to perform the actual installation. Once both queues are empty, the worker thread will go to sleep with a call to WaitForSingleObject. Because the entire product is placed in the passive installation queue during initialization, an empty queue implies that the entire product has been installed.

The sample calls CMsiUtil::EnablePassiveInstall() to enable or disable passive installation. EnablePassiveInstall(true) increments the enable count for passive installation, and EnablePassiveInstall(false) decrements it. If the enable count is greater than 0, the class will process the passive installation queue. The sample allows passive installation when any of the following is true:

  • The user is viewing the initial introduction sequence.
  • The user is navigating in the sample menu.
  • The user is viewing the statistics at the end of a level.
  • The sample application loses its focus and goes to the background.

The methods of CMsiUtil are listed below:

Method | Description
AbortAllRequests | Causes the current installation to abort and empties the active installation request queue.
AbortCurrentRequest | Causes the installation in progress to abort. The worker thread then processes the next request in the queue, if one exists.
EnablePassiveInstall | Increments or decrements passive installation enable count. The sample uses this call to control when passive installation can and cannot happen.
GetCurrentFeatureName | Returns the name of the feature that is actively being installed.
GetFeatureProgress | Returns the current tick position for the feature that is being installed.
GetFeatureProgressMax | Returns the maximum number of progress tick for the feature that is being installed.
GetLastError | Use this method to retrieve the return code from the previous installation request.
GetPassiveProgress | Returns the progress bar tick position for passive installation.
GetPassiveProgressMax | Returns the current tick position and the maximum number of ticks for passive installation. Together, the sample can use them to show the overall progress of the passive installation.
GetProgress | Returns the progress bar tick position for the active feature set installation. This is used when the sample renders the installation progress bar. Because the Windows Installer only provides progress information for the one feature being installed, the method divides the progress bar among the requested features so that the user still sees the entire installation as one task.
GetProgressMax | Returns the maximum progress bar tick count for the active feature set installation. This is used when the sample renders the installation progress bar.
Initialize | Initializes the class with the product globally unique identifier (GUID). This method also enumerates every feature of the application which has been advertised but not yet installed, and places it in the passive installation queue to set up the passive installation.
IsInstallInProgress | Use this method to find out whether an active installation is being processed.
UseFeature | Private method called by UseFeatureSet. Checks if a feature is installed. If the requested feature is installed the method returns. If the feature is not yet installed (advertised), the method queues a new active installation request for the worker thread and then returns. The optional event handle that will be signaled when the requested installation is complete.
UseFeatureSet | Called by the sample when it needs to access functionalities provided by a particular feature or any of its sub-features. The method enumerates all features of the sample and calls UseFeature() for sub-features of the specified root feature. The sample can pass in an event handle that will be signaled when the entire feature set is installed. Because the features all installed as a set, The handle is specified for the last feature queued by UseFeature() instead of every feature, so that the sample gets notified once after all requested features are installed.
UseProduct | Queues an active installation request for the worker thread to call the installer to perform a full product installation. The optional event handle that will be signaled when the requested installation is complete.

Limitation

The current version of installer is not designed for simultaneous access by multiple threads. Therefore, when the worker thread is calling into the installer, the main thread should not call the installer. An example of this limitation occurs in the sample when the main thread requests a feature, then requests the same feature again before the worker thread completes the installation. The second request calls MsiQueryFeatureState() to find out whether the requested feature is already installed, since the installer may sometimes indicate that the feature is completely installed when the worker thread is still copying the files.

Fortunately, there is an easy work-around for this. CMsiUtil will check whether a feature is being installed by the worker thread before it calls functions such as MsiQueryFeatureState() or MsiUseFeature() to ask for the install state of the feature in question. Be aware that this limitation can also become an issue elsewhere.

Patching can affect how well install-on-demand works on an end-user's computer. Applying a patch that only contains data that has changed from the previous version may require that the previous version of the updated file be installed in order to apply the delta. In this situation, the patch must request that the installer install affected advertised features before applying the patch to the game.

The sample is installed by launching InstallOnDemand.msi because it assumes that the Windows Installer is present on the computer. If the installer is absent, .msi files are not recognized and launching them will not work. To overcome this problem, an application should use an installation program to perform the task. This program should first check to see if the installer is present, and if so, its version. If the version does not meet the application's requirement, the installation program should install the Windows Installer, then launch the .msi file. This process is known as bootstrapping. Applications typically name their bootstrapping installation program Setup.exe. The sample does not handle bootstrapping. However, complete details on bootstrapping can be found in the Windows Installer.

Developers should also pay attention to the size of each feature in their games. When canceling an installation in progress, the installer restores the computer to the state before the installation. This means that the installation of the feature is completely undone, and there is no partial feature installation. A large feature requires longer time to install, which either increases the likelihood that the install will be interrupted and cancelled or the install will interfere with the main application. An example would be enabling passive installation when the user brings up the game menu in the middle of game play. If a feature is installing and the user goes back to playing, the game can do one of two things: it can let the passive installation complete, or it can cancel the passive installation. A large feature would fit poorly with either model. If the game lets the large installation complete, the installation may hinder the game's rendering performance for a long time. Conversely, if the game cancels the installation, then the user must stay in the menu for a long time before returning to the game. Developers should find a balanced feature size that works best for their individual games.


Installation and Maintenance of Games

By Dave Bartolomeo, Software Design Engineer

Microsoft Corporation

July 2003

This article describes a set of best practices that can help reduce user frustration about the time required to install a game, prevent unnecessary support calls, and allow users to start playing your game as quickly and painlessly as possible.

This article is divided into the following parts: Initial Installation and Post-Installation Game-Play.

Initial Installation

Users buy games because they enjoy playing them, not because they enjoy installing them. Installing a game should be as quick, straightforward, and as painless as possible for the end user. Ideally, end users should not even see an installation UI; they should be able to just drop the game disc into the tray and begin playing.

Streamlining the Installation UI

Common aspects of existing game installation UIs interfere with the desired end-user experience:

  • Asking the user unnecessary questions.

    For example, many games ask if the user wants to install DirectX. If the game requires Microsoft DirectX to run, and the right version of DirectX isn't installed already, the game should simply install DirectX.

  • Asking the user questions that a vast majority of users will answer in the same way.

    For typical users, the default settings for installation path, Start menu location, and so on, are all fine. Offer advanced options for users who want to change these settings.

The installation UI should be designed to allow the typical user to begin playing the game as soon as possible. If AutoRun is enabled on the user's computer, which is the default, the setup program should assume that the user wants to be playing the game as soon as possible, bypassing any unnecessary questions. The setup program should begin installing the game to the default installation path, preferably using a setup like that described in Install on Demand. It is appropriate to give users a chance to change the installation settings before automatically starting the installation. However, this should be accomplished by prompting the user to hit a key for advanced setup options, and then proceeding automatically with the default options if the user does not hit that key within five to ten seconds.

If AutoRun is not enabled on the user's computer, the setup program should assume that the user does not want the setup program to begin installing the game automatically. If the setup program is started by some means other than AutoRun, it should launch the advanced setup UI.

Reducing the Time Required for Installation

Most Microsoft Windows games today take anywhere from five minutes to half an hour to finish the installation process. In contrast, most console games take no more than thirty seconds from the time the user inserts the game CD to the time the user can play the game. This difference is due to the fact that most Windows games are designed to run most, if not all, of their content from the computer's hard drive; consoles, which lack a place to permanently store large amounts of content, require that the content be run from the source media. While loading content from the local hard drive makes for faster in-game load times, the downside is that all of that content has to be copied from the source media to the hard drive at some point. Most Windows games choose to copy all of the content to the hard drive all at once, as part of an installation process. This detracts from the user's initial experience with the game by making the user watch a progress bar for several minutes before being able to play the game.

There are two approaches that can be used to minimize the time spent initially installing the game: Minimal Installation and Install on Demand.

Minimal Installation

In a minimal installation scenario, the game installs only a bare minimum set of content to the hard drive. Usually, this consists of only the game executable and DLLs. The remainder of the content is accessed directly from the source media. This drastically reduces the time required to install, since a game's executable is rarely larger than 10-20 MB. The drawback is that the game takes longer to load content during the game, since it must load it from the slower source media.

To create a minimal installation configuration in a Windows Installer-based setup:

  • Group all of the components to be installed to the hard drive into a feature that is marked to install locally.

    This feature will be referred to as the "Bootstrap" feature.

  • Group all of the components that are to be run from the source media into a feature that is marked as "run from source."

  • When opening a file that might be on the source media, use the MsiGetComponentPath function to determine the path to the file, instead of hard-coding the path.

    Doing so ensures that the file can be found even if the drive letter of the user's CD/DVD drive changes.

  • Compress content that stays on the CD/DVD.

    The amount of CPU time spent decompressing the content will usually be hidden by the slow transfer rate of data from the CD/DVD drive.

  • Group content into large, contiguous files and access it in sequential order.

    The seek times of CD/DVD drives are abysmal compared to those of hard drives, and most CD/DVD drives don't reach peak transfer rates unless they are reading a large, contiguous file.

  • Lay out content on the CD/DVD in the order that it is likely to be accessed.

    Seek times are greatly reduced when files are accessed in the same order as their on-disk layout.

Install on Demand

In an install-on-demand scenario, as for minimal installation, the game initially installs to the hard drive only those files necessary to start the game. However, instead of accessing the remaining content from the source media every time it is needed, the game actually installs each piece of content to the hard drive as it is needed for the first time, and then accesses it from the local hard drive on each subsequent use. The time required for the initial installation is just as small as in for a minimal installation, but after the first time that each piece of content is accessed, the load times improve.

To create an install-on-demand configuration in a Windows Installer-based setup:

  • Group all of the components to be initially installed to the hard drive into a feature that is marked to install locally.

    Note that this is identical to the Bootstrap feature for a minimal installation.

  • Group the remaining content into multiple features based on components likely to be used together.

    For example, in a level-based game, group all the content used on a given level into one feature. Note that Windows Installer allows a component to be shared by multiple features, so if you have content that is used on multiple levels, you can add that content to the features for all of the necessary levels without replicating the content. All of these features should be marked as "Advertised", which means that they won't be installed initially, but can be installed later as needed.

  • When a file is needed, first check whether the file is already installed using the function MsiQueryFeatureState.

    If it is not yet installed (that is, its state is INSTALLSTATE_ADVERTISED), call the function MsiConfigureFeature to install the feature locally. When opening the file after it is installed, call MsiGetComponentPath to determine the path to the file. While not strictly necessary for this scenario (since the content will always be installed to the hard drive before it is used), this makes it easier to support minimal installation in addition to installation on demand.

  • If possible, anticipate what content is likely to be needed soon, and install it in the background during idle time.

    Background installation is most appropriate when the game is at a point that doesn't need every last ounce of performance out of the computer; for example, while displaying an intro movie, cut-scene, menu, and so on.

  • Create an option in the game's options menu to force installation of all remaining content.

    To implement this, create a feature that is a parent of all of the install-on-demand features, and then call MsiConfigureFeature to install this master feature locally. This will cause the subfeatures to be installed locally as well.

  • Content layout should be similar to that for a minimal installation, except that content should be clustered only with other content that is likely to be needed at the same time (for example, all of the content for one level should be together).

Post-Installation Game-Play

AutoRun

To play a game that is already installed, the user should only need to drop the installation disc in the drive tray. The first thing that the AutoRun executable on the disc should do is to check to see if the game has already been installed, and if so, launch the game. Assuming that the game was installed using a Windows Installer-based setup, the check to determine if the game is installed can be accomplished with a single call to the function MsiQueryProductState.

Converting an Install-on-Demand Installation to a Full Installation

While an install-on-demand installation allows the user to begin playing the game much sooner than a full installation, a user may want to explicitly install the remainder of the game content to the local hard drive. The user may want to be able to play the game without requiring the source media, or he or she may simply want to avoid the longer in-game load times that result from installing content on demand. If the game's setup uses Windows Installer, the game can provide an option in the in-game options UI to finish installing the remaining content. When the user selects this option, the game can call MsiConfigureFeature to force the remaining features to be installed locally; there is no need to spawn a separate setup application to do so.

Maintenance of Game Software and Content

One of the advantages that Windows games have over console games is the relative ease with which the publisher can release updates to the game after its initial release. Whether these updates introduce new content or just fix bugs, it is important to make the update process as easy as possible for the end user. The update process is even more important for online games, which typically require that all users are running the latest version of the game in order to connect.

Checking for Updates Automatically

Users should not have to remember to go looking for patches. If there is an update available for the game, the user should at least be notified, and ideally, the patch should already be downloaded.

A simple way for a game to check for updates is to connect to a Web server hosted by the publisher using a specific URL, and download a text file that specifies the version number of the latest available version of the game, along with a URL from which to download a package that will update the game to the latest version.

Checking for updates each time that the user plays the game is adequate to make sure that the user is running the latest version. However, if the existence of a new update is discovered immediately before the user tries to play the game, the user may be forced to delay playing the game until the update has finished downloading. For large updates or slow connections, this delay may be on the order of hours. To avoid forcing the user to wait before playing the game, the game can use Task Scheduler to schedule periodic checks for new updates. If an update is detected, the game can begin downloading the update immediately, so that it is likely to be completely downloaded and ready to install by the next time the user plays the game.

Downloading Patches Automatically

Once the game has detected that a new update is available, it should immediately begin downloading the update. Since the task that checks for updates is typically running silently in the background, the download needs to be as unobtrusive as possible. The Background Intelligent Transfer Service (BITS) is an operating system feature that allows applications to download files from the Internet even while the application itself is not running. BITS download jobs run only when the user is logged on, and only when the machine is already connected to the network. BITS will not attempt to force the machine to connect to the network on its own. If the user disconnects from the network, or logs off, the BITS job is paused, and will resume downloading the next time the user logs in and connects to the network. The application can configure its BITS jobs to use only network bandwidth that would otherwise remain unused, in order to prevent the job from impacting the performance of any other applications that might be using the network (for example, an online game). BITS is available on Windows XP and Windows 2000 Service Pack 3.

Other Resources

For more information on the technologies referenced in this paper, refer to the relevant sections of the MSDN Library:

  • Windows Installer
  • Task Scheduler
  • Background Intelligent Transfer Service (BITS)

For more information on using Windows Installer for games, tune in to next month's Driving DirectX column, "Introduction to Windows Installer for Game Developers."

See Also

MsiConfigureFeature, MsiQueryProductState, MsiQueryFeatureState, MsiGetComponentPath


Lockless Programming Considerations for Xbox 360 and Microsoft Windows

By Bruce Dawson, Software Design Engineer

XNA Developer Connection (XDC)

February 2007

Lockless programming is a way to safely share changing data between multiple threads without the cost of acquiring and releasing locks. This sounds like a panacea, but lockless programming is complex and subtle, and sometimes doesn't give the benefits that it promises.

Using lockless programming correctly and safely requires significant knowledge of both your hardware and your compiler. Hardware and compiler differences between Xbox 360 and Windows make lockless programming on Xbox 360 particularly complex.

Lockless programming is a valid technique for multi-threaded programming, but it should not be used lightly. Before using it you must understand the complexities, and you should measure carefully to make sure that it is actually giving you the gains that you expect. In many cases there are simpler and faster solutions, such as sharing data less frequently, which should be used instead.

This paper gives an overview of some of the issues to consider when trying to use lockless programming techniques.

Programming with Locks

When writing multi-threaded code it is often necessary to share data between threads. If multiple threads are simultaneously reading and writing the shared data structures, then memory corruption can occur. The simplest way of solving this problem is using locks. For instance, if ManipulateSharedData should only be executed by one thread at a time, then a CRITICAL_SECTION can be used to guarantee this, as in the following code:

// Initialize
CRITICAL_SECTION cs;
InitializeCriticalSection(&cs);

// Use
void ManipulateSharedData()
{
    EnterCriticalSection(&cs);
    // Manipulate stuff...
    LeaveCriticalSection(&cs);
}

// Destroy
DeleteCriticalSection(&cs);

This code is fairly simple and straightforward, and it is easy to tell that it is correct. However, programming with locks comes with several potential disadvantages. For eample, if two threads try to acquire the same two locks but acquire them in a different order, then a deadlock may result. If a program holds a lock for too long—because of poor design or because the thread has been swapped out by a higher priority thread—then other threads may be blocked for a long time. This risk is particularly great on Xbox 360, because the software threads are assigned a hardware thread by the developer, and the operating system won't move them to another hardware thread, even if one is idle. The Xbox 360 also has no protection against priority inversion, where a high-priority thread spins in a loop while waiting for a low-priority thread to release a lock. Finally, if a deferred procedure call or interrupt service routine tries to acquire a lock, then a deadlock may occur.

Despite these problems, synchronization primitives, such as critical sections, are generally the best way of coordinating multiple threads. If the synchronization primitives are too slow, then the best solution is usually to use them less frequently. However, for those who can afford the extra complexity, another option is lockless programming.

Lockless Programming

Lockless programming, as the name suggests, is a family of techniques for safely manipulating shared data without using locks. There are lockless algorithms available for passing messages, sharing lists and queues of data, and other tasks.

When doing lockless programming, there are two challenges that you must deal with: non-atomic operations and reordering.

Non-Atomic Operations

An atomic operation is one that is indivisible—one where other threads are guaranteed to never see the operation when it is half done. Atomic operations are important for lockless programming, because without them, other threads might see half-written values, or otherwise inconsistent state.

On all modern processors, you can assume that reads and writes of naturally aligned native types are atomic. As long as the memory bus is at least as wide as the type being read or written, the CPU reads and writes these types in a single bus transaction, making it impossible for other threads to see them in a half completed state.

Reads and writes of types that are not naturally aligned—for instance, writing DWORDs that cross four-byte boundaries—are not guaranteed to be atomic. The CPU may have to do these reads and writes as multiple bus transactions, which could allow another thread to modify or see the data in the middle of the read or write.

Composite operations, such as the read-modify-write sequence that occurs when you increment a shared variable, are not atomic. On Xbox 360 these operations are implemented as multiple instructions (lwz, addi, and stw), and the thread could be swapped out partway through the sequence. On x86 there is a single instruction (inc) that can be used to increment a variable in memory. If this instruction is used, then incrementing a variable is atomic on single-processor systems, but it is still not atomic on multi-processor systems. Making inc atomic on x86-based multi-processor systems requires using the lock prefix, which prevents another processor from doing its own read-modify-write sequence between the read and the write of the inc instruction.

The following code shows some examples:

// This write is not atomic because it is not natively aligned.
DWORD* pData = (DWORD*)(pChar + 1);
*pData = 0;

// This is not atomic because it is three separate operations.
++g_globalCounter;

// This write is atomic.
g_alignedGlobal = 0;

// This read is atomic.
DWORD local = g_alignedGlobal;

Guaranteeing Atomicity

You can be sure you are using atomic operations by a combination of the following:

  • naturally atomic operations
  • locks to wrap composite operations
  • operating system functions that implement atomic versions of popular composite operations

Incrementing a variable is not an atomic operation, and incrementing may lead to data corruption if executed on multiple threads.

// This will be atomic.
g_globalCounter = 0;

// This is not atomic and gives undefined behavior
// if executed on multiple threads
++g_globalCounter;

Win32 comes with a family of functions that offer atomic read-modify-write versions of several common operations. These are the Interlocked Xxx family of functions. If all modifications of the shared variable use these functions, then the modifications will be thread safe.

// Incrementing our variable in a safe lockless way.
InterlockedIncrement(&g_globalCounter);

Reordering

A more subtle problem is reordering. Reads and writes do not always happen in the order that you have written them in your code, and this can lead to very confusing problems. In many multi-threaded algorithms, a thread writes some data and then writes to a flag that tells other threads that the data is ready. This is known as a write-release. If the writes are reordered then other threads may see that the flag is set before they can see the written data.

Similarly, in many cases a thread reads from a flag and then reads some shared data if a flag says that the thread has acquired access to the shared data. This is known as a read-acquire. If reads are reordered then the read of the flag may occur at a later time than the reads of the data, and the data may be out of date.

Reordering of reads and writes can be done both by the compiler and by the processor. Compilers and processors have done this reordering for years, but on single-processor machines it was less of an issue. This is because CPU rearrangement of reads and writes is invisible on single-processor machines (for non-device driver code that is not part of a device driver), and compiler rearrangement of reads and writes is less likely to cause problems on single-processor machines.

If the compiler or the CPU rearranges the writes shown in the following code, then another thread may see that the alive flag is set while still seeing the old values for x or y. Similar rearrangement can happen when reading.

In this code, one thread adds a new entry to the sprite array:

// Create a new sprite by writing its position into an empty
// entry and then setting the ‘alive' flag. If ‘alive' is
// written before x or y then errors may occur.
g_sprites[nextSprite].x = x;
g_sprites[nextSprite].y = y;
g_sprites[nextSprite].alive = true;

In this next code block, another thread reads from the sprite array:

// Draw all sprites. If the reads of x and y are moved ahead of
// the read of ‘alive' then errors may occur.
for( int i = 0; i < numSprites; ++i )
{
    if( g_sprites[nextSprite].alive )
    {
        DrawSprite( g_sprites[nextSprite].x,
                g_sprites[nextSprite].y );
    }
}

To make this sprite system safe, we need to prevent both compiler and CPU reordering of reads and writes.

Understanding CPU Rearrangement of Writes

Some CPUs rearrange writes so that they are externally visible to other processors or devices in non-program order. This rearranging is never visible to single-threaded non-driver code, but it can cause problems in multi-threaded code.

Xbox 360

While the Xbox 360 CPU does not reorder instructions, it does rearrange write operations, which complete after the instructions themselves. This rearranging of writes is specifically allowed by the PowerPC memory model.

Writes on Xbox 360 do not go directly to the L2 cache. Instead, in order to improve L2 cache write bandwidth, they go through store queues and then to store-gather buffers. The store-gather buffers allow 64-byte blocks to be written to the L2 cache in one operation. There are eight store-gather buffers, which allow efficient writing to several different areas of memory.

The store-gather buffers are normally written to the L2 cache in first-in-first-out (FIFO) order. However if the target cache-line of a write is not in the L2 cache, then that write may be delayed while the cache-line is fetched from memory.

Even when the store-gather buffers are written to the L2 cache in strict FIFO order, this does not guarantee that individual writes are written to the L2 cache in order. For instance, imagine that the CPU writes to location 0x1000, then to location 0x2000, and then to location 0x1004. The first write allocates a store-gather buffer and puts it at the front of the queue. The second write allocates another store-gather buffer and puts it next in the queue. The third write adds its data to the first store-gather buffer, which remains at the front of the queue. Thus, the third write ends up going to the L2 cache before the second write.

Reordering caused by store-gather buffers is fundamentally unpredictable, especially because both threads on a core share the store-gather buffers, making the allocation and emptying of the store-gather buffers highly variable.

This is one example of how writes can be reordered. There may be other possibilities.

x86

While x86 CPUs do reorder instructions, they generally do not reorder write operations. There are some exceptions for write-combined memory. Additionally, some string operations (MOVS and STOS) can be internally reordered, but normal writes are not reordered.

Understanding CPU Rearrangement of Reads

Some CPUs rearrange reads so that they effectively come from shared storage in non-program order. This rearranging is never visible to single-threaded non-driver code, but can cause problems in multi-threaded code.

Xbox 360

Cache misses can cause some reads to be delayed, which effectively causes reads to come from shared memory out of order, and the timing of these cache misses is fundamentally unpredictable. This is just one example of how reads can be reordered. There may be other possibilities. This rearranging of reads is specifically allowed by the PowerPC memory model.

x86

The guarantees for reordering of reads on x86 are not well documented, and the documented behavior may be conservative compared to actual implementations. Contact your processor manufacturer if you need precise read-reordering guarantees for x86 processors.

Read-Acquire and Write-Release Barriers

The main constructs used to prevent reordering of reads and writes are called read-acquire and write-release barriers. A read-acquire is a read of a flag or other variable to gain ownership of a resource, coupled with a barrier against reordering. Similarly, a write-release is a write of a flag or other variable to give away ownership of a resource, coupled with a barrier against reordering.

The formal definitions, courtesy of Herb Sutter, are:

  • A read-acquire executes before all reads and writes by the same thread that follow it in program order.
  • A write-release executes after all reads and writes by the same thread that precede it in program order.

When your code acquires ownership of some memory, either by acquiring a lock or by pulling an item off of a shared linked list (without a lock), there is always a read involved — testing a flag or pointer to see if ownership of the memory has been acquired. This read may be part of an Interlocked Xxx operation, in which case it involves both a read and a write, but it is the read that indicates whether ownership has been gained. After ownership of the memory is acquired, values are typically read from or written to that memory, and it is very important that these reads and writes execute after acquiring ownership. A read-acquire barrier guarantees this.

When ownership of some memory is released, either by releasing a lock or by pushing an item on to a shared linked list, there is always a write involved which notifies other threads that the memory is now available to them. While your code had ownership of the memory, it probably read from or wrote to it, and it is very important that these reads and writes execute before releasing ownership. A write-release barrier guarantees this.

It is simplest to think of read-acquire and write-release barriers as single operations; however, they sometimes have to be constructed from two parts: a read or write and a barrier that does not allow reads or writes to move across it. In this case, the placement of the barrier is critical. For a read-acquire barrier, the read of the flag comes first, then the barrier, and then the reads and writes of the shared data. For a write-release barrier the reads and writes of the shared data come first, then the barrier, and then the write of the flag.

// Read that acquires the data.
if( g_flag )
{
    // Guarantee that the read of the flag executes before
    // all reads and writes that follow in program order.
    BarrierOfSomeSort();

    // Now we can read and write the shared data.
    int localVariable = sharedData.y;
    sharedData.x = 0;

    // Guarantee that the write to the flag executes after all
    // reads and writes that precede it in program order.
    BarrierOfSomeSort();

    // Write that releases the data.
    g_flag = false;
}

The only difference between a read-acquire and a write-release is the location of the memory barrier. A read-acquire has the barrier after the lock operation, and a write-release has the barrier before. In both cases the barrier is in-between the references to the locked memory and the references to the lock.

To understand why barriers are needed both when acquiring and when releasing data, it is best (and most accurate) to think of these barriers as guaranteeing synchronization with shared memory, not with other processors. If one processor uses a write-release to release a data structure to shared memory, and another processor uses a read-acquire to gain access to that data structure from shared memory, then the code will work properly. If either processor doesn't use the appropriate barrier, then the data sharing may fail.

Using the right barrier to prevent compiler and CPU reordering for your platform is critical.

One of the advantages of using the synchronization primitives provided by the operating system is that all of them include the appropriate memory barriers.

Preventing Compiler Reordering

A compiler's job is to aggressively optimize your code in order to improve performance. This includes rearranging instructions wherever it is helpful and wherever it will not change behavior. Because the C++ Standard never mentions multithreading, and because the compiler doesn't know what code needs to be thread-safe, the compiler assumes that your code is single-threaded when deciding what rearrangements it can safely do. Therefore, you need to tell the compiler when it is not allowed to reorder reads and writes.

With Visual C++ you can prevent compiler reordering by using the compiler intrinsic _ReadWriteBarrier. Where you insert _ReadWriteBarrier into your code, the compiler will not move reads and writes across it.

#if _MSC_VER < 1400
    // With VC++ 2003 you need to declare _ReadWriteBarrier
    extern "C" void _ReadWriteBarrier();
#else
    // With VC++ 2005 you can get the declaration from intrin.h
    #include <intrin.h>
#endif
// Tell the compiler that this is an intrinsic, not a function.
#pragma intrinsic(_ReadWriteBarrier)

// Create a new sprite by filling in a previously empty entry.
g_sprites[nextSprite].x = x;
g_sprites[nextSprite].y = y;
// Write-release, barrier followed by write.
// Guarantee that the compiler leaves the write to the flag
// after all reads and writes that precede it in program order.
_ReadWriteBarrier();
g_sprites[nextSprite].alive = true;

In the following code, another thread reads from the sprite array:

// Draw all sprites.
for( int i = 0; i < numSprites; ++i )
{

    // Read-acquire, read followed by barrier.
    if( g_sprites[nextSprite].alive )
    {

        // Guarantee that the compiler leaves the read of the flag
        // before all reads and writes that follow in program order.
        _ReadWriteBarrier();
        DrawSprite( g_sprites[nextSprite].x,
                g_sprites[nextSprite].y );
    }
}

It is important to understand that _ReadWriteBarrier does not insert any additional instructions, and it does not prevent the CPU from rearranging reads and writes — it only prevents the compiler from rearranging them. Thus, _ReadWriteBarrier is sufficient when implementing a write-release barrier on x86 (because x86 does not reorder writes, and a normal write is sufficient for releasing a lock), but in most other cases, it is also necessary to prevent the CPU from reordering reads and writes.

_ReadWriteBarrier can also be used when writing to non-cacheable write-combined memory to prevent reordering of writes. In this case _ReadWriteBarrier helps to improve performance, by guaranteeing that the writes happen in the processor's preferred linear order.

It is also possible to use the _ReadBarrier and _WriteBarrier intrinsics for more precise control of compiler reordering.

Preventing CPU Reordering

CPU reordering is more subtle than compiler reordering. You can't ever see it happen directly, you just see inexplicable bugs. In order to prevent CPU reordering of reads and writes you need to use memory barrier instructions, on some processors. The all-purpose name for a memory barrier instruction, on Xbox 360 and on Windows, is MemoryBarrier. This macro is implemented appropriately for each platform.

On Xbox 360 MemoryBarrier is defined as lwsync (lightweight sync), also available through the __lwsync intrinsic, which is defined in ppcintrinsics.h. __lwsync also serves as a compiler memory barrier, preventing rearranging of reads and writes by the compiler.

The lwsync instruction is a memory barrier on Xbox 360 that synchronizes one processor core with the L2 cache. It guarantees that all writes before lwsync make it to the L2 cache before any writes that follow. It also guarantees that any reads that follow lwsync don't get older data from L2 than previous reads.

PowerPC also has the synchronization instructions sync (also known as heavyweight sync), eieio, and isync. These synchronization instructions should not be needed for normal synchronization purposes.

On Windows MemoryBarrier is defined in Winnt.h and gives you a different memory barrier instruction depending on whether you are compiling for x86 or x64.

On Xbox 360, and on many other CPUs, there is one additional way that read-reordering by the CPU can be prevented. If you read a pointer and then use that pointer to load other data, then the CPU guarantees that the reads off of the pointer are not older than the read of the pointer. If your lock flag is a pointer and if all reads of shared data are off of the pointer, then the MemoryBarrier can be omitted, for a modest performance savings.

Data* localPointer = g_sharedPointer;
if( localPointer )
{
    // No import barrier is needed--all reads off of localPointer
    // are guaranteed to not be reordered past the read of
    // localPointer.
    int localVariable = localPointer->y;
    // A memory barrier is needed to stop the read of g_global
    // from being speculatively moved ahead of the read of
    // g_sharedPointer.
    int localVariable2 = g_global;
}

The MemoryBarrier instruction only prevents reordering of reads and writes to cacheable memory. If you allocate memory as PAGE_NOCACHE or PAGE_WRITECOMBINE, a common technique for device driver authors and for game developers on Xbox 360, then MemoryBarrier has no effect on accesses to this memory. Synchronization of non-cacheable memory is not needed by most developers and is beyond the scope of this document.

Interlocked Functions and CPU Reordering

Sometimes the read or write that acquires or releases a resource is done using one of the Interlocked Xxx functions. On Windows this simplifies things, because on Windows, the Interlocked Xxx functions are all full-memory barriers — they effectively have a CPU memory barrier both before and after them, which means that they are a full read-acquire or write-release barrier all by themselves.

On Xbox 360 the Interlocked Xxx functions do not contain CPU memory barriers. They prevent compiler reordering of reads and writes but not CPU reordering. Therefore, in most cases when using Interlocked Xxx functions on Xbox 360, you should precede or follow them with an __lwsync, to make them a read-acquire or write-release barrier. For convenience and for easier readability there are Acquire and Release versions of many of the Interlocked Xxx functions. These come with a built-in memory barrier. For instance, InterlockedIncrementAcquire does an interlocked increment followed by an __lwsync memory barrier to give the full read-acquire functionality.

It is recommended that you use the Acquire and Release versions of the Interlocked Xxx functions (most of which are available on Windows as well, with no performance penalty) to make your intent more obvious and to make it easier to get the memory barrier instructions in the correct place. Any use of Interlocked Xxx on Xbox 360 without a memory barrier should be examined very carefully, because it is often a bug.

This sample demonstrates how one thread can pass tasks or other data to another thread using the Acquire and Release versions of the Interlocked Xxx SList functions. The Interlocked Xxx SList functions are a family of functions for maintaining a shared singly linked list without a lock. Note that Acquire and Release variants of these functions are not available on Windows, but the regular versions of these functions are a full memory barrier on Windows.

// Declarations for the Task class go here.

// Add a new task to the list using lockless programming.
void AddTask( DWORD ID, DWORD data )
{
    Task* newItem = new Task( ID, data );
    InterlockedPushEntrySListRelease( g_taskList, newItem );
}

// Remove a task from the list, using lockless programming.
// This will return NULL if there are no items in the list.
Task* GetTask()
{
    Task* result = (Task*)
            InterlockedPopEntrySListAcquire( g_taskList );
    return result;
}

Volatile Variables and Reordering

The C++ Standard says that reads of volatile variables cannot be cached, volatile writes cannot be delayed, and volatile reads and writes cannot be moved past each other. This is sufficient for communicating with hardware devices, which is the purpose of the volatile keyword in the C++ Standard.

However, the guarantees of the standard are not sufficient for using volatile for multi-threading. The C++ Standard does not stop the compiler from reordering non-volatile reads and writes relative to volatile reads and writes, and it says nothing about preventing CPU reordering.

Visual C++ 2005 goes beyond standard C++ to define multi-threading-friendly semantics for volatile variable access. Starting with Visual C++ 2005, reads from volatile variables are defined to have read-acquire semantics, and writes to volatile variables are defined to have write-release semantics. This means that the compiler will not rearrange any reads and writes past them, and on Windows it will ensure that the CPU does not do so either.

It is important to understand that these new guarantees only apply to Visual C++ 2005 and future versions of Visual C++, and that on Xbox 360, the compiler does not insert any instructions to prevent the CPU from reordering reads and writes.

Xbox 360 Performance

The performance of synchronization instructions and functions on Xbox 360 will vary depending on what other code is running. Acquiring locks will take much longer if another thread currently owns the lock. InterlockedIncrement and critical section operations will take much longer if other threads are writing to the same cache line. The contents of the store queues can also affect performance. Therefore, all of these numbers are just approximations, generated from very simple tests:

  • lwsync was measured as taking 33-48 cycles.
  • InterlockedIncrement was measured as taking 225-260 cycles.
  • Acquiring or releasing a critical section was measured as taking about 345 cycles.
  • Acquiring or releasing a mutex was measured as taking about 2350 cycles.

Windows Performance

The performance of synchronization instructions and functions on Windows vary widely depending on the processor type and configuration, and on what other code is running. Multi-core and multi-socket systems often take longer to execute synchronizing instructions. Acquiring locks take much longer if another thread currently owns the lock. However, even some measurements generated from very simple tests are helpful:

  • MemoryBarrier was measured as taking 20-90 cycles.
  • InterlockedIncrement was measured as taking 36-90 cycles.
  • Acquiring or releasing a critical section was measured as taking 40-100 cycles.
  • Acquiring or releasing a mutex was measured as taking about 750-2500 cycles.

The short times were on a single-processor machine, and the longer times were on a multi-processor machine.

While acquiring and releasing locks is more expensive than using lockless programming, it is even better to share data less frequently, thus avoiding the cost altogether.

Performance Thoughts

Acquiring or releasing a critical section consists of a memory barrier, an Interlocked Xxx operation, and some extra checking to handle recursion and to fall back to a mutex, if necessary. You should be wary of implementing your own critical section, because spinning in a loop waiting for a lock to be free, without falling back to a mutex, can waste considerable performance. For critical sections that are heavily contended but not held for long, you should consider using InitializeCriticalSectionAndSpinCount so that the operating system will spin for a while waiting for the critical section to be available rather than immediately deferring to a mutex if the critical section is owned when you try to acquire it. In order to identify critical sections that can benefit from a spin count, it is necessary to measure the length of the typical wait for a particular lock.

If a shared heap is used for memory allocations — the default behavior — then every memory allocation and free involves acquiring a lock. As the number of threads and the number of allocations increases, performance levels off, and eventually starts to decrease. Using per-thread heaps, or reducing the number of allocations, can avoid this locking bottleneck.

If one thread is generating data and another thread is consuming data, then they may end up sharing data frequently. This can happen if one thread is loading resources and another thread is rendering the scene. If the rendering thread references the shared data on every draw call, then the locking overhead will be high. Much better performance can be realized if each thread has private data structures which are then synchronized once per frame or less.

Platform Differences Summary

  • Interlocked Xxx functions prevent CPU read/write reordering on Windows, but not on Xbox 360.
  • Reading and writing of volatile variables using Visual Studio C++ 2005 prevents CPU read/write reordering on Windows, but on Xbox 360, it only prevents compiler read/write reordering.
  • Writes are reordered on Xbox 360, but not on x86.

Recommendations

  • Prefer using locks when possible, because they are easier to use correctly.
  • Avoid locking too frequently, so that locking costs do not become significant.
  • Avoid holding locks for too long, in order to avoid long stalls.
  • Use lockless programming when appropriate, but be sure that the gains justify the complexity.
  • Use lockless programming when sharing data between deferred procedure calls and normal code.
  • Only use standard lockless programming algorithms that have been proven to be correct.
  • When doing lockless programming, be sure to use volatile flag variables and memory barrier instructions as needed.
  • When using Interlocked Xxx on Xbox 360 use the Acquire and Release variants.

References

MSDN Library. "volatile (C++)." C++ Language Reference.
http://msdn2.microsoft.com/en-us/library/12a04hfd.aspx
Vance Morrison. "Understand the Impact of Low-Lock Techniques in Multithreaded Apps." MSDN Magazine, October 2005.
http://msdn.microsoft.com/msdnmag/issues/05/10/MemoryModels/default.aspx
Lyons, Michael. "PowerPC Storage Model and AIX Programming." IBM developerWorks, 16 Nov 2005.
http://www-128.ibm.com/developerworks/eserver/articles/powerpc.html
McKenney, Paul E. "Memory Ordering in Modern Microprocessors, Part II." Linux Journal, September 2005. [This article has some x86 details.]
http://www.linuxjournal.com/article/8212
Intel Architecture Software Developer's Manual, System Programming Guide, "Memory Ordering" section.
http://www.intel.com/
Niebler, Eric. "Trip Report: Ad-Hoc Meeting on Threads in C++." The C++ Source, 17 Oct 2006.
http://www.artima.com/cppsource/threads_meeting.html
Hart, Thomas E. 2006. "Making Lockless Synchronization Fast: Performance Implications of Memory Reclamation." Proceedings of the 2006 International Parallel and Distributed Processing Symposium (IPDPS 2006), Rhodes Island, Greece, April 2006.
http://www.cs.toronto.edu/~tomhart/papers/hart_ipdps06.pdf


Installation Best Practices for Massively Multiplayer Online Games

Kev Gee, Software Development Engineer

XNA Developer Connection (XDC)

February 2007

This document describes creating a chain of trust design for MMOG client installation and custom game update systems which works well with the Windows operating system and the new Windows Vista security model. The approach is designed to enable patching of MMOG titles while supporting standard user accounts which have restricted access to the hard drive and system registry.

Why MMOG Clients Have Different Requirements to Traditional Retail Purchased Games

The constantly connected and evolving nature of MMOGs makes it a fundamental requirement to provide regular updates of client code and content to fix security vulnerabilities and extend the gameplay experience. With the potential for almost daily updates, the MMOG scenario requires careful management to ensure a user friendly experience. This differs from the traditional retail purchase model where a small number of patches may be provided close to the retail ship date of the product. The Windows Installer limited user patching technology provided with the operating system is designed to handle small numbers of application patches, and not the large quantity and high frequency needed by MMOGs. It is therefore often necessary for custom patching systems to be developed to address the needs of MMOGs, including any special requirements specific to the particular MMOG being developed.

In the interests of providing a more secure computing environment in Windows Vista given the prevelance of Internect-connected PCs, the operating system has added tougher security restrictions and safeguards for users which limit the access rights of application code for various areas of the hard drive. Unlike Windows XP, these restrictions are enabled for the default mode for user accounts. These restrictions must be taken into account when designing the layout of a game executable and data and its associated patching system. For more details of the security measures provided in the operating system please see User Account Control for Game Developers.

Overview of a Chain of Trust Approach

The custom update approach presented in this whitepaper is based upon having a trustworthy loader application installed to the protected Program Files folder while keeping the games executable files and data in a shared all-user-accessible area. A chain of trust starts with the loader which performs validity checks on the game binaries and data before launch.

The trustworthy loader needs to have enough logic to be able to verify that the game's executable and other binaries have not been tampered with before launching the game. The loader may also verify game data as often as needed, however, the size of game data is usually too large to allow it be checked every time in a single pass. An alternative approach is to use a sampling pattern which ensures that verification of the entire data set occurs over an extended period of time. The loader application may contain a game patching engine, which provides a trust worthy method by to integrate updates with the installed game.

Everything is validated on the server, why should I worry if my client gets hacked?

It is impossible to trust that the client has not been compromised; therefore it is common for MMOG servers to validate all data received from the client. While this processing can identify compromised or cheating game clients within the game universe, the server cannot easily identify all issues the game client can be exposed to. It's important to strengthen protection from hackers who wish to use your client as a platform for attacks on your service, other users, or even simply as a vector for attacking the client machines themselves. The application of code signing and data verification techniques can help detect compromised clients before they get executed. Since the patching mechanism requires exposing executable and DLL binaries that are not protected by the standard read-only permissions on Program Files, validating these files before launching them is important for overall system security.

This model does not attempt to deal with the malicious admin user scenario where the loader itself could become compromised but focuses on protecting standard users from accidentally running tampered code. Traditional server-client validation techniques are really the only possible mitigation for malicious client system administrators.

Construction of the Trust-Worthy Loader Application

Background Reading

Readers should familiarize themselves with the following white papers which provide details of the foundation technology for ensuring best practice for software based trust.

Code Signing

Authenticode Signing for Game Developers

Sign Tool

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/seccrypto/security/signtool.asp

The following section details the APIs that should be used to construct the loader application which support disc layout for install and verification of trust checking.

Installation of the Trusted Loader and Patcher

The trusted loader and base version of the patcher utility should be installed under the protected Program Files folder on the HDD just as in traditional installs. Installation and patching of the loader application requires Admin rights so it is important to minimize the frequency of update for the loader to ensure end users do not need to elevate often, although Windows Installer limited user patching could be used to avoid elevation for loader patches.

See the article Patching Game Software in Windows XP and Windows Vista

Installation of the Game Executables, DLLs, and Data

In order to facilitate Standard User updates of the game without administrative privilege, the games executable, DLLs, and data must be installed to an area of the hard disk that is write accessible for all users. The operating system provides an "All Users Application Data" area which can be used as the default location for installation. The SHGetFolderPath API should be used with the CSIDL_COMMON_APPDATA key to determine the file path for this area. It is important that no assumptions be made about the path to which this key returns as it may be user configurable.

The installation needs to alter or manage the folder permissions in order to achieve the all-user-shared-write access needed for updating the title. With the correct permissions, the game updater functionality of the loader program can easily patch the game without the need for special privilege from any users account including times when launched by standard users.

Access Control List Modification Code

For Windows XP you will need to execute code to change the access control list (ACL) manually, here follows an example function demonstrating how to do this:

HRESULT ChangeACLtoAllowUserRW( WCHAR* strDir )
{
    EXPLICIT_ACCESS explicitaccess;
    PACL NewAcl = NULL;
    DWORD dwError;

    BuildExplicitAccessWithName( &explicitaccess, L"BUILTIN\\Users",
                                 GENERIC_ALL, GRANT_ACCESS,
                                 SUB_CONTAINERS_AND_OBJECTS_INHERIT );

    dwError = SetEntriesInAcl( 1, &explicitaccess, NULL, &NewAcl );
    if( dwError == ERROR_SUCCESS)
    {
        dwError = SetNamedSecurityInfo( strDir, SE_FILE_OBJECT,
                                        DACL_SECURITY_INFORMATION,
                                        NULL, NULL, NewAcl, NULL );
        if( dwError == ERROR_SUCCESS)
        {
            if( NewAcl != NULL ) AccFree( NewAcl );
            return S_OK;
        }
    }

    if( NewAcl != NULL ) AccFree( NewAcl );
    return E_FAIL;
}

This code example will also work for Windows Vista however, Windows Vista provides the command line utility icacls to edit file ACLS which you may choose to use instead.

The tool provides a detailed help when executed however, one example usage for the tool is:

icacls "C:\Users\All Users\Game" /grant Rex:(D,WDAC)

This usage will grant the user Rex Delete and Write DAC permissions to game folder stored in the All Users areas of the hard drive.

Installations for Advanced Users

For advanced user installation scenarios, a user may want to specify the games installation path manually. The directory selection should be restricted to one outside of program files to ensure the folder is in a truly sharable area of the hard drive. The user selected path should only be used for the games exes and data as the game Loader and Patcher exes should always be installed under the secure Program Files folder for better security.

The Loader's Verification of Trust

Windows provides the WinVerifyTrust API for checking the validity of signed code and is based on the cryptographic services in the operating system. The API is fully documented on MSDN in the following areas: http://msdn2.microsoft.com/en-us/library/aa388208.aspx

The following linked example details use of the API in order to determine if a program executable is signed with a valid certificate.

http://msdn2.microsoft.com/en-us/library/aa382384.aspx

For the purposes of verifying the signed game executable is trust worthy to be executed from within the loader, the Generic Verify action will suffice:

Value
WINTRUST_ACTION_GENERIC_VERIFY_V2
Meaning
Verify a file or object using the Authenticode policy provider.

The function takes an input structure argument which contains information that the trust provider needs to process the specified action. Typically, as in the example case referred to above, the structure includes information that identifies the object that the trust provider must evaluate.

The format of the structure is specific to the action identifier. The following link details the example structure for the WinTrust provider: http://msdn2.microsoft.com/en-us/library/aa388205.aspx

If the trust provider verifies that the subject is trusted for the specified action, the return value is zero. No other value besides zero should be considered a successful return.

Data Validation

The codesigning mechanism only supports signing a few specific types of files, including executables, DLLs, Windows Installer pagages (.msi files), and cabinet (.cab) files. The WinVerifyTrust API should not be used to verify that large data files (.cab files for example) have not been tampered with, as there are some issues with performance and stability when validating very large files. Program executables tend be small enough for a full trust check to occur using the WinTrust provider but data files for games are often of the realm of many gigabytes in size. The approach taken by the loader for verification of game data should be one where a small sample of the dataset is tested over the run time of the game. This approach spreads the cost of verification tests over the life of the game play experience and can provide a seamless user experience without long wait times. To achieve this, careful organization of the data may be required. Some MMOGs employ a database approach to help manage, maintain and verify correctness of game assets over time.

From a security standpoint, the client code should be designed to not trust data files even if using some kind of basic data validation with the trusted loader. Header checks, hashes, and other traditional integrity checking should be employed. Work to hardened the client's I/O code should also be done using techniques such as fuzz testing as well as taking advantage of automatic static code analysis tools such as the /analyze switch in Visual Studio 2005 (available in Visual Studio Team System and the free compiler that ships with the Windows SDK).

See the article Best Security Practices in Game Development for more details.


Installing and Using Input Method Editors

By Jack Lin, Software Design Engineer

Microsoft Corporation

December 2004

Introduction

This article offers a tutorial for how to install and use the standard Windows Input Method Editor (IME).

Contents:

  • Installing an Input Method Editor
  • Simplified Chinese IME
  • Traditional Chinese IME
  • Japanese IME
  • Korean IME
  • Requirements

Installing an Input Method Editor

The following sections describe how to install and use Input Method Editors (IMEs) to enter complex characters in four different East Asian languages. Features unique to each language are discussed.

To implement Input Method Editor (IME) functionality in an application, see Using an Input Method Editor in a Game.

An IME is not installed on Microsoft Windows XP systems by default. To install, complete the following steps.

  1. From the Control Panel, open Regional and Language Options.
  2. On the Languages tab, select the Install files for East Asian languages checkbox.

    Languages tab of the Regional and Language Options control panel

    An Install Supplemental Language Support dialog box appears informing you of the storage requirements for the language files.

    Install Supplemental Language Support dialog box

  3. Click OK to close the dialog box.
  4. Click OK on the Languages tab.
  5. Another dialog box appears requesting a Windows XP installation disk or network share location where the language support files are located. Insert a Windows XP compact disk or browse to the appropriate network location, and click OK. Microsoft Windows installs the necessary files and prompts for you to restart the computer.
  6. Click Yes to restart the computer.
  7. After restarting, open the Regional and Language Options control panel once again.
  8. On the Languages tab, click Details. The Text Services and Input Languages window appears.

    Text Services and Input Languages window, Settings tab

  9. On the Settings tab, click Add. The Add Input Language window appears.

    The Add Input Language window, with Chinese (Taiwan) language and Microsoft New Phonetic IME 2002a selected

  10. Select Chinese (Taiwan) for input language and Microsoft New Phonetic IME 2002a for keyboard layout/IME.
  11. Click OK. Now you can add additional languages and IMEs in a similar fashion.
  12. Click Add again, select Chinese (PRC) for input language and Chinese (Simplified) - Microsoft Pinyin IME 3.0 for keyboard layout/IME, then click OK.
  13. Click Add again, select Japanese for input language and Microsoft IME Standard 2002 ver. 8.1 for keyboard layout/IME, then click OK.
  14. Click Add again, select Korean for input language and Korean Input System (IME 2002) for keyboard layout/IME, then click OK. In the Text Services and Input Languages window, the Installed services list box should now contain the four newly-added IMEs.

    Installed services list box within Text Services and Input Languages Settings

  15. Click OK to close the Text Services and Input Languages window.
  16. Click OK to close the Regional and Language Options control panel. The Windows taskbar should now contain an input locale indicator circled in red. The existence of the indicator signifies that more than one input language has been installed on the system.

    Input locale indicator on the Windows taskbar

Simplified Chinese IME

This section describes how to use the Simplified Chinese IME (PinYin) with Microsoft Notepad to enter a few Chinese characters.

  1. Launch Notepad (available from the Start button, then select All Programs and Accessories). Type some characters in Notepad. These characters will help you visualize the IME window better later.

    English characters entered in Notepad

  2. With Notepad as the active application, click the input locale indicator and select Chinese (PRC). The indicator display changes to CH to reflect that the new input language is Chinese (PRC).

    Input locale indicator displaying Chinese (PRC)

  3. Place the cursor in Notepad. Press HOME on the keyboard so that the cursor is at the beginning of the line. On the keyboard type "N", then "I". The following figure shows the appearance of the display. The small horizontal rectangle is the reading window, which displays the current reading string. Currently, the reading string is "ni" as a result of typing "N" and "I".

    Notepad with reading window that displays the current reading string

  4. Type "3". Now Notepad has the following display. Because N+I+3 is a complete pronunciation in Simplified Chinese Pinyin, the IME has enough information to anticipate the character that the user may have intended to enter. The reading window disappears because you have entered a complete pronunciation. A character is displayed on top of the Notepad cursor. This character is not part of Notepad, rather it is displayed in another window on top of Notepad and hides the existing characters in Notepad that are beneath. This new window is called the composition window, and the string in it is called the composition string. The composition string is underlined in the display.

    Simplified Chinese character displayed in composition window on top of Notepad

  5. Now type "H", "A", "O", "3" to enter another character. Note that the reading window shows up when "H" is typed and disappears when "3" is typed. As shown below, the composition string now contains two characters.

    Possible Simplified Chinese characters displayed in composition window on top of Notepad

  6. Press the left arrow on the keyboard once. The composition cursor moves one character to the left, at the second character you typed. A window appears on top of Notepad as shown below. This window is called the candidate window. It displays a list of characters or phrases that match the pronunciation that you have typed. You can select the intended word from the entries in the candidate list. In this example, two candidate characters are available with the same pronunciation.

    Candidate window with three possible Simplified Chinese characters displayed on top of Notepad

  7. Type "2" to select the second entry. The candidate window now closes, and the composition string is updated with the selected character.

    Composition window updated with second Simplified Chinese character

  8. Press ENTER. This tells the IME that the composition is complete and the string should be sent to the application - Notepad in this example. The composition window closes, and the two characters are sent to Notepad via WM_CHAR. The underline is gone in the following figure because the two characters shown are part of the text in Notepad. The existing text "ABCDEFG" in Notepad is moved to the right because two more characters have been inserted. You have now successfully entered two Simplified Chinese characters using an IME.

    Two Simplified Chinese characters displayed in Notepad

Traditional Chinese IME

This section describes how to use the Traditional Chinese IME (New Phonetic) with Notepad to enter a few Chinese characters.

  1. Launch Notepad. Type some characters in Notepad. These characters will help you visualize the IME window better later.

    English characters entered in Notepad

  2. Click the input locale indicator on the Windows taskbar, and select Chinese (Taiwan). The indicator display changes to CH to reflect that the new input language is Chinese (Taiwan).

    Input locale indicator displaying Chinese (Taiwan)

  3. Place the cursor in Notepad. Press HOME on the keyboard so that the cursor is at the beginning of the line. On the keyboard type "S", then "U". The following figure shows the appearance of the display. The small vertical rectangle is the reading window, which displays the current reading string. As shown in the following figure, the reading string has two characters as a result of typing "S" and "U".

    Notepad with reading window that displays the current reading string

  4. Type "3". Now Notepad has the following display. Because S+U+3 is a complete pronunciation in Traditional Chinese, the IME has enough information to anticipate the character that the user may have intended to enter. The reading window disappears because you have entered a complete pronunciation. A character is displayed on top of the Notepad cursor. This character is not part of Notepad, rather it is displayed in another window on top of Notepad and hides the existing characters in Notepad that are beneath. This new window is called the composition window, and the string in it is called the composition string. The composition string is underlined in the display.

    Traditional Chinese character displayed in composition window on top of Notepad

  5. Now type "C", "L", and "3" to enter another character. Note that the reading window shows up when "C" is typed and disappears when "3" is typed. As shown below, the composition string now contains two characters.

    Additional possible Traditional Chinese characters displayed in composition window on top of Notepad

  6. Type the down arrow on the keyboard once. A window appears on top of Notepad as shown below. This window is called the candidate window. It displays a list of characters or phrases that match the pronunciation that you have typed. You can select the intended word from the entries in the candidate list. In this example, three candidate characters are available with the same pronunciation.

    Candidate window with three possible Traditional Chinese characters displayed on top of Notepad

  7. Type "2" to select the second entry. The candidate window now closes, and the composition string is updated with the selected character.

    Composition window updated with second Traditional Chinese character

  8. Press ENTER. This tells the IME that the composition is complete and the string should be sent to the application - Notepad in this example. The composition window closes, and the two characters are sent to Notepad via WM_CHAR. The underline is gone in the following figure because the two characters shown are part of the text in Notepad. The existing text "ABCDEFG" in Notepad is moved to the right because two more characters have been inserted. You have now successfully entered two Traditional Chinese characters using an IME.

    Two Traditional Chinese characters displayed in Notepad

Japanese IME

This section is a walk-through of using the Japanese IME with Notepad to enter a few Japanese characters.

  1. Launch Notepad. Type some characters in Notepad. These characters will help you visualize the IME window better later.

    English characters entered in Notepad

  2. With Notepad as the active application, click the input locale indicator, and select Japanese. The indicator display changes to JP to reflect that the new input language is Japanese.

    Input locale indicator displaying Japanese

  3. Place the cursor in Notepad. Press HOME on the keyboard so that the cursor is at the beginning of the line. On the keyboard type "N", then "I". The following figure shows the appearance of the display. Because N+I is a complete pronunciation in Japanese, the IME has enough information to anticipate the character that the user may have intended to enter. A character is displayed on top of the Notepad cursor. This character is not part of Notepad, rather it is displayed in another window on top of Notepad and hides the existing characters in Notepad that are beneath. This new window is called the composition window, and the string in it is called the composition string. The composition string is underlined in the display.

    Japanese character display in composition window on top of Notepad

  4. Now type "H", "O", "N", "G", and "O" to enter two more characters. The composition string now contains four characters, as shown below.

    Additional possible Japanese character displayed in composition window on top of Notepad

  5. Press the Space Bar. This instructs the IME to convert the entered text into clauses. In the figure below, the IME converts the pronunciation "Nihongo" to a clause written in Kanji that means "Japanese Language."

    Clause in composition string converted to Japanese Kanji characters

  6. Press the down arrow on the keyboard once. A window appears on top of Notepad as shown below. This window is called the candidate window. It displays a list of clauses that match the pronunciation that you have typed. You can select the intended word from the list of candidates. In this example, three candidate characters are available with the same pronunciation. Note that the second entry is highlighted, and the composition string changes. This is caused by typing the down arrow, which tells the IME to select the entry after the one that was previously displayed.

    Candidate character selection in Japanese IME

  7. Type "2" to select the second entry. The candidate window now closes, and the composition string is updated with the selected character.

    Japanese IME composition window updated to display the selected candidate character

  8. Press ENTER. This tells the IME that the composition is complete and the string should be sent to the application - Notepad in this example. The composition window closes, and the two characters are sent to Notepad via WM_CHAR. The underline is gone in the following figure because the two characters shown are part of the text in Notepad. The existing text "ABCDEFG" in Notepad is moved to the right because two more characters have been inserted. You have now successfully entered a few Japanese characters using an IME.

    Japanese characters displayed in Notepad

Korean IME

This section describes how to use the Korean IME with Notepad to enter a few Korean characters.

  1. Launch Notepad. Type some characters in Notepad. These characters will help you visualize the IME window better later.

    English characters entered in Notepad

  2. With Notepad as the active application, click the input locale indicator, and select Korean. The indicator display changes to KO to reflect that the new input language is Korean.

    Input locale indicator displaying Korean

  3. Place the cursor in Notepad. Press HOME on the keyboard so that the cursor is at the beginning of the line, then type "G". The following figure shows the appearance of the display. The phonetic element corresponding to "G" appears on Notepad and is highlighted with a block cursor. This highlighted character is called the composition string. Note that unlike the IME for other languages, the composition string is sent to Notepad and inserted to the left of the existing text as soon as the user enters a single phonetic element.

    Notepad with reading window that displays the current Korean composition string

  4. At this time, the composition string consists of an interim character because any additional phonetic elements entered by the user change the composition string in place. Now type "K", then "S". Note that the interim character changes with each keystroke.

    Interim character displayed in the Korean IME composition string

  5. Now press the right CTRL key. A candidate window appears that lists the Hanja characters you can select for the pronunciation entered, G+K+S.

    Korean IME candidate window that lists Hanja characters

  6. Type the numeral "1" to select the first entry in the list. The candidate window closes, and the composition string is updated with the character selected.

    Korean character displayed in composition window on top of Notepad

  7. Type "R", "N", and "R". Then press the right CTRL key to enter another character.

    Additional character candidate entered into the Korean IME

  8. Type "1" to select the first entry. You have now successfully entered two Korean characters using an IME. The Korean characters are already part of the text string in Notepad.

    Two Korean characters displayed in Notepad

Requirements

Operating System | Windows XP
Available Hard Disk Space | At least 230 MB
Foreign Language File Locations | Windows XP installation compact disk or network location with Windows XP installation files
Time | About ten minutes to install foreign language files; about ten minutes each to review four different IMEs.


Introduction to the 10-Foot Experience for Windows Game Developers

By Jon Steed, Software Design Engineer

Microsoft Corporation

April 2005

Introduction

A growing number of people are using their personal computers in a completely new way. When you think of a typical PC interaction you probably envision sitting at a desk with a monitor, and using a mouse and keyboard (or perhaps a joystick device); this is referred to as the "2-foot experience," and it's still the most common scenario for Windows gaming, but there's another trend which you'll probably start hearing more about: the 10-foot experience, which describes using your computer as an entertainment device outputting to a TV. This article introduces the 10-foot experience and explores the list of things you should consider first about this new interaction pattern, even if you aren't expecting your game to be played this way. Some portion of your customers will run your Windows game on a Media Center PC - it's better that you know what that experience will be like before your customers try it.

Contents:

  • What is Windows XP Media Center Edition?
  • The 10-Foot Experience
  • Aspect Ratio and Widescreen
  • Title-Safe Region
  • NTSC Suggestions
  • Installing Games on Windows XP Media Center Edition
  • Conclusion

What is Windows XP Media Center Edition?

Windows XP Media Center Edition 2005 (now in its third iteration) is a special version of Windows XP; in addition to the normal Windows XP functionality (minus a few features like Domain Controller support), it features the integrated Media Center application which can act as the interface to the multimedia capabilities of the host machine. The Media Center Edition website offers a much more thorough introduction and shows off all the good stuff available in the new version.

Traditionally the only way to get Media Center Edition was to buy a Media Center PC (which comes preloaded with Windows XP Media Center Edition) from a tier-1 system manufacturer. Under the new Microsoft OEM System Builder License, Media Center Edition is now available to mid-tier distributors who may resell it to the public provided it's bundled with non-peripheral hardware, so the potential marketplace is suddenly much larger. It's expected that the number of PC's running Media Center Edition will grow from about 2 million at the start of 2005 to 20 million by 2008.

Computer systems sold as Media Center PC's are typically higher-end machines with very capable video cards and multimedia peripherals like video capture/edit boards, but they are nonetheless still PC's capable of running Windows XP applications. If you're currently shipping a Windows game title, it's more likely that some of your customers are running your game on a Media Center PC; whether your game is accessed through the regular Windows shell or through the Media Center interface is largely dependent on which experience turns out to be more pleasant for the user. Directions on how to ensure Media Center properly handles the presentation and launch of your title are found later in this article.

The 10-Foot Experience

The Media Center PC was designed around the idea that people could use a Windows PC for a rich living room entertainment experience, and it follows that most users prefer to interact with a Media Center PC differently than a normal desktop workstation. For one, it's likely that a Media Center PC will output video to a display other than a conventional computer monitor: Analog TV's, high-definition digital TV's, and any number of LCD displays are all likely candidates. These types of displays are usually viewed from a distance of roughly 10 feet, hence the label "10-foot experience."

The 10-foot experience isn't confined to Media Center Edition users either; it's become common in recent years for users to connect their workstation or notebook computer to their TV and audio system. It's increasingly common for consumer display devices to expose RGB or DVI connections, the standard video output ports on computers. In addition, S-Video ports are a typical feature of high-end video cards, and offer an easy way to output to an alternate display device.

There are some important design guidelines which should be considered for a pleasant 10-foot experience:

  • Installation - During the average 2-foot experience, the user is within reaching distance of the computer; if during startup or gameplay the user is required to insert/switch media, the user can at least remain seated. The average 10-foot experience places the computer across the room from the user, and therefore anything that requires the user to physically interact with the computer forces the user to get up and cross the room. For this reason, developers should avoid forcing the user to change optical media; consider allowing a complete install of your application to the hard drive.
  • User input - Another feature of Media Center Edition is support for a standard remote, which is the generally preferred input device. Although the genre of your game title will largely decide whether the remote control is suitable for providing game input, you may still wish to allow the user to pause the game and access in-game menus with the remote; however, make certain you allow the user to control the menus via the primary game input device. Please see the Microsoft Windows XP Media Center Edition Software Development Kit (SDK) for detailed information about handling input from the standard remote.

    Avoid any physical interaction between the user and the Media Center PC or peripherals. Required input controller changes during gameplay are undesirable since it's likely the user is positioned near the primary input device only.

    Microsoft has announced plans to release a common gamepad controller for use with Windows and the future version of Microsoft Xbox. Making sure that your title plays well on the common controller will ease some of the headache associated with testing your game against potential input devices.

  • Display - Part of what makes the display considerations difficult is the wide range of potential display devices, each of which carries a number of special caveats. Some of the issues surrounding specific display technologies are introduced later in the article. Regardless of what the video output device is, at a range of 10 feet it's important that fonts and UI graphics are sized large enough for comfortable readability. Also note that antialiased fonts will generally offer better readability.

    You should also avoid single-pixel thick horizontal lines or static UI elements with single-pixel detail. Older televisions may simply not display fine detail, and even on the latest displays your content will flicker when running on an interlaced display mode since a single row of pixels will be visible only half the time. As a replacement for small detail, realize that a 2-pixel gray line will appear 'thinner' than a 2-pixel white line (this is essentially the same as blurring a 1-pixel white line).

Aspect Ratio and Widescreen

Aspect ratio describes the width and height proportion of the display. Standard TV and computer monitor displays have an aspect ratio of 4:3 (meaning for every 4 pixels running along the width of the frame buffer there are 3 pixels along the height, sometimes also represented simply as 1.33).

With the advent of HDTV, an aspect ratio of 16:9 (a.k.a. widescreen) has become the standard for the future of TV. There are three EDTV/HDTV modes you're likely to encounter which will output to widescreen:

  • 480p EDTV - 480 scan lines presented progressively. This mode can output either 4:3 (with a frame buffer resolution of 640x480) or 16:9 (720x480).
  • 720p HDTV - 720 scan lines presented progressively. This mode is always 16:9 (1280x720).
  • 1080i HDTV - 1080 scan lines presented interlaced. This mode is always 16:9 (1920x1080, or 1920x540 if rendering the interlace fields separately).

If your game is hard-coded to work on a 4:3 display, then a user who outputs your game to a 16:9 display will likely have three options to choose from, none of which are particularly satisfying:

  • Stretch - The 4:3 frame buffer is stretched to perfectly cover the 16:9 native resolution of the display, resulting in your scene objects appearing wider than desired. Some TV's offer additional stretch modes which attempt to preserve the aspect ratio near the center of the display and gradually increase the stretch at the image sides.
  • Centered - The 4:3 frame buffer is displayed undistorted in the center of the display, with solid color bars filling the remaining pixels on the sides.
  • Zoom - The 4:3 frame buffer is cropped to a 16:9 region, which then fills the native display resolution undistorted; note that the pixels above and below the clip rectangle are completely discarded, which are common regions for a game's UI elements.

A better approach is to add support for widescreen to your game. The most important change is to set the game camera's projection transform to use a 16:9 aspect ratio, which avoids the stretching distortion. Even if you leave the backbuffer at a 4:3 resolution, switching the projection transform to use 16:9 will greatly improve the perceived accuracy of the rendered image; of course the final image will undergo some filtering to upscale the 4:3 backbuffer resolution to meet the 16:9 native display resolution, but this is a less noticeable artifact than the stretch distortion caused by a mismatch of aspect ratios.

The cost of rendering the scene through 16:9 camera may be higher than a 4:3 camera (even at identical resolutions) because more scene objects will be visible in the wider view frustum. You should also be aware of how the enlarged viewable area may influence gameplay, as a game camera with a 16:9 ratio will reveal more of your game world than a 4:3 camera.

For the best results on a 16:9 display you should render to a 16:9 backbuffer, but this will obviously require filling more pixels. The difference between 640x480 and 720x480 is almost 38,400 pixels, a gain of 12.5%. If you can afford the extra fill cost this is strongly suggested.

Title-Safe Region

The entire image frame buffer may not be visible to the end user; often a certain amount of border pixels are covered by the display's front bezel. To ensure that critical UI elements are visible across the spectrum of potential consumer display hardware you should observe the "title-safe region" requirements for your target display mode: For non-HDTV modes, the title-safe region is the inner 85 percent of the frame buffer; for HDTV modes, the title-safe area is the inner 90 percent. For the greatest compatibility across current and future display hardware you should therefore keep all your game's critical UI elements and heads-up display indicators within the inner 85 percent of the frame buffer.

NTSC Suggestions

Since NTSC is the most common video standard in the United States for consumer display hardware, it's important to know about some of the guidelines you should follow for your output image:

  • Clamp the RGB color component values between 16 and 235. Colors outside this range can certainly be sent to an NTSC TV, but it's likely these out-of-range values will be interpreted as audio data. This is often called "audio buzz", and would be most apparent if your content were presented over a solid white background. You can easily implement output color clamping within a pixel shader.
  • Similar RGB colors may appear identical on an NTSC display. The NTSC color gamut doesn't offer the same palette as a typical computer monitor, so avoid using similar colors wherever the game requires the player to recognize the difference.
  • Avoid sharp contrast differences. Although this guideline is not always practical to follow, you can mitigate some of the color bleeding annoyances on NTSC displays (a.k.a. chroma crawl) by selecting proper colors for your UI foreground and background elements; white text on a colored background will probably give better results than contrasting colors.

Installing Games on Windows XP Media Center Edition

To make your application easily accessible using the Media Center interface, there are two available options:

Option 1: Webpage Hosted Games

Using the extensibility model of Media Center offers the tightest integration with Media Center, but requires that the game be hosted on a webpage. By using the extensibility model, your game title will appear as a first-class citizen within the Media Center UI, and will also be able to interface with the Now Playing experience. If this approach is suitable for your title, the Microsoft Windows XP Media Center Edition Software Development Kit (SDK) documents the extensibility model and demonstrates this approach with a sample application.

Option 2: Separate process, full-screen games

You can also install your game so that it runs in a separate process in full-screen mode, by adding a couple extra files to your installation. This will expose your game application through the Media Center UI which is probably the most practical option for any game which is also intended to be played on a non-Media Center version of Windows. In this approach the game itself will need to relaunch the Media Center UI when it finishes.

Typical fullscreen Windows games that use stand-alone exes will use option 2. A working example of the process for full screen games is explained below and can be found in the DirectX SDK with the MediaCenterGame sample. The steps to properly install and register your game in the Media Center UI are:

  • Step 1: Create an MCL file
  • Step 2: Install the MCL file
  • Step 3: Launching your game from the MCL file
  • Step 4: Re-launch the Media Center UI upon exit

Step 1: Create an MCL file

To make your game show up in the Media Center UI, you must first create an MCL file which is an XML file with any name and the .mcl filename extension. Here is the MCL file that is included with the MediaCenterGame sample:

<application
    Title = "MediaCenterGame"
    ID = ""
    Run = ".\MCELauncher.lnk"
    BGColor = "RGB(0,0,0)"
    Name = "MediaCenterGame"
    CompanyName = "Microsoft"
    StartImage = ".\icon_128.jpg"
    ThumbnailImage = ".\icon_128.jpg"
    SharedViewport = ""
    NowPlayingDirective = ""
>
    <capabilitiesRequired
        directX="True"
        audio="False" <!-- Set false even if your game uses audio -->
        video="False" <!-- Set false even if your game uses video -->
        intensiveRendering="True"
        console="False"
    />
</application>

The most important parameters are described as follows:

  • Title is a string that specifies the title of the application.
  • Run is a string that contains the filename (including the file path) that is launched when the button is clicked. See Step 3 for an explanation of this string.
  • Name is a string that specifies the string label that appears on the button in the Media Center button.
  • StartImage is a string that contains the filename (including the file path) to the icon which appears when the button has focus.
  • ThumbnailImage is a string that contains the filename (including the file path) to the icon that appears on the More Programs page.

The values shown in the capabilitiesRequired section should work well for all Windows games. All other values in the application section can be safely ignored.

Step 2: Install the MCL file

To register this MCL file with the Media Center UI, you need to place the MCL file or a shortcut to the MCL file in a known folder location:

  • On Windows XP use:
    CSIDL_COMMON_STARTMENU + "\Programs\Accessories\Media Center\Media Center Programs"
  • On Windows Vista use:
    CSIDL_COMMON_APPDATA + "\Media Center Programs"

Note The location specified by these paths is relative to the location returned by SHGetFolderPath.

Do not use a hard-coded path when installing. Instead query the operating system for the proper folder location using the SHGetFolderPath API, For example, if you install for all users (the generally preferred manner), then a call with the CSIDL_COMMON_STARTMENU appended with the Unicode string L" Programs\Accessories\Media Center\Media Center Programs" should be used. Use CSIDL_STARTMENU instead if you want to install for the current user only.

Step 3: Launching your game from the MCL file

In the MCL file's Run tag, you specify what you want to launch when the button is clicked from within the Media Center UI. If you need command line arguments passed to your game .exe, you must make the MCL file run a shortcut that has the command line arguments in it. In other words, use the Run tag to specify a shortcut such as MyGame.lnk, and include the command line arguments in the .lnk file.

There is one important issue you might see when you try doing this depending on your game initialization code. You may get an error when trying to create the Direct3D device because the Media Center UI and the game may compete for the same Direct3D device.

The performance and stability of the Media Center UI is due to the fact that it renders everything via Direct3D, typically in full-screen exclusive mode. This means that when the Media Center UI atempts to launch a full-screen game (from inside its Direct3D-based UI), the game may also try to immediately create a full-screen exclusive-mode device which can fail if the Media Center UI has not yet released it's Direct3D device.

There are two solutions for a device creation problem:

  • Change the game initialization code so that the game delays creating an exclusive full-screen device until the device is available.
  • Use an external launcher application which does this.

While it may be easier to use an external launcher (since one is supplied in the DirectX SDK), a game which handles this initial start condition gracefully provides a better end-user experience and is therefore preferred. DXUT has been updated to handle this scenario, so any application using DXUT will get the "keep trying to create an exclusive device" behavior automatically.

If you choose to use the external launcher, MCELauncher.exe (which is in the DirectX SDK) simply tries to create a full screen device for a certain amount of time and when it succeeds it will launch the game that is specified on the command line. Using this approach, make sure MCELauncher.exe is installed with your game.

Step 4: Re-launch the Media Center UI upon exit

After exiting the game, the user should be returned to the Media Center UI. The game itself must re-launch MCE by doing this:

bool ReLaunchMediaCenter()
{
    // Skip if not running on a Media Center
    if( GetSystemMetrics( SM_MEDIACENTER ) == 0 )
        return false;

    // Get the path to Media Center
    WCHAR szExpandedPath[MAX_PATH];
    if( !ExpandEnvironmentStrings( L"%SystemRoot%\\ehome\\ehshell.exe", szExpandedPath, MAX_PATH) )
        return false;

    // Skip if ehshell.exe doesn't exist
    if( GetFileAttributes( szExpandedPath ) == 0xFFFFFFFF )
        return false;

    // Launch ehshell.exe
    INT_PTR result = (INT_PTR)ShellExecute( NULL, TEXT("open"), szExpandedPath, NULL, NULL, SW_SHOWNORMAL);
    return (result > 32);
}

If you are using DXUT, you can add the command line parameter -relaunchmce which will do this for you, or you can use the helper function called DXUTReLaunchMediaCenter().

Conclusion

This article was an attempt to offer a first look at the 10-foot experience from the perspective of a Windows game developer, but it is by no means comprehensive; you should research these topics further if you're developing a Windows game title (even if it's not intended for Media Center PC's). The true test is to try your game on a variety of video displays to ensure your game offers a pleasant experience on each. Based on the typical life-span of a Windows game and the predicted growth of Media Center enabled PC's, it's almost guaranteed that a game you release today is going to take part in a 10-foot experience (at least people will try it). Whether they can play your game from a couch or they're forced to sit at a desk is largely up to you.


Making Video Games Accessible: Business Justifications and Design Considerations

by Brannon Zahand, Software Test Engineer Lead

XNA Game Quality (XGQ)

August 2006

Introduction

Game publishers and developers love to focus on features that will get their titles noticed by the mainstream gaming community, such as graphics and audio. But there is another audience, eager to take part in these games as well. These gamers come from the accessibility community — a community of people with disabilities, as well as those who care about their welfare.

This paper is for game content developers and producers who want to reach this market by adding basic accessibility features to help people with disabilities or impairments. The following topics will be discussed:

    What is Accessibility?

    Often, when people think of accessibility, they think of things like wheelchair ramps and closed captioning on television. This is because these sorts of accessibility features stand out and are used by those with obvious disabilities. However, accessibility features aren't designed just for those with the most severe disabilities. Among US computer users who range from 18 to 64 years old, 57% (74.2 million) are likely to benefit from the use of accessible technology due to disabilities and impairments that may impact computer use. ("The Market for Accessible Technology: The Wide Range of Abilities and Its Impact on Computer Use," Microsoft Corporation) Being able to turn up a payphone's volume allows people with mild hearing loss to use them. A hand rail on a flight of stairs allows a mobility-impaired person to climb them more easily.

    Sometimes, regular features of a product end up being features that can help people with impairments. For instance, someone with a visual impairment can use the contrast settings on a television to make the screen easier to see. A person with Parkinson's disease can use one touch dialing to make it easier to make a telephone call.

    Accessibility features generally tend to serve one of five types of disabilities:

    • Vision - Blindness, inability to distinguish colors, blurred Vision, etc.

    • Hearing - Hard-of-hearing, deafness.

    • Speech - Speech impairments, language differences.

    • Mobility - Wrist, arm, leg, and hand impairments.

    • Cognitive - Learning impairments and reasoning challenges, including dyslexia.

    In the context of video games, adding accessibility means making a title usable to someone with one of these disabilities.

    Why is Accessibility Important?

    There are both social and financial reasons why game developers should think about making their products accessible.

    For children and young adults who have disabilities that range from mild to severe, video games can offer a number of benefits. Researchers at the Wheeling Jesuit University recently discovered that playing sports games or fighting games helps distract children and young adults suffering from chronic pain (The Edmonton Journal, Feb 13th 2006). Furthermore, video games have been proven to help children facing surgery more effectively-and with fewer side effects-than tranquilizers (The Associated Press, Dec 19th 2004). Games are even being used for cancer treatment; exercise, vitally important to recovery after chemotherapy, has been encouraged through the use of games such as Dance Dance Revolution(c) when children refuse to participate in other forms of physical activity.

    In addition, allowing people with impairments (especially children) to participate in activities that most individuals enjoy and take for granted can help reduce emotional pain and the feeling of being an outsider.

    Social reasons aren't the only reasons why game developers should introduce accessibility features into their titles. Accessibility features can increase sales by encouraging people with disabilities to buy an accessible title. Increased sales can also come from gamers who want to support a company that supports the accessibility community. And finally, the positive P.R. from the media as well as accessibility advocacy groups provides free advertising.

    The demand for accessibility will continue to grow as the gaming population ages. As people grow older, mild impairments can become more severe. Also, people are likely to develop new difficulties and impairments as they age. Adding basic accessibility features to titles can help publishers and developers continue to draw revenue from these customers.

    The State of Accessibility in the Games Industry

    For most of the games industry, accessibility in video games is a low priority. One reason is because of a lack of awareness among developers about accessibility issues-developers who are not disabled might not be aware of the ways that they can make a title more accessible to people with disabilities or impairments.

    Another reason is that developers have limited amounts of time and resources. Cost-benefit analyses often conclude that accessibility issues aren't worth the attention and investment of the games industry because of assumptions like:

    • The cost of implementing accessibility features isn't worth the return.

    • There isn't a wide-enough audience to make accessibility development worthwhile.

    These assumptions are faulty. Making games accessible is well worth the investment.

    The Need for Accessible Games

    In 2003, Microsoft Corporation commissioned Forrester Research, Inc., to conduct a comprehensive study to measure the current and potential market of accessible technology in the United States and understand how accessible technology is being used today. The study determined that 57% of computer users are likely or very likely to benefit from the use of accessible technology. And the future demand for accessibility is only projected to grow ("Accessible Technology in Computing: Examining Awareness, Use, and Future Potential," Microsoft Corporation).

    Figure 1. Predicted Growth in Number of Accessible Technology Users from 2003 to 2010

    The study also determined that the use of accessibility features was not restricted to people with disabilities. Among computer users who use built-in accessibility options and utilities:

    • 32% have no disability or impairment.

    • 68% have a mild or severe disability or impairment.

    Empirical observation suggests this is not just a trend limited to PCs. Accessibility features are often used by people without any disability just to improve their game experience. For instance, a gamer could be compensating for a temporary disability (like a broken thumb), environmental issues (such as background noise), or other situational factors.

    Given the potential increase in the use of accessibility technology, it is crucial to educate management, designers, developers, and testers. Many companies are looking for ways to expand into new markets outside of the 18-32 male demographic. While publishers mull over how to convince little Suzy to play games or Grandma and Grandpa to pick up a controller, there is a market comprised of people who want desperately to play mainstream games that is going unnoticed. The potential revenue to be gained from a relatively small amount of effort providing basic accessibility features in a title is very tangible.

    Including basic accessibility features in a title can increase sales through a "domino effect"-for example, by reaching gamers who would normally be unable to play the title or would have their experience significantly diminished. By reaching these gamers, you also reach the accessibility community (which is known for a rapid sharing of information on accessible products and its loyal support of businesses that promote accessibility). By extension, businesses that take an active role in this community benefit from positive media exposure.

    By not including accessibility features, you run the risk of potential boycotts and lawsuits-and the resulting loss of sales. Many retailers and airlines have been sued for lack of accessibility, and in the technology sector, the blind community boycotted Internet Explorer 4 for its lack of accessibility.

    Below are different categories of disabilities. Each category includes some relatively easy-to-implement suggestions that can make a title accessible to a wider audience.

    Visual Impairments

    "My presentation was followed by a lively question and answer session, and one notable moment occurred when one of the staffers asked a question about accessibility in [our] games... this 28-year-old staffer is an avid gamer who used to play [our game] with a wide circle of friends. Because he is color blind, however, it was hard for him to tell the good guys from the bad guys and the game finally became too frustrating. When the new version... came out and [we] hadn't fixed the problem, he and his friends all decided to buy a competitor's game instead."—an anonymous industry executive

    The term "visual impairment" often brings to mind someone who is completely blind. However, it is startling to know that 8.7% of the male population is affected by some level of color blindness ("How do people inherit colorblindness? How often?," WebExhibits.org). Another 1.2% of individuals are affected by more severe forms of visual impairment ("Disability Info: Visual Impairments Fact Sheet," National Dissemination Center for Children with Disabilities). That means almost one out of every ten potential gamers have issues affecting their eyesight that can impact their gaming experience.

    To help you understand visual impairment issues, imagine that:

    You Are A Gamer | And You Are In This Scenario
With normal vision | It is bright and sunny so you can't see dark objects on your screen.
 | You have an old television set so you can't see small objects and text because of poor picture quality.
With impaired vision | Some game text is so small you can't read it.
 | You are color blind so you don't know which button to press when the game tells you to press the red button.

    With a few simple steps and features, you can address these issues and improve the gaming experience for both gamers with normal vision and gamers with a visual impairment.

    1. Test titles on black and white televisions. Note any instances where items, players, objectives, and commands can't be distinguished and adjust your color palette accordingly.

    2. Give gamers an option to increase the size of text on their screen. Also provide the capability to change the scrolling rate of text. It is important to remember that that the console experience is 10-foot, not the 2-foot gaming experience many PC developers are used to. Even for gamers with no vision problems, small UI and text can be difficult to read at long distances.

    3. Provide text-to-speech features that can voice all game text, including game menus that track focus on buttons. Allow the user to control the speed, pitch, and gender of the voice. To help prevent text-to-speech from being drowned out by other game noises, give users the ability to adjust the volume of speech, ambient noise, active game sounds, and music. Also, include the option to play distinct sounds when transitioning through menu items and over buttons.

    4. Finally, give gamers the option to change brightness and contrast settings in- game. Provide users with the ability to choose their own custom color schemes so that text, background, and HUD colors can be custom configured to suit an individual's needs.

    Auditory Impairments

    "Memories of Half-Life return to haunt us as yet another technological masterpiece [Halo] is useless to the deaf gamer... Let's hope, no pray! that if Halo 2 ever sees the light of day that it will be fully subtitled."—www.DeafGamers.com

    The next most prevalent form of impairments that can affect game play is auditory impairments. ("UCSF: Disabilities Statistics Center," Abstract 5, University of California, San Francisco). In the U.S. alone, over 28 million people are affected by some sort of hearing impairment. While hearing impairments are often associated with age, 17 out of every 1,000 children under the age of 18 are affected with a hearing impairment ("Statistics about Hearing Disorders, Ear Infections, and Deafness," National Institute on Deafness and Other Communication Disorders). When one considers that the gamers of today are getting older and losing their hearing at an ever-increasing rate, it is clear that demand for audio accessibility will only grow.

    To help you understand auditory impairment issues, imagine that:

    You Are A Gamer | And You Are In This Scenario
With normal hearing | You don't want to disturb anyone so you play with the sound muted but you can't play the game because the directions are only given in audio.
 | You are gaming at a loud party but you can't tell that you are under fire because you can't hear the gun shots.
With a hearing impairment | The game has a lot of ambient noise and you can't hear the verbal instructions given to you.
 | The audio commentary is so soft, you can't hear it, even in a quiet room.
Who is deaf | All of your objectives are given to you in audio and you can't determine what you are supposed to do.
 | All of the storyline is given verbally, and you can't follow along.

    With some relatively minor work, you can make your game usable and enjoyable for gamers with normal hearing and for gamers who have an auditory impairment.

    1. Close caption all dialogs. This includes in-game content and cinematics. Give the gamer the ability to turn these captions on and off.

    2. When a sound effect delivers vital information, provide a textual or tactile (vibration) mechanism for feedback as well. For example, if normally a bomb in your game makes a faster beeping noise close to its explosion, provide a visual indicator (such as a time bar) that also allows the gamer to know how much time is left before the explosion.

    3. If your game supports online play, give gamers the option to send text messages as well as use their voice to deliver information amongst team members and other online players. A headset is not useful to an individual who can't hear and, more and more, players are looking to play with other individuals with whom they can communicate and strategize online.

    Mobility Impairments

    "Videogames offer people with disabilities the opportunity to reconnect with their peers and abilities that have been lost or never had. My personal experience comes from being paralyzed at the age of 14 years old and visiting the recreational center in the hospital and the only interest I had to break out of my depression was to play the videogame system. I quickly lost interest when I learned I could not play them..."—Robert Florio

    Mobility impairments are perhaps the hardest of the various impairments to get firm statistics on. This is primarily due to the fact that these impairments can be caused by disease, neurological disorders, loss of limbs/digits, paralysis, etc. which each can have a varying degree of impact on a video gamer's experience. These impairments may be congenital, or may occur later in life.

    To help you understand auditory impairment issues, imagine that:

    You Are A Gamer | And You Are In This Scenario
With no mobility impairment | The game controller has so many buttons, you (as a casual gamer) are intimidated and you don't want to learn how to use it.
With a temporary mobility impairment | You have a broken thumb so you can't use the thumbstick on your controller.
 | You have a broken leg so you can't use the dance pad for a dancing title.
With a permanent and severe mobility impairment | You have lost an arm so you cannot use a two handed controller.
 | You have Parkinson's disease, your hands shake, and that makes you accidentally trigger buttons on the controller.
 | You are paralyzed from the neck down so you cannot use a standard game controller at all.

    Thinking about accommodating all these gamers is challenging, but there are some easy things you can keep in mind when developing your games.

    1. Minimize button use and think more about menu interfaces for commands. This is particularly useful for individuals who may be missing digits or a hand. It is also useful for paralyzed individuals who use custom controllers.

    2. Allow gamers to customize their controller configuration and button/thumbstick sensitivity. This will allow individuals who have fine motor skills problems customize the controller to minimize the impact their disability has on game play. It also allows for better support of custom controllers for the disabled.

    3. If your game utilizes a specific type of peripheral (dance pad, light gun, etc.), allow other controllers to perform the same functions. For instance, a game such as Dance Dance Revolution(c) allows even wheelchair-restricted individuals to play along with their friends through the use of a regular hand- held controller.

    Vocal Impairments

    Vocal impairments make up a relatively small percentage of the disability community. Specific statistics are hard to come by, but evidence shows that a majority of vocal impairments are linked to other disabilities (such as motor or hearing impairments). However, as more game publishers begin to explore making use of voice conferencing and speech recognition in their titles, people with vocal impairments will begin to see the quality of their gaming experience decline. To counter this, there are basic accessibility features that can be implemented.

    To help you understand auditory impairment issues, imagine that:

    You Are A Gamer | And You Are In This Scenario
With no vocal impairment | You are playing a game that requires spoken commands to control your characters and you can't play because you don't have a microphone.
 | You are playing late at night and you don't want to disturb anyone so you can't use your communicator.
Who has a speech impairment | You are playing a game that requires spoken commands to control your characters and you can't play because the game can't recognize what you are saying.
Who is unable to speak | The game you are playing requires speech input so you are unable to play.
 | The online game you're playing expects you to coordinate strategy via the communicator so you cannot play effectively.

    Fortunately, there are some easy fixes that can make your game usable and enjoyable for these gamers.

    1. If a game uses speech recognition, provide gamers with an option to choose commands from a menu or button combination.
    2. If your title also supports online multiplayer, give gamers the option of a customizable macro with either audio messages or (even better for those with hearing impairments) text messages. Providing keyboard support for chat is also an option.

    Conclusion

    At this point, you might be thinking that you couldn't possibly accommodate all of these gamers in all of these scenarios. And even if you were to implement every suggestion in this paper, you couldn't ensure that a title would be completely accessible to everyone. But by following these accessibility guidelines, you can make your title much more appealing to the accessibility community. And that can only increase sales.

    To make a title more accessible, developers and publishers need to find people with various types of disabilities to usability test their games. This approach provides first-hand information about whether or not a game is accessible for a certain audience. As an added benefit, having diverse development and testing resources can offer additional insights that can improve game play for all gamers. Most importantly, engage the accessibility community and get to know these potential customers. Hold a game bash for your title at a local deaf service center, children's hospital, or veteran's center. Encourage developers and testers to volunteer with local organizations that work with the disabled, to take a sign language class, or to sign up for accessibility-related newsletters to keep up with the community. Solicit feedback on previous titles from disabled-gamers at local schools and colleges.

    No one likes feeling an outsider. By including the accessibility community in game testing and design, you will be able to market your title to a much wider audience and do the right thing for the community and your bottom line.

    More Resources

    There are a number of web resources available that discuss video game accessibility, as well as a number of companies that focus on disabled gamers. In addition, the Accessible Technology Group at Microsoft can be contacted with PC-related accessibility questions at: ablecat@microsoft.com. Xbox-related accessibility questions can be sent to: xaccess@microsoft.com

    General Disability sites:

    • Game Accessibility
    • IGDA Game Accessibility Group
    • Microsoft's Accessibility Site
    • MSDN Accessibility Information

    Auditory Impairment Sites:

    • DeafGamers.com
    • The Deaf Resource Library

    Visual Impairment Sites:

    • National Eye Institute
    • Vischeck
    • WebExhibits.org

    Mobility impairment Sites:

    • RobertFlorio.com
    • WebAIM

    Speech Impairment Sites:

    • American Speech-Language-Hearing Association


Optimizing DVD performance for Windows Games

XNA Developer Connection (XDC)

April 2006

Introduction

Today, a high percentage of computers running Microsoft® Windows® have a DVD drive, and many upcoming games are shipping on DVD. As a result, it is important for developers to be sure that their games use the DVD drive to its full advantage. By understanding how data is read from a DVD and how the data's location affects its reading time, you can reduce loading times and improve the overall performance during game play.

Basic Layout of a DVD

Data on a DVD is stored as a continuous spiral, like on a CD; however, the files are broken up into blocks and sectors. Files are spread over error correction code (ECC) blocks, and each block is divided into sixteen 2-KB sectors (that is, 32 KB of data in each block). Files are aligned along the sector boundaries, and any unused space in a sector is left empty. If a file has only 10 bytes, then the rest of the space in that 2-KB sector is wasted; so when possible, bundle files into 2-KB increments to get the best data density. Be aware that these specifications are for DVD only, and CD and HD-DVD have different specifications.

Reading from a DVD

The sequence that a DVD drive executes upon receiving a request to read from a DVD is as follows:

  1. Change layers, if necessary
  2. Seek
  3. Refocus the optical pickup unit (OPU) to read data
  4. Check the actual position
  5. Adjust and repeat until the correct data is found

Drive reading operations are quantized differently, depending on whether they are logical drive reads or physical drive reads. Logical drive reads can only read an integer quantity of DVD sectors, while a physical drive read request can only read an integer quantity of ECC blocks. Typically, physical drive receives a read request; it will try to fill its cache. The DVD drive cache size depends on the individual drive's specifications.

When a DVD drive gets a read request that exceeds the cache size, the request is broken down into cache-sized requests. The drive seeks the ECC block that contains the first sector of the request and reads the whole ECC block. The drive firmware decodes the ECC block and then reads the next ECC block. The process is repeated till the drive cache is filled or all requests are fulfilled. The kernel then reads the decoded data from the drive cache. It then flushes the cache and starts the next read operation, if any read requests remain.

Note Every uncached read flushes the drive cache.

Reading Errors

DVDs and DVD drives are not perfect, and errors can occur during reading. Like CDs, portions of a DVD can become unreadable from dust or scratches. If any part of a block is unreadable, the whole block is considered unreadable. If a read error occurs, the drive tries re-reading the ECC block. If the block is still unreadable, the drive aborts the read operation and returns a value to the kernel that indicates that the block was unreadable. The kernel then decides what step to take next. The kernel can either reissue the request, abort the reading altogether, or spin the drive down and reissue the request.

Data Throughput

The data throughput of a DVD drive depends on multiple factors: the location of requested data, how clean or scratched the disk is, the number of streams that are being read from the disk, the size of the buffers associated with those streams, and the specifications of the individual drive. Throughput also depends on whether the drive has constant angular velocity (CAV) or constant linear velocity (CLV). If a drive spins with CAV, the disc spins at the same speed regardless of where the optical pickup unit (OPU) is located. This means that the data track moves past the OPU faster as the OPU gets closer to the outer edge of the disc. With CLV, the disc spins more slowly as the OPU moves outward, so the data track moves past the OPU at a constant speed. The DVD drives in most PCs use CLV.

While the drive is seeking and changing layers, data can't be read from the disc. It is a good practice to minimize these operations, especially when reading data for an initial loading screen.

Examples of Wasted Throughput

To understand how data throughput can be wasted, consider a hypothetical drive and DVD. Let's assume that a file in the middle of the disc needs to be read. The throughput from that area of the disc is approximately 8.25 MB/sec. If the seek stroke is a half or a third of full, then the average seek time is 150 ms. In this example, 1.2 MB (150 ms × 8.25 MB/sec) could have been read in the time that it took just to get the OPU to where it can read. Adding a layer change raises the wasted throughput to 1.8 MB (225 ms × 8.25 MB/sec).

Another example that demonstrates wasted throughput is loading 20 poorly located files from a CAV drive with no layer changes. If the seek time for each file, plus the latency before data can be read, is approximately 200 ms, then 4 seconds (20 files × 200 ms) are spent just seeking the data. If the files are located on the outer diameter and read at 11× speed, then the throughput averages 15.2 MB/sec (11 speed/12 speed × 16 MB/sec). The wasted throughput in this example is approximately 60.8 MB (15.2 MB/sec × 4 sec).

Reading Synchronously vs. Asynchronously

Asynchronous reading is more efficient than synchronous reading. When reading synchronously, one or more ECC blocks of data are read into system memory before being copied into application memory. In contrast, asynchronous reading copies decoded ECC blocks directly to application memory, which avoids the L2 cache and creates less CPU overhead. To read asynchronously, use the FILE_FLAG_OVERLAPPED flag when using the CreateFile function to open files. The ReadFile function also needs a valid OVERLAPPED structure passed in to perform asynchronous I/O.

More information on asynchronous I/O can be found at Synchronous and Asynchronous I/O

Reading Optimally

The best principle in reading from a DVD is to avoid seeking and reading small amounts of data. When the amount of data read is less than the capacity of an ECC block — less than 32 KB — the rest of the block is wasted. Since cache sizes vary from drive to drive, developers must decide on a minimum amount of data for read requests and not make any smaller than that. The minimum size should be an integer multiple of an ECC block to avoid wasting time on reading and decoding data that won't be used. It is also important to avoid seeking at all costs, because any time spent seeking is time spent not reading data.

DVD Compatibility

There are some important compatibility issues to be aware of when releasing on DVD. First, DVD drives in Windows-based computers can vary in performance, so if your DVD has a specific requirement for throughput, it is important to make sure that your users' hardware meets those requirements. Also, multilayer DVDs can cause compatibility issues on the some DVD drives. To avoid these issues, it is advisable to deliver a single-layer DVD or to thoroughly test a multi-layer DVD on a majority of drives before release.

Summary

To improve DVD performance, some general rules can be applied. The following techniques can help maximize throughput and reduce wasted data:

  • Avoid reads that are smaller than 32 KB
  • Lay out data to reduce or eliminate seeks
  • Lay out data on ECC block boundaries
  • Maximize capacity by bundling small files into 2-KB blocks, and reduce padding space in DVD sectors
  • Read asynchronously to reduce CPU load and excessive memory usage
  • Avoid releasing multilayer DVDs


Patching Game Software in Windows XP and Windows Vista

XNA Developer Connection (XDC)

April 2006

Introduction

Windows Vista adds a number of features to make the operating system more secure. Added security means that applying patches to software is not as simple as it was in the past. This article examines some methods of patching that will work well in Windows Vista and Windows XP.

There are two main categories of games that require patches:

  • Games that require only occasional patches, such as most offline games.
  • Games that require frequent patches, such as most online games.

This article also offers a brief introduction to the Windows Vista User Account Control (UAC) to serve as background about the privileges that developers can expect users to have in Windows Vista.

Windows Vista User Account Control

Windows Vista has 2 primary types of user accounts: Standard User and Administrator. A Standard User account has several access restrictions; for example, it cannot write data to the file system in %SystemDrive%\Program Files or to the registry in the HKEY_LOCAL_MACHINE. This has implications for applying patches to a game if it is installed in a read-only location. Unlike in Windows XP, the Standard User account will be much more common in Windows Vista. The Standard User account type is also required for important features of the operating system, like parental controls. Parental controls in Windows Vista requires that the child account be Standard User, and elevating such an account to Administrator for even one game prevents parental controls from working with all other games. So, it important for games to be designed for Standard User.

Windows Vista changes the traditional privilege model to help prevent users from running programs that attempt to perform operations that the user doesn't intend or authorize. To that end, User Account Control (formerly called Least-privileged User Account or LUA) enables users to run at low privilege most of the time, while being able to easily run applications requiring more privilege as necessary. This means that Standard User accounts and Administrator accounts both run applications with Standard User privileges, but only Administrator accounts have the ability to grant applications elevated privileges. The operating system asks users with Administrator accounts for explicit consent before running an application with elevated privilege, and if a program that requires Administrator rights is run on a Standard User account, the system prompts for administrator approval.

Games that Require Only Occasional Patches

Some games only require a few patches throughout their lifecycle. Two methods that you can employ for this frequency of patching are to distribute patches as Windows Installer packages, which does not generally require Administrator rights, or to use some other type of distribution that directly modifies game files.

Note Regardless of whether a game requires frequent patching, applications typically require Administrator privileges to be installed or removed.

Method 1: Use Windows Installer for Occasional Patches

In this method, a Windows Installer is used to install a package (.msi file) and a Windows Installer patch (.msp file) is distributed to install patches. The package must have an MsiPatchCertificate table and the patch must be digitally signed by a certificate in the table. More information about digital signing can be found at Authenticode Signing for Game Developers.

More details and requirements to use this patching method can be found in the Windows Installer documentation:

  • Patching and Upgrades
  • User Account Control (UAC) Patching

The disadvantage to this method is that if the game was not installed from removable media on Windows XP, then patching requires Administrator privileges. However, this not likely to be too restrictive, because most users administrators on Windows XP, and the restriction to software installed from removable media is not present on Windows Vista.

The main advantage of this method is that patches can be applied by a Standard User account without requiring a prompt and authentication for elevated rights. This provides a better user experience, because to play a game, a user with a Standard User account doesn't need to ask someone with an Administrator account to install the patch or to provide the Standard User account with permanent Administrator privileges.

It is possible that this method might work for games that require frequent patches, but the overhead of using Windows Install packages, in terms of build integration and supporting large numbers of files, might make this method less desirable than others.

Method 2: Require Administrator Rights to Apply Patches

In this method, the executable file that applies the patch requires Administrator rights to run. With Administrator rights, the patching executable can directly modify the game files located in %SystemDrive%\Program Files.

The advantage of this method is its simplicity. However, this method is unsuitable if the game needs frequent patches, because if a user with a Standard User account wants to play a game that requires frequent patches, like a massively multi-player online game, then that user has two choices:

  • Get an Administrator to log on and patch the game, which might be inconvenient for both parties.
  • Have their account permanently elevated with Administrator rights.

Note The latter solution not only weakens the security of the system as a whole, but it prevents important features, like parental controls, from working.

When implementing this method, the executable file that applies the patch must be different from the game executable. The manifest of the patching executable should specify requireAdministrator for requestedExecutionLevel to denote it as an application that requires Administrator rights. More information about how to do this can be found at Developer Best Practices and Guidelines for Applications in a Least Privileged Environment, in the "Application Manifest Schema" section.

Overall, method 1 is preferable for games that need just a few patches over their lifetimes.

Games that Require Frequent Patches

Many Internet-based games are being improved continuously, and they usually require regular patches. For these games, patches could be applied per-user or per-computer, as discussed in the follow topics. Other possible solutions include altering the ACL that protects %SystemDrive%\Program Files or creating a custom service.

Method 3: Install Per-User

One recommended and easy approach is to install the entire game to a per-user subfolder of the local application data folder, which you can find by calling SHGetFolderPath wih CSIDL_LOCAL_APPDATA. An example path is C:\Documents and Settings\user_name\Local Settings\Application Data\ExampleGame. Such a location allows an application running with Standard User rights to directly modify game files.

However, there is a disadvantage to this approach when a computer has multiple users: each user has a copy of the game installed, and patches must be downloaded and applied by each user. This wastes not only users' time and disk space, but it also increases use of network bandwidth to the server that provides patches. Also, because any application with standard user privileges can modify the game, game executables are less protected; it is up to the game manufacturer to decide if this is acceptable or not.

Method 4: Install to a Common Per-Computer Location

Another method is to install the non-executable game data to a subdirectory of the path specified by SHGetFolderPath CSIDL_COMMON_APPDATA; an example path is C:\Documents and Settings\All Users\Application Data\ExampleGame. This is a shared location for all users, and it can be modified by applications that run with Standard User rights. This method minimizes the need to reapply large patches when the game is played from more than one account. Executable files for the game should be kept in %SystemDrive%\Programs Files to minimize the risk to other accounts on the system. The executable files should verify the integrity of the new content in the shared directory, since that location can be modified by a program or person with Standard User rights; consider using MapFileAndCheckSum to compute a checksum of the files.

This method has the advantage of working equally well on both Windows XP and Windows Vista, and it doesn't require Administrator rights.

Other Possibilities

Outside of the methods already discussed, another possibility is to alter the ACL of %SystemDrive%\Program Files when installing the game so that a patching tool can write directly to the game's files even when run with Standard User rights. While this is not difficult, it does bypass the security protection that the system offers to the game's files and provides an opportunity for malicious programs to alter the contents of the directory. This is not advisable, and it is strongly recommended that an alternative be used instead.

One final possibility is to write a custom service. In general, writing a custom service to patch games is not a good idea, because doing so is complicated and error-prone. It is recommended that patching be done by use of other methods discussed in this article. However, a custom service might be necessary when combined with anti-cheat or anti-piracy solutions. Such a service should support a large number of games and be designed so that it can only download the patch files and write only to the installation directory for the target game. It is important that the service be small, have a minimal surface area vulnerable to attack, and use as few system resources as possible when the game is not running.

Summary

Ultimately it is up to you to decide which method to implement. You need to weigh the factors are that are important to you. Security, frequency of patching, ease of use by customer, workload required to implement, complexity of solution, and platform feature compliance are the factors that each developer must consider before deciding on a particular method.

You can find more information about user account protection in Windows Vista in Developer Best Practices and Guidelines for Applications in a Least-Privileged Environment.


Resource Management Best Practices

By Chuck Walbourn, Software Design Engineer

XNA Developer Connection (XDC)

June 2005

Managed textures, also known as automatic texture management, have been available in DirectX since version 6, with several revisions and enhancements made in subsequent releases. As of the release of the Direct3D 9 API, the automatic resource management includes support for textures, vertex buffers, and index buffers, all with a consistent shared interface. By using the Direct3D resource manager, applications can greatly simplify the handling of lost-device situations and can rely on the system to handle a reasonable amount of over-commitment of video memory resources.

Developers sometimes have difficulties using managed resources, in part due to the abstract nature of the system. While many common scenarios for resources are a good fit for managed resources, some cases perform better when using unmanaged resources. This article discusses best practices for dealing with resources generally, how managed and unmanaged resources behave, and provides some detail on how resources are typically handled by the runtime and drivers.

The technical article covers the following:

  • Video Memory
  • Managed Resources
  • Driver-Managed Resources
  • Default Resources
  • System Memory Resources
  • General Recommendations

Video Memory

For the video system to make use of a resource, it must be located in memory that is accessible to the GPU. Local video memory provides the best performance for the GPU, and certain resources (such as render targets and depth/stencil buffers) must be located in local video memory. With the advent of AGP, the GPU can also access a portion of the system memory directly. This memory area, known as the AGP aperture, is referred to as non-local video memory and is not available for other purposes. Non-local video memory can be read from and written to by the CPU, which typically has no high-performance access to local video memory, and is thus ideal for use as a shared memory resource. A key thing to remember about AGP memory is that it, like local video memory, is invalidated in lost-device situations, and persistent assets located there must be restored.

Figure 1. Relationship of the GPU, CPU, video RAM, and system RAM

Some integrated video solutions make use of a unified memory architecture (UMA), where main memory is addressable by all components of the systems. Direct3D supports UMA without requiring any change to the application, utilizing the same hints as for local video memory configurations. For such systems, resources are always located in system memory, and the driver is responsible for ensuring that resources work much like they do in a more traditional architecture while taking advantage of UMA's properties and any specific behavior of the hardware implementation.

Figure 2. GPU and CPU have equal access to system RAM in a unified memory architecture

Managed Resources

The majority of your resources should be created as managed resources in POOL_MANAGED. All your resources will be created in system memory and then copied as needed into video memory. Lost-device situations will be handled automatically from the system memory copy. Since not all managed resources are required to fit into video memory all at once, you can over-commit memory where a smaller video memory working set of resources is all that is required to render in any given frame. Note that it is likely that the majority of this backing-store system memory will be paged out to disk over time, which is why the Reset operation can be slow due to the need to page this data back in to restore the lost video memory.

The runtime keeps a timestamp for the last time a resource is used, and when a video memory allocation fails for loading a needed managed resource, it will release resources based on this timestamp in a LRU fashion. Usage of SetPriority takes precedence over the timestamp, so more commonly used resources should be set to a higher priority value. Direct3D 9.0 has limited information about the video memory managed by the driver, so the runtime may need to evict several resources to create a large enough region for the allocation to succeed. Proper priorities can help eliminate situations where something gets evicted and then is required again shortly there-after. The application can also call EvictManagedResources to force all the managed resources to be removed. Again, this can be a time-consuming operation to reload all the resources required for the next frame, but is very useful for level transitions where the working set changes significantly and for removing video memory fragmentation.

A frame count is also kept to allow the runtime to detect if the resource it just chose to evict was used early the current frame, which implies a thrashing situation where more resources are in use in a single frame than will fit into video memory. This triggers the replacement policy to switch to a MRU fashion rather than LRU for the remainder of the frame as this tends to perform slightly better under such conditions. Such thrashing behavior will significantly impact the rendering performance. Note that the notion of current frame is tied to EndScene, so any application making use of managed resources needs to make regular calls to this method.

Developers looking to find more information about how managed resources are behaving in their application can make use of the RESOURCEMANAGER event query via the IDirect3DQuery9 interface. This only works when using the debug runtimes, so this information cannot be depended upon by the application, but it provides deep detail on the resources managed by the runtime.

While understanding how the resource manager works can help when tuning and debugging your applications, it is important to not tie your application too tightly to the implementation details of the current runtime or drivers. Revisions of the driver or changes in hardware can significantly change the behavior, and future versions of Direct3D will have significantly improved and sophisticated resource management.

Driver-Managed Resources

Direct3D drivers are free to implement the driver managed textures capability, indicated by D3DCAPS2_CANMANAGERESOURCE, which allows the driver to handle the resource management instead of the runtime. For the (rare) driver that implements this feature, the exact behavior of the driver's resource manager can vary widely, and you should contact the driver's vendor for details on how this works for their implementation. Alternatively, you can ensure that the runtime manager is always used instead by specifying D3DCREATE_DISABLE_DRIVER_MANAGEMENT when creating the device.

Default Resources

While managed resources are simple, efficient, and easy to use, there are times when using video memory directly is preferred or even required. Such resources are created in the POOL_DEFAULT category. Making use of such resources does cause additional complications for your application. Code is required to cope with the lost-device situation for all the POOL_DEFAULT resources, and performance considerations must be taken into account when copying data into them. Failure to specify USAGE_WRITEONLY or making a render target lockable can also impose serious performance penalties.

Calling Lock on a POOL_DEFAULT resource is more likely to cause the GPU to stall than working with a POOL_MANAGED resource, unless using certain hint flags. Depending on the location of the resource, the pointer returned could be to a temporary system memory buffer, or it can be a pointer directly into AGP memory. If it is a temporary system memory buffer, data will need to be transferred to the video memory after the Unlock call. If the video resource is not write-only, data will have to be transferred into the temporary buffer during the Lock. If it is an AGP memory area, temporary copies are avoided but the cache behavior required can result in slow performance.

Care should be taken to write a full cache line of data into any pointer to AGP aperture memory to avoid the penalty of write-combing, which induces a read-write cycle, and sequential access of the memory area is preferred. If your application needs to make random access to data during creation, and you do not wish to make use of a managed resource for the buffer, you should work with a system memory copy instead. Once the data has been created, you can then stream the result into the locked resource memory to avoid paying a high penalty for the cache write-combining operation.

The LOCK_NOOVERWRITE flag can be used to append data in an efficient manner for some resources, but ideally, multiple Lock and Unlock calls to the same resource can be avoided. Making proper use of the various lock flags is important to optimal performance, as is using a cache-friendly pattern of data access when filling locked memory.

Using Both Managed and Default Resources

Mixing allocations of managed and POOL_DEFAULT resources can cause video memory fragmentation and confuse the runtime's view of the video memory available for managed resources. Ideally, you should create all POOL_DEFAULT resources before making use of POOL_MANAGED resources or make use of the EvictManagedResources call before allocating unmanaged resources. Remember that all allocations made from POOL_DEFAULT that reside in video memory tie up memory for the life that resource that is unavailable for use by the resource manager or for any other purpose.

Note that unlike previous versions of Direct3D, the version 9 runtime automatically evicts some managed resources before giving up on a failed unmanaged resource allocation for a lack of video memory, but this can potentially create additional fragmentation and even force a resource into a sub-optimal location (for example, having a static texture in non-local video memory). Again, it is best to allocate all required unmanaged resources up front and before using any managed resources.

Dynamic Default Resources

Data that is generated and updated at a high frequency has no need for the backing-store since all the information will be re-created when restoring the device. Such data is typically best created in POOL_DEFAULT, specifying the USAGE_DYNAMIC hint, so that the driver can make optimization decisions when placing the resource, knowing that it will be updated often. This typically means putting the resource into non-local video memory, and thus, it is usually much slower for the GPU to access than local video memory. For UMA architectures, the driver might choose a particular placement for dynamic resources to optimize for CPU write access.

This usage is typical for software skinning solutions and CPU-based particle systems filling out vertex/index buffers, and the LOCK_DISCARD flag will ensure that stalls are not created in cases where the resource is still in use from the previous frame. Using a managed resource in this case would update a system memory buffer, which would then be copied to video memory, and then used for only a frame or two before being replaced. For systems with non-local video memory, the extra copy is eliminated by proper use of this dynamic pattern.

Standard textures cannot be locked, and can only be updated via UpdateSurface or UpdateTexture. Some systems support dynamic textures, which can be locked, and use the LOCK_DISCARD pattern, but a capabilities bit (D3DCAPS2_DYNAMICTEXTURES) must be checked before making use of such resources. For highly dynamic textures (video or procedural), your application could create matching POOL_DEFAULT and POOL_SYSTEMMEM resources and handle video-memory updates by using UpdateTexture. For highly frequent and partial updates, the UpdateTexture paradigm is likely the better choice.

As useful as dynamic resources can be, be careful when designing systems that rely heavily on dynamic submission. Static resources should be placed into POOL_MANAGED to ensure both good utilization of local video memory, and to make more efficient use of limited bus and main memory bandwidth. For resources that are semi-static, you may find that the cost of an occasional upload to local video memory is much less than the constant bus traffic generated by making them dynamic.

System Memory Resources

Resources can also be created in POOL_SYSTEMMEM. While they cannot be used by the graphics pipeline, they can be used as sources for updating POOL_DEFAULT resources by using UpdateSurface and UpdateTexture. Their locking behavior is simple, although stalls might occur if they are in use by one of the previously mentioned methods.

Though they reside in system memory, POOL_SYSTEMMEM resources are limited to the same formats and capabilities (such as maximum size) supported by the device driver. The POOL_SCRATCH resource type is another form of system memory resource that can utilize all formats and capabilities supported by the runtime, but cannot be accessed by the device. Scratch resources are intended primarily for use by content tools.

Figure 3. Memory resources in video RAM, AGP aperature, and system RAM

General Recommendations

Getting the technical implementation details of resource management correct will go a long way toward achieving your performance goals for your application. Planning how the resources are presented to Direct3D and the architectural design around getting the data loaded in a timely fashion is a more complicated task. We recommend a number of best practices when making these decisions for your application:

  • Pre-process all your resources. Relying on expensive load-time conversion and optimization for your resources is convenient during development, but doing so puts a great performance burden on your users' computers. Pre-processed resources are faster to load, faster to use, and give you the option of doing sophisticated off-line work.
  • Avoid creating many resources per frame. The driver interactions required can serialize the CPU and GPU, and the operations involved are heavy-weight, as they often require kernel transitions. Spread out creation over several frames or reuse resources without creating/releasing them. Ideally, you should wait several frames before locking or releasing resources that were recently used to render.
  • At the end of the frame, be sure to unbind all resource channels (that is, stream sources, texture stages, and current indices). Doing so will ensure that dangling references to resources are removed before they cause the resource manager to keep resources resident that are actually no longer in use.
  • For textures, use compressed formats (for example, DXTn) with mip-maps, and consider making use of a texture atlas. These greatly reduce bandwidth requirements, and they can reduce the overall size of the resources, thus making them more efficient.
  • For geometry, make use of indexed geometry as this helps compress vertex buffer resources, and modern video hardware is heavily optimized around reuse of vertices. By making use of programmable vertex shaders, you can compress the vertex information and expand it during the vertex processing. Again, this helps reduce bandwidth requirements and makes vertex buffer resources more efficient.
  • Avoid over-optimizing your resource management. Future revisions of drivers, hardware, and the operating system can potentially cause compatibility problems if the application is tuned too heavily to a particularly combination. Since most applications are CPU-bound, expensive CPU-based management generally causes more performance issues than it solves.

See Also

Managing Resources (Direct3D 9), Lost Devices (Direct3D 9), Performance Optimizations (Direct3D 9), Compressed Texture Resources (Direct3D 9), Queries (Direct3D 9), D3DUSAGE, D3DPOOL, D3DCREATE


Simplifying Game Installation

XNA Developer Connection (XDC)

December 2005

Introduction

One major advantage of games that run on a console instead of on Windows is the installation process — or the lack thereof. When a game is first run on a console, the player makes a few choices or confirmations and is able to start playing almost immediately. Installing a game on Windows is more complicated, by comparison, by its need for substantial user input and its potentially long installation process. However this installation process can be improved to provide a better experience for players of Windows-based games. This article outlines some concepts that developers of games for Windows can and should implement to improve the overall experience.

Typical Game Installation

When comparing the ease of installation and the amount of time required to begin playing a game, the typical Xbox experience is much better than Windows. The flow chart in Figure 1 shows the typical installation processes on Xbox and on Windows, for comparison.

Figure 1. Typical Installation Process, Xbox vs. Windows

Simplified Game Installation

However, the greater requirements placed on the user to install a game on Windows does not need to be. By implementing the following concepts, you will decrease the number of steps a user must complete, which can shorten the amount of time needed for installation.

  • Ask All Questions Up Front
  • Provide Special Installation Modes
  • Minimize the Quantity of Installation Questions
  • Change Optional Components Into Required Components
  • Always Install DirectX, and Do So Silently
  • Think About Your EULA
  • Automatically Launch After Installation
  • Optimize Your Installation Performance
  • Register with Windows Firewall During Installation
  • Install for All Users, Not Just the Current User

Ask All Questions Up Front

All of the choices that the gamer selects during installation that might cause installation to abort should be offered before those that won't stop the installation; the worst-case scenario is for the gamer to be offered a choice that could cause installation to abort after the game has been completely copied from the installation media. This can be especially frustrating if the installation requires swapping of multiple disks to complete. You should design your installer to ask all important questions (such as acceptance of the EULA) at the beginning of the process, so that the installation doesn't need to be rolled back at or near its completion.

You could also prompt the user to accept the EULA and to enter the product key when the game starts for the first time, rather than asking for these as part of installation. In this scenario, refusing to accept the EULA or cancelling during entry of the product key won't roll back the installation, because these prompts are part of the game itself. This might be useful if you have preinstalled or OEM scenarios. However, take care not to prompt the user to make choices during initial startup that require administrative credentials.

Provide Special Installation Modes

Ideally, Windows game installers should only offer completely automatic and custom modes of installation and nothing in between.

The automatic mode should not ask any more questions than absolutely necessary to create a functioning installation, and simply use default settings without prompting for other options. Many gamers don't care about the location of the game on the hard drive or the initial game settings — they just want to play the game as soon as possible.

The custom mode should only be for power users who need or want to change the installation path or other installation options, and it should not be the default mode.

The custom mode can offer the choice of either a full installation or of a minimum installation that installs only the files necessary to play the game. If the gamer chooses minimum installation, the game can use install-on-demand or streaming techniques to read the remaining installation data, which allows the gamer to begin playing the game quickly without having to wait for a full installation to complete. However, installing data in this manner has an impact on the design of the game engine. For more information about installing content on demand, see Install-on-Demand for Games.

Minimize the Quantity of Installation Questions

In both installation modes, you should try to limit the number of times that you prompt the gamer during installation. This will reduce the amount of reading required to get the game installed and running. If necessary, there should only be one follow up prompt after the installation is finished. As you can see, the example shown in Figure 1 has too many post-installation prompts.

Change Optional Components Into Required Components

Make the installation of all components required rather than making any of them optional, unless there is a good reason to do otherwise. Simply installing all of the components will make the game start without further delay and fuss.

Always Install DirectX, and Do So Silently

It is strongly recommended that the game silently install the DirectX redistributable that the game was built against. The DirectX installation process is designed so that it verifies whether anything needs to be updated and quickly returns if it doesn't. So, there is no need to ask users if they want DirectX installed. A silent installation of DirectX can be done by running this command from your installation package: dxsetup.exe /silent

Asking a user if he wants to install DirectX can cause many problems. For example, if the user assumes he has the latest redistributable installed and chooses to skip installation of DirectX; installation of the game could continue successfully anyway. However, if the game requires a specific version of D3DX, or other updated functionality that was skipped, then the game won't work, and the user will be very frustrated.

If for some reason you must ask the user if he wants to install DirectX, your installer should — at least — abort and roll back the entire installation process if the user chooses not to install DirectX. Rolling back the installation will avoid any errors caused by the system not having the latest version of DirectX installed when the game launches.

Note that it is important to ship the redistributable that your game was built against instead of simply shipping the redistributable from the latest DirectX SDK. The latest redistributable might not contain all of the components found in a previous version.

It is also important to have the installer check to see what is already installed and determine whether rebooting the system is necessary. If DirectX is up to date, the copying of one DLL shouldn't require rebooting. For more information see Installing DirectX with DirectSetup.

Think About Your EULA

The DirectX EULA can and should be appended to the game developer's EULA. There is no point in allowing the user to agree to the developer's EULA and not the DirectX EULA. Either the user must agree to both EULAs or not install the game. If a developer feels she must offer the user the choice, the whole installation should fail if the user chooses not to agree to the DirectX EULA.

If possible, consult with your legal department to see if you can avoid EULAs altogether, and use a shrink-wrapped EULA like console games use. This will avoid needing to ask users if they want to accept the EULA. The DirectX EULA needs to be appended to the shrink-wrapped EULA; otherwise, the DirectX EULA must be displayed and accepted which defeats the purpose of using a shrink-wrapped EULA.

One exception to a shrink-wrapped EULA is for a content editor. Any editor needs to display a EULA during the editor's installation or when the editor is started for the first time. Many gamers are only interested in playing and not in making content, so the installation of an editor should be a separate process.

Automatically Launch After Installation

Almost all gamers want to play a game as soon as they receive it. By default, the installer should launch the game after finishing the installation, although it is good practice, in a custom installation, to specify this in a check box that the user may override.

Optimize Your Installation Performance

Developers should be testing their installations to determine how much time is required for installation. Developers can decrease installation time by using the latest version of their installation tools and by optimizing the data layout on the installation media. Most DVD authoring tools have options for layout optimization that can improve installation times without increasing development workload.

Register with Windows Firewall During Installation

If your game can run as a server or the game networking model is peer-to-peer, register your game with Windows firewall at installation time. This will prevent the firewall dialog from popping up in the middle of the game when they user tries to access the network. If the game is a pure client, then the installer shouldn't add the game to the firewall's exceptions list.

For more information see, Windows Firewall for Game Developers.

Install for All Users, Not Just the Current User

Simply default to installing the game for all users. This will allow any new user on the system to play the game without having to install it for them. If installation for all users is attempted on a Least-Privileged User Account, the installer will either fail or prompt the user for an administrator password. So, try to detect if the account has proper privileges before offering the option to install for all users. If the user does choose to install the game for the current user only, be sure to change the installation path to a location within the user's profile. Ideally, change the path to somewhere in non-roaming application data (for example, a subdirectory of CSIDL_LOCAL_APPDATA).

Example of Simplified Installation

Following in Figure 2 is an example of an improved process for installing a game in Windows, with simplified installation dialogs.

Figure 2. Simplified Installation Process

The following are important points of note:

  • The installer is automatically launched upon insertion of the installation disc (auto run).
  • The splash screen — with options to install, remove, view the Web site, or exit — is not shown if the game is not yet installed on the computer.
  • The Installation dialog is the first dialog shown by the installer.
  • The Install button is the implementation of the automatic installation mode.
  • The Options button is the implementation of the custom installation mode.
  • The Cancel button will immediately exit the installer. Because launching the installer is a trivial action for the user, do not prompt for confirmation.
  • Once the user accepts the EULA and enters a valid product key, the installation starts.
  • When the installation process is complete, the game will either launch automatically or display a dialog that alerts the user that installation is complete and offer any additional options, based on whether Run game after installation was selected.
  • The Run game checkbox provides another chance to launch the game, for convenience. This option is always unselected by default, as the Installation Complete dialog can only be shown if Run game after installation was unselected in the Installation Options dialog.
  • The OK button dismisses the dialog, optionally taking action on the Run and View the Readme checkboxes.

Summary

Gamers want to be playing a game as soon as possible. The last thing that a gamer wants to be doing is wading through dialogs and making choices that are the same as for all of the other games that he or she has installed. Implementing these ideas can shorten the amount time that a gamer spends installing a game on Windows and help improve the overall quality of the Windows gaming experience.


Taking Advantage of High-Definition Mouse Movement

XNA Developer Connection (XDC)

April 2006

Introduction

A standard computer mouse returns data at 400 dots per inch (DPI), whereas a high-definition mouse generates data at 800 DPI or greater. This makes input from a high-definition mouse much more precise than that from a standard mouse. However, high-definition data cannot be obtained through the standard WM_MOUSEMOVE messages. In general, games will benefit from high-definition mouse devices but games that obtain mouse data using just WM_MOUSEMOVE won't be able to access the full, un-filtered resolution of the mouse.

A number of companies are manufacturing high-definition mouse devices, such as Microsoft and Logitech. With the increasing popularity of high-resolution mouse devices, it is important that developers understand how to use the information generated by these devices optimally. This article focuses on the best way to optimize the performance of such mouse input in a game like a first-person shooter.

More general information about high-definition input devices can be found on product Web sites, like Microsoft Mouse and Keyboard Hardware: High-Definition Technology.

Retrieving Mouse Movement Data

There are three primary methods to retrieve mouse data:

  • WM_MOUSEMOVE
  • WM_INPUT
  • DirectInput

There are advantages and disadvantages to each method, depending on how the data will be used.

WM_MOUSEMOVE

The simplest method of reading mouse movement data is through WM_MOUSEMOVE messages. The following is example of how to read mouse movement data from the WM_MOUSEMOVE message:

    case WM_MOUSEMOVE:
    {
        int xPosAbsolute = GET_X_PARAM(lParam);
        int yPosAbsolute = GET_Y_PARAM(lParam);
        // ...
        break;
    }

The primary disadvantage to data from WM_MOUSEMOVE is that it is limited to the screen resolution. This means that if you move the mouse slightly — but not enough to cause the pointer to move to the next pixel — then no WM_MOUSEMOVE message is generated. So, using this method to read mouse movement negates the benefits of high-definition input.

The advantage to WM_MOUSEMOVE, however, is that Windows applies pointer acceleration (also known as ballistics) to the raw mouse data, which makes the mouse pointer behave as customers expect. This makes WM_MOUSEMOVE the preferred option for pointer control (over WM_INPUT or DirectInput), since it results in more natural behavior for users. While WM_MOUSEMOVE is ideal for moving mouse pointers, it is not so good for moving a first-person camera, since the high-definition precision will be lost.

More information about WM_MOUSEMOVE can be found at WM_MOUSEMOVE

WM_INPUT

The second method of obtaining mouse data is to read WM_INPUT messages. Processing WM_INPUT messages is more complicated than processing WM_MOUSEMOVE messages, but WM_INPUT messages are read directly from the Human Interface Device (HID) stack and reflect high-definition results.

To read mouse movement data from the WM_INPUT message, the device must first be registered; the following code provides an example of this:

    #ifndef HID_USAGE_PAGE_GENERIC
    #define HID_USAGE_PAGE_GENERIC         ((USHORT) 0x01)
    #endif
    #ifndef HID_USAGE_GENERIC_MOUSE
    #define HID_USAGE_GENERIC_MOUSE        ((USHORT) 0x02)
    #endif

    RAWINPUTDEVICE Rid[1];
    Rid[0].usUsagePage = HID_USAGE_PAGE_GENERIC;
    Rid[0].usUsage = HID_USAGE_GENERIC_MOUSE;
    Rid[0].dwFlags = RIDEV_INPUTSINK;
    Rid[0].hwndTarget = hWnd;
    RegisterRawInputDevices(Rid, 1, sizeof(Rid[0]);

The following code handles WM_INPUT messages in the application's WinProc handler:

    case WM_INPUT:
    {
        UINT dwSize = 40;
        static BYTE lpb[40];

        GetRawInputData((HRAWINPUT)lParam, RID_INPUT,
                        lpb, &dwSize, sizeof(RAWINPUTHEADER));

        RAWINPUT* raw = (RAWINPUT*)lpb;

        if (raw->header.dwType == RIM_TYPEMOUSE)
        {
            int xPosRelative = raw->data.mouse.lLastX;
            int yPosRelative = raw->data.mouse.lLastY;
        }
        break;
    }

The advantage to using WM_INPUT is that your game receives raw data from the mouse at the lowest level possible.

The disadvantage is that WM_INPUT has no ballistics applied to its data, so if you want to drive a cursor with this data, extra effort will be required to make the cursor behave like it does in Windows. For more information about applying pointer ballistics, see Pointer Ballistics for Windows XP

More information about WM_INPUT can be found at About Raw Input

DirectInput

DirectInput is a set of API calls that abstracts input devices on the system. Internally, DirectInput creates a second thread to read WM_INPUT data, and using the DirectInput APIs will add more overhead than simply reading WM_INPUT directly. DirectInput is only useful for reading data from DirectInput joysticks; however, if you only need to support the Xbox 360 controller for Windows, then use XInput instead. Overall, using DirectInput offers no advantages when reading data from mouse or keyboard devices, and the use of DirectInput in these scenarios is discouraged.

Compare the complexity of using DirectInput, shown in the following code, to the methods previously decribed. The following set of calls are needed to create a DirectInput mouse:

    LPDIRECTINPUT8 pDI;
    LPDIRECTINPUTDEVICE8 pMouse;

    hr = DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION,
                             IID_IDirectInput8, (VOID**)&pDI, NULL );
    if( FAILED(hr) )
        return hr;

    hr = pDI->CreateDevice( GUID_SysMouse, &pMouse, NULL );
    if( FAILED(hr) )
        return hr;

    hr = pMouse->SetDataFormat( &c_dfDIMouse2 );
    if( FAILED(hr) )
        return hr;

    hr = pMouse->SetCooperativeLevel( hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND );
    if( FAILED(hr) )
        return hr;

    if( !bImmediate )
    {
        DIPROPDWORD dipdw;
        dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
        dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
        dipdw.diph.dwObj        = 0;
        dipdw.diph.dwHow        = DIPH_DEVICE;
        dipdw.dwData            = 16; // Arbitrary buffer size

        if( FAILED( hr = pMouse->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) )
            return hr;
    }

    pMouse->Acquire();

And then the DirectInput mouse device can be read each frame:

    DIMOUSESTATE2 dims2;
    ZeroMemory( &dims2, sizeof(dims2) );

    hr = pMouse->GetDeviceState( sizeof(DIMOUSESTATE2),
                                 &dims2 );
    if( FAILED(hr) )
    {
        hr = pMouse->Acquire();
        while( hr == DIERR_INPUTLOST )
            hr = pMouse->Acquire();

        return S_OK;
    }

    int xPosRelative = dims2.lX;
    int yPosRelative = dims2.lY;

Summary

Overall, the best method to receive high-definition mouse movement data is WM_INPUT. If your users are just moving a mouse pointer, then consider using WM_MOUSEMOVE to avoid needing to perform pointer ballistics. Both of these window messages will work well even if the mouse isn't a high-definition mouse. By supporting high definition, Windows games can offer more precise control to users.


The Direct3D Transformation Pipeline

Microsoft Corporation

April 1998

Introduction

This white paper provides a technical explanation for Direct3D application developers on how to set the parameters of the Direct3D Transformation Pipeline by the direct manipulation of Direct3D matrices.

Overview

Direct3D uses three transformations to change your 3D model coordinates into pixel coordinates (screen space). These transformations are world transform, view transform, and projection transform.

World transform controls how model coordinates are transformed into world coordinates. World transform can include translations, rotations, and scalings, but it does not apply to lights. For more information on working with world transforms, see World Transform (Direct3D 9).

View transform controls the transition from world coordinates into "camera space," determining camera position in the world. For an example of working with view transforms, see View Transform (Direct3D 9).

Projection transform changes the geometry from camera space into "clip space" and applies perspective distortion. The term "clip space" refers to how the geometry is clipped to the view volume during this transform. For an example of working with projection transforms, see Projection Transform (Direct3D 9).

Finally, the geometry in clip space is transformed into pixel coordinates (screen space). This transformation is controlled by the viewport settings.

Clipping and transforming vertices must take place in homogenous space (simply put, space in which the coordinate system includes a fourth element), but the final result for most applications needs to be non-homogenous three-dimensional (3D) coordinates defined in "screen space." This means that both the input vertices and the clipping volume must be translated into homogenous space to perform the clipping and then translated back into non-homogenous space to be displayed.

The three Direct3D transformations-world, view, and projection transform-are defined by Direct3D matrices. A Direct3D matrix is a 4x4 homogenous matrix defined by a D3DMATRIX structure. Although Direct3D matrices are not standard objects-they are not represented by a COM interface-you can create and set them just as you would any other Direct3D object. For more information on Direct3D matrices, see Transforms (Direct3D 9).

The Transformation Pipeline

If a vertex in the model coordinate is given by Pm = (Xm, Ym, Zm, 1), then the following transformations are applied to compute screen coordinates Ps = (Xs, Ys, Zs, Ws):

The seven stages are as follows:

  1. World matrix Mworld transforms vertices from the model space to the world space. This matrix is set by:

    d3dDevice->SetTransform (D3DTRANSFORMSTATE_WORLD, matrix address)

    Direct3D implementation assumes that the last column of this matrix is (0, 0, 0, 1). No error is returned if the user specifies a matrix with a different last column, but the lighting and fog will be incorrect.

  2. View matrix Mview transforms vertices from the world space to the camera space. This matrix is set by:

    d3dDevice->SetTransform (D3DTRANSFORMSTATE_VIEW, matrix address)

    Direct3D implementation assumes that the last column of this matrix is (0, 0, 0, 1). No error is returned if the user specifies a matrix with different last column, but the lighting and fog will be incorrect.

  3. Projection matrix Mproj transforms vertices from the camera space to the projection space. This matrix is set by:

    d3dDevice->SetTransform (D3DTRANSFORMSTATE_PROJECTION, matrix address)

    The last column of the projection matrix should be (0, 0, 1, 0), or (0, 0, a, 0) for correct fog and lighting effects. (0, 0, 1, 0) form is preferred.

    Clipping volume for all points Xp = (Xp, Yp, Zp, Wp) in the projection space is defined as:

    -Wp < Xp <= Wp

    -Wp < Yp <= Wp

    0 < Zp <= Wp

    All points that do not satisfy these equations will be clipped.

    If a view volume is defined as:

    Sw-screen window width in camera space in near clipping plane

    Sh-screen window height in camera space in near clipping plane

    Zn-distance to the near clipping plane along Z axes in camera space

    Zf-distance to the far clipping plane along Z axes in camera space,

    then a perspective projection matrix could be written as follows:

    where Mij are members of Mproj.

    For the orthogonal projection we have:

    Direct3D assumes that the perspective projection matrix has the form:

    If the perspective projection matrix does not have this form, there will be some artifacts. For example, table fog will not work.

  4. Direct3D allows the user to change the clip volume as follows:

    This can be rewritten as:

    where:

    Cx, Cy - dvClipX, dvClipY from D3DVIEWPORT2

    Cw, Ch - dvClipWidth, dvClipHeight from D3DVIEWPORT2

    Zmin, Zmax - dvMinZ, dvMaxZ from D3DVIEWPORT2

    This transformation can provide increased precision and is equivalent to scaling and shifting the clipping volume.

    The corresponding Mclip matrix is:

    A vertex is transformed by:

    (Xc, Yc, Zc, Wc) = (Xp, Yp, Zp, Wp) * Mclip

    If you do not want to scale the clip volume, you can set viewport parameters to default values:

    dvClipWidth = 2

    dvClipHeight = 2

    dvClipX = -1

    dvClipY = 1

    dvMinZ = 0

    dvMaxZ = 1

  5. The clipping stage is optional if the user specifies the D3DDP_DONOTCLIP flag in a DrawPrimitive call. In this case, all matrices (including Mvs) can be combined.

  6. The viewport scale matrix Mvs scales coordinates to be within the viewport window and flips the Y axis from up to down:

    where:

    dwX, dwY - viewport offsets in pixels from D3DVIEWPORT2

    dwWidth, dwHeight - viewport width and height in pixels from D3DVIEWPORT2

  7. Finally, screen coordinates are computed and passed to the rasterizer:

Usage Tips

  1. The last column of the world and view matrices should be (0, 0, 0, 1), or the lighting will be incorrect.

  2. Set the viewport parameters to build an identity Mclip matrix, unless you understand exactly what it is needed for.

    dvClipWidth = 2

    dvClipHeight = 2

    dvClipX = -1

    dvClipY = 1

    dvMinZ = 0

    dvMaxZ = 1

See Also

World Transform (Direct3D 9), View Transform (Direct3D 9), Projection Transform (Direct3D 9), D3DMATRIX, Transforms (Direct3D 9)


Top Issues for Windows Titles

By Chuck Walbourn, Software Design Engineer

XNA Developer Connection (XDC)

December 2006

The Microsoft Windows Gaming and Graphics Technologies Developer Relations group performs performance analysis for many Windows games each year. During these sessions, we get hands-on experience to tie into the developer feedback and queries we receive daily. Occasionally we help track down a mysterious crash or other problem in a title, which gives us further insight into problems that developers are encountering.

This document highlights many of the common issues we've seen in current-generation PC games:

  • CPU-Limited Performance
  • Poor Batch Management
  • Excessive Memory Copying
  • Excessive Use of Dynamic Draw Submission
  • High Overhead in File Processing
  • Slow and Frustrating Installation
  • Lack of Consideration of Physical Memory
  • Over-Reliance on Real-Time Audio Sample Rate Conversion
  • Fragmention of Virtual Memory
  • Manipulation of the Float-Point Control Word
  • Optional Installation of the DirectX Runtime
  • Excessive Use of Thread Synchronization
  • Use of RDTSC

CPU-Limited Performance

The vast majority of games are limited by CPU performance on systems with high-performance graphics processing units (GPUs). This is sometimes due to poor use of batching for draw submissions, but more typically, this is due to other game systems consuming a large portion of the available CPU cycles. In the few cases in which we have seen the GPU as the limitation, the cause is very high fill rates or pixel shader demand, in high-resolution settings, or low vertex-shader performance by a video card.

Because most titles are CPU-limited, the biggest performance wins come from optimizing CPU-intensive game systems. Typically, the AI or physics systems and the associated collision-detection logic are the primary consumers of CPU cycles in well-behaving Microsoft Direct3D applications. Any work to improve these systems can improve the overall performance of the game.

Poor Batch Management

Achieving good parallelism with the GPU requires that draw batches contain enough geometry — and the shaders have the right complexity — to keep the video card busy, while not using so many batches that the command buffer is flooded. On current-generation hardware, we recommend approximately 300 or fewer draw-batch submissions per frame (fewer on lower-performance CPUs) to prevent the driver's processing of the command-buffer from becoming a performance bottleneck. Some other API state calls and driver combinations can result in costly CPU processing (driver compiling of shaders, for example), so we highly recommend routine performance analysis with PIX and other tools.

Excessive Memory Copying

During the development of most PC titles, developers use convenient data structures and strings for content management. The CPU work required for string comparison, copying, and other manipulations often has a measurable overhead, particularly when taking into account the performance hits associated with the cache and memory subsystem. Plans should be made when developing these systems for removing or minimizing the reliance on string processing once the product enters into the primary testing and release phases.

Excessive Use of Dynamic Draw Submission

Modern video hardware performs well when dealing with static data. High-end adapters often have a very large amount of video memory, but this memory cannot be effectively utilized by dynamic data.

While reasonably efficient usage patterns of dynamic vertex buffers/index buffers can be implemented for dynamic content, many titles overuse this idiom for what is otherwise static content. We most often see this with binary space partitioning (BSP) trees and portal-based systems that store geometry in a data structure that does not map to the hardware and must be processed into buffers for every frame. Putting as much content into static resources as possible can greatly reduce the bandwidth overhead of transferring data to the video card, make better use of on-board VRAM, and reduce the CPU/cache overhead involved in processing this content.

High Overhead in File Processing

PC games have gotten a reputation for long loading times, particular when compared with console titles with strict loading-time requirements. Our analysis of the way that many titles make use of the file subsystem reveals some common issues.

The overhead of opening a file is usually much higher than developers expect. With on-demand virus scanners in widespread use, and the additional functionality of NTFS, opening a file is a fairly expensive operation. Opening many files at once or opening and closing the same file repeatedly is therefore a poor method of dealing with file management. Some games have attempted to mitigate this performance cost by testing for the existence of a file before opening it. The reality is that testing for the existence of a file on NTFS requires opening the file, so testing before opening results in paying the cost twice.

Games that allow add-on modifications, or mods, or that still include development scaffolding to check for override data files, can have significant delays in loading the game because of checking for these files, even when those files are not present. We recommend that games only check for these files when run with a special command-line switch, or other mode indicator, so that only those users who make use of this functionality actually pay the performance cost of these (often extensive) checks.

Additional performance can be obtained from the file system by the following:

  • Appropriate use of the file system hints FILE_FLAG_RANDOM_ACCESS and FILE_FLAG_SEQUENTIAL_SCAN
  • Sizing buffers to avoid a large quantity of calls to the read/write APIs of the OS
  • Accessing files asynchronously
  • Loading threads in the background

We also strongly recommend converting data offline (at build or installation time) rather than relying on conversion when the game is first run, as doing so imposes a significant performance tax for every user.

Slow and Frustrating Installation

Another common issue we've seen is very long installation times required for many modern PC games. The installers prompt the user many times, sometimes simply to tell the user, for example, "You do not need DirectX installed." Generally, these offending installers require the user to select Next or OK many times before installation of the game actually begins. Once it does begin, we've seen some titles take an hour or more before the user gets the opportunity to play the game. We feel strongly that the first hour of game play experience should not be the installation.

We recommend a number of approaches for dealing with installation. First, keep the prompts simple and to a minimum. Second, architect your game data such that some or all the data files can be used directly from the distribution disk where possible — modern DVD drives have very high bandwidth. Third, consider implementing install-on-demand in your titles to reduce or eliminate the installation process and allow users to get into the game as quickly as possible. (For more information about installing on demand, see Install-on-Demand for Games.)

For more recommendations about game installation, see Simplifying Game Installation.

Lack of Consideration of Physical Memory

Because of the wide variability of PC hardware in the market, titles typically make use of ad hoc configuration tests to select default settings for the level of graphical detail. Some of the titles we've seen are using video memory size in these tests, but failing to correlate this with physical memory size. In order to handle lost-device situations, the majority of the video memory (both local VRAM on the card and the non-local AGP memory aperture) must be backed by physical memory, either through the use of managed resources or custom data structures. Some high-end video cards have VRAM sizes rivaling the size of low-end CPU memories. In situations where the system has limited physical memory compared to the video card, most of that VRAM cannot be effectively utilized, and lower detail settings should be configured.

Over-Reliance on Real-Time Audio Sample Rate Conversion

Another common source of CPU cycle burn we've seen occurs when the audio system is required to convert the playback rate during mix into the hardware buffer. With Windows Driver Model (WDM) drivers, the hardware buffer format is not under direct application control, because it is a kernel-level resource; instead, the format is selected based on the highest-quality format of all sources and the capabilities of the hardware. By default, Windows XP uses a high-quality sample rate conversion for this process, and if the majority of the audio samples require a rate conversion, a significant portion of the CPU cycles will be consumed.

We recommend creating all of your DirectSound buffers with the same sample rate. If you make any use of Microsoft Win32 waveOut functions, you should use a consistent sample rate with these, too. With WDM drivers, the buffers will all be mixed by the kernel, and if you use a higher sampling rate on some of them, the sample rates of all of the rest will be converted to match. Note that this implies using the same playback rate for all your audio samples, including any streaming audio decompression buffers. Setting the primary buffer rate has no effect unless you are targeting either Windows 98 or Windows Millennium Edition.

Fragmention of Virtual Memory

We've seen a number of recent issues related to the 32-bit limit on process memory space. While 2 GB of virtual address space for user-mode processes has been more than adequate historically, the increased use of large memory-mapped files, custom memory allocators, and increasing VRAM size (which must be mapped into process space) has started to cause situations where allocations of virtual memory space are failing. Some non-Microsoft DLLs are using fixed-start locations in the middle of the virtual address space, which is causing fragmentation that results in failed allocations.

These problems most often appear when the game makes use of a custom memory allocation scheme that attempts to allocate a large continuous chunk of virtual memory space. Our recommendation is to write allocators such that they request more reasonably sized portions of the virtual address space as needed. For example, requesting 64 or 256 MB at a time, but not 1 GB. However, care should be taken to not cause further fragmentation. The advent of 64-bit operating systems and hardware will greatly help these issues in the future, but care must be taken on current-generation 32-bit systems.

Manipulation of the Float-Point Control Word

As a debugging aid, some developers have been enabling exceptions on the floating-point unit (FPU) via manipulations of the floating-point control word. Doing this is highly problematic and will likely cause the process to crash. Just like the calling convention requires that the ebx register be preserved, the majority of the system assumes that the FPU is in a default state, will give reasonable results, and won't generate exceptions. Drivers and other system components will often compute results based on the assumption that standard error values will appear in the registers for bad conditions, but if exceptions are enabled, these will go unhandled and result in crashes.

Direct3D will set the floating-point unit to single-precision, round-to-nearest as part of initialization, unless the D3DCREATE_FPU_PRESERVE flag is used, in which case the floating-point control word is untouched. In any libraries where we need to have different rounding rules or other behavior — such as dealing with software vertex shaders or compilation — we save and restore the control word. If the game needs to make use of non-standard rounding or FPU exceptions, it should save and restore the floating-point control word and be sure to not call any external code not proven to be safe from these problems, including system APIs.

Optional Installation of the DirectX Runtime

A number of games ask the user whether to install DirectX. This can cause problems if the user assumes that the system has the latest DirectX redistributable installed and skips installation, and subsequently, the installation continues successfully. If the game requires a specific version of D3DX, or other updated functionality that was not installed, then the game won't work, and the user will get very frustrated.

It is strongly recommended that the game's installer silently install the DirectX redistributable that the game was built against. The DirectX installation process is designed so that it verifies whether anything needs to be updated and quickly returns if it doesn't. So, there is no need to ask the user about installing DirectX.

A silent installation of DirectX can be done by running this command from your installation package: dxsetup.exe /silent

Furthermore, the actual size of the redistributable folder can be configured to include only those cabinet files (.cab) that are actually needed for the game's target platforms and usage. For more information about installing DirectX, see Installing DirectX with DirectSetup.

Excessive Use of Thread Synchronization

When profiling games, the top hotspots are often found to be related to entering and leaving critical sections. With the prevalence of multi-core CPUs, the use of multithreading in games has increased dramatically, and many implementations rely on heavy use of thread synchronization. The CPU time to take a critical section even without any contention is quite significant, and all other forms of thread synchronization are even more expensive. So, care must be taken to minimize the use of these primitives.

A common source of excessive synchronization in games is the use of D3DCREATE_MULTITHREADED. This flag, while making Direct3D thread-safe for rendering from multiple threads, takes a very conservative approach, resulting in high synchronization overhead. Games should avoid this flag. Instead, architect the engine so that all communication with Direct3D is from a single thread and any communication between threads is handled directly. For more information about designing multi-threaded games, see the article Coding For Multiple Cores on Xbox 360 and Microsoft Windows.

Use of RDTSC

Use of the x86 instruction RDTSC is not recommended. RDTSC fails to correctly compute timing on some power management schemes that change the CPU frequency dynamically and on many multi-core CPUs for which the cycle counter is not synchronized between cores. Games should instead use the QueryPerformanceCounter API. For more information about issues with RDTSC and implementing high-resolution timing with QueryPerformanceCounter, see the article Game Timing and Multicore Processors.


Top Tools and Techniques for Making More Robust Windows Games

XNA Developer Connection (XDC)

April 2006

Introduction

One of the more undesirable costs facing game production is support calls. Each time that a user contacts customer support, profit from the game is reduced. While some calls to customer support are not preventable, others can be eliminated or reduced by employing good development practices. To help reduce the number of support calls, developers can use the tools and techniques described in this article.

All of the tools described here are free, and the techniques are simple enough to add to most development methods.

Tools and techniques:

    PREfast

    PREfast for Drivers is a tool offered by Microsoft that analyzes execution paths in compiled C or C++ to help find run-time bugs. PREfast operates by working through all execution paths in all functions and assessing each path for problems. While this tool is normally used to develop drivers and other kernel code, it can help game developers save time by eliminating some bugs that are hard to find or that are ignored by the compiler.

    Use of PREfast is an excellent way of reducing your post-release workload and support costs. A new version of PREfast comes with Visual Studio 2005 Team System.

    For more information about PREfast, see PREfast for Drivers and Visual Studio 2005 Team System: Building Robust and Reliable Software.

    AppVerifier

    The Microsoft Application Verifier, or AppVerifier, is a tool that can help testers by providing multiple functions in one tool. AppVerifier was developed to make common programming errors more easily tested. AppVerifier can check parameters that are passed to API calls, inject erroneous input to check error handling ability, and log changes to the registry and file system. AppVerifier can also detect buffer overruns in the heap, check that an access control list (ACL) has been properly defined, and enforce the safe use of socket APIs.

    While not exhaustive, AppVerifier can be one more component of a tester's toolbox to help a development studio release a quality product and reduce potential post-release costs.

    More information on AppVerifier can be found at Security Developer Center: Analyzing Your Applications with Windows Application Verifier. You can download AppVerifier from the following page: Download details: Application Verifier.

    A similiar tool for drivers, Driver Verifier, is also available. For more information, see How to Use Driver Verifier to Troubleshoot Windows Drivers.

    Microsoft Application Compatibility Toolkit

    The Microsoft Application Compatibility Toolkit is a set of free tools to help developers quickly check to see how their releases will perform on newly released service packs for Microsoft Windows. By being ready for new service packs, developers can prevent or be ready for any issues.

    The Application Compatibility Toolkit, and more information, can be found at Windows Application Compatibility

    User Account Protection Testing

    Windows Vista has two primary types of user accounts: Standard User and Administrator. Standard User accounts are the preferred account type for all users, since they reduce the risk of damage to the system by malicious applications. Because a Standard User account has access restrictions — such as not being able to write to the Program Files folder or to HKEY_LOCAL_MACHINE (HKLM) in the registry — it is important that games be designed and tested to work with a Standard User account.

    More information about this topic and found in the articles Patching Game Software in Windows XP and Windows Vista and User Account Control for Game Developers.

    PIX for Windows

    PIX is a tool for collecting and analyzing performance information from a running application. PIX can gather statistical data on why some frames render more slowly than others and can identify poor API usage. PIX can also be automated to test the daily build and flag sudden changes in application performance. By using PIX across a variety of hardware configurations, testers and developers can help minimize support calls related to game performance.

    For more information about PIX, see PIX for Windows.

    Configuation Detection

    Device capabilities that are exposed by drivers are not always correct. One solution is to use a database-driven system for application configuration like the system demonstrated in the sample ConfigSystem, which is included with the DirectX SDK. A detection model that is similar to that in the sample can help identify device capabilities that are hampering game performance, and thus, reduce the number of support calls about performance.

    Enable Full Compiler Warnings

    It is a good practice to restore any compiler warnings that were disabled by #pragma warning once a project has become stable. Developers should try to eliminate all warnings before releasing a product. Even if a warning doesn't cause a crash or error on a developer's system, it might still cause a problem on a user's system. If a warning can't be eliminated, the test team needs to ascertain whether the warning will cause few or no errors on a user's system.

    Microsoft Symbol Server

    Microsoft provides an Internet-accessible server that provides symbol files for the Microsoft Windows operating systems, as well as other Microsoft products. Symbols are also available from the server for current betas and release candidates of Windows products, as well as hot fixes and service packs. You can configure the debugger to download symbols as needed during a debugging session, rather than downloading symbol files separately before a debugging session. The symbols are downloaded to a directory location that you specify, and the debugger loads them from there.

    For more information about the Microsoft Symbol Server, see Debugging Tools and Symbols: Getting Started.

    Windows Error Reporting

    Windows Error Reporting (WER) is a service provided by Microsoft to help developers collect error information from applications in a unified and organized manner. While it is completely voluntary, developers should take advantage of this service to help determine which bugs occur most often. Use of WER can help with the debugging of commonly reported problems, which will help eliminate support calls for the most commons bugs.

    For more information about WER, see Crash Dump Analysis.

    Performance Tuning Tools

    Developers can use performance analyzers to tune performance of their game. In addition to PIX, there are a number of popular performance analyzers for Windows, such as the Intel VTune Performance Analyzer for Windows and the AMD CodeAnalyst Performance Analyzer for Windows. These tools help with identifying bottlenecks and with deciding how to improve the overall performance of an application. Improving performance bottlenecks prior to release will help bring down post-release costs.

    Summary

    Everyone involved in the design, development, and testing needs to consider how his or her work will impact the post-release cost of a product. By using the aforementioned tools and methods in the production process, the volume of support calls can be reduced. This will, in turn, increase profits by reducing the post-release costs of game development.


User Account Control for Game Developers

Dave Bonora, Software Development Engineer

XNA Developer Connection (XDC)

February 2007

This article describes the guidelines and best practices for game developers to work effectively with the User Account Control (UAC) security feature introduced in Windows Vista.

  • Overview of User Account Control
  • User Accounts in Windows Vista
  • File Access as a Standard User
  • Registry Access as a Standard User
  • Privilege Elevation
  • Setting the Execution Level in the Application Manifest
  • UAC Compatibility with Older Games
  • Conclusion
  • Further Reading

Overview of User Account Control

User Account Control (UAC), introduced in Windows Vista, is a security feature that is designed to help prevent malicious attackers from using weaknesses or bugs found in widely-used applications to alter the operating system or other installed programs. This is accomplished by running the vast majority of programs and processes as a Standard User (also known as a Limited User, Restricted User, or Least-Privileged User) even if the current user’s account has administrative credentials. A process with standard user privileges has many inherent restrictions that prevent it from making system-wide changes.

UAC is also responsible for privilege elevation of a process by use of a dialog-based, authentication scheme initiated upon execution of certain processes that are designated as requiring administrative privileges. Privilege elevation allows administrators to run the majority of their applications at a safe privilege level (the same as any other standard user), but also allow processes and operations that require administrative privileges. UAC supports over-the-shoulder authentication so that an administrator can grant elevated privileges to a program while a standard user is currently logged onto the system.

The UAC feature is enabled by default. While it is possible for an administrator to disable UAC system-wide, doing so has a number of negative ramifications. First, this weakens the security of all administrative accounts, as all processes would be run with administrative credentials, even when most applications do not actually require them. With UAC disabled, a standard user application that exposes an exploitable vulnerability in security can potentially be used to steal private information, install rootkits or spyware, destroy the system integrity, or host zombie attacks on other systems. Whereas with UAC enabled, running the majority of software as a standard user greatly limits the potential damage from such a bug. Secondly, turning off UAC disables many of the workarounds for application compatibility that allow true standard users to successfully run a broad range of applications. Disabling UAC should never be recommended as a compatibility workaround.

It is important to note that applications should strive to only use standard user rights if at all possible. While administrators can easily elevate the privileges of a process, the elevation still requires user interaction and acknowledgement every time that an application is run that requires administrative credentials. This elevation must also be done at the time that the program starts, so requiring administrative credentials — even for a single operation — requires exposing the system to greater risk for the entire running time of the application. Standard users without any ability to elevate their privileges are also common in family and business settings. "Run As Administrator" is not a good workaround for compatibility, exposes the user and the system to greater security risk, and creates frustration for users in many situations.

User Accounts in Windows Vista

Windows Vista categorizes every user into two user account types: administrators and standard users.

A standard user account is similar to a limited-user account in Windows XP. Like in Windows XP, a standard user cannot write to the Program Files folder, cannot write to the HKEY_LOCAL_MACHINE portion of the registry, and cannot perform tasks that alter the system, such as installing a kernel-mode driver or accessing system-level process spaces.

The Administrator account has significantly changed since Windows XP was released. Previously, all processes launched by a member of the Administrators group were given administrative privileges. With UAC enabled, all processes execute with standard user privileges, unless specifically elevated by an administrator. This difference makes accounts in the Administrators group more secure by reducing the security risk posed by potential bugs in most programs.

It is important that all applications, especially games, operate effectively and responsibly when run as a standard user process. All operations that require administrative privileges should be done either at installation time or by auxiliary programs that explicitly request administrative credentials. While privilege elevation is fairly trivial for a member of the Administrators group, standard users must defer to someone with administrative credentials to physically enter their password to elevate privileges. Since accounts protected by parental controls must be standard users, this will be a very common situation for gamers who are using Windows Vista.

If your game is already working on Windows XP with limited-user accounts, then the move to User Account Control on Windows Vista should be very easy. The majority of such applications will work as-is, although adding an application manifest is highly recommended. (Manifests are described later in this topic in Setting the Execution Level in the Application Manifest.)

File Access as a Standard User

The aspect of your game most affected by standard user restrictions is file system organization and accessibility. You should never assume that your game can write files to the folder where your game is installed. In Windows Vista for instance, a user’s privileges must be elevated by the operating system before an application can write to the Program Files folder. To avoid this, you should categorize your game’s data files by scope and accessibility, and use the SHGetFolderPath function, along with the CSIDL constants provided by the Windows shell, to generate the appropriate file paths. The CSIDL constants correspond to known folders in the file system that the operating system uses and promotes to partition global and user-specific files.

Attempting to create or write a file or directory under a folder which does not grant write permission to the process will fail under Windows Vista if the application does not have administrative privileges. If your 32-bit game executable is running in legacy mode, because it did not declare a requested execution level, its write operations will succeed, but they will be subjected to virtualization as described in the section "UAC Compatibility with Older Games" later in this article.

Table 1. Known Folders

CSIDL Name | Typical Path (Windows Vista) | Standard User Rights | Administrator Rights | Access Scope | Description | Examples
CSIDL_PERSONAL | C:\Users\user name\Documents | Read/Write | Read/Write | Per-User | User-specific game files that are read and modified and can be manipulated outside of the game context. | creen shots. Saved game files with a file extension association.
CSIDL_LOCAL_APPDATA | C:\Users\user name\AppData\Local | Read/Write | Read/Write | Per User | User-specific game files that are read and modified and are of use only within the game context. | Game cache files. Player configurations.
CSIDL_COMMON_APPDATA | C:\ProgramData | Read/Write if owner | Read/Write | All Users | Game files that can be created by a user and read by all users. Write access is granted only to the creator of the file (owner). | User Profiles
CSIDL_PROGRAM_FILES | C:\Program Files or C:\Program Files (x86) | Read only | Read/Write | All Users | Static game files written by the game’s installer that are read by all users. | Game assets, such as materials and meshes.

Your game will typically be installed in a folder under the folder represented by the CSIDL_PROGRAM_FILES constant. However, this is not always the case. You should instead use a relative path from your executable file when generating path strings to files or directories located under your installation folder.

You should also refrain from hard-coded assumptions about the known folder paths. For example, on Windows XP Professional 64-bit Edition and Windows Vista x64, the program files path is C:\Program Files (x86) for 32-bit programs and C:\Program Files for 64-bit programs. These known paths are changed from Windows XP, and users can reconfigure the location of many of these folders and even locate them on different drives. So, always use the CSIDL constants to avoid confusion and potential problems. Windows Setup understands these known folder locations and will move the data when upgrading the operating system from Windows XP; in contrast, use of non-standard locations or hard-coded paths may well fail after an OS upgrade.

Attention should be given to the subtle usability differences between the user-specific folders specified by CSIDL_PERSONAL and CSIDL_LOCAL_APPDATA. The recommended practice for selecting the CSIDL constant to use for writing a file is to use CSIDL_PERSONAL if the user is expected to interact with the file, such as double-clicking on it to open it in a tool or application, and to use CSIDL_LOCAL_APPDATA for other files. Both folders can be leveraged by your application to store and organize user-specific data files, as there is no difference in their access scope or privilege level. Care should be taken to create path names that are unique enough to not collide with other applications, but short enough to keep the number of characters in the full path fewer than the value of MAX_PATH, 260.

The following code provides an example of how to write a file to a known folder:

#include <windows.h>
#include <shlobj.h>
#include <shlwapi.h>
...
...
...
TCHAR strPath[MAX_PATH];
if( SUCCEEDED(
SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, strPath ) ) )
{
    PathAppend( strPath, TEXT( "Company Name\\Title" ) );

    if( !PathFileExists( strPath ) )
    {
        if( ERROR_SUCCESS != SHCreateDirectoryEx( NULL, strPath, NULL ) )
            return E_FAIL;
    }

    PathAppend( strPath, TEXT( "gamefile.txt" ) );

    // strPath is now something like:
    // C:\Users\<current user>\Documents\Company Name\Title\gamefile.txt
    // Open the file for writing
    HANDLE hFile = CreateFile(strPath, GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    if( INVALID_HANDLE_VALUE != hFile )
    {
        // TODO: Write to file
        CloseHandle(hFile);
    }
}

Registry Access as a Standard User

Registry access by a standard user is restricted in a similar fashion as the file system. A standard user is permitted read access to all keys in the registry; however, write access is only granted to the HKEY_CURRENT_USER (HKCU) subtree, which is mapped internally to the user-specific subkey HKEY_USERS\Security ID (SID) of current user. An application that needs to write to any registry location other than HKEY_CURRENT_USER requires administrative privileges.

If the 32-bit application does not contain a requested execution level in its manifest, then all writes to HKEY_LOCAL_MACHINE\Software will be virtualized, while writes to other locations outside of HKEY_CURRENT_USER will fail.

Storing persistent data in the registry, like a user’s configuration, is not recommended. The preferred method of storing persistent data from your game is to write the data to the file system by calling SHGetFolderPath and to get the value of a CSIDL constant, described in the previous section.

Privilege Elevation

In Windows Vista, any application that requires administrative privileges must declare a request for an administrative execution level in its manifest (described in the next section, Setting the Execution Level in the Application Manifest).

Elevation, as it is known, is the procedure driven by UAC to promote a process to an administrative process. The privileges of a process can only be elevated at creation time. Once created, a process will never be promoted to a higher privilege level. For this reason. operations that require administrative credentials should be isolated to separate installers and other auxiliary programs.

Upon execution of a program, UAC inspects the requested execution level in the manifest, and if elevated privileges are required, prompts the current user with one of two standard dialog boxes: one for a standard user and one for an administrator.

If the current user is a standard user, UAC prompts the user for the credentials of an administrator before allowing the program to run.

Figure 1. Prompt for a Standard User to enter credentials for an administrative account

If the current user is an administrator, UAC prompts the user for permission before allowing the program to run.

Figure 2. Prompt for an Administrator to authorize changes to the computer

The application will only be granted administrative privileges if a standard user provides the proper administrative credentials or an administrative user provides acknowledgement; anything else will cause the application to terminate.

It is important to note that a process with elevated privileges runs as the administrative user who entered credentials in the UAC prompt rather than as the standard user who is currently logged in. This is similar to RunAs in Windows XP — the elevated process gets the administrator’s folder and registry keys when accessing per-user data, and all programs that the elevated process launches also inherit both the administrative rights and user account locations. For administrators who are prompted for acknowledgement (Continue or Cancel), these locations will match the currently user’s locations. In general, however, processes that require elevation should not operate on per-user data. Note that this can substantially affect how your installer must operate! If the installer, running as an administrator, writes to HKCU or to a user’s profile, it may very well be writing to the wrong location. Consider creating these per-user values upon the first run of the game.

Setting the Execution Level in the Application Manifest

You declare the requested execution level of your game by adding an extension to the application’s manifest. The following XML code shows the minimal configuration required to set the execution level for an application:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
   <ms_asmv2:trustInfo xmlns:ms_asmv2="urn:schemas-microsoft-com:asm.v2">
      <ms_asmv2:security>
         <ms_asmv2:requestedPrivileges>
            <ms_asmv2:requestedExecutionLevel level="asInvoker" uiAccess="false" />
         </ms_asmv2:requestedPrivileges>
      </ms_asmv2:security>
   </ms_asmv2:trustInfo>
</assembly>

In the preceding code, the operating system is informed that the game only requires standard user privileges by the following tag:

<ms_asmv2:requestedExecutionLevel level="asInvoker" uiAccess="false" />

By explicitly setting requestedExecutionLevel to "asInvoker", this example asserts to the operating system that the game will behave properly without administrative privileges. As a result, UAC disables virtualization and runs the game with the same privileges as the invoker — which is typically standard user privileges, since Windows Explorer runs as standard user.

The operating system can be informed a the game requires elevation to administrative privileges by replacing "asInvoker" with "requireAdministrator", to create the following tag:

<ms_asmv2:requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

With this configuration, the operating system prompts the current user with one of the standard UAC elevation dialogs every time that the game is executed. It is highly recommended that no game require administrator privileges to run, because not only will this dialog quickly become annoying, but it also makes the game incompatible with parental controls. Think very carefully before adding this requirement to any executable.

A common misconception is that adding a manifest that sets requestedExecutionLevel to "requireAdministrator" bypasses the need for an elevation prompt. This is not true. It simply prevents the operating system from guessing whether your setup or update application needs administrative privileges. The user is still prompted to authorize elevation.

Windows checks the signature of any application that is marked for elevation before it displays the UAC prompt. A large executable that is marked for elevation takes longer to check than a small executable and longer than an executable that is marked as "asInvoker". Setup executables that are self-extracting should, therefore, be marked as "asInvoker", and any portion that needs to be marked as "requireAdministrator" should be placed in a seperate helper executable.

The uiAccess attribute, shown in the preceding examples, should always be FALSE for games. This attribute specifies whether UI automation clients have access to the protected system UI, and it has special security implications if set to TRUE.

Note At the time of this writing, there is a bug in mt.exe, the tool used by Visual Studio 2005 to automatically merge and embed a manifest into an executable. The tool redefines the default namespace upon declaration of <trustInfo>, and this causes Windows XP to stop. Fortunately, it is easy to bypass the issue entirely by explicitly declaring a different namespace in the <trustInfo> block and by scoping the child nodes to the new namespace, as demonstrated in the example at the beginning of this section.

UAC Compatibility with Older Games

If your game appears to be saving and loading a file successfully to the Program Files directory, yet no evidence of the file is found, chances are your game is running in legacy mode and was subjected to virtualization.

On Windows Vista, any 32-bit application that does not contain a requested execution level in its manifest is considered a legacy application. Prior to Windows Vista, most applications were typically run by users with administrative privileges. As a result, these applications could freely read and write system files and registry keys, and many developers did not make the changes needed to work properly on Limited User Accounts on Windows XP. However on Windows Vista, these same applications would now fail due to insufficient access privileges under the new security model, which enforces standard user execution for legacy applications. To mitigate the impact of this, virtualization was also added to Windows Vista. Virtualization will keep thousands of legacy applications working well on Windows Vista without requiring those applications to have elevated privileges at all times simply to succeed at a few minor operations.

Virtualization affects the file system and registry by redirecting system-sensitive writes (and subsequent file or registry operations) to a per-user location within the current user’s profile. For example, if an application attempts to write to the following file:

C:\Program Files\Company Name\Title\config.ini

the write is automatically redirected to:

C:\Users\user name\AppData\Local\VirtualStore\Program Files\Company Name\Title\config.ini

Likewise, if an application attempts to write a registry value like the following:

HKEY_LOCAL_MACHINE\Software\Company Name\Title

it will be redirected instead to:

HKEY_CURRENT_USER\Software\Classes\VirtualStore\MACHINE\Software\Company Name\Title

Files and registry keys affected by virtualization are only be accessed by file and registry operations from virtualized applications that are running as the current user.

However, there are many restrictions to virtualization. One is that 64-bit applications are never run in legacy mode for compatibility — operations subjected to virtualization in 32-bit applications will just fail in 64-bit. Also if a legacy application running as a standard user tries to write any type of executable file to a location that requires administrative credentials, then virtualization will not occur and the write will fail.

Figure 3. Virtualization Process

When a legacy application attempts a read operation on system-sensitive locations in the file system or registry, the virtual locations are searched first. If the file or registry key is not found, then the operating system accesses the default system locations.

Virtualization will be removed from subsequent versions of Windows so it important not to rely on this feature. Instead, you should explicitly configure your application manifest for either standard user or administrative privileges, as this will disable virtualization. Virtualization is also not obvious to end users, so even though virtualization may allow your application to run, it can generate support calls and make it difficult to trouble-shoot for these customers.

Note that if UAC is disabled, then virtualization is also disabled. If virtualization is disabled, standard user accounts behave exactly like limited user accounts in Windows XP, and legacy applications may not function correctly for standard users that would otherwise have succeeded due to virtualization.

Conclusion

As a game developer targeting the Windows multi-user environment, it is imperative that you design your game to operate effectively and responsibly. Your game’s main executable file should not be dependent on administrative privileges. This not only prevents the appearance of prompts for elevation every time that your game is run — which can negatively impact the overall user experience — but it also enables your game to take advantage of other features that require execution with standard user privileges, such as Parental Controls.

Applications that are properly designed to operate as with the credentials of a standard user (or limited user) under previous versions of Windows will not be impacted by UAC — they will run without elevation. However, they should include a manifest with their requested execution level set to "asInvoker" to conform to application standards for Vista.

Further Reading

For assistance with designing applications for Windows Vista that are compliant with User Account Control, download the following white paper: Windows Vista Application Development Requirements for User Account Control Compatibility

This white paper provides detailed steps about the design process, along with code samples, requirements, and best practices. This paper also details the technical updates and changes to the user experience in Windows Vista.

For more information about User Account Control, visit Windows Vista: User Account Control on Microsoft TechNet.

Another useful resource is the article Teach Your Apps To Play Nicely with Windows Vista User Account Control, from MSDN Magazine, January 2007. This article discusses general issues of application compatibility, as well as the advantages and issues of using Windows Installer packages on Windows Vista.

For more information about the bug and the fix for mt.exe, the tool used by Visual Studio 2005 to automatically merge and embed a manifest into an executable, see Exploring Manifests Part 2: Default Namespaces and UAC Manifests in Windows Vista on Chris Jackson’s blog on MSDN.


Using an Input Method Editor in a Game

By Jack Lin, Software Design Engineer

Microsoft Corporation

December 2004

Introduction

An input method editor (IME) is a program that allows easy text entry using a standard keyboard for East Asian languages such as Chinese, Japanese, Korean, and other languages with complex characters. For example, with IMEs a user can type complex characters in a word processor, or a player of a massive multiplayer online game can chat with friends in complex characters.

This topic explains how you can implement a basic IME edit control in a full-screen Microsoft DirectX application. Applications that take advantage of DXUT automatically get IME functionality. For applications that do not make use of the framework, this topic describes how to add IME support to an edit control.

Contents:

  • Default IME Behavior
  • Using IMEs with DXUT
  • Overriding the Default IME Behavior
  • Functions
  • Messages
  • Examples
  • IME Messages
  • Rendering
  • Limitations
  • Registry Information
  • Appendix A: CHT Versions per Operating System
  • Further Information

Default IME Behavior

IMEs map keyboard input to phonetic components or other language elements specific to a selected language. In a typical scenario, the user types keys that represent pronunciation of a complex character. If the IME recognizes the pronunciation as valid, it presents the user with a list of word or phrase candidates from which the user can select a final choice. The chosen word is then sent to the application through a series of Microsoft Windows WM_CHAR messages. Because the IME works at a level below the application by intercepting keyboard input, the presence of an IME is transparent to the application. Almost all Windows applications can readily take advantage of IMEs without being aware of their existence and without requiring special coding.

A typical IME displays several windows to guide the user through character entry, as shown in the following examples.

IME character entry display windows

Window Type | Description | IME Output
A. Reading Window | Contains keystrokes from the keyboard; typically changes after each keystroke. | reading string
B. Composition Window | Contains the collection of characters that the user has composed with the IME. These characters are drawn by the IME on top of the application. When the user notifies the IME that the composition string is satisfactory, the IME then sends the composition string to the application via a series of WM_CHAR messages. | composition string
C. Candidate Window | When the user has entered a valid pronunciation, the IME displays a list of candidate characters that all match the given pronunciation. The user then selects the intended character from this list, and the IME adds this character to the Composition Window display. | the next character in the composition string
D. Input Locale indicator | Shows the language the user has selected for keyboard input. This indicator is embedded in the Windows taskbar. The input language can be selected by opening the Regional and Language Options Control Panel and then clicking Details on the Languages tab. | -

Using IMEs with DXUT

In DXUT, the CDXUTIMEEditBox class implements IME functionality. This class is derived from the CDXUTEditBox class, the basic edit control provided by the framework. CDXUTIMEEditBox extends that edit control to support IMEs by overriding the CDXUTIMEEditBox methods. The classes are designed this way to help developers learn what they need to take from the framework to implement IME support in their own edit controls. The rest of this topic explains how the framework, and CDXUTIMEEditBox in particular, overrides a basic edit control to implement IME functionality.

Most of the IME-specific variables in CDXUTIMEEditBox are declared as static, because many IME buffers and states are specific to the process. For instance, a process has only one buffer for the composition string. Even if the process has ten edit controls, they will all be sharing the same composition string buffer. The composition string buffer for CDXUTIMEEditBox is therefore static, preventing the application from taking up unnecessary memory space.

CDXUTIMEEditBox is implemented in the following DXUT code:

(SDK root)\Samples\C++\Common\DXUTgui.cpp

Overriding the Default IME Behavior

Normally an IME uses standard Windows procedures to create a window (see Using Windows). Under normal circumstances, this produces satisfactory results. However, when the application presents in full-screen mode, as is common for games, standard windows no longer work and may not display on top of the application. To overcome this issue, the application must draw the IME windows itself instead of relying on Windows to perform this task.

When the default IME window creation behavior does not provide what an application requires, the application can override the IME window handling. An application can achieve this by processing IME-related messages and calling the Input Method Manager (IMM) API. See Input Method Editor.

When a user interacts with an IME to input complex characters, the IMM sends messages to the application to notify it of important events, such as starting a composition or showing the candidate window. An application typically ignores these messages and passes them to the default message handler, which causes the IME to handle them. When the application, instead of the default handler, handles the messages, it controls exactly what happens at each of the IME events. Often the message handler retrieves the content of the various IME windows by calling the IMM API. Once the application has this information, it can properly draw the IME windows itself when it needs to render to the display.

Functions

An IME needs to get the reading string, hide the reading window, and get the orientation of reading window. This table shows the the functionalities per IME version:

 | Getting reading string | Hiding reading window | Orientation of reading window
Before version 6.0 | Access IME private data directly. See "4 Structure" | Trap IME private messages. See "3 Messages" | Examine registry information. See "5 Registry Information"
After version 6.0 | GetReadingString | ShowReadingWindow | GetReadingString

Messages

The following messages don't have to be processed for newer IME that implements ShowReadingWindow().

The following messages are trapped by application message handler (i.e. they are not passed to DefWindowProc) to prevent the reading window from showing up.

Msg == WM_IME_NOTIFY
wParam == IMN_PRIVATE
lParam == 1, 2 (CHT IME version 4.2, 4.3 and 4.4 / CHS IME 4.1 and 4.2)
lParam == 16, 17, 26, 27, 28 (CHT IME version 5.0, 5.1, 5.2 / CHS IME 5.3)

Examples

The following examples illustrate how to get reading string information from older IME that doesn't have GetReadingString(). The code generates the following outputs:

DWORD dwlen | Length of the reading string
DWORD dwerr | Index of error char
LPWSTR wstr | Pointer to the reading string
BOOL unicode | If true, the reading string is in Unicode format. Otherwise it's in multibyte format.
  • CHT IME version 4.2, 4.3 and 4.4
  • CHT IME version 5.0
  • CHT IME version 5.1, 5.2 and CHS IME version 5.3
  • CHS IME version 4.1
  • CHS IME version 4.2

CHT IME version 4.2, 4.3 and 4.4

LPINPUTCONTEXT lpIMC = _ImmLockIMC(himc);
LPBYTE p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIMC->hPrivate) + 24);
if (!p) break;
dwlen = *(DWORD *)(p + 7*4 + 32*4);
dwerr = *(DWORD *)(p + 8*4 + 32*4);
wstr = (WCHAR *)(p + 56);
unicode = TRUE;

CHT IME version 5.0

LPINPUTCONTEXT lpIMC = _ImmLockIMC(himc);
LPBYTE p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIMC->hPrivate) + 3*4);
if (!p) break;
p = *(LPBYTE *)((LPBYTE)p + 1*4 + 5*4 + 4*2 );
if (!p) break;
dwlen = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16);
dwerr = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 + 1*4);
wstr = (WCHAR *)(p + 1*4 + (16*2+2*4) + 5*4);
unicode = FALSE;

CHT IME version 5.1, 5.2 and CHS IME version 5.3

LPINPUTCONTEXT lpIMC = _ImmLockIMC(himc);
LPBYTE p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIMC->hPrivate) + 4);
if (!p) break;
p = *(LPBYTE *)((LPBYTE)p + 1*4 + 5*4);
if (!p) break;
dwlen = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * 2);
dwerr = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * 2 + 1*4);
wstr  = (WCHAR *) (p + 1*4 + (16*2+2*4) + 5*4);
unicode = TRUE;

CHS IME version 4.1

// GetImeId(1) returns VS_FIXEDFILEINFO:: dwProductVersionLS of IME file
int offset = ( GetImeId( 1 ) >= 0x00000002 ) ? 8 : 7;
LPINPUTCONTEXT lpIMC = _ImmLockIMC(himc);
BYTE p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIMC->hPrivate) + offset * 4);
if (!p) break;
dwlen = *(DWORD *)(p + 7*4 + 16*2*4);
dwerr = *(DWORD *)(p + 8*4 + 16*2*4);
dwerr = min(dwerr, dwlen);
wstr = (WCHAR *)(p + 6*4 + 16*2*1);
unicode = TRUE;

CHS IME version 4.2

int nTcharSize = IsNT() ? sizeof(WCHAR) : sizeof(char);
LPINPUTCONTEXT lpIMC = _ImmLockIMC(himc);
BYTE p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIMC->hPrivate) + 1*4 + 1*4 + 6*4);
if (!p) break;
dwlen = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * nTcharSize);
dwerr = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * nTcharSize + 1*4);
wstr  = (WCHAR *) (p + 1*4 + (16*2+2*4) + 5*4);
unicode = IsNT() ? TRUE : FALSE;

IME Messages

A full-screen application must properly handle the following IME-related messages:

  • WM_INPUTLANGCHANGE
  • WM_IME_SETCONTEXT
  • WM_IME_STARTCOMPOSITION
  • WM_IME_COMPOSITION
  • WM_IME_ENDCOMPOSITION
  • WM_IME_NOTIFY

WM_INPUTLANGCHANGE

The IMM sends a WM_INPUTLANGCHANGE message to the active window of an application after the input locale has been changed by the user with a key combination (usually ALT+SHIFT), or with the input locale indicator on the taskbar or language bar. The language bar is an on-screen control with which the user can configure a text service. (See How to show the language bar.) The following screen shot shows a language selection list that is displayed when the user clicks on the locale indicator.

Input locale indicator on the Windows taskbar

When the IMM sends a WM_INPUTLANGCHANGE message, CDXUTIMEEditBox must perform several important tasks:

  1. The GetKeyboardLayout method is called to return the input locale identifier (ID) for the application thread. The CDXUTIMEEditBox class saves this ID in its static member variable s_hklCurrent for later use. It is important for the application to know the current input locale, because the IME for each language has its own distinct behavior. The developer may need to provide different code for different input locales.
  2. CDXUTIMEEditBox initializes a string to display in the edit box language indicator. This indicator can display the active input language when the application is running in full-screen mode and neither the taskbar nor language bar is visible.
  3. The ImmGetConversionStatus method is called to indicate whether the input locale is in native or non-native conversion mode. Native conversion mode lets the user enter text in the chosen language. Non-native conversion mode makes the keyboard act as a standard English keyboard. It is important to give the user a visual cue as to what type of conversion mode the IME is in, so that the user can easily know what characters to expect when hitting a key. CDXUTIMEEditBox provides this visual cue with a language indicator color. When the input locale uses an IME with native conversion mode, the CDXUTIMEEditBox class draws the indicator text with the color defined by the m_IndicatorImeColor parameter. When the IME is in non-native conversion mode, or no IME is used at all, the class draws the indicator text with the color defined by the m_IndicatorEngColor parameter.
  4. CDXUTIMEEditBox checks the input locale and sets the static member variable s_bInsertOnType to TRUE for Korean and FALSE for all other languages. This flag is required because of the different behaviors of Korean IMEs and all other IMEs. When entering characters in languages other than Korean, the user-entered text is displayed in the composition window, and the user can freely change the content of the composition string. The user presses the ENTER key when satisfied with the composition string, and the composition string is sent to the application as a series of WM_CHAR messages. In Korean IMEs, however, when a user presses a key to enter text, a character is immediately sent to the application. When the user subsequently presses more keys to modify that initial character, the character in the edit box changes to reflect additional input from the user. Essentially, the user is composing characters in the edit box. These two behaviors are different enough that CDXUTIMEEditBox must code for each of them specifically.
  5. The static member method SetupImeApi is called to retrieve addresses of two functions from the IME module: GetReadingString and ShowReadingWindow. If these functions exist, ShowReadingWindow is called to hide the default reading window for this IME. Because the application renders the reading window itself, it notifies the IME to disable drawing the default reading window so that it will not interfere with full-screen rendering.

WM_IME_SETCONTEXT

The IMM sends a WM_IME_SETCONTEXT message when a window of the application is activated. The lParam parameter of this message contains a flag that indicates to the IME which windows should get drawn and which should not. Because the application is handling all of the drawing, it does not need the IME to draw any of the IME windows. Therefore, the application's message handler simply sets lParam to 0 and returns.

In order for applications to support IME, special processing is needed for the IME-related message WM_IME_SETCONTEXT. Since Windows typically sends this message to the application prior to calling the PanoramaInitialize() method, Panorama doesn't have a chance to process the UI for showing candidate list windows.

The following code snippet specifies to Windows applications not to display any UI associated with the candidate list window, allowing Panorama to specifically handle this UI.

case WM_IME_SETCONTEXT:
         lParam = 0;
    lRet = DefWindowProc(hWnd, msg, wParam, lParam);
    break;
    //... more message processing
    return lRet;

WM_IME_STARTCOMPOSITION

The IMM sends a WM_IME_STARTCOMPOSITION message to the application when an IME composition is about to begin as a result of keystrokes by the user. If the IME uses the composition window, it displays the current composition string in a composition window. CDXUTIMEEditBox handles this message by performing two tasks:

  1. CDXUTIMEEditBox clears the composition string buffer and attribute buffer. These buffers are static members of CDXUTIMEEditBox.
  2. CDXUTIMEEditBox sets the s_bHideCaret static member variable to TRUE. This member, defined in the base CDXUTEditBox class, controls whether the cursor in the edit box should be drawn when the edit box is rendered. The composition window functions similarly to an edit box with text and cursor. To avoid confusion when the composition window is visible, the edit box hides its cursor so that only one cursor is visible at a time.

WM_IME_COMPOSITION

The IMM sends a WM_IME_COMPOSITION message to the application when the user enters a keystroke to change the composition string. The value of lParam indicates what type of information the application can retrieve from the Input Method Manager (IMM). The application should retrieve the available information by calling ImmGetCompositionString and then should save the information in its private buffer so that it can render the IME elements later.

CDXUTIMEEditBox checks for and retrieves the following composition string data:

WM_IME_COMPOSITION lParam Flag Value | Data | Description
GCS_COMPATTR | Composition Attribute | This attribute contains information such as the status of each character in the composition string (for example, converted or non-converted). This information is needed because CDXUTIMEEditBox colors the composition string characters differently based upon their attributes.
GCS_COMPCLAUSE | Composition Clause Information | This clause information is used when the Japanese IME is active. When a Japanese composition string is converted, characters may be grouped together as a clause that gets converted to a single entity. When the user moves the cursor, CDXUTIMEEditBox uses this information to highlight the entire clause, instead of just a single character within the clause.
GCS_COMPSTR | Composition String | This string is the up-to-date string being composed by the user. This is also the string displayed in the composition window.
GCS_CURSORPOS | Composition Cursor Position | The composition window implements a cursor, similar to the cursor in an edit box. The application can retrieve the cursor position when processing the WM_IME_COMPOSITION message in order to draw the cursor properly.
GCS_RESULTSTR | Result String | The result string is available when the user is about to complete the composition process. This string should be retrieved and the characters should be sent to the edit box.

WM_IME_ENDCOMPOSITION

The IMM sends a WM_IME_ENDCOMPOSITION message to the application when the IME composition operation is ending. This can occur when the user presses the ENTER key to approve the composition string, or the ESC key to cancel the composition. CDXUTIMEEditBox handles this message by setting the composition string buffer to be empty. It then sets s_bHideCaret to FALSE because the composition window is closed and the cursor in the edit box should again be visible.

The CDXUTIMEEditBox message handler also sets s_bShowReadingWindow to FALSE. This flag controls whether the class draws the reading window when the edit box renders itself, so it must be set to FALSE when a composition ends.

WM_IME_NOTIFY

The IMM sends a WM_IME_NOTIFY message to the application whenever an IME window changes. An application that handles the drawing of the IME windows should process this message so that it is aware of any update to the content of the window. The wParam indicates the command or the change that is taking place. CDXUTIMEEditBox handles the following commands:

IME Command | Description
IMN_SETOPENSTATUS | Sent to the application when the open status of the input context is changed. For a language that uses IME, this command can be sent when the user changes from native conversion mode to non-native, or vice versa. (See WM_INPUTLANGCHANGE for definitions of native and non-native modes.) CDXUTIMEEditBox handles this command similar to the way it handles WM_INPUTLANGCHANGE. It must retrieve the current input language and conversion mode, and it must initialize the indicator text and color.
IMN_OPENCANDIDATE / IMN_CHANGECANDIDATE Sent to the application when the candidate window is about to be opened or updated, respectively. The candidate window opens when a user wishes to change the converted text choice. The window is updated when a user moves the selection indicator or changes the page. CDXUTIMEEditBox uses one message handler for both of these commands because the tasks required are exactly the same:
  1. CDXUTIMEEditBox sets the bShowWindow member of the candidate list structure s_CandList to TRUE to indicate that the candidate window needs to be drawn during frame rendering.
  2. CDXUTIMEEditBox retrieves the candidate list by calling ImmGetCandidateList, first to get the required buffer size, and then again to get the actual data.
  3. The private candidate list structure s_CandList is initialized with the retrieved candidate data.
  4. The candidate strings are stored as an array of strings.
  5. The index of the selected entry, as well as the page index, is saved.
  6. CDXUTIMEEditBox checks whether the candidate window style is vertical or horizontal. If the window style is horizontal, an additional string buffer, the HoriCand member of s_CandList, must be initialized with all of the candidate strings, with space characters inserted between all adjacent strings. When rendering a vertical candidate window, the individual candidate strings are drawn one at a time, with the y coordinates incremented for each string. However, this HoriCand string should be used when rendering a horizontal candidate window, because the space character is the best way to separate two adjacent strings on the same line.
IMN_CLOSECANDIDATE | Sent to the application when a candidate window is about to close. This happens when a user has made a selection from the candidate list. CDXUTIMEEditBox handles this command by setting the visible flag of the candidate window to FALSE and then clearing the candidate string buffer.
IMN_PRIVATE Sent to the application when the IME has updated its reading string as a result of the user typing or removing characters. The application should retrieve the reading string and save it for rendering. CDXUTIMEEditBox has two methods to retrieve the reading string, based upon how reading strings are supported in the IME:
  • If the IME supports the GetReadingString function, GetReadingString is called to retrieve the reading string.
  • If the IME does not implement GetReadingString, CDXUTIMEEditBox retrieves the reading string from the input context content.

Rendering

Rendering of the IME elements and windows is straightforward. CDXUTIMEEditBox lets the base class render first because IME windows should appear on top of the edit control. After the base edit box is rendered, CDXUTIMEEditBox checks the visibility flag of each IME window (indicator, composition, candidate, and reading window) and draws the window if it should be visible. See Default IME Behavior for descriptions of the different IME window types.

  • Input Locale Indicator
  • Composition Window
  • Reading and Candidate Windows

Input Locale Indicator

The input locale indicator is rendered before any other IME windows because it is an element that is always displayed. It should therefore appear below other IME windows. CDXUTIMEEditBox renders the indicator by calling the RenderIndicator method, in which the indicator font color is determined by examining the s_ImeState static variable, which reflects the current IME conversion mode. When the IME is enabled and native conversion is active, the method uses m_IndicatorImeColor as the indicator color. If the IME is disabled or is in non-native conversion mode, m_IndicatorImeColor is used to draw the indicator text. By default, the indicator window itself is drawn to the right of the edit box. Applications can change this behavior by overriding the RenderIndicator method.

The following figure shows the different appearances of an input locale indicator for English, Japanese in alphanumeric conversion mode, and Japanese in native conversion mode:

IME locale indicators

Composition Window

The drawing of the composition window is handled in the RenderComposition method of CDXUTIMEEditBox. The composition window floats above the edit box. It should be drawn at the cursor position of the underlying edit control. CDXUTIMEEditBox handles the rendering as follows:

  1. The entire composition string is drawn using the default composition string colors.
  2. Characters with certain special attributes should be drawn in different colors, so CDXUTIMEEditBox reviews the characters of the composition string and inspects the string attribute. If the attribute calls for different colors, the character is drawn again with the appropriate colors.
  3. The cursor of the composition window is drawn to complete the rendering.

The cursor should blink for Korean IMEs, but it should not for other IMEs. RenderComposition determines whether the cursor should be visible based upon timer values when the Korean IME is used.

Reading and Candidate Windows

The reading and candidate windows are rendered by the same CDXUTIMEEditBox method, RenderCandidateReadingWindow. Both windows contain an array of strings for vertical layout, or a single string in the case of horizontal layout. The bulk of the code in RenderCandidateReadingWindow is used to position the window so that no part of the window falls outside the application window and gets clipped.

Limitations

IMEs sometimes contain advanced features to improve the ease of inputting text. Some of the features found in newer IMEs are shown in the following figures. These advanced features are not present in DXUT. Implementing support for these advanced features can be challenging because there is no interface defined to obtain the necessary information from the IMEs.

Advanced Traditional Chinese IME with expanded candidate list:

Advanced IME for Traditional Chinese

Advanced Japanese IME with some candidate entries that contain additional text to describe their meanings:

Advanced IME for Japanese

Advanced Korean IME that includes a handwriting recognition system:

Advanced IME for Korean

Registry Information

The following registry information is checked to determine the orientation of the reading window, when the current IME is older CHT New Phonetic that doesn't implement GetReadingString().

Key | Value
HKCU\software\microsoft\windows\currentversion\IME_Name | keyboard mapping

Where: IME_Name is MSTCIPH if the IME file version is 5.1 or later; otherwise IME_Name is TINTLGNT.

The orientation of reading window is horizontal if either:

  • The IME is version 5.0 and keyboard mapping value is 0x22 or 0x23
  • The IME is version 5.1 or version 5.2 and keyboard mapping value is 0x22, 0x23 or 0x24.

If neither condition is met, the reading window is vertical.

Appendix A: CHT Versions per Operating System

Operating System | CHT IME Version
Windows 98 | 4.2
Windows 2000 | 4.3
unknown | 4.4
Windows ME | 5.0
Office XP | 5.1
Windows XP | 5.2
Standalone web downloadble | 6.0

Further Information

For additional information, see the following:

  • Installing and Using Input Method Editors
  • International Text Display
  • Microsoft Global Development and Computing Portal
  • The Unicode Consortium
  • Developing International Software. Dr. International. 2nd ed. Redmond, WA: Microsoft Press, 2003.

GetReadingString

Gets reading string information.

Parameters

himc
[in] Input context.
uReadingBufLen
[in] Length of lpwReadingBuf, in WCHAR. If it is zero, it means query reading buffer length.
lpwReadingBuf
[out] Return reading string (not zero end).
pnErrorIndex
[out] Return index of error character in the reading string if there is.
pfIsVertical
[out] If it is TRUE, reading UI is vertical. Otherwise, horizontal puMaxReadingLen.
puMaxReadingLen
[out] The reading UI length. The max reading length is not fixed; it depends not only on keyboard layout, but also on input mode (for example, internal code, surrogate input).

Return Values

The reading string length.

Remarks

If the return value is greater than the value of uReadingBufLen, then all output parameters are undefined.

This function is implemented in CHT IME 6.0 or later, and can be acquired by GetProcAddress on an IME module handle; the IME module handle can be acquired by ImmGetIMEFileName and LoadLibrary.

Requirements

Header

Declared in Imm.h.

Import Library

Use Imm.lib.

ShowReadingWindow

Show (or hide) the reading window.

Parameters

himc
[in] Input context.
bShow
[in] Set to TRUE to show the reading window (or FALSE to hide it).

Return Values

Return TRUE if successful or FALSE if otherwise.

Remarks

This function is implemented in CHT IME 6.0 or later, and can be acquired by GetProcAddress on an IME module handle; the IME module handle can be acquired by ImmGetIMEFileName and LoadLibrary.

Requirements

Header

Declared in Imm.h

Import Library

Use Imm.lib.


Windows Firewall for Game Developers

XNA Developer Connection (XDC)

December 2004

Updated: December 2006

Introduction

This article describes the Windows Firewall - why it exists, what it accomplishes, and how it does so. Most importantly, it describes how to configure your game to work well with the firewall.

Contents:

  • What is a Firewall?
  • How can I tell if my game is affected?
  • The Firewall Before Windows XP SP2
  • Windows XP SP2 Firewall Is Better
  • Working with the Windows Firewall
  • Integrating using InstallShield InstallScript
  • Integrating into Wise for Windows Installer
  • Integrating into Windows Installer
  • Recommendations

What is a Firewall?

The firewall provides a barrier against network-based intrusions. It blocks unsolicited incoming traffic, and makes the system mostly invisible on the internet by rejecting Internet Control Message Protocol (ICMP) requests. This means that ping and tracert will not work. The firewall also looks and rejects invalid packets.

This barrier prevents opportunistic attacks. Attacks spread by finding many systems with the same vulnerability. The firewall can thwart many attacks by putting up a "do not disturb" sign for those features not currently in use; the attack is ignored and does not strike home. The essential benefit of the Windows Firewall is that features and applications that are not in use cannot be avenues for attack.

The user configures the system to identify what applications and features are needed and should be open to the network. This happens either when an application is installed or when it tries to open itself to the network.

How can I tell if my game is affected?

With the arrival of Windows XP SP2, the Windows Firewall has been widely deployed. All multiplayer Windows games are affected to some degree. While clients are generally in good shape, servers, hosts, and peers in peer-to-peer all need the firewall configured to continue working. Specifically, incoming unsolicited traffic is dropped. The firewall intercepts network-traffic filter packets based on the packet contents and recent network activity. The firewall uses the contents and activity to decide to forward or drop a packet. Once the firewall is properly configured, a game will be able to accept inbound unsolicited traffic as before.

Who has inbound unsolicited traffic?

  • Client/Server: All participants connect to a central server. The central server is the one with incoming unsolicited traffic. The clients connecting to the server are soliciting return traffic, which is expected and is allowed to pass through the firewall if the rules for clients are followed. The central server must be configured to accept the unsolicited traffic to allow the client traffic to pass through the firewall.
  • Massively Multiplayer (MMP): All participants are connected to a data center. This amounts to a complex client/server relationship, as the data center has the inbound unsolicited traffic. The participants are clients, and in general do not need to accept unsolicited traffic.
  • Peer-to-Peer, where all participants are connected to each other directly: All participants must be ready to accept unsolicited traffic from any new player joining the group. In a sense, each of the participants must function as a host, so they must all be configured as if they were hosts.

Clients are generally in good shape. Their outgoing Transmission Control Protocol/Internet Protocol (TCP/IP) connections will work fine, as will outgoing User Datagram Protocol (UDP) messages along with timely responses to those messages - the firewall keeps the port open for 90 seconds after each outgoing message in anticipation of a reply.

The Firewall Before Windows XP SP2

The Internet Connection Firewall (ICF) in Windows XP and Windows Server 2003 is a stateful packet filter, and handles both Internet Protocol, version 4 (IPv4) and Internet Protocol, version 6 (IPv6). However, it is not on by default and does not support 3rd party network stacks, of which there are a significant number in the world, such as large internet providers including national telephone companies.

For those not on Windows XP SP2, turning on the ICF is highly recommended. See the instructions "Use an Internet Firewall" on http://www.microsoft.com/security/protect as the first step to securing your PC. The Internet Connection Firewall (ICF) provides port mapping to override the packet filter. Essentially, you specify the port to open and it remains opened until you close it. If the user reboots before it is closed, it will remain open until specifically closed. The control of the firewall and the management of the port mappings is done via INetSharingManager (IPv4) and INetFWV6Mgr (IPv6).

The Windows Firewall for Windows XP SP2 is a more comprehensive solution that does support 3rd party network stacks, and handles ports more intelligently: ports are kept open only so long as the application that needs them is still active.

Windows XP SP2 Firewall Is Better

Windows XP SP2 puts the security choices and settings out front. The goal is to protect by default, and allow the user to make informed choices about what applications are allowed to run on their machine.

The new Windows Firewall is available on both Windows XP SP2 and Windows Server 2003 Service Pack 1 (SP1). Like the ICF, it is a software firewall that supports both IPv4 and IPv6, but unlike ICF the Windows Firewall:

  • Has boot-time protection of the system, eliminating a small window of vulnerability during boot.
  • Supports 3rd party network stacks.
  • Has an "on with no exceptions" mode that blocks all unsolicited incoming packets. This is great when you're using a public network, such as in an airport or coffee shop.

In the "on with no exceptions" mode, all static holes are closed. API calls to open a static hole are allowed but deferred; that is, they are not applied until the firewall switches back to normal operation. All listen requests by applications will also be ignored. Outbound connections will still succeed.

For new applications, add your application to the "Exceptions List" during installation. You can add the application using the INetFWAuthorizedApplications interface, supplying the full path. We'll cover the details in the sample.

As a side note, you may be wondering if it is a security risk that applications can add and remove applications from the exceptions list any user intervention, or perhaps you think that the bigger risk is that applications can disable the firewall altogether. To perform these feats, the application must have administrator privledges. If you have malicious code running in administrator mode on your system, the game is already over and the hacker has already won. The hacker's ability to disable the firewall would merit little more than a footnote.

Legacy applications, including applications installed before the user upgraded to Windows XP SP2, are handled with the Exceptions List popup (see Figure 1). This dialog shows when an application tries to open a port for incoming traffic - either when calling bind() with a non-zero port for UDP, or accept() for TCP/IP protocol. You must be running as an Administrator to "Unblock" applications, while "Ask Me Later" disallows this time around but asks again next time.

This is a non-blocking, system modal dialog box. When running a fullscreen Microsoft Direct3D application, the dialog comes in underneath; and the user can then handle it when the application exits fullscreen mode or alt-tabs back to the desktop. However, it is not always obvious to the user that this dialog has appeared when a game is running fullscreen, so it is important to avoid causing this dialog to appear by using INetFWAuthorizedApplications interface as discussed below.

Figure 1. Exceptions List Popup Dialog

You'll notice that the popup knows the name and publisher of the application. There's no magic here - it's pulled from the executable's version information. This information is an important system administration tool; it is even used for ongoing application compatibility work. Some applications neglect to keep this version information up-to-date.

Users can also add their applications through the user interface (UI) (see Figure 2)

Figure 2. Configuring the Firewall

Figure 3. Adding a Program to the Firewall Exceptions List

The best scenario is to make additions and removals from the exception list automated. The best time to perform these additions and removals is during the install and uninstall process. Adding or removing from the firewall exception list requires administrator privledges, so be sure to take this into account.

Working with the Windows Firewall

Again, most games only need to be added to the firewall exception list if they can function as a server or if they implement a peer-to-peer communication protocol. The FirewallInstallHelper.dll is a sample DLL that can be called from an installer. Source is provided if you want to integrate the source directly into your own application. The sample can be found here:

Source: | (SDK root)\Samples\C++\Misc\FirewallInstallHelper
Executable: | (SDK root)\Samples\C++\Misc\Bin\<arch>\FirewallInstallHelper.dll

The functions exported by this DLL are the following:

AddApplicationToExceptionListW
This function adds an application to the exception list. It takes a complete path to the executable and a friendly name that will appear in the firewall exception list. This function requires administrator privileges.
AddApplicationToExceptionListA
ANSI version of AddApplicationToExceptionListW
RemoveApplicationFromExceptionListW
This function removes the application from the exception list. It takes in a complete path to the executable. This function requires administrator privileges
RemoveApplicationFromExceptionListA
ANSI version of RemoveApplicationFromExceptionListW
CanLaunchMultiplayerGameW
This function reports if the application has been disabled or removed from the exceptions list. It should be called every time the game is run. The function takes in a complete path to the executable. This function does not require administrator privileges.
CanLaunchMultiplayerGameA
ANSI version of CanLaunchMultiplayerGameW
SetMSIFirewallProperties
Call this only if you are using custom actions in Windows Installer. See below for more details
AddToExceptionListUsingMSI
Call this only if you are using custom actions in Windows Installer. See below for more details
RemoveFromExceptionListUsingMSI
Call this only if you are using custom actions in Windows Installer. See below for more details

The following sections describe specific methods of calling the exported DLL functions from this FirewallInstallHelper from within an InstallShield, Wise, or Windows Installer package. All methods render the same results and it is up to the developer to determine which method to implement.

Integrating using InstallShield InstallScript

An alternate method of using the Firewall APIs is to add the function calls to an InstallShield InstallScript. The steps required to integrate are fairly simple:

  1. Open an InstallScript project in the InstallShield editor.
  2. Add the FirewallInstallHelper.dll to the project as a support file.
    1. Under Project Assistant tab, open the Application Files tab.
    2. Click on the Add Files button to add files to the Application Target Folder.
    3. Browse to the FirewallInstallHelper.dll that you have built or use the one provided in the DirectX SDK and add it to the project.
  3. Add InstallScript to the project.

    1. Open the Installation Designer view, and click on the Behavior and Logic | InstallScript

    2. Click on the InstallScript file (usually setup.rul) to open it in the editor

    3. Paste the following code into the InstallScript file:

      #include "ifx.h"

prototype BOOL FirewallInstallHelper.AddApplicationToExceptionListW( WSTRING, WSTRING );
prototype BOOL FirewallInstallHelper.RemoveApplicationFromExceptionListW( WSTRING );

function OnMoved()
    WSTRING path[256];
begin
    // The DLL has been been installed into the TARGETDIR
    if !MAINTENANCE then // TRUE when installing
        UseDLL( TARGETDIR ^ "FirewallInstallHelper.dll" );
        path = TARGETDIR ^ "TODO: change to relative path to executable from install directory";
        FirewallInstallHelper.AddApplicationToExceptionListW( path, "TODO: change to friendly app name" );
        UnUseDLL( TARGETDIR ^ "FirewallInstallHelper.dll" );
    endif;
end;

function OnMoving()
    WSTRING path[256];
begin
    // The DLL is about to be removed from TARGETDIR
    if MAINTENANCE && UNINST != "" then // TRUE when uninstalling
        UseDLL( TARGETDIR ^ "FirewallInstallHelper.dll" );
        path = TARGETDIR ^ "TODO: change to relative path to executable from install directory";
        FirewallInstallHelper.RemoveApplicationFromExceptionListW( path );
        UnUseDLL( TARGETDIR ^ "FirewallInstallHelper.dll" );
    endif;
end;
    4. Change the TODO comments with the application name that will be shown in the Firewall Exception List and the path to the game executable relative to the installation directory.

Integrating into Wise for Windows Installer

To integrate with Wise for Windows Installer, these steps have to be done:

  1. Open your Wise for Windows Installer project.
  2. Select the "Installation Expert" tab at the bottom
  3. Click on Files, and add the FirewallInstallHelper.dll from the DXSDK to the game's install directory
  4. Select the "MSI script" tab at the bottom
  5. Select the "Execute Immediate" tab near the bottom
  6. After CostFinalize, add a "Set Property" action that sets FULLPATH to "[INSTALLDIR]relative path to executable from install directory". For example, "[INSTALLDIR]game.exe" without the quotes
  7. Select the "Execute Deferred" tab near the bottom
  8. After PublishProduct, add an "If statement" with the condition "NOT Installed" (case sensitive)
  9. Within the If block add a "Call Custom DLL from Destination" action.
    1. Set the DLL File field to "[INSTALLDIR]FirewallInstallHelper.dll"
    2. Set the Function Name field to "AddApplicationToExceptionListA"
    3. Add a parameter with type "string pointer", value source "Property", and property name "FULLPATH".
    4. Add a second parameter with type "string pointer", value source "Constant", and set the constant value to the friendly application name you want displayed in the firewall exception list.
    5. Close the If block by adding an "End Statement"
  10. Just above the RemoveFiles action near the top, add another If block, with the condition to be "REMOVE~="ALL"" (case sensitive and without the outer quotes).
  11. Within the second If block add a "Call Custom DLL from Destination" action
    1. Set the DLL File field to "[INSTALLDIR]FirewallInstallHelper.dll"
    2. Set the Function Name field to "RemoveApplicationFromExceptionListA"
    3. Add a parameter with type "string pointer", value source "Property", and property name "FULLPATH"
    4. Close the second If block by adding an "End Statement"

Integrating into Windows Installer

To integrate with Windows Installer at the high level, these steps have to be done. They will be explained in detail below:

  • Add 2 properties "FriendlyNameForFirewall" and "RelativePathToExeForFirewall" as described below.
  • After the CostFinalize action, call "SetMSIFirewallProperties" in an immediate custom action to set the appropriate MSI properties for the other custom actions.
  • During install after the InstallFiles action, call a deferred custom action that uses the FirewallInstallHelper's "AddToExceptionListUsingMSI" function.
  • During uninstall after the InstallFiles action, call a deferred custom action that uses the FirewallInstallHelper's "RemoveFromExceptionListUsingMSI" function.
  • During rollback, call a deferred custom action which also calls the FirewallInstallHelper's "RemoveFromExceptionListUsingMSI" function.

The following is the steps need to do this using an MSI editor such as Orca found in the Platform SDK. Note that some editors have use wizards which simplify some of these steps:

  1. Open the MSI package in Orca
  2. Add the following to the Binary table:
    Name | Data
    FIREWALL | Point it to the FirewallInstallHelper.dll. This file will be embedded in the MSI package so you will have to do this step every time you recompile FirewallInstallHelper.dll.
  3. Add the following to CustomAction table:
    Action | Type | Source | Target
    FirewallSetMSIProperties | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue = 65 | FIREWALL | SetMSIFirewallProperties
    FirewallAdd | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeInScript + msidbCustomActionTypeNoImpersonate = 3137 | FIREWALL | AddToExceptionListUsingMSI
    FirewallRemove | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeInScript + msidbCustomActionTypeNoImpersonate = 3137 | FIREWALL | RemoveFromExceptionListUsingMSI
    FirewallRollBackAdd | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeRollback + msidbCustomActionTypeInScript + msidbCustomActionTypeNoImpersonate = 3393 | FIREWALL | RemoveFromExceptionListUsingMSI
    FirewallRollBackRemove | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeRollback + msidbCustomActionTypeInScript + msidbCustomActionTypeNoImpersonate = 3393 | FIREWALL | AddToExceptionListUsingMSI
  4. Add the following to the InstallExecuteSequence table
    Action | Condition | Sequence | Notes
    FirewallSetMSIProperties | 1010 | This places soon after CostFinalize
    FirewallAdd | NOT Installed | 4021 | This custom action will only happen during a fresh install. The sequence number places the action after InstallFiles and after the rollbacks.
    FirewallRollBackAdd | NOT Installed | 4020 | This custom action will only happen when a fresh install is cancelled. The sequence number places the action after InstallFiles and before the Add custom action.
    FirewallRemove | Installed | 3461 | This custom action will only happen during uninstall. The sequence number places the action directly before RemoveFiles and after the rollbacks.
    FirewallRollBackRemove | NOT Installed | 3460 | This custom action will only happen when an uninstall is cancelled. The sequence number places the action directly before RemoveFiles and before the Remove custom action.
  5. Add the following to the Property table:
    Property | Value
    FriendlyNameForFirewall | Needs to be the name the exception list will display. For example, "Example Game"
    RelativePathToExeForFirewall | Needs to be the installed executable of the game. For example, "ExampleGame.exe"

For more information on Windows Installer, see Windows Installer

Recommendations

The firewall is here to stay. These recommendations will give your customers a good firewall experience with your Windows game:

  • Don't tell users to disable the firewall to play your game. This makes the entire machine vulnerable even when they aren't playing your game.
  • Make the firewall configuration seamless for your users. Add your application to the exception list during installation, and remove your application from the exception list during installation.
  • Give feedback to the user if multiplayer is blocked by the firewall state. For example, disable networking features if they won't work either because the application is disallowed or because the system is in the "no exceptions" mode.


Windows Game Explorer for Game Developers

XNA Developer Connection (XDC)

December 2005

Updated: December 2006

Introduction

Microsoft Windows Vista improves the user experience of gaming on Windows by including Game Explorer. Game Explorer is exposed in the Windows Vista Start Menu as the Games folder and provides a central location for accessing games. This article outlines the process of registering a game with Game Explorer and parental controls.

Contents:

  • Prerequisites
  • Integration Process
  • Game Explorer Tasks
  • Removal Process
  • Integrating into an Installer
  • Integrating into InstallScript
  • Integrating into an MSI Package
  • Debugging Tips
  • Summary

Prerequisites

Before you can integrate a game into Game Explorer, you must create a game definition file (GDF). A GDF is an XML file that contains metadata describing the game. Microsoft provides a tool for authoring GDFs in the DirectX SDK, Game Definition File Editor, to make this creation process easier. This tool also helps you create localized versions of a GDF.

Once a GDF has been authored and localized, it must be encapsulated within a resource section of a binary file (either an executable or DLL), along with the game's thumbnail and icon. The GDF contains all the metadata associated with the game including the game's rating. Windows Vista parental controls use the game's rating to allow parents to control access to the game. The binary file which contains the GDF must be digitally signed with a valid Authenticode certificate; otherwise, Game Explorer and the parental control system will ignore the game's rating, because the rating information cannot be trusted without certification. For more details about signing code with Authenticode, see Authenticode Signing for Game Developers

Integration Process

Once the GDF and related files have been added to a binary resource, it is then possible to integrate the game with Game Explorer. It is strongly advised that games integrate with Game Explorer during the installation process. The outline to the integration process is as follows:

  1. Install ALL files to the user's hard drive. The AddGame step activates parental controls and could potentially lock the user out of the installation directory.
  2. Create an instance to the IGameExplorer interface.
  3. Call the VerifyAccess method, of the IGameExplorer interface and pass it the path to the GDF.
  4. Call the AddGame method, of the IGameExplorer interface and pass it the path to the GDF, the path to the root installation directory, and a unique GUID called the game instance ID. If passing in GIS_ALL_USERS, administrator privileges are required.
  5. Create shortcuts, which are called Game Explorer tasks, by using the game instance ID. Game Explorer tasks are explained in the next section.

Game Explorer Tasks

Game Explorer tasks are what users see when they right-click on a game in Game Explorer. Tasks are simply shortcuts located in known folders. Tasks are divided into play tasks and support tasks. For example, if you want a shortcut that launches a game into a multiplayer mode, that is a play task. If you want a shortcut to a web site, that shortcut is a support task. Play tasks and support tasks are stored in directories with the corresponding names PlayTasks and SupportTasks. Play tasks can be customized by the user, while support tasks can not. You are responsible for creating both the shortcuts and the directories where they are placed.

In the following example layout of a task folder, the paths to the shortcuts begin with the path returned from SHGetFolderPath by passing it either CSIDL_COMMON_APPDATA or CSIDL_LOCAL_APPDATA; which should be passed depends on whether the game is being installed for all users or just the current user. Also, {game instance ID} is the GUID that is passed to the AddGame function.

The following are example shortcuts:

.\Microsoft\Windows\GameExplorer\{game instance ID}\PlayTasks\0\Play.lnk

.\Microsoft\Windows\GameExplorer\{game instance ID}\PlayTasks\1\Play Online.lnk

.\Microsoft\Windows\GameExplorer\{game instance ID}\SupportTasks\0\Developer's Website.lnk

Note The location specified by these paths is relative to the location returned by SHGetFolderPath.

When tasks are shown, the name of the link is displayed to the user, with the exception of the first link in PlayTasks, which is always called Play. The tasks are displayed in ascending order by the numbered subdirectory of their link. More information about tasks can be found in the documentation for Game Explorer.

Removal Process

The process of removing a game from Game Explorer is easy, and you can do so by performing the following steps:

  1. Create an instance to the IGameExplorer interface.
  2. Call the RemoveGame method with the game instance ID that was used during the integration process. If the game was added with GIS_ALL_USERS, administrator privileges are required otherwise you must use the same user account that was used to add the game.
  3. Delete the appropriate game files and task folders.

This process only removes one unique installation. If a game has been installed multiple times, this process must be repeated for each unique installation.

Integrating into an Installer

If possible, you should call the Game Explorer APIs during installation. GameuxInstallHelper is a sample DLL to help you in this process, and it and its source code are provided in the DirectX SDK. GameuxInstallHelper is designed to work with scripts for InstallShield and Wise Installation System, as well as MSI custom actions and custom installation tools. The functions exported by this DLL are the following:

GenerateGUID
Creates a unique game instance ID.
AddToGameExplorerW
Registers a game with Game Explorer, given a game instance ID and a path to the GDF binary.
AddToGameExplorerA
Registers a game with Game Explorer; ANSI version of AddToGameExplorerW.
RetrieveGUIDForApplicationW
Returns a game instance ID, given the path to a GDF binary that has already been registered.
RetrieveGUIDForApplicationA
Returns a game instance ID; ANSI version of RetrieveGUIDForApplicationW.
RemoveFromGameExplorer
Removes a game from registration with Game Explorer, given a game instance GUID.
CreateTaskW
Creates a task shortcut in the proper location, given a game instance ID.
CreateTaskA
Creates a task shortcut in the proper location; ANSI version of CreateTaskW.
RemoveTasks
Removes all of the tasks associated with a game instance ID.
SetupRichSavedGamesW
Creates the registry keys to enable rich saved games.
SetupRichSavedGamesA
Creates the registry keys to enable rich saved games; ANSI version of SetupRichSavedGamesW.
RemoveRichSavedGamesW
Removes the registry keys to enable rich saved games.
RemoveRichSavedGamesA
Removes the registry keys to enable rich saved games; ANSI version of RemoveRichSavedGamesW.
SetMSIGameExplorerProperties
Configures the CustomActionData properties for the actions of an MSI deferred custom installation. Usage of this function is described in detail below.
AddToGameExplorerUsingMSI
Adds a game to Game Explorer; for use during an MSI custom action installation.
RemoveFromGameExplorerUsingMSI
Removes a game from Game Explorer; for use during an MSI custom action installation.

Integrating into InstallScript

Calling Game Explorer APIs from InstallShield's InstallScript is made easy by using the sample DLL, GameuxInstallHelper, described earlier. The steps required to integrate with InstallShield are as follows:

  1. Open an InstallScript project in the InstallShield editor.

  2. Add GameuxInstallHelper.dll to the project to be installed to the target directory.

    To add GameuxInstallHelper.dll to an InstallScript project:

    1. On the Installation Designer tab, click Application Data in the navigation pane on the left.

    2. Click Files and Folders and browse in Source computer's folders to locate GameuxInstallerHelper.dll in Source computer's files.

      The default location for GameuxInstallerHelper.dll is DirectX SDK root\Samples\C++\Misc\Bin\x86.

    3. Under Destination computer's folders, click Application Target Folder.
    4. Drag GameuxInstallerHelper.dll from Source computer's files to Destination computer's files.
  3. In the InstallScript explorer, click the InstallScript file (usually setup.rul) that calls the DLL function.
  4. Paste this InstallScript into the file:
    typedef GUID
begin
LONG  Data1;
SHORT Data2;
SHORT Data3;
CHAR  Data4(8);
end;

prototype LONG GameuxInstallHelper.AddToGameExplorerW( WSTRING, WSTRING, NUMBER, GUID POINTER );
prototype LONG GameuxInstallHelper.RemoveFromGameExplorer( GUID POINTER );
prototype LONG GameuxInstallHelper.RetrieveGUIDForApplicationW( WSTRING, GUID POINTER );
prototype LONG GameuxInstallHelper.GenerateGUID( GUID POINTER );
prototype LONG GameuxInstallHelper.CreateTaskW( NUMBER, GUID POINTER, NUMBER, NUMBER, WSTRING, WSTRING, WSTRING );
prototype LONG GameuxInstallHelper.RemoveTasks( GUID POINTER );
prototype LONG GameuxInstallHelper.SetupRichSavedGamesW( WSTRING, WSTRING, WSTRING );
prototype LONG GameuxInstallHelper.RemoveRichSavedGamesW( WSTRING );

function OnMoved()

WSTRING gdfbin[256];
WSTRING path[256];
NUMBER scope;
NUMBER supportTask;
NUMBER playTask;
GUID guid;
GUID POINTER pGuid;

begin

if !MAINTENANCE then

UseDLL( TARGETDIR ^ "GameuxInstallHelper.dll" );
UseDLL( WINSYSDIR ^ "OLE32.dll" );

path = TARGETDIR;
gdfbin = path ^ "bin\\ExampleGame.exe";  // TODO: Change this to point to binary containing the GDF
pGuid = &guid;
playTask = 0;
supportTask = 1;

if ALLUSERS == 1 then
scope = 3;
else
scope = 2;
endif;

GameuxInstallHelper.GenerateGUID( pGuid );
GameuxInstallHelper.AddToGameExplorerW( gdfbin, path, scope, pGuid );

// TODO: Add/remove/change tasks

// Play tasks.  You can define up to 6
GameuxInstallHelper.CreateTaskW( scope, pGuid, playTask, 0, "Play", gdfbin, "" );
GameuxInstallHelper.CreateTaskW( scope, pGuid, playTask, 1, "Network Play", gdfbin, "-network" );
GameuxInstallHelper.CreateTaskW( scope, pGuid, playTask, 2, "Safe Mode", gdfbin, "-safe" );

// Support tasks.  You can define up to 5
GameuxInstallHelper.CreateTaskW( scope, pGuid, supportTask, 0, "Support", "http://www.msn.com", "" );

// Setup rich save game support
// TODO: change the saved game file extension
GameuxInstallHelper.SetupRichSavedGamesW( ".ExampleSaveGame", gdfbin, "%1" );

UnUseDLL( TARGETDIR ^ "GameuxInstallHelper.dll" );
UnUseDLL( WINSYSDIR ^ "OLE32.dll" );

endif;

end;

function OnMoving()

WSTRING gdfbin[256];
GUID guid;
GUID POINTER pGuid;

begin

if MAINTENANCE && UNINST != "" then

UseDLL( TARGETDIR ^ "GameuxInstallHelper.dll" );
UseDLL( WINSYSDIR ^ "OLE32.dll" );

gdfbin = path ^ "bin\\ExampleGame.exe";  // TODO: Change this to point to binary containing the GDF
pGuid = &guid;

GameuxInstallHelper.RetrieveGUIDForApplicationW( gdfbin, pGuid );
GameuxInstallHelper.RemoveFromGameExplorer( pGuid );
GameuxInstallHelper.RemoveTasks( pGuid );
GameuxInstallHelper.RemoveRichSavedGamesW( ".ExampleSaveGame" );

UnUseDLL( TARGETDIR ^ "GameuxInstallHelper.dll" );
UnUseDLL( WINSYSDIR ^ "OLE32.dll" );

endif;

end;

Integrating into an MSI Package

The following is a high-level description of the steps required to call the Game Explorer APIs using MSI custom actions:

  1. Add a property to the MSI Property table called "RelativePathToGDF" containing the relative path to the GDF binary.
  2. After the CostFinalize action, call the GameuxInstallHelper DLL function SetMSIGameExplorerProperties in an immediate custom action to set the appropriate MSI properties for the other custom actions.
  3. Upon installation, trigger a deferred custom action after the InstallFiles action that calls the GameuxInstallHelper DLL function AddToGameExplorerUsingMSI. If the install is installing for all users, then the custom action must have the msidbCustomActionTypeNoImpersonate flag set otherwise it must not set this flag. Therefore two nearly identical custom actions are defined below: GameUXAddAsAdmin and GameUXAddAsCurUser.
  4. Upon uninstall, trigger a deferred custom action before the RemoveFiles action that calls the GameuxInstallHelper DLL function RemoveFromGameExplorerUsingMSI. If the install was for all users, then the custom action must have the msidbCustomActionTypeNoImpersonate flag set otherwise it must not set this flag. Therefore two nearly identical custom actions are defined below: GameUXRemoveAsAdmin and GameUXRemoveAsCurUser.
  5. Define rollback custom actions to handle the case where the user cancels out the install or uninstall process after one of the above custom actions has already happened. This results in an additional 4 custom actions: GameUXRollBackAddAsAdmin, GameUXRollBackAddAsCurUser, GameUXRollBackRemoveAsAdmin, and GameUXRollBackRemoveAsCurUser

This procedure is described in detail in the following instructions, which can be done using an MSI editor such as as the Orca editor found in the Platform SDK. Some MSI editors have wizards which simplify some of these configuration steps.

To configure an MSI package for integration with Game Explorer

  1. Open the MSI package in Orca.
  2. Add the row shown in the following table to the Binary table in the MSI package.
    Name | Data
    GAMEUX | file path to the DLL\GameuxInstallHelper.dll

    Note This file will be embedded in the MSI package, so you must do this step every time you recompile GameuxInstallHelper.dll.

  3. Add the rows shown in the following table to the CustomAction table in the MSI package.
    Action | Type | Source | Target
    GameUXSetMSIProperties | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue = 65 | GAMEUX | SetMSIGameExplorerProperties
    GameUXAddAsAdmin | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeInScript + msidbCustomActionTypeNoImpersonate = 3137 | GAMEUX | AddToGameExplorerUsingMSI
    GameUXAddAsCurUser | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeInScript = 1089 | GAMEUX | AddToGameExplorerUsingMSI
    GameUXRollBackAddAsAdmin | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeRollback + msidbCustomActionTypeInScript + msidbCustomActionTypeNoImpersonate = 3393 | GAMEUX | RemoveFromGameExplorerUsingMSI
    GameUXRollBackAddAsCurUser | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeRollback + msidbCustomActionTypeInScript = 1345 | GAMEUX | RemoveFromGameExplorerUsingMSI
    GameUXRemoveAsAdmin | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeInScript + msidbCustomActionTypeNoImpersonate = 3137 | GAMEUX | RemoveFromGameExplorerUsingMSI
    GameUXRemoveAsCurUser | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeInScript = 1089 | GAMEUX | RemoveFromGameExplorerUsingMSI
    GameUXRollBackRemoveAsAdmin | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeRollback + msidbCustomActionTypeInScript + msidbCustomActionTypeNoImpersonate = 3393 | GAMEUX | AddToGameExplorerUsingMSI
    GameUXRollBackRemoveAsCurUser | msidbCustomActionTypeDll + msidbCustomActionTypeBinaryData + msidbCustomActionTypeContinue + msidbCustomActionTypeRollback + msidbCustomActionTypeInScript = 1345 | GAMEUX | AddToGameExplorerUsingMSI
  4. Add the values shown for Action, Condition, and Sequence in the following table to the InstallExecuteSequence table in the MSI package.
    Action | Condition | Sequence | Notes
    GameUXSetMSIProperties | 1015 | The sequence number places the action soon after CostFinalize.
    GameUXAddAsAdmin | NOT Installed AND ALLUSERS | 4003 | This custom action will only happen during a fresh install for all users. The sequence number places the action after InstallFiles and after the rollbacks.
    GameUXAddAsCurUser | NOT Installed AND NOT ALLUSERS | 4004 | This custom action will only happen during a fresh install for the current user only. The sequence number places the action after InstallFiles and after the rollbacks.
    GameUXRollBackAddAsAdmin | NOT Installed AND ALLUSERS | 4001 | This custom action will only happen when a fresh install for all users is cancelled. The sequence number places the action after InstallFiles and before the Add custom action.
    GameUXRollBackAddAsCurUser | NOT Installed AND NOT ALLUSERS | 4002 | This custom action will only happen when a fresh install for the current user only is cancelled. The sequence number places the action after InstallFiles and before the Add custom action.
    GameUXRemoveAsAdmin | REMOVE~="ALL" AND ALLUSERS | 3452 | This custom action will only happen during uninstall for all users. The sequence number places the action directly before RemoveFiles and after the rollbacks.
    GameUXRemoveAsCurUser | REMOVE~="ALL" AND NOT ALLUSERS | 3453 | This custom action will only happen during uninstall for the current user. The sequence number places the action directly before RemoveFiles and after the rollbacks.
    GameUXRollBackRemoveAsAdmin | REMOVE~="ALL" AND ALLUSERS | 3450 | This custom action will only happen when an uninstall for all users is cancelled. The sequence number places the action directly before RemoveFiles and before the Remove custom action.
    GameUXRollBackRemoveAsCurUser | REMOVE~="ALL" AND NOT ALLUSERS | 3451 | This custom action will only happen when an uninstall for the current user is cancelled. The sequence number places the action directly before RemoveFiles and before the Remove custom action.
  5. Add the row shown in the following table to the Property table in the MSI package.
    Property | Value
    RelativePathToGDF | relative file path\name of binary file that contains the GDF

    Note The location specified by the path is relative to the location specified by the installation path. For example, bin\GDF.dll.

  6. Save the MSI package.

For more detailed information about MSI packages and Windows Installer, see Windows Installer on MSDN.

Debugging Tips

The following are some tips to help debug issues when calling Game Explorer APIs:

  • Test with sample code.

    Building the GameuxInstallHelper sample solution will create a GameUXInstallHelper.dll and a GDFInstall.exe. The GDFInstall.exe is a sample application that uses GameUXInstallHelper.dll. Running GDFInstall.exe will prompt if you want install or remove a GDF binary from game explorer. You can test your GDF binary file by passing it in as the first command line arg to GDFInstall.exe.

    If you don't have a GDF binary or yours fails to install, try using the sample GDF in the DirectX SDK. The GDFExampleBinary sample is found in the DirectX SDK and is just a DLL that only contains a GDF file. Also included in the source is its GDFMaker project. You can build it and test it using GDFInstall.exe. You can also compare the its XML to yours to pinpoint exactly where the issue is.

  • Make sure your game was removed properly.

    If the game is already installed in Game Explorer, then subsequent calls to IGameExplorer::AddGame will return E_FAIL so make sure your game isn't installed before testing. This also applies if you install the GDF for only the current user and then try to install the GDF for all users. You must first remove the game from the current users before IGameExplorer::AddGame will succeed.

    If you run GDFInstall.exe enum, the sample application will enter a different mode which will enumerate all of the installed Game Explorer games and prompt you to remove them. You can also browse and search the registry in HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\GameUX to make sure that your game isn't installed for another user on the system. However, do not alter these registry keys for any other purpose, as they are not guaranteed to remain compatible in future versions of the operating system.

  • Be sure to sign using Authenticode.

    If you have provided a rating, but are not seeing it in Game Explorer, make sure that you have used Authenticode to sign the executable or DLL file that contains the rating. Game Explorer ignores ratings information in unsigned files. For more information about Authenticode, see Authenticode Signing for Game Developers

  • Be sure that parental controls are available.

    Ensure that you are testing parental controls on an edition of Windows Vista that provides parental controls: Home Basic, Home Premium, or Ultimate. Also, if you are testing on Windows Vista Ultimate, and the test computer is joined to a domain, you must manually enabled parental controls. Windows Vista Business and Windows Vista Enterprise do not provide parental controls.

  • Verify that tasks are of the correct type.

    If you have specified support tasks that do not appear in Game Explorer, verify that they are all Web links. Any other shortcut tasks must be created as play tasks. Tasks are covered earlier in this topic in Game Explorer Tasks.

Summary

Game Explorer in Windows Vista provides an easy, customizable way to present your game to users of Windows Vista, but it also requires you to register the game with the system during the installation process. By using the sample code and the DLL described in this article, GameuxInstallerHelper, this registration process is simplified.


Windows Installer for Game Developers

By Dave Bartolomeo, Software Design Engineer

Microsoft Corporation

October 2003

Introduction

Shows how Windows Installer can be used to install games on end-user machines. Windows Installer offers full support for a customized user interface, as well as for patching. (4 printed pages)

Microsoft Windows Installer is the preferred API for installing software on Windows-based computers. While many of the features of Windows Installer are designed to support deployment of business applications in a corporate environment, Windows Installer is also completely suitable for installing games on end-user machines. The primary advantages of using Windows Installer for game installation are:

  • Reliable uninstall.
  • Ability to install content on demand.
  • Support for completely custom user interface.
  • Efficient patching.

In this article, I'll give an overview of Windows Installer, specifically targeted to game developers. For detailed documentation on the features and APIs mentioned in this article, please refer to the Windows Platform SDK.

Overview

All Windows Installer-based setups use an installation database file called an MSI file to describe how the application is to be installed. The MSI file contains information on what files, registry keys, desktop shortcuts, file associations, and other application elements are to be installed. The actual files to be installed can be compressed within the MSI file itself, bundled and compressed into separate "cabinet files", or stored elsewhere on the installation media as individual uncompressed files. The MSI file can also reference externally implemented custom actions, in order to allow for actions for which the MSI file does not natively allow.

An MSI file can optionally contain a user interface to guide the user through the installation process. This UI is adequate for most applications. However, it has the look and feel of a regular Windows application, and many game developers prefer to have their setup application maintain the look and feel of the game itself, in order to provide a more consistent end-user experience. To support this fully custom UI scenario, a setup application can turn off Windows Installer's built-in UI, and handle the entire user interface itself. The Windows Installer API exposes a callback mechanism to allow a custom setup UI to be notified of the progress of the installation, as well as important events such as disk change requests.

Windows Installer is not an end-to-end solution for creating setups. It is only an API that can be used by a setup program to do the actual installation of files, registry keys, desktop shortcuts, and other elements of the application. Recent versions of all of the major commercial setup tools (for example, InstallShield, WISE, and Microsoft Visual Studio) support Windows Installer. These tools provide convenient user interfaces for creating the setup for a game, but they rely on the Windows Installer API to do much of the actual installation. These tools can also be used just to build an MSI database containing the setup package, which can then be installed from a custom-written setup UI. As an alternative to third-party tools, the Windows Installer API provides all of the functions necessary for creating and manipulating an MSI database programmatically, and the Windows Platform SDK includes a bare-bones MSI database-editing tool called Orca.

Key Windows Installer Concepts

Components

An application is made up of one or more components, identified by a GUID component ID. A component is an atomic unit; it is either entirely installed or not installed at all. A component can consist of a single file, multiple files, registry keys, desktop shortcuts, or some combination thereof. The resources (files, and so on) within a component must be unique to that component-no two components can contain the same resource. A component is never installed explicitly; it is only installed as part of a feature (see below).

Features

A feature is a group of components, identified by a GUID feature ID. Unlike components, multiple features may contain the same component. A component shared between multiple features will be installed if any of those features is installed, and removed only when all features that reference the component have been uninstalled. Installation of a feature can be done automatically as part of the installation of a product, or it can be done manually using the MsiConfigureFeature API.

Although few games have multiple "features" that can be installed independently, the Windows Installer concept of a feature is still useful. Since a Windows Installer feature is nothing more than a collection of components that can be installed together, games can use features to group together all of the content needed for a particular stage of the game. For example, a level-oriented game could define one feature per level, consisting of all of the content required for that level. This would allow the game to install the content one level at a time from within the game itself, rather than installing all of the content for all of the levels during the initial installation.

Install States

Each component or feature has an associated install state, which determines whether the component or feature is available, and if so, where the files for the component or feature are installed. The possible install states for a feature are:

  • Absent. The feature is not installed and is therefore inaccessible.
  • Local. The feature is available and is installed to run from the local hard drive.
  • Source. The feature is available and is installed to run from the original source media (usually a CD or DVD).
  • Advertised. The feature is not installed, but can be installed on demand using the MsiConfigureFeature API. When the feature is actually installed, it can be installed either to the Local or Source state.

A component can have any of the above states except for "Advertised." If a component is part of an advertised feature, the component will appear as "Absent" until the feature is installed.

Install on Demand

Windows Installer allows an application to mark features as Advertised, meaning that the feature is not yet installed, but is available to install at runtime if it is needed. Installing features at runtime is known as "Install on Demand." Games can use Install on Demand to drastically reduce the time required for the initial game setup by deferring the installation of game content until it is needed at runtime. The delay required to install the content at runtime can often be partially or completely hidden by doing the on-demand installation in a background thread, while the user is otherwise occupied with the game.

Custom User Interface

Although Windows Installer provides a default user interface that guides the user through the installation of the application, this interface looks like that of a standard Windows application. Many game developers prefer that their installation UI have the same look and feel as the game itself, to provide the user with a taste of the game's ambiance. To support this, Windows Installer allows its built-in user interface to be completely disabled, allowing the developer to provide a completely custom UI.

The custom setup program first disables Windows Installer's built-in user interface using the MsiSetInternalUI API to set the UI level to INSTALLUILEVEL_NONE. It then calls the MsiSetExternalUI API to specify a callback function that will be called during the installation process to notify the setup program of key events during the installation.

The actual installation process is then started by calling the MsiInstallProduct API. This API accepts a parameter string that allows the caller to specify values for named properties. These properties can be used within the installation database itself to customize how the application is to be installed. These properties can be used to specify:

  • The directory to which the application is to be installed.
  • Which features are to be installed locally and which are to be installed to run from the CD/DVD. (For example, to enable choosing between a minimal install and a full install.)
  • Whether the application should be installed for all users of the machine, or for only the current user.

During the course of the installation, the setup program uses the notification messages sent to its callback function to determine when to update its progress indicator UI, when to prompt the user to insert the next CD, or when to notify the user about an error in the installation process.

Patching

Windows Installer allows installed applications to be patched by applying a patch file. A patch file contains the new files to be added by the patch, the files that are modified by the patch, and a list of changes to make to the installation database. To conserve space, instead of storing the complete contents of a file changed by the patch, the patch file actually contains only the differences between the original version of the file and the new version of the file.

In order to create a patch, you need the setup image for each of the versions of the application that you wish the patch to upgrade from, as well as the setup image for the new, upgraded version of the application. A setup image consists of the MSI database and all of the actual data files for the application. The best way to create a setup image for a new version of the application is to copy the setup image from the previous version of the application, and then make any changes necessary to update that copy to the patched version.

Once you have all of the necessary setup images, you can create the patches using Msimsp.exe, which is a patch creation tool available as part of the Platform SDK. The tool will ask for the locations of each of the setup images, and then determine how to efficiently represent the differences between the successive versions. The output of the tool is the final patch file (identified by the extension MSP). In order to install the patch programmatically, call the MsiApplyPatch API. The user can also install the patch manually by double-clicking on the MSP file in Explorer.

Other Resources

  • For detailed information on the Windows Installer API, refer to the Windows Installer
  • For information on best practices for game installation, see my previous column, Installation and Maintenance of Games.


Topic Not Found

Topic Not Supported

The page you have reached contains conceptual or programmatic material that is not supported in this release of the SDK.

Support will be added in later versions of the SDK.

© 2006 Microsoft Corporation. All rights reserved.


Topic Not Found

Overview Material Under Construction

Overview material for this topic has not yet been written. More overview material will be available in upcoming releases of the SDK.

© 2006 Microsoft Corporation. All rights reserved.